mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 04:52:54 -05:00
Merge main into feat/plugin-api-events
# Conflicts: # crates/engine/src/cmd/plugin.rs # crates/plugins/src/lib.rs # crates/plugins/src/manifest.rs # crates/plugins/src/runtime.rs # crates/ui-egui/src/app.rs # crates/ui-egui/src/dialogs/tests.rs # crates/ui-egui/src/i18n/tests.rs # docs/target-app-parity.md
This commit is contained in:
commit
156fdce3f4
1661 files changed
+294428
-270319
No files matched your search
@@ -1,5 +1,6 @@
|
||||
//! How the host's generated dialogs show a plug-in's parameters: the optional `label`, `unit`,
|
||||
//! `group`, `help`, `helpUrl` and `visibleWhen` keys of each one (docs/plugins.md › Parameters).
|
||||
//! `group`, `help`, `helpUrl`, `visibleWhen` and `widget` keys of each one
|
||||
//! (docs/plugins.md › Parameters).
|
||||
//!
|
||||
//! These keys are presentation only. A host from before them ignores them, so a plug-in that
|
||||
//! declares them still installs there, and a plug-in is given every parameter whether its dialog
|
||||
@@ -58,6 +59,48 @@ pub struct ParamUi {
|
||||
/// Shown only while each parameter named here has one of the values listed for it.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub visible_when: BTreeMap<String, Vec<Value>>,
|
||||
/// The control that shows a number: [`Widget::Slider`] adds a slider beside its field.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub widget: Option<Widget>,
|
||||
}
|
||||
|
||||
/// The control a `number` or `int` parameter's row shows besides its number field (`widget`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Widget {
|
||||
/// A slider over `min..max`, beside the number field.
|
||||
Slider,
|
||||
}
|
||||
|
||||
/// The largest whole number an `f64` holds exactly, which bounds an `int` slider's range.
|
||||
const EXACT_INT: i64 = 1 << 53;
|
||||
|
||||
impl ParamUi {
|
||||
/// The range a slider shows `spec`'s value over, when the parameter asks for one
|
||||
/// ([`Widget::Slider`]) and `spec` is a `number` or `int` the manifest checks allow it on.
|
||||
pub fn slider_range(&self, spec: &ParamSpec) -> Option<std::ops::RangeInclusive<f64>> {
|
||||
if self.widget != Some(Widget::Slider) {
|
||||
return None;
|
||||
}
|
||||
match spec {
|
||||
ParamSpec::Number { min, max, .. } if min < max => Some(*min..=*max),
|
||||
ParamSpec::Int { min, max, .. } if min < max && -EXACT_INT <= *min && *max <= EXACT_INT => Some(*min as f64..=*max as f64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks `widget` against parameter `spec`; `bad` builds the error.
|
||||
fn validate_slider(&self, spec: &ParamSpec, bad: impl Fn(&str) -> Result<()>) -> Result<()> {
|
||||
if self.widget.is_none() || self.slider_range(spec).is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
match spec {
|
||||
ParamSpec::Number { .. } | ParamSpec::Int { .. } => {
|
||||
bad(&format!("a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT}"))
|
||||
}
|
||||
_ => bad("a slider is only for `number` and `int` parameters"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `s` 1 to `max` characters, not all spaces, without control characters (`\n` too, unless
|
||||
@@ -86,6 +129,9 @@ impl ParamUi {
|
||||
return bad(&format!("`helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes"));
|
||||
}
|
||||
}
|
||||
if let Some((_, p)) = m.params.get(index) {
|
||||
self.validate_slider(&p.spec, bad)?;
|
||||
}
|
||||
if self.visible_when.len() > MAX_CONDITIONS {
|
||||
return bad(&format!("`visibleWhen` names at most {MAX_CONDITIONS} parameters"));
|
||||
}
|
||||
@@ -124,6 +170,8 @@ impl Manifest {
|
||||
let mut shown = BTreeSet::new();
|
||||
for (name, p) in &self.params {
|
||||
let met = p.ui.visible_when.iter().all(|(other, allowed)| {
|
||||
#[cfg(test)]
|
||||
tests::count_check();
|
||||
shown.contains(other.as_str())
|
||||
&& match values.get(other) {
|
||||
Some(v) => allowed.contains(v),
|
||||
@@ -173,6 +221,19 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
thread_local! {
|
||||
/// The conditions [`Manifest::visible`] may still check on this thread before the test fails.
|
||||
static CHECKS_LEFT: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
|
||||
}
|
||||
|
||||
/// Counts one condition [`Manifest::visible`] checks, and fails the test once it checked more
|
||||
/// than it was allowed, so a check that would run forever ends the test instead.
|
||||
pub(super) fn count_check() {
|
||||
let left = CHECKS_LEFT.with(|n| n.get());
|
||||
assert!(left > 0, "more conditions were checked than the test allows");
|
||||
CHECKS_LEFT.with(|n| n.set(left - 1));
|
||||
}
|
||||
|
||||
const RICH: &str = r#"{"id":"org.example.hatch","name":"Hatch","kind":"effect","params":{
|
||||
"pattern":{"type":"choice","options":["lines","crosshatch","dots"],"default":"lines",
|
||||
"label":"Pattern","group":"Fill","help":"How the shape is filled."},
|
||||
@@ -244,7 +305,8 @@ mod tests {
|
||||
|
||||
/// Conditions that each name several earlier parameters are checked once per parameter, not
|
||||
/// once per path through them: 256 checkboxes, each shown while the 8 before it are checked,
|
||||
/// would otherwise take longer than the age of the universe on every frame of the dialog.
|
||||
/// would otherwise take longer than the age of the universe on every frame of the dialog. The
|
||||
/// test counts the conditions checked, so it ends however slow the machine is.
|
||||
#[test]
|
||||
fn overlapping_conditions_are_checked_once_per_parameter() {
|
||||
let params: Vec<String> = (0..256)
|
||||
@@ -254,9 +316,11 @@ mod tests {
|
||||
})
|
||||
.collect();
|
||||
let m = Manifest::parse(format!(r#"{{"id":"a","name":"x","kind":"filter","params":{{{}}}}}"#, params.join(",")).as_bytes()).unwrap();
|
||||
let (done, finished) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || done.send(m.visible(&Map::new()).len()));
|
||||
let shown = finished.recv_timeout(std::time::Duration::from_secs(10)).expect("the check took more than 10 s");
|
||||
// Each parameter names at most `MAX_CONDITIONS` others, so checking each condition once
|
||||
// stays within this.
|
||||
CHECKS_LEFT.with(|n| n.set(256 * MAX_CONDITIONS));
|
||||
let shown = m.visible(&Map::new()).len();
|
||||
CHECKS_LEFT.with(|n| n.set(usize::MAX));
|
||||
assert_eq!(shown, 256, "every checkbox is checked, so every parameter is shown");
|
||||
// Unchecking the first hides the rest: each names it or one it hides.
|
||||
let m = Manifest::parse(format!(r#"{{"id":"a","name":"x","kind":"filter","params":{{{}}}}}"#, params.join(",")).as_bytes()).unwrap();
|
||||
@@ -304,4 +368,46 @@ mod tests {
|
||||
let fine = with("help", r#""Two\nlines.""#);
|
||||
assert!(Manifest::parse(fine.as_bytes()).is_ok());
|
||||
}
|
||||
|
||||
/// A `number` or `int` parameter with a range may ask for a slider; the key reads back as
|
||||
/// written, and a parameter without it asks for none.
|
||||
#[test]
|
||||
fn slider_key_parses_and_round_trips() {
|
||||
let m = Manifest::parse(
|
||||
br#"{"id":"a","name":"x","kind":"filter","params":{
|
||||
"area":{"type":"number","min":0,"max":100,"default":10,"widget":"slider"},
|
||||
"count":{"type":"int","min":1,"max":20,"default":4,"widget":"slider"},
|
||||
"plain":{"type":"number","min":0,"max":100,"default":10}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (area, count, plain) = (m.param("area").unwrap(), m.param("count").unwrap(), m.param("plain").unwrap());
|
||||
assert_eq!(area.ui.slider_range(&area.spec), Some(0.0..=100.0));
|
||||
assert_eq!(count.ui.slider_range(&count.spec), Some(1.0..=20.0));
|
||||
assert_eq!(plain.ui.slider_range(&plain.spec), None);
|
||||
assert_eq!(Manifest::parse(&serde_json::to_vec(&m).unwrap()).unwrap(), m);
|
||||
assert_eq!(serde_json::to_value(&m).unwrap()["params"]["count"]["widget"], json!("slider"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slider_keys_that_cannot_apply_are_refused() {
|
||||
let param = |p: &str| format!(r#"{{"id":"a","name":"x","kind":"filter","params":{{"p":{p}}}}}"#);
|
||||
for bad in [
|
||||
// Only numbers have a slider, over a range that has room to move.
|
||||
r#"{"type":"bool","widget":"slider"}"#,
|
||||
r#"{"type":"choice","options":["a","b"],"widget":"slider"}"#,
|
||||
r#"{"type":"numberList","min":0,"max":1,"widget":"slider"}"#,
|
||||
r#"{"type":"number","min":5,"max":5,"default":5,"widget":"slider"}"#,
|
||||
r#"{"type":"int","min":0,"max":9007199254740993,"widget":"slider"}"#,
|
||||
// A control the host doesn't have.
|
||||
r#"{"type":"number","min":0,"max":1,"default":0,"widget":"knob"}"#,
|
||||
] {
|
||||
assert!(Manifest::parse(param(bad).as_bytes()).is_err(), "{bad}");
|
||||
}
|
||||
// A command's parameters are checked the same way.
|
||||
let command = |p: &str| format!(r#"{{"id":"a","name":"x","kind":"filter","commands":[{{"id":"go","label":"Go","params":{{"p":{p}}}}}]}}"#);
|
||||
assert!(Manifest::parse(command(r#"{"type":"number","min":0,"max":1,"default":0,"widget":"slider"}"#).as_bytes()).is_ok());
|
||||
assert!(Manifest::parse(command(r#"{"type":"bool","widget":"slider"}"#).as_bytes()).is_err());
|
||||
let fine = param(r#"{"type":"int","min":0,"max":10,"widget":"slider"}"#);
|
||||
assert!(Manifest::parse(fine.as_bytes()).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -807,7 +807,7 @@ mod tests {
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = std::env::temp_dir().join(format!("vc-effect-overlap-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert_eq!(crate::safe_mode::begin_launch(&dir), None);
|
||||
assert_eq!(crate::safe_mode::begin_launch(&dir), []);
|
||||
let marker = || {
|
||||
let files = std::fs::read_dir(&dir).unwrap().filter_map(|e| Some(e.ok()?.path()));
|
||||
let json = files.filter(|p| p.extension().is_some_and(|x| x == "json")).collect::<Vec<_>>();
|
||||
@@ -816,8 +816,8 @@ mod tests {
|
||||
};
|
||||
let src = crate::wat::returning(&crate::wat::manifest("test.effect.overlap", "effect", "{}"), r#"{"objects":[]}"#);
|
||||
let plugin = registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap()).unwrap();
|
||||
let named = Some(crate::safe_mode::Item::of(&plugin));
|
||||
assert_eq!(marker(), None);
|
||||
let named = vec![crate::safe_mode::Item::of(&plugin)];
|
||||
assert_eq!(marker(), []);
|
||||
|
||||
assert!(begin_run(&plugin), "the first run is guarded");
|
||||
assert!(begin_run(&plugin), "a run that starts while the first is running is guarded");
|
||||
@@ -829,9 +829,9 @@ mod tests {
|
||||
end_run(plugin.serial(), true);
|
||||
assert_eq!(marker(), named, "the third run is still running");
|
||||
end_run(plugin.serial(), false);
|
||||
assert_eq!(marker(), None, "no run is running");
|
||||
assert_eq!(marker(), [], "no run is running");
|
||||
assert!(!begin_run(&plugin), "later runs aren't guarded");
|
||||
assert_eq!(marker(), None);
|
||||
assert_eq!(marker(), []);
|
||||
|
||||
crate::safe_mode::end_launch();
|
||||
crate::safe_mode::forget_previous();
|
||||
|
||||
@@ -688,7 +688,7 @@ impl Run {
|
||||
}
|
||||
}
|
||||
|
||||
fn progress(&mut self, done: i64, total: i64) {
|
||||
pub(crate) fn progress(&mut self, done: i64, total: i64) {
|
||||
let total = u64::try_from(total).unwrap_or(0);
|
||||
let done = u64::try_from(done).unwrap_or(0);
|
||||
let done = if total > 0 { done.min(total) } else { done };
|
||||
@@ -710,12 +710,12 @@ impl Run {
|
||||
vectorcraft_doc::cancel::progress(done, total, PROGRESS_STEP);
|
||||
}
|
||||
|
||||
fn cancelled(&self) -> i32 {
|
||||
pub(crate) fn cancelled(&self) -> i32 {
|
||||
i32::from(vectorcraft_doc::cancel::is_cancelled() || self.deadline.passed())
|
||||
}
|
||||
|
||||
/// Writes the `len` bytes at `ptr` in `memory` as a line of `level` → what `vc_log` returns.
|
||||
fn log(&mut self, level: i32, memory: &[u8], ptr: usize, len: usize) -> i32 {
|
||||
pub(crate) fn log(&mut self, level: i32, memory: &[u8], ptr: usize, len: usize) -> i32 {
|
||||
let Some(level) = LogLevel::from_code(level) else { return LOG_BAD_LEVEL };
|
||||
let Some(bytes) = ptr.checked_add(len).and_then(|end| memory.get(ptr..end)) else { return LOG_OUTSIDE_MEMORY };
|
||||
if self.report.truncated {
|
||||
|
||||
@@ -7,6 +7,10 @@
|
||||
//! sorts first opens it ([`for_extension`]). File › Open With and `document.open {importer}` pick an
|
||||
//! importer by its format id (`plugin.<id>`), also for an extension a built-in format reads.
|
||||
//!
|
||||
//! An importer whose manifest sets `place` also reads its files for File › Place (`file.place`),
|
||||
//! by the same rules among the importers that set it ([`placing`]): its objects become one group in
|
||||
//! the open document, and it is told so in `_context.mode` ([`Mode::Place`]).
|
||||
//!
|
||||
//! The host hands the importer the file's bytes as they are, at most [`MAX_INPUT_BYTES`] of them,
|
||||
//! and reads back the objects of the new document in the same form filters return them
|
||||
//! ([`crate::objects`]): `{"objects": [...], "warnings"?: ["…"]}`, or `{"error": "…"}` to decline.
|
||||
@@ -61,6 +65,38 @@ pub fn for_extension(ext: &str) -> Vec<Arc<Plugin>> {
|
||||
installed().into_iter().filter(|p| p.manifest().extensions.contains(&ext)).collect()
|
||||
}
|
||||
|
||||
/// The installed importers whose manifests set `place` and that list extension `ext` (any case,
|
||||
/// leading dot allowed), by plug-in id: the first is the one File › Place uses.
|
||||
pub fn placing(ext: &str) -> Vec<Arc<Plugin>> {
|
||||
for_extension(ext).into_iter().filter(|p| p.manifest().place).collect()
|
||||
}
|
||||
|
||||
/// The error of importer `m`, whose manifest doesn't set `place`, asked to place a file.
|
||||
pub fn not_placing(m: &crate::Manifest) -> Error {
|
||||
let shown = crate::permissions::display_text(&m.name, crate::permissions::MAX_SHOWN_NAME);
|
||||
Error::Params(format!("“{shown}” opens files but doesn't place them: its manifest doesn't set `place`"))
|
||||
}
|
||||
|
||||
/// What an import is for, which the importer is told as `_context.mode`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Mode {
|
||||
/// File › Open: the objects become a new document (`"import"`).
|
||||
Import,
|
||||
/// File › Place: the objects become one group in the open document (`"place"`). Only an
|
||||
/// importer whose manifest sets `place` runs for it.
|
||||
Place,
|
||||
}
|
||||
|
||||
impl Mode {
|
||||
/// Its name in `_context.mode`.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Mode::Import => "import",
|
||||
Mode::Place => "place",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What an importer returned.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Imported {
|
||||
@@ -93,15 +129,24 @@ pub fn limits(plugin: &Plugin) -> Limits {
|
||||
/// Runs importer `plugin` on `file`, the bytes of the file being opened, with `params` (checked
|
||||
/// against its manifest: missing ones take their defaults) for the file `source`.
|
||||
pub fn run(plugin: &Plugin, file: &[u8], params: &Value, source: Source) -> Result<Imported> {
|
||||
run_as(plugin, file, params, source, Mode::Import)
|
||||
}
|
||||
|
||||
/// [`run`] for `mode`. [`Mode::Place`] is refused for an importer whose manifest doesn't set `place`
|
||||
/// ([`not_placing`]), before it runs.
|
||||
pub fn run_as(plugin: &Plugin, file: &[u8], params: &Value, source: Source, mode: Mode) -> Result<Imported> {
|
||||
let m = plugin.manifest();
|
||||
if m.kind != Kind::Importer {
|
||||
return Err(not_importer(m));
|
||||
}
|
||||
if mode == Mode::Place && !m.place {
|
||||
return Err(not_placing(m));
|
||||
}
|
||||
if file.len() > MAX_INPUT_BYTES {
|
||||
return Err(too_large());
|
||||
}
|
||||
let mut params = Value::Object(m.resolve_params(params)?);
|
||||
params["_context"] = json!({"mode": "import", "extension": source.extension, "name": source.name});
|
||||
params["_context"] = json!({"mode": mode.name(), "extension": source.extension, "name": source.name});
|
||||
let params = serde_json::to_vec(¶ms).map_err(|e| Error::Params(e.to_string()))?;
|
||||
decode(&plugin.run_limited(file, ¶ms, &limits(plugin))?)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,517 @@
|
||||
//! JavaScript plug-ins: an object filter whose manifest gives `"runtime": "js"`, with its code in a
|
||||
//! JavaScript file instead of a WebAssembly module, run on `vectorcraft-js`.
|
||||
//!
|
||||
//! On disk the plug-in is a manifest file (`.vcplugin`, JSON) with `"runtime": "js"` and `script`,
|
||||
//! the name of its `.js` file in the same folder ([`crate::registry::read_js_package`]). The host
|
||||
//! loads it as one JSON object, the manifest with the script's text in `source`
|
||||
//! ([`read_bundle`]): that object is what `plugin.install {dataBase64}` takes, what the plug-in
|
||||
//! store keeps, and what the SHA-256 a grant records covers, so a change to the manifest or to the
|
||||
//! script needs a new approval. Loading parses the script and runs none of it.
|
||||
//!
|
||||
//! Each run gets a fresh realm with the language's built-ins and a `vc` object: `vc.input`
|
||||
//! and `vc.params` hold the input and parameter JSON a WebAssembly filter's `vc_run` is given, and
|
||||
//! with the `progress` permission `vc.progress(done, total)`, `vc.cancelled()` and
|
||||
//! `vc.log(level, text)` do what `vc_progress`, `vc_cancelled` and `vc_log` do ([`crate::host`]).
|
||||
//! The realm has no `$`, `File`, `Folder`, `app` or other global of the script runner, no clock
|
||||
//! (`Date.now()` is `NaN`) and no host function besides these. The script's top level runs, then
|
||||
//! `run(input, params)` is called with the parsed JSON, and the value it returns, written as JSON,
|
||||
//! is the run's output, which the host checks as it checks a WebAssembly filter's.
|
||||
//!
|
||||
//! A run is held to the filter's instruction budget (one budget for the top level and the call,
|
||||
//! checked in slices between which the deadline and Cancel are checked), a heap of at most the
|
||||
//! plug-in's memory cap, and the interpreter's frame and re-entry limits. A thrown error, a limit
|
||||
//! or a malformed result fails the run with an [`Error`] that names the plug-in, its script and,
|
||||
//! when known, the line and column.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
use vectorcraft_js::{Data, HostError, HostItem, JsValue, LimitKind, Progress, Realm, RunError, RunErrorKind};
|
||||
|
||||
use crate::host::{Deadline, LOG_BAD_LEVEL, LOG_DROPPED, LOG_WRITTEN, Report, Run};
|
||||
use crate::manifest::{MAX_MANIFEST_BYTES, Manifest, Runtime};
|
||||
use crate::permissions::{self, Permission};
|
||||
use crate::runtime::SELECTION_TOO_LARGE;
|
||||
use crate::{Error, Limits, Result};
|
||||
|
||||
/// The extension of a JavaScript plug-in's manifest file.
|
||||
pub const PACKAGE_EXT: &str = "vcplugin";
|
||||
|
||||
/// Largest script, in bytes.
|
||||
pub const MAX_SCRIPT_BYTES: usize = 8 << 20;
|
||||
|
||||
/// Longest script file name, in bytes.
|
||||
pub const MAX_SCRIPT_NAME: usize = 128;
|
||||
|
||||
/// The script's name when the plug-in's JSON gives none.
|
||||
pub const DEFAULT_SCRIPT: &str = "plugin.js";
|
||||
|
||||
/// Instructions a run executes between two checks of its deadline and Cancel.
|
||||
pub const FUEL_SLICE: u64 = 1_000_000;
|
||||
|
||||
/// Longest error message a run reports, in characters.
|
||||
const MAX_ERROR_TEXT: usize = 512;
|
||||
|
||||
/// What `script` may hold.
|
||||
const SCRIPT_NAME_RULE: &str =
|
||||
"`script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.`";
|
||||
|
||||
/// Where the script's text may be given.
|
||||
pub const SOURCE_RULE: &str =
|
||||
"`source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script`";
|
||||
|
||||
/// The error of a plug-in's JSON without `"runtime": "js"`.
|
||||
pub(crate) const NOT_JS: &str = "a JavaScript plug-in's manifest gives `runtime` \"js\"";
|
||||
|
||||
/// What the arguments of `vc.progress` and `vc.log` may be.
|
||||
const PROGRESS_ARGS: &str = "vc.progress(done, total) takes two numbers";
|
||||
const LOG_ARGS: &str = "vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string";
|
||||
|
||||
/// What runs the plug-in: its script's top level is done, `run` is called with the input and the
|
||||
/// parameters, and what it returns is written as JSON.
|
||||
const ENTRY: &str = "(function () {\n\
|
||||
if (typeof run !== 'function') throw new TypeError('the script defines no function run(input, params)');\n\
|
||||
return JSON.stringify(run(JSON.parse(vc.input), JSON.parse(vc.params)));\n\
|
||||
})()";
|
||||
|
||||
/// A JavaScript plug-in's code.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Script {
|
||||
/// Its file name, which errors give.
|
||||
pub(crate) name: String,
|
||||
pub(crate) source: String,
|
||||
}
|
||||
|
||||
/// Is `name` a script file name `script` may give: a `.js` file directly in the manifest's folder?
|
||||
pub fn valid_script_name(name: &str) -> bool {
|
||||
(1..=MAX_SCRIPT_NAME).contains(&name.len())
|
||||
&& !name.starts_with('.')
|
||||
&& !name.chars().any(|c| matches!(c, '/' | '\\' | ':') || c.is_control())
|
||||
&& name.len() > 3
|
||||
&& name.get(name.len() - 3..).is_some_and(|ext| ext.eq_ignore_ascii_case(".js"))
|
||||
}
|
||||
|
||||
/// The `script` a manifest's JSON gives, checked.
|
||||
pub(crate) fn script_name(v: &Value) -> Result<String> {
|
||||
match v.as_str() {
|
||||
Some(name) if valid_script_name(name) => Ok(name.to_string()),
|
||||
_ => Err(Error::Manifest(SCRIPT_NAME_RULE.into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The error of a manifest with `"runtime": "js"` and no `script`.
|
||||
pub(crate) fn no_script() -> Error {
|
||||
Error::Manifest("`runtime` \"js\" needs `script`: the name of the plug-in's .js file, next to the manifest".into())
|
||||
}
|
||||
|
||||
/// Does `map`, a plug-in's JSON, give `"runtime": "js"`?
|
||||
pub(crate) fn is_js(map: &Map<String, Value>) -> bool {
|
||||
map.get("runtime").and_then(Value::as_str) == Some(Runtime::Js.name())
|
||||
}
|
||||
|
||||
/// How the script is read.
|
||||
fn options() -> vectorcraft_js::Options {
|
||||
vectorcraft_js::Options { max_source_units: MAX_SCRIPT_BYTES, ..vectorcraft_js::Options::default() }
|
||||
}
|
||||
|
||||
/// Reads a JavaScript plug-in given as one JSON object: its manifest, with the script's text in
|
||||
/// `source` and its file name in `script` (left out: [`DEFAULT_SCRIPT`]). The manifest is checked as
|
||||
/// a module's is, and the script is parsed, not run.
|
||||
pub(crate) fn read_bundle(bytes: &[u8]) -> Result<(Manifest, Script)> {
|
||||
let mut map: Map<String, Value> = serde_json::from_slice(bytes).map_err(|e| Error::Manifest(e.to_string()))?;
|
||||
if !is_js(&map) {
|
||||
return Err(Error::Manifest(NOT_JS.into()));
|
||||
}
|
||||
let named = map.remove("script");
|
||||
let source = match map.remove("source") {
|
||||
Some(Value::String(s)) => s,
|
||||
Some(_) => return Err(Error::Manifest(SOURCE_RULE.into())),
|
||||
None if named.is_some() => return Err(Error::Manifest(SOURCE_RULE.into())),
|
||||
None => return Err(no_script()),
|
||||
};
|
||||
let name = named.as_ref().map_or_else(|| Ok(DEFAULT_SCRIPT.to_string()), script_name)?;
|
||||
if source.len() > MAX_SCRIPT_BYTES {
|
||||
return Err(Error::Module(format!("{} is {} bytes (limit {})", name, source.len(), MAX_SCRIPT_BYTES)));
|
||||
}
|
||||
// The manifest is read from `bytes`, so `params` keep their order; its size is counted
|
||||
// without `script` and `source`.
|
||||
let size = serde_json::to_vec(&map).map_err(|e| Error::Manifest(e.to_string()))?.len();
|
||||
if size > MAX_MANIFEST_BYTES {
|
||||
return Err(Error::Manifest(format!("manifest is {size} bytes (limit {MAX_MANIFEST_BYTES})")));
|
||||
}
|
||||
let text = std::str::from_utf8(bytes).map_err(|_| Error::Manifest("manifest is not UTF-8".into()))?;
|
||||
let manifest = Manifest::parse_text(text)?;
|
||||
if let Err(e) = vectorcraft_js::parse(&source, &options()) {
|
||||
let named = Named { id: &manifest.id, script: &name };
|
||||
return Err(Error::Module(located(&permissions::display_text(&e.message, MAX_ERROR_TEXT), &named, Some((e.line, e.column)))));
|
||||
}
|
||||
Ok((manifest, Script { name, source }))
|
||||
}
|
||||
|
||||
/// `reason` followed by where it happened: the plug-in's id, its script's name and, when `at` gives
|
||||
/// them, the line and column.
|
||||
fn located(reason: &str, named: &Named<'_>, at: Option<(u32, u32)>) -> String {
|
||||
let (id, script) = (named.id, named.script);
|
||||
match at {
|
||||
Some((line, column)) if line > 0 => format!("{reason} ({id}, {script} line {line}, column {column})"),
|
||||
_ => format!("{reason} ({id}, {script})"),
|
||||
}
|
||||
}
|
||||
|
||||
/// One run's input and budgets.
|
||||
pub(crate) struct Call<'a> {
|
||||
pub(crate) input: &'a [u8],
|
||||
pub(crate) params: &'a [u8],
|
||||
pub(crate) limits: &'a Limits,
|
||||
/// The plug-in's memory cap, which the run's heap stays within.
|
||||
pub(crate) max_memory: usize,
|
||||
pub(crate) deadline: Deadline,
|
||||
}
|
||||
|
||||
/// The heap a run may use with memory cap `max_memory`.
|
||||
fn heap_bytes(max_memory: usize) -> usize {
|
||||
vectorcraft_js::Limits::default().heap_bytes.min(max_memory)
|
||||
}
|
||||
|
||||
/// Runs `script`, the code of the plug-in `m` describes, on `call`'s input in a fresh realm → the
|
||||
/// output JSON. What it reported with `vc.progress` and `vc.log` goes to `report`.
|
||||
pub(crate) fn run(script: &Script, m: &Manifest, call: &Call<'_>, state: Run, report: &mut Report) -> Result<Vec<u8>> {
|
||||
let heap = heap_bytes(call.max_memory);
|
||||
// Each UTF-8 byte may become a UTF-16 code unit of two bytes, and the parsed JSON takes more.
|
||||
if call.input.len().saturating_add(call.params.len()) > heap / 8 {
|
||||
return Err(Error::Limit(SELECTION_TOO_LARGE.into()));
|
||||
}
|
||||
// The host writes the input and the parameters with serde_json, so they are UTF-8.
|
||||
let (input, params) = (String::from_utf8_lossy(call.input), String::from_utf8_lossy(call.params));
|
||||
let state = Rc::new(RefCell::new(state));
|
||||
let out = run_realm(script, m, (&*input, &*params), call, heap, &state);
|
||||
*report = std::mem::take(&mut state.borrow_mut().report);
|
||||
out
|
||||
}
|
||||
|
||||
/// What errors name: the plug-in's id and its script's file name.
|
||||
struct Named<'a> {
|
||||
id: &'a str,
|
||||
script: &'a str,
|
||||
}
|
||||
|
||||
fn run_realm(
|
||||
script: &Script,
|
||||
m: &Manifest,
|
||||
(input, params): (&str, &str),
|
||||
call: &Call<'_>,
|
||||
heap: usize,
|
||||
state: &Rc<RefCell<Run>>,
|
||||
) -> Result<Vec<u8>> {
|
||||
let defaults = vectorcraft_js::Limits::default();
|
||||
let fuel = call.limits.fuel_base.saturating_add((call.input.len() as u64).saturating_mul(call.limits.fuel_per_byte));
|
||||
let limits = vectorcraft_js::Limits { fuel, heap_bytes: heap, ..defaults };
|
||||
let mut realm = Realm::with_options(options(), limits);
|
||||
realm.set_clock(|| f64::NAN);
|
||||
let named = Named { id: &m.id, script: &script.name };
|
||||
realm.define_host_object("vc", vc_items(input, params, m, state)).map_err(|e| match e.kind {
|
||||
RunErrorKind::Limit(LimitKind::Heap) => Error::Limit(SELECTION_TOO_LARGE.into()),
|
||||
_ => js_error(&realm, e, vectorcraft_js::UNKNOWN_SOURCE, &named),
|
||||
})?;
|
||||
let (_, tag) = drive(&mut realm, &script.source, &call.deadline, &named, None)?;
|
||||
// The call takes what the top level left of the budget.
|
||||
let left = realm.fuel_left();
|
||||
realm.set_limits(vectorcraft_js::Limits { fuel: left, ..realm.limits().clone() });
|
||||
let (value, _) = drive(&mut realm, ENTRY, &call.deadline, &named, Some(tag))?;
|
||||
vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?;
|
||||
call.deadline.check()?;
|
||||
match value {
|
||||
JsValue::String(s) if s.len() > call.limits.max_output_bytes => {
|
||||
let (what, len, max) = ("the output", s.len(), call.limits.max_output_bytes);
|
||||
Err(Error::Limit(format!("output size ({what} is {len} bytes, limit {max})")))
|
||||
}
|
||||
JsValue::String(s) => Ok(s.into_bytes()),
|
||||
_ => Err(Error::Output(located(NO_OUTPUT, &named, None))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The error of a `run` that returned nothing JSON can write.
|
||||
const NO_OUTPUT: &str = "run(input, params) returned no output object";
|
||||
|
||||
/// The limit a run that nested its calls too deeply exceeded.
|
||||
const CALL_DEPTH: &str = "call depth";
|
||||
|
||||
/// Runs `source` in `realm` to its end, in slices of [`FUEL_SLICE`] with the deadline and Cancel
|
||||
/// checked between them → its completion value, and the source tag of the plug-in's script:
|
||||
/// `script_tag`, or with `None` the tag of `source`, which is then the script.
|
||||
fn drive(realm: &mut Realm, source: &str, deadline: &Deadline, named: &Named<'_>, script_tag: Option<u32>) -> Result<(JsValue, u32)> {
|
||||
let started = realm.start(source);
|
||||
let tag = script_tag.unwrap_or_else(|| realm.script_tag());
|
||||
started.map_err(|e| js_error(realm, e, tag, named))?;
|
||||
loop {
|
||||
match realm.advance(FUEL_SLICE) {
|
||||
Ok(Progress::Done(v)) => return Ok((v, tag)),
|
||||
Ok(Progress::Paused) => {}
|
||||
Err(e) => return Err(js_error(realm, e, tag, named)),
|
||||
}
|
||||
if vectorcraft_doc::cancel::check().is_err() {
|
||||
realm.end();
|
||||
return Err(Error::Cancelled);
|
||||
}
|
||||
if let Err(e) = deadline.check() {
|
||||
realm.end();
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The plug-in error for `e`, which a run of `realm` ended with: it names the plug-in and the script,
|
||||
/// and the line and column when the error is in the script (source tag `tag`).
|
||||
fn js_error(realm: &Realm, e: RunError, tag: u32, named: &Named<'_>) -> Error {
|
||||
let at = (realm.error_tag() == tag).then_some((e.line, e.column));
|
||||
let message = permissions::display_text(&e.message, MAX_ERROR_TEXT);
|
||||
match e.kind {
|
||||
RunErrorKind::Syntax => Error::Module(located(&message, named, at)),
|
||||
RunErrorKind::Thrown | RunErrorKind::Limit(LimitKind::Host) => Error::Failed(located(&message, named, at)),
|
||||
RunErrorKind::Limit(LimitKind::Jobs) => Error::Limit(located(&message, named, at)),
|
||||
RunErrorKind::Limit(LimitKind::Fuel | LimitKind::Unbroken) => Error::Limit(located("instruction budget", named, at)),
|
||||
RunErrorKind::Limit(LimitKind::Heap) => Error::Limit(located("memory budget", named, at)),
|
||||
RunErrorKind::Limit(LimitKind::Frames | LimitKind::Reentry) => Error::Limit(located(CALL_DEPTH, named, at)),
|
||||
RunErrorKind::Limit(LimitKind::Interrupted) => Error::Cancelled,
|
||||
RunErrorKind::Internal => Error::Trap(located(&message, named, at)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The members of the realm's `vc` object.
|
||||
fn vc_items(input: &str, params: &str, m: &Manifest, state: &Rc<RefCell<Run>>) -> Vec<(String, HostItem)> {
|
||||
let mut items = vec![
|
||||
("input".to_string(), HostItem::Value(Data::String(input.into()))),
|
||||
("params".to_string(), HostItem::Value(Data::String(params.into()))),
|
||||
];
|
||||
if !m.permissions().contains(&Permission::Progress) {
|
||||
return items;
|
||||
}
|
||||
let number = |args: &[Data], i: usize, rule: &str| match args.get(i) {
|
||||
Some(Data::Number(n)) => Ok(*n),
|
||||
_ => Err(HostError::Type(rule.into())),
|
||||
};
|
||||
let run = state.clone();
|
||||
items.push((
|
||||
"progress".into(),
|
||||
HostItem::Function(Rc::new(move |args| {
|
||||
let (done, total) = (number(&args, 0, PROGRESS_ARGS)?, number(&args, 1, PROGRESS_ARGS)?);
|
||||
// `as` turns NaN into 0 and clamps the rest, as `vc_progress` clamps negative values.
|
||||
run.borrow_mut().progress(done as i64, total as i64);
|
||||
Ok(Data::Undefined)
|
||||
})),
|
||||
));
|
||||
let run = state.clone();
|
||||
items.push(("cancelled".into(), HostItem::Function(Rc::new(move |_| Ok(Data::Bool(run.borrow().cancelled() == 1))))));
|
||||
let run = state.clone();
|
||||
items.push((
|
||||
"log".into(),
|
||||
HostItem::Function(Rc::new(move |args| {
|
||||
let level = number(&args, 0, LOG_ARGS)?;
|
||||
let Some(Data::String(text)) = args.get(1) else { return Err(HostError::Type(LOG_ARGS.into())) };
|
||||
let level = if level.fract() == 0.0 && (0.0..=3.0).contains(&level) { level as i32 } else { LOG_BAD_LEVEL };
|
||||
match run.borrow_mut().log(level, text.as_bytes(), 0, text.len()) {
|
||||
LOG_WRITTEN => Ok(Data::Bool(true)),
|
||||
LOG_DROPPED => Ok(Data::Bool(false)),
|
||||
_ => Err(HostError::Range(LOG_ARGS.into())),
|
||||
}
|
||||
})),
|
||||
));
|
||||
items
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{Error, Limits, Plugin};
|
||||
|
||||
/// A JavaScript filter `id` with `source` as its code, and `extra` manifest keys.
|
||||
fn bundle(id: &str, source: &str, extra: Value) -> Vec<u8> {
|
||||
let mut m = json!({"id": id, "name": "JS test", "kind": "filter", "runtime": "js", "script": "test.js", "source": source});
|
||||
if let (Some(m), Value::Object(extra)) = (m.as_object_mut(), extra) {
|
||||
m.extend(extra);
|
||||
}
|
||||
serde_json::to_vec(&m).unwrap()
|
||||
}
|
||||
|
||||
fn load(bytes: &[u8]) -> crate::Result<Plugin> {
|
||||
load_with(bytes, Limits::default())
|
||||
}
|
||||
|
||||
fn load_with(bytes: &[u8], limits: Limits) -> crate::Result<Plugin> {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
Plugin::load(bytes, limits)
|
||||
}
|
||||
|
||||
const PATH: &str = r#"{"objects":[{"id":7,"type":"path","fills":[{"type":"solid","color":{"model":"rgb","r":1,"g":0,"b":0}}]}]}"#;
|
||||
|
||||
/// The output of `run(input, params)` is the run's output JSON.
|
||||
#[test]
|
||||
fn a_filter_returns_its_objects_as_json() {
|
||||
let src = "function run(input, params) { return {objects: input.objects.map(function (o) { \
|
||||
return {id: o.id, fills: [{type: 'solid', color: {model: 'rgb', r: 0, g: 0, b: params.blue}}]}; })}; }";
|
||||
let p = load(&bundle("test.js.blue", src, json!({}))).unwrap();
|
||||
assert_eq!((p.runtime(), p.script()), (crate::Runtime::Js, Some("test.js")));
|
||||
let out: Value = serde_json::from_slice(&p.run(PATH.as_bytes(), br#"{"blue":1}"#).unwrap()).unwrap();
|
||||
assert_eq!(out, json!({"objects": [{"id": 7, "fills": [{"type": "solid", "color": {"model": "rgb", "r": 0, "g": 0, "b": 1}}]}]}));
|
||||
}
|
||||
|
||||
/// The realm has none of the script runner's globals, so code that reads them throws a
|
||||
/// `ReferenceError` naming the global, the plug-in and where in its script.
|
||||
#[test]
|
||||
fn file_folder_and_app_are_not_defined() {
|
||||
for name in ["File", "Folder", "$", "app", "BridgeTalk"] {
|
||||
let src = format!("function run(input) {{\n return {name}.x;\n}}");
|
||||
let e = load(&bundle("test.js.globals", &src, json!({}))).unwrap().run(PATH.as_bytes(), b"{}").unwrap_err();
|
||||
let Error::Failed(why) = &e else { panic!("{name}: {e:?}") };
|
||||
assert!(why.starts_with("ReferenceError") && why.contains(name), "{name}: {why}");
|
||||
assert!(why.ends_with("(test.js.globals, test.js line 2, column 10)"), "{name}: {why}");
|
||||
}
|
||||
let p = load(&bundle("test.js.clock", "function run() { return {objects: [], n: String(Date.now())}; }", json!({}))).unwrap();
|
||||
let out: Value = serde_json::from_slice(&p.run(b"{\"objects\":[]}", b"{}").unwrap()).unwrap();
|
||||
assert_eq!(out["n"], "NaN", "no clock");
|
||||
}
|
||||
|
||||
/// Each run has a realm of its own: what one run changes in the built-ins, the next run doesn't
|
||||
/// see.
|
||||
#[test]
|
||||
fn a_polluted_prototype_does_not_reach_the_next_run() {
|
||||
let src = "function run() { var seen = Object.prototype.polluted; Object.prototype.polluted = 1; \
|
||||
Array.prototype.map = null; return {objects: [], seen: String(seen)}; }";
|
||||
let p = load(&bundle("test.js.pollute", src, json!({}))).unwrap();
|
||||
for _ in 0..2 {
|
||||
let out: Value = serde_json::from_slice(&p.run(b"{\"objects\":[]}", b"{}").unwrap()).unwrap();
|
||||
assert_eq!(out["seen"], "undefined");
|
||||
}
|
||||
}
|
||||
|
||||
/// An endless loop ends with the instruction budget, naming the plug-in and the line.
|
||||
#[test]
|
||||
fn an_endless_loop_ends_with_the_instruction_budget() {
|
||||
let p = load(&bundle("test.js.loop", "function run() {\n for (;;) {}\n}", json!({}))).unwrap();
|
||||
let limits = Limits { fuel_base: 3 * super::FUEL_SLICE, fuel_per_byte: 0, ..Limits::default() };
|
||||
let e = p.run_limited(b"{\"objects\":[]}", b"{}", &limits).unwrap_err();
|
||||
assert!(matches!(&e, Error::Limit(why) if why.starts_with("instruction budget (test.js.loop, test.js line 2")), "{e:?}");
|
||||
}
|
||||
|
||||
/// A plug-in that fills its heap ends with its memory budget, and a realm another caller holds
|
||||
/// meanwhile, such as a script's, runs on as before.
|
||||
#[test]
|
||||
fn heap_exhaustion_leaves_a_held_realm_usable() {
|
||||
let mut held = vectorcraft_js::Realm::new();
|
||||
held.run("var kept = 41;").unwrap();
|
||||
let src = "function run() { var a = []; for (;;) { a.push(new Array(1000).join('x') + a.length); } }";
|
||||
let small = load_with(&bundle("test.js.heap", src, json!({})), Limits { max_memory_bytes: 8 << 20, ..Limits::default() }).unwrap();
|
||||
let e = small.run(b"{\"objects\":[]}", b"{}").unwrap_err();
|
||||
assert!(matches!(&e, Error::Limit(why) if why.starts_with("memory budget (test.js.heap")), "{e:?}");
|
||||
assert_eq!(held.run("kept + 1").unwrap(), vectorcraft_js::JsValue::Number(42.0));
|
||||
}
|
||||
|
||||
/// An input too large for the heap is refused before it is copied in.
|
||||
#[test]
|
||||
fn a_selection_too_large_for_the_heap_is_refused() {
|
||||
let small =
|
||||
load_with(&bundle("test.js.big", "function run(i) { return i; }", json!({})), Limits { max_memory_bytes: 1 << 20, ..Limits::default() })
|
||||
.unwrap();
|
||||
let input = format!(r#"{{"objects":[],"pad":"{}"}}"#, "x".repeat(200_000));
|
||||
assert_eq!(small.run(input.as_bytes(), b"{}"), Err(Error::Limit(crate::runtime::SELECTION_TOO_LARGE.into())));
|
||||
}
|
||||
|
||||
/// A result that isn't an output object, and a script without `run`, fail the run.
|
||||
#[test]
|
||||
fn a_missing_entry_or_result_fails_the_run() {
|
||||
let e = load(&bundle("test.js.none", "var x = 1;", json!({}))).unwrap().run(b"{\"objects\":[]}", b"{}").unwrap_err();
|
||||
assert!(matches!(&e, Error::Failed(why) if why.contains("defines no function run")), "{e:?}");
|
||||
let e = load(&bundle("test.js.undef", "function run() {}", json!({}))).unwrap().run(b"{\"objects\":[]}", b"{}").unwrap_err();
|
||||
assert!(matches!(&e, Error::Output(why) if why.contains("test.js.undef")), "{e:?}");
|
||||
let e = load(&bundle("test.js.cycle", "function run() { var o = {}; o.o = o; return o; }", json!({})))
|
||||
.unwrap()
|
||||
.run(b"{\"objects\":[]}", b"{}")
|
||||
.unwrap_err();
|
||||
assert!(matches!(&e, Error::Failed(why) if why.starts_with("TypeError")), "{e:?}");
|
||||
}
|
||||
|
||||
/// With `progress`, `vc.progress` and `vc.log` report as their imports do; without it, `vc`
|
||||
/// has neither.
|
||||
#[test]
|
||||
fn progress_and_log_need_the_progress_permission() {
|
||||
let src = "function run() { vc.progress(3, 4); vc.log(2, 'half'); return {objects: [], cancelled: vc.cancelled()}; }";
|
||||
let p = load(&bundle("test.js.progress", src, json!({"api": 2, "permissions": ["progress"]}))).unwrap();
|
||||
let (out, report) = p.run_reporting(b"{\"objects\":[]}", b"{}", p.limits());
|
||||
let out: Value = serde_json::from_slice(&out.unwrap()).unwrap();
|
||||
assert_eq!(out["cancelled"], false);
|
||||
assert_eq!(report.progress, Some((3, 4)));
|
||||
assert_eq!(report.lines, vec![crate::LogLine { level: crate::LogLevel::Info, text: "half".into() }]);
|
||||
let e = load(&bundle("test.js.quiet", src, json!({}))).unwrap().run(b"{\"objects\":[]}", b"{}").unwrap_err();
|
||||
assert!(matches!(&e, Error::Failed(why) if why.starts_with("TypeError")), "{e:?}");
|
||||
}
|
||||
|
||||
/// Loading checks the manifest and the script, and runs none of it.
|
||||
#[test]
|
||||
fn loading_refuses_a_bad_manifest_or_script() {
|
||||
let ok = "function run() { return {objects: []}; }";
|
||||
let refused = |bytes: Vec<u8>| load(&bytes).unwrap_err();
|
||||
let e = refused(bundle("test.js.syntax", "function run( {", json!({})));
|
||||
assert!(matches!(&e, Error::Module(why) if why.contains("(test.js.syntax, test.js line 1, column")), "{e:?}");
|
||||
let big = "x".repeat(super::MAX_SCRIPT_BYTES + 1);
|
||||
assert!(matches!(refused(bundle("test.js.big", &big, json!({}))), Error::Module(why) if why.starts_with("test.js is")));
|
||||
let e = refused(bundle("test.js.effect", ok, json!({"kind": "effect"})));
|
||||
assert!(matches!(&e, Error::Manifest(why) if why.contains("`runtime` \"js\" is for an object filter")), "{e:?}");
|
||||
let e = refused(bundle("test.js.settings", ok, json!({"api": 2, "permissions": ["settings"]})));
|
||||
assert!(matches!(&e, Error::Manifest(why) if why.contains("`settings`")), "{e:?}");
|
||||
let e = refused(bundle("test.js.name", ok, json!({"script": "../x.js"})));
|
||||
assert!(matches!(&e, Error::Manifest(why) if why.starts_with("`script`")), "{e:?}");
|
||||
let e = refused(bundle("test.js.py", ok, json!({"runtime": "py"})));
|
||||
assert!(matches!(&e, Error::Manifest(why) if why == super::NOT_JS), "{e:?}");
|
||||
let mut no_source: Value = serde_json::from_slice(&bundle("test.js.nosource", ok, json!({}))).unwrap();
|
||||
no_source.as_object_mut().unwrap().remove("source");
|
||||
let e = refused(serde_json::to_vec(&no_source).unwrap());
|
||||
assert!(matches!(&e, Error::Manifest(why) if why.contains("`source`")), "{e:?}");
|
||||
// Top-level code that would throw does not run at load.
|
||||
assert!(load(&bundle("test.js.lazy", "throw new Error('ran');", json!({}))).is_ok());
|
||||
}
|
||||
|
||||
/// A WebAssembly module's manifest can't give `"runtime": "js"`.
|
||||
#[test]
|
||||
fn a_module_manifest_cannot_be_javascript() {
|
||||
let manifest = r#"{"id":"test.js.wasm","name":"T","kind":"filter","runtime":"js"}"#;
|
||||
let bytes = wat::parse_str(crate::wat::returning(manifest, r#"{"objects":[]}"#)).unwrap();
|
||||
assert!(matches!(load(&bytes), Err(Error::Manifest(why)) if why.contains("`runtime`")));
|
||||
}
|
||||
|
||||
/// The SHA-256 a grant records is the bundle's, so another script is another module.
|
||||
#[test]
|
||||
fn the_hash_covers_the_script() {
|
||||
let a = load(&bundle("test.js.hash", "function run() { return {objects: []}; }", json!({}))).unwrap();
|
||||
let b = load(&bundle("test.js.hash", "function run() { return {objects: [] }; }", json!({}))).unwrap();
|
||||
assert_ne!(a.hash(), b.hash());
|
||||
}
|
||||
|
||||
/// The parameters, and a command's, keep the order the plug-in's JSON declares them in.
|
||||
#[test]
|
||||
fn params_keep_their_declaration_order() {
|
||||
let num = r#"{"type": "number", "min": 0, "max": 10, "default": 1}"#;
|
||||
let text = format!(
|
||||
r#"{{"id": "test.js.order", "name": "JS test", "kind": "filter", "runtime": "js", "script": "test.js",
|
||||
"params": {{"z": {num}, "a": {num}, "m": {num}}},
|
||||
"commands": [{{"id": "go", "label": "Go", "params": {{"y": {num}, "b": {num}}}}}],
|
||||
"source": "function run(i) {{ return i; }}"}}"#
|
||||
);
|
||||
let (manifest, _) = super::read_bundle(text.as_bytes()).unwrap();
|
||||
let names = |p: &[(String, crate::manifest::Param)]| p.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>();
|
||||
assert_eq!(names(&manifest.params), ["z", "a", "m"]);
|
||||
assert_eq!(names(&manifest.commands[0].params), ["y", "b"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_names_stay_in_the_manifest_s_folder() {
|
||||
for ok in ["tint.js", "Tint Tool.JS", "a.b.js"] {
|
||||
assert!(super::valid_script_name(ok), "{ok}");
|
||||
}
|
||||
for bad in ["", ".js", ".hidden.js", "../x.js", "sub/x.js", "sub\\x.js", "c:x.js", "x.jsx", "x.js\n", "x.wasm"] {
|
||||
assert!(!super::valid_script_name(bad), "{bad:?}");
|
||||
}
|
||||
assert!(!super::valid_script_name(&format!("{}.js", "a".repeat(126))));
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,10 @@
|
||||
//! 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`. Any kind may also react to the
|
||||
//! [`events`] its manifest names, through `vc_event`, without changing the document.
|
||||
//!
|
||||
//! 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
|
||||
//! run, with the same input, output, permissions and budgets.
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod deferred;
|
||||
@@ -42,6 +46,8 @@ pub mod events;
|
||||
pub mod export;
|
||||
pub mod host;
|
||||
pub mod import;
|
||||
pub mod js;
|
||||
pub mod loader;
|
||||
pub mod manifest;
|
||||
pub mod objects;
|
||||
pub mod painted;
|
||||
@@ -55,7 +61,7 @@ pub mod wat;
|
||||
pub use dialog::ParamUi;
|
||||
pub use events::Event;
|
||||
pub use host::{LogLevel, LogLine, Report};
|
||||
pub use manifest::{Budget, Command, InputKind, Kind, Manifest, Param, ParamSpec};
|
||||
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};
|
||||
#[doc(hidden)]
|
||||
pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE};
|
||||
|
||||
@@ -0,0 +1,760 @@
|
||||
//! Loads plug-ins on worker threads.
|
||||
//!
|
||||
//! [`Loads::start`] hands its jobs to a pool of at most [`MAX_WORKERS`] threads and returns at
|
||||
//! once. The web build has no threads, so there it runs the jobs one after the other before it
|
||||
//! returns. Each job runs inside a panic boundary: a job that panics fails with [`Error::Failed`],
|
||||
//! and the launch marker stops naming its item ([`crate::safe_mode::loading`]), as when it loads.
|
||||
//! A job that takes [`LOAD_DEADLINE`] or longer fails too, and the marker names its item until its
|
||||
//! thread returns; while it is still running, its thread is left to finish on its own, and another worker
|
||||
//! takes the jobs after it, up to twice as many threads as were started. While
|
||||
//! [`MAX_STUCK_THREADS`] threads in the process still run jobs past their deadline, no load starts
|
||||
//! a thread. When no thread is left to take them, the jobs not started fail.
|
||||
//!
|
||||
//! The caller takes the outcomes in the order of the jobs, whatever order they finish in
|
||||
//! ([`Loads::ready`]), so it installs them in the same order on every launch. A job starts only
|
||||
//! while fewer than twice the workers' count of outcomes before it are waiting to be taken or are
|
||||
//! still held by the caller ([`Loads::release`]), so the loaded modules held at once stay bounded
|
||||
//! however many jobs there are.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
|
||||
use std::time::Duration;
|
||||
|
||||
use web_time::Instant;
|
||||
|
||||
use crate::safe_mode::{self, Item};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// The most worker threads one [`Loads`] starts, besides those that replace a worker whose job
|
||||
/// passed [`LOAD_DEADLINE`].
|
||||
pub const MAX_WORKERS: usize = 4;
|
||||
|
||||
/// How long one job may take; one that takes longer fails as not finished.
|
||||
pub const LOAD_DEADLINE: Duration = Duration::from_secs(10);
|
||||
|
||||
/// How often a wait looks at the deadlines while no job finishes.
|
||||
const TICK: Duration = Duration::from_millis(50);
|
||||
|
||||
/// The most loader threads in the process still running a job past its deadline. While that many
|
||||
/// are, no [`Loads`] starts another thread, so loads started again and again on files whose reads
|
||||
/// never return don't pile up threads.
|
||||
pub const MAX_STUCK_THREADS: usize = 2 * MAX_WORKERS;
|
||||
|
||||
/// Loader threads in the process running a job past its deadline, across every [`Loads`].
|
||||
static STUCK_THREADS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// The [`Error::Failed`] message of a job that failed because no thread was left to run it.
|
||||
pub const NO_THREAD: &str = "no thread was left to load it";
|
||||
|
||||
/// One plug-in to load: the item the launch marker names while it loads, and the work, which runs
|
||||
/// on a worker thread.
|
||||
pub struct Job<T> {
|
||||
pub item: Option<Item>,
|
||||
pub work: Box<dyn FnOnce() -> Result<T> + Send>,
|
||||
}
|
||||
|
||||
impl<T> Job<T> {
|
||||
pub fn new(item: Option<Item>, work: impl FnOnce() -> Result<T> + Send + 'static) -> Self {
|
||||
Job { item, work: Box::new(work) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The time since a fixed start, for the deadlines.
|
||||
type Clock = Arc<dyn Fn() -> Duration + Send + Sync>;
|
||||
|
||||
/// A job's outcome as its worker sends it: the job, its result and how long it took.
|
||||
type Done<T> = (usize, Result<T>, Duration);
|
||||
|
||||
/// What the workers and [`Loads`] share.
|
||||
struct State<T> {
|
||||
/// The jobs not started yet, in order.
|
||||
queue: VecDeque<(usize, Job<T>)>,
|
||||
/// When each job started, and whether it has finished or passed its deadline.
|
||||
started: Vec<Option<Duration>>,
|
||||
finished: Vec<bool>,
|
||||
expired: Vec<bool>,
|
||||
/// Jobs whose index is below this may start.
|
||||
limit: usize,
|
||||
/// Worker threads alive, and how many of them run a job past its deadline.
|
||||
workers: usize,
|
||||
stuck: usize,
|
||||
}
|
||||
|
||||
struct Pool<T> {
|
||||
state: Mutex<State<T>>,
|
||||
/// Told when a job may start, or when the queue is emptied.
|
||||
wake: Condvar,
|
||||
}
|
||||
|
||||
impl<T> Pool<T> {
|
||||
fn lock(&self) -> MutexGuard<'_, State<T>> {
|
||||
self.state.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
/// Counts a worker as alive until its thread ends, however it ends.
|
||||
struct Alive<T>(Arc<Pool<T>>);
|
||||
|
||||
impl<T> Drop for Alive<T> {
|
||||
fn drop(&mut self) {
|
||||
self.0.lock().workers -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Jobs loading on worker threads ([`Loads::start`]).
|
||||
pub struct Loads<T: Send + 'static> {
|
||||
pool: Arc<Pool<T>>,
|
||||
results: Mutex<Receiver<Done<T>>>,
|
||||
send: Sender<Done<T>>,
|
||||
outcomes: Vec<Option<Result<T>>>,
|
||||
/// The outcomes before this one were taken ([`Loads::ready`]).
|
||||
next: usize,
|
||||
/// Of those, the ones the caller is done with ([`Loads::release`]).
|
||||
released: usize,
|
||||
/// How many jobs past `next` may start.
|
||||
window: usize,
|
||||
clock: Clock,
|
||||
deadline: Duration,
|
||||
/// The workers [`Loads::begin`] starts, and whether it has.
|
||||
workers: usize,
|
||||
begun: bool,
|
||||
/// The process's count of stuck loader threads ([`STUCK_THREADS`]), and its most.
|
||||
stuck_threads: &'static AtomicUsize,
|
||||
max_stuck: usize,
|
||||
/// Tests: no thread can be started from now on.
|
||||
#[cfg(test)]
|
||||
pub(crate) refuse_threads: bool,
|
||||
}
|
||||
|
||||
impl<T: Send + 'static> Loads<T> {
|
||||
/// Starts `jobs` on `min(available parallelism, MAX_WORKERS)` threads.
|
||||
pub fn start(jobs: Vec<Job<T>>) -> Self {
|
||||
let mut loads = Self::deferred(jobs);
|
||||
loads.begin();
|
||||
loads
|
||||
}
|
||||
|
||||
/// `jobs` to start on `min(available parallelism, MAX_WORKERS)` threads once [`Loads::begin`]
|
||||
/// is called (or something waits for them).
|
||||
pub fn deferred(jobs: Vec<Job<T>>) -> Self {
|
||||
Self::deferred_on(jobs, std::thread::available_parallelism().map_or(1, |n| n.get()).min(MAX_WORKERS))
|
||||
}
|
||||
|
||||
/// [`Loads::deferred`] on `workers` threads (at least one).
|
||||
pub(crate) fn deferred_on(jobs: Vec<Job<T>>, workers: usize) -> Self {
|
||||
let origin = Instant::now();
|
||||
Self::with(jobs, workers, LOAD_DEADLINE, Arc::new(move || origin.elapsed()))
|
||||
}
|
||||
|
||||
/// Starts the jobs, unless they started already.
|
||||
pub fn begin(&mut self) {
|
||||
if self.begun {
|
||||
return;
|
||||
}
|
||||
self.begun = true;
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
// The web build has no threads: each job runs here, in order.
|
||||
let jobs: Vec<_> = self.pool.lock().queue.drain(..).collect();
|
||||
for (i, job) in jobs {
|
||||
// A job can't be stopped here, but one that took past its deadline fails as on
|
||||
// the desktop.
|
||||
let at = (self.clock)();
|
||||
let r = run_job(job);
|
||||
let took = (self.clock)().saturating_sub(at);
|
||||
self.record((i, r, took));
|
||||
}
|
||||
} else {
|
||||
for _ in 0..self.workers.min(self.outcomes.len()) {
|
||||
self.spawn_worker();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn start_with(jobs: Vec<Job<T>>, workers: usize, deadline: Duration, clock: Clock) -> Self {
|
||||
let mut loads = Self::with(jobs, workers, deadline, clock);
|
||||
loads.begin();
|
||||
loads
|
||||
}
|
||||
|
||||
fn with(jobs: Vec<Job<T>>, workers: usize, deadline: Duration, clock: Clock) -> Self {
|
||||
let n = jobs.len();
|
||||
let workers = workers.max(1);
|
||||
let window = workers * 2;
|
||||
let state = State {
|
||||
queue: jobs.into_iter().enumerate().collect(),
|
||||
started: vec![None; n],
|
||||
finished: vec![false; n],
|
||||
expired: vec![false; n],
|
||||
limit: window,
|
||||
workers: 0,
|
||||
stuck: 0,
|
||||
};
|
||||
let (send, results) = mpsc::channel();
|
||||
Loads {
|
||||
pool: Arc::new(Pool { state: Mutex::new(state), wake: Condvar::new() }),
|
||||
results: Mutex::new(results),
|
||||
send,
|
||||
outcomes: (0..n).map(|_| None).collect(),
|
||||
next: 0,
|
||||
released: 0,
|
||||
window,
|
||||
clock,
|
||||
deadline,
|
||||
workers,
|
||||
begun: false,
|
||||
stuck_threads: &STUCK_THREADS,
|
||||
max_stuck: MAX_STUCK_THREADS,
|
||||
#[cfg(test)]
|
||||
refuse_threads: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts a thread that takes jobs until none are left → whether it started.
|
||||
fn spawn_worker(&self) -> bool {
|
||||
#[cfg(test)]
|
||||
if self.refuse_threads {
|
||||
return false;
|
||||
}
|
||||
if self.stuck_threads.load(Ordering::SeqCst) >= self.max_stuck {
|
||||
log::warn!("not starting a thread to load plug-ins: {} loader threads are still running loads past their deadline", self.max_stuck);
|
||||
return false;
|
||||
}
|
||||
let pool = self.pool.clone();
|
||||
let send = self.send.clone();
|
||||
let clock = self.clock.clone();
|
||||
let target = self.workers;
|
||||
let stuck_threads = self.stuck_threads;
|
||||
self.pool.lock().workers += 1;
|
||||
let spawned = std::thread::Builder::new().name("plug-in loader".into()).spawn(move || {
|
||||
let alive = Alive(pool);
|
||||
loop {
|
||||
let (i, job, at) = {
|
||||
let mut s = alive.0.lock();
|
||||
loop {
|
||||
match s.queue.front() {
|
||||
None => return,
|
||||
Some((i, _)) if *i < s.limit => break,
|
||||
Some(_) => s = alive.0.wake.wait(s).unwrap_or_else(|e| e.into_inner()),
|
||||
}
|
||||
}
|
||||
let Some((i, job)) = s.queue.pop_front() else { return };
|
||||
let at = clock();
|
||||
s.started[i] = Some(at);
|
||||
(i, job, at)
|
||||
};
|
||||
let r = run_job(job);
|
||||
// A worker whose job passed its deadline and was replaced ends once the job
|
||||
// returns, unless the workers able to take jobs are fewer than started. The time
|
||||
// the job took is read while the job is marked finished, so a deadline check that
|
||||
// finds it unfinished counts a time that its own outcome reaches too.
|
||||
let (took, retire) = {
|
||||
let mut s = alive.0.lock();
|
||||
let took = clock().saturating_sub(at);
|
||||
s.finished[i] = true;
|
||||
let retire = s.expired[i] && {
|
||||
s.stuck -= 1;
|
||||
stuck_threads.fetch_sub(1, Ordering::SeqCst);
|
||||
s.workers - s.stuck > target
|
||||
};
|
||||
(took, retire)
|
||||
};
|
||||
let _ = send.send((i, r, took));
|
||||
if retire {
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
self.pool.lock().workers -= 1;
|
||||
log::warn!("can't start a thread to load plug-ins: {e}");
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Takes the outcomes that came in and fails the jobs past their deadline → whether every job
|
||||
/// has its outcome.
|
||||
pub fn poll(&mut self) -> bool {
|
||||
loop {
|
||||
let next = self.results.lock().unwrap_or_else(|e| e.into_inner()).try_recv();
|
||||
let Ok(done) = next else { break };
|
||||
self.record(done);
|
||||
}
|
||||
self.expire();
|
||||
self.outcomes.iter().all(Option::is_some)
|
||||
}
|
||||
|
||||
/// The outcomes not taken yet that come in order from the last one taken, without waiting
|
||||
/// ([`Loads::poll`] first). The jobs after them start as the caller releases them
|
||||
/// ([`Loads::release`]).
|
||||
pub fn ready(&mut self) -> Vec<Result<T>> {
|
||||
self.poll();
|
||||
let mut out = Vec::new();
|
||||
while let Some(o) = self.outcomes.get_mut(self.next).and_then(Option::take) {
|
||||
out.push(o);
|
||||
self.next += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The caller is done with `n` more of the outcomes it took (installed or dropped them): as
|
||||
/// many more jobs may start, so the outcomes held, here and by the caller, stay at most twice
|
||||
/// the workers' count.
|
||||
pub fn release(&mut self, n: usize) {
|
||||
let released = (self.released + n).min(self.next);
|
||||
if released != self.released {
|
||||
self.released = released;
|
||||
self.pool.lock().limit = released + self.window;
|
||||
self.pool.wake.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether every outcome has been taken.
|
||||
pub fn taken(&self) -> bool {
|
||||
self.next == self.outcomes.len()
|
||||
}
|
||||
|
||||
/// Whether the next outcome in order can be taken ([`Loads::ready`]).
|
||||
pub fn next_ready(&mut self) -> bool {
|
||||
self.poll();
|
||||
self.outcomes.get(self.next).is_some_and(Option::is_some)
|
||||
}
|
||||
|
||||
/// Waits until the next outcome in order can be taken, or every one has been. Jobs that have
|
||||
/// not been started are started first ([`Loads::begin`]).
|
||||
pub fn wait_next(&mut self) {
|
||||
self.begin();
|
||||
while !self.taken() && !self.next_ready() {
|
||||
let next = self.results.lock().unwrap_or_else(|e| e.into_inner()).recv_timeout(TICK);
|
||||
match next {
|
||||
Ok(done) => self.record(done),
|
||||
Err(RecvTimeoutError::Timeout | RecvTimeoutError::Disconnected) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for every outcome → those not taken yet, in the order of the jobs. The outcomes taken
|
||||
/// before ([`Loads::ready`]) count as released, so the jobs after them start.
|
||||
pub fn wait(mut self) -> Vec<Result<T>> {
|
||||
self.release(self.next - self.released);
|
||||
let mut out = Vec::new();
|
||||
while !self.taken() {
|
||||
self.wait_next();
|
||||
let ready = self.ready();
|
||||
self.release(ready.len());
|
||||
out.extend(ready);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Tests: waits for the next outcome a worker sends and records it → its job (`None`: the
|
||||
/// channel the outcomes come on was closed).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn record_next(&mut self) -> Option<usize> {
|
||||
let done = self.results.lock().unwrap_or_else(|e| e.into_inner()).recv().ok()?;
|
||||
let i = done.0;
|
||||
self.record(done);
|
||||
Some(i)
|
||||
}
|
||||
|
||||
fn record(&mut self, (i, r, took): Done<T>) {
|
||||
let r = if took >= self.deadline { Err(self.too_long()) } else { r };
|
||||
// An outcome that comes after the job failed past its deadline is dropped.
|
||||
if let Some(slot @ None) = self.outcomes.get_mut(i) {
|
||||
*slot = Some(r);
|
||||
}
|
||||
}
|
||||
|
||||
fn too_long(&self) -> Error {
|
||||
let secs = self.deadline.as_secs();
|
||||
Error::Failed(format!("did not finish loading within {secs} s"))
|
||||
}
|
||||
|
||||
/// Fails the jobs still running past their deadline, starting a worker in place of each one's
|
||||
/// while the threads alive are fewer than twice the workers started. When no worker is left to
|
||||
/// take the jobs not started (none could be made, or every one is stuck), those fail too.
|
||||
fn expire(&mut self) {
|
||||
if !self.begun {
|
||||
return;
|
||||
}
|
||||
let mut expired = Vec::new();
|
||||
{
|
||||
let mut s = self.pool.lock();
|
||||
// Read while the workers can't mark a job finished ([`Loads::spawn_worker`]).
|
||||
let now = (self.clock)();
|
||||
for i in 0..self.outcomes.len() {
|
||||
let late = s.started[i].is_some_and(|at| now.saturating_sub(at) >= self.deadline);
|
||||
if late && !s.finished[i] && !s.expired[i] && self.outcomes[i].is_none() {
|
||||
s.expired[i] = true;
|
||||
s.stuck += 1;
|
||||
self.stuck_threads.fetch_add(1, Ordering::SeqCst);
|
||||
expired.push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
for i in &expired {
|
||||
self.outcomes[*i] = Some(Err(self.too_long()));
|
||||
}
|
||||
for _ in &expired {
|
||||
let room = {
|
||||
let s = self.pool.lock();
|
||||
!s.queue.is_empty() && s.workers < 2 * self.workers
|
||||
};
|
||||
if !room || !self.spawn_worker() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// The jobs not started are taken from the queue under the lock that finds no worker able to
|
||||
// take them, so a stuck worker that returns can't start one of them in between. Only those
|
||||
// fail: a job already started reports its own outcome.
|
||||
let stranded: Vec<usize> = {
|
||||
let mut s = self.pool.lock();
|
||||
if s.workers <= s.stuck { s.queue.drain(..).map(|(i, _)| i).collect() } else { Vec::new() }
|
||||
};
|
||||
for i in stranded {
|
||||
if let Some(o @ None) = self.outcomes.get_mut(i) {
|
||||
*o = Some(Err(Error::Failed(NO_THREAD.into())));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Send + 'static> Drop for Loads<T> {
|
||||
/// Jobs not started yet are dropped; the running ones are given until their deadline, so the
|
||||
/// launch marker is not left naming a plug-in that was still loading when the app quit.
|
||||
fn drop(&mut self) {
|
||||
self.pool.lock().queue.clear();
|
||||
self.pool.wake.notify_all();
|
||||
loop {
|
||||
let running = {
|
||||
let s = self.pool.lock();
|
||||
let now = (self.clock)();
|
||||
(0..self.outcomes.len())
|
||||
.any(|i| !s.finished[i] && !s.expired[i] && s.started[i].is_some_and(|at| now.saturating_sub(at) < self.deadline))
|
||||
};
|
||||
if !running {
|
||||
break;
|
||||
}
|
||||
let next = self.results.lock().unwrap_or_else(|e| e.into_inner()).recv_timeout(TICK);
|
||||
if let Ok(done) = next {
|
||||
self.record(done);
|
||||
}
|
||||
}
|
||||
// A job still running past its deadline leaves its thread stuck, and the thread counts
|
||||
// against the process's stuck threads until the job returns.
|
||||
let mut s = self.pool.lock();
|
||||
for i in 0..self.outcomes.len() {
|
||||
if s.started[i].is_some() && !s.finished[i] && !s.expired[i] {
|
||||
s.expired[i] = true;
|
||||
s.stuck += 1;
|
||||
self.stuck_threads.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `job` inside a panic boundary, with the launch marker naming its item while it runs.
|
||||
fn run_job<T>(job: Job<T>) -> Result<T> {
|
||||
let token = job.item.as_ref().map(safe_mode::loading);
|
||||
let result = catch_unwind(AssertUnwindSafe(job.work));
|
||||
if let Some(t) = token {
|
||||
safe_mode::loaded(t);
|
||||
}
|
||||
match result {
|
||||
Ok(r) => r,
|
||||
Err(panic) => {
|
||||
let what = panic.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| panic.downcast_ref::<String>().cloned());
|
||||
Err(match what {
|
||||
Some(what) => Error::Failed(format!("panicked while loading: {what}")),
|
||||
None => Error::Failed("panicked while loading".into()),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::mpsc::sync_channel;
|
||||
|
||||
/// A clock the test moves.
|
||||
fn manual() -> (Arc<AtomicU64>, Clock) {
|
||||
let ms = Arc::new(AtomicU64::new(0));
|
||||
let read = ms.clone();
|
||||
(ms, Arc::new(move || Duration::from_millis(read.load(Ordering::SeqCst))))
|
||||
}
|
||||
|
||||
/// A job that says it started on `started`, then waits for `go` and returns `v`.
|
||||
fn held(v: u32, started: mpsc::SyncSender<u32>, go: Receiver<()>) -> Job<u32> {
|
||||
Job::new(None, move || {
|
||||
let _ = started.send(v);
|
||||
let _ = go.recv();
|
||||
Ok(v)
|
||||
})
|
||||
}
|
||||
|
||||
/// The channel `loads`' workers send their outcomes on, taken out of `loads` so that the test
|
||||
/// still receives them once `loads` is dropped. A worker sends its outcome after it stopped
|
||||
/// counting its thread as stuck, so receiving it shows that the count went down.
|
||||
fn take_results(loads: &mut Loads<u32>) -> Receiver<Done<u32>> {
|
||||
std::mem::replace(&mut *loads.results.lock().unwrap(), mpsc::channel().1)
|
||||
}
|
||||
|
||||
/// The outcomes come back in the order of the jobs when they finish in the reverse order.
|
||||
#[test]
|
||||
fn outcomes_keep_the_order_of_the_jobs() {
|
||||
let (started, starts) = sync_channel(3);
|
||||
let mut go = Vec::new();
|
||||
let mut jobs = Vec::new();
|
||||
for v in 0..3 {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
go.push(tx);
|
||||
jobs.push(held(v, started.clone(), rx));
|
||||
}
|
||||
let (_, clock) = manual();
|
||||
let mut loads = Loads::start_with(jobs, 3, LOAD_DEADLINE, clock);
|
||||
// Bound after `loads`, so a failing assertion drops the senders first: the held jobs then
|
||||
// return, and dropping `loads` does not wait on them while the test clock stands still.
|
||||
let release = go;
|
||||
for _ in 0..3 {
|
||||
starts.recv().unwrap();
|
||||
}
|
||||
// Each job is let go only once the one after it has finished.
|
||||
let mut finished = Vec::new();
|
||||
for v in (0..3).rev() {
|
||||
release[v].send(()).unwrap();
|
||||
finished.extend(loads.record_next());
|
||||
}
|
||||
assert_eq!(finished, vec![2, 1, 0], "they finished in reverse");
|
||||
assert_eq!(loads.wait().into_iter().map(|r| r.unwrap()).collect::<Vec<_>>(), vec![0, 1, 2]);
|
||||
}
|
||||
|
||||
/// A job that panics fails with the panic's message, and the others load.
|
||||
#[test]
|
||||
fn a_job_that_panics_fails_alone() {
|
||||
let jobs: Vec<Job<u32>> = vec![Job::new(None, || Ok(1)), Job::new(None, || panic!("broken module")), Job::new(None, || Ok(3))];
|
||||
let (_, clock) = manual();
|
||||
let out = Loads::start_with(jobs, 2, LOAD_DEADLINE, clock).wait();
|
||||
assert_eq!(out[0], Ok(1));
|
||||
assert!(matches!(&out[1], Err(Error::Failed(m)) if m.contains("panicked") && m.contains("broken module")), "{:?}", out[1]);
|
||||
assert_eq!(out[2], Ok(3));
|
||||
}
|
||||
|
||||
/// With one worker, a job that never finishes fails at its deadline, and the job after it
|
||||
/// still loads, on the worker that takes its place.
|
||||
#[test]
|
||||
fn a_job_that_hangs_fails_at_its_deadline_and_the_rest_load() {
|
||||
let (started, starts) = sync_channel(2);
|
||||
let (go, held_until) = mpsc::channel();
|
||||
let jobs = vec![held(0, started.clone(), held_until), Job::new(None, || Ok(1))];
|
||||
let (ms, clock) = manual();
|
||||
let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock);
|
||||
assert_eq!(starts.recv().unwrap(), 0);
|
||||
assert!(!loads.poll(), "the first job is still running and the second waits for a worker");
|
||||
ms.store(10_000, Ordering::SeqCst);
|
||||
// The first job fails at its deadline. Unless the second job failed with it, for want of a
|
||||
// worker, the worker started in place of the stuck one sends the second job's outcome.
|
||||
loads.poll();
|
||||
if loads.outcomes[1].is_none() {
|
||||
loads.record_next();
|
||||
}
|
||||
let done = loads.poll();
|
||||
go.send(()).unwrap();
|
||||
assert!(done, "the job after the one that hangs never got its outcome");
|
||||
let out = loads.wait();
|
||||
assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("did not finish")), "{:?}", out[0]);
|
||||
assert_eq!(out[1], Ok(1));
|
||||
}
|
||||
|
||||
/// Workers that replace stuck ones stop at twice the workers started: with one worker and two
|
||||
/// jobs that never finish, the third job fails instead of a third thread taking it.
|
||||
#[test]
|
||||
fn replacements_stop_at_twice_the_workers() {
|
||||
let (started, starts) = sync_channel(3);
|
||||
let (go0, held0) = mpsc::channel();
|
||||
let (go1, held1) = mpsc::channel();
|
||||
let jobs = vec![held(0, started.clone(), held0), held(1, started, held1), Job::new(None, || Ok(2))];
|
||||
let (ms, clock) = manual();
|
||||
let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock);
|
||||
assert_eq!(starts.recv().unwrap(), 0);
|
||||
ms.store(10_000, Ordering::SeqCst);
|
||||
loads.poll();
|
||||
// The second job fails at once when no worker is left to take it; otherwise one starts it.
|
||||
assert!(loads.outcomes[1].is_none(), "no worker took the place of the stuck one: {:?}", loads.outcomes[1]);
|
||||
assert_eq!(starts.recv(), Ok(1), "a worker took the place of the stuck one");
|
||||
ms.store(20_000, Ordering::SeqCst);
|
||||
let done = loads.poll();
|
||||
go0.send(()).unwrap();
|
||||
go1.send(()).unwrap();
|
||||
assert!(done, "every job has its outcome");
|
||||
let out = loads.wait();
|
||||
assert!(matches!(&out[2], Err(Error::Failed(m)) if m.contains("no thread")), "{:?}", out[2]);
|
||||
}
|
||||
|
||||
/// A job that finished but took longer than the deadline fails, however soon it is looked at.
|
||||
#[test]
|
||||
fn a_job_that_took_too_long_fails_when_it_is_taken() {
|
||||
let (ms, clock) = manual();
|
||||
let moved = ms.clone();
|
||||
let jobs = vec![Job::new(None, move || {
|
||||
moved.store(10_000, Ordering::SeqCst);
|
||||
Ok(1u32)
|
||||
})];
|
||||
let out = Loads::start_with(jobs, 1, Duration::from_secs(10), clock).wait();
|
||||
assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("did not finish")), "{:?}", out[0]);
|
||||
}
|
||||
|
||||
/// Only twice the workers' count of jobs past the last outcome taken start: the next one waits
|
||||
/// until an outcome is taken.
|
||||
#[test]
|
||||
fn jobs_past_the_window_wait_until_outcomes_are_taken() {
|
||||
let ran = Arc::new(AtomicUsize::new(0));
|
||||
let jobs: Vec<Job<u32>> = (0..5)
|
||||
.map(|v| {
|
||||
let ran = ran.clone();
|
||||
Job::new(None, move || {
|
||||
ran.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(v)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let (_, clock) = manual();
|
||||
let mut loads = Loads::start_with(jobs, 1, LOAD_DEADLINE, clock);
|
||||
let loaded = [loads.record_next(), loads.record_next()];
|
||||
assert_eq!(loaded, [Some(0), Some(1)], "the first two loaded");
|
||||
let early = ran.load(Ordering::SeqCst);
|
||||
assert_eq!(loads.ready(), vec![Ok(0), Ok(1)]);
|
||||
assert_eq!(early, 2, "the third job waited for the first outcomes to be taken");
|
||||
// The worker starts the third job only once the limit passes it.
|
||||
loads.poll();
|
||||
let (may_start, started) = {
|
||||
let s = loads.pool.lock();
|
||||
(s.limit > 2, s.started[2].is_some())
|
||||
};
|
||||
assert!(!may_start && !started, "taken but not released");
|
||||
assert_eq!(ran.load(Ordering::SeqCst), 2, "the third job waits until the caller is done with the first outcomes");
|
||||
loads.release(2);
|
||||
assert_eq!(loads.wait(), vec![Ok(2), Ok(3), Ok(4)]);
|
||||
}
|
||||
|
||||
/// `wait` after outcomes were taken and not released still gets the rest: it counts the outcomes
|
||||
/// taken as released, so the job past the window starts.
|
||||
#[test]
|
||||
fn wait_after_outcomes_were_taken_gets_the_jobs_past_the_window() {
|
||||
let jobs: Vec<Job<u32>> = (0..3).map(|v| Job::new(None, move || Ok(v))).collect();
|
||||
let (_, clock) = manual();
|
||||
let mut loads = Loads::start_with(jobs, 1, LOAD_DEADLINE, clock);
|
||||
let loaded = [loads.record_next(), loads.record_next()];
|
||||
assert_eq!(loaded, [Some(0), Some(1)], "the first two loaded");
|
||||
assert_eq!(loads.ready(), vec![Ok(0), Ok(1)]);
|
||||
let (done, rest) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let _ = done.send(loads.wait());
|
||||
});
|
||||
assert_eq!(rest.recv(), Ok(vec![Ok(2)]));
|
||||
}
|
||||
|
||||
/// When no worker can take the jobs left, because the only one is stuck past its deadline and
|
||||
/// no thread takes its place, those jobs fail instead of being waited for.
|
||||
#[test]
|
||||
fn jobs_no_worker_can_take_fail() {
|
||||
let (started, starts) = sync_channel(1);
|
||||
let (go, held_until) = mpsc::channel();
|
||||
let jobs = vec![held(0, started, held_until), Job::new(None, || Ok(1))];
|
||||
let (ms, clock) = manual();
|
||||
let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock);
|
||||
starts.recv().unwrap();
|
||||
loads.refuse_threads = true;
|
||||
ms.store(10_000, Ordering::SeqCst);
|
||||
let done = loads.poll();
|
||||
go.send(()).unwrap();
|
||||
assert!(done, "every job has its outcome");
|
||||
let out = loads.wait();
|
||||
assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("did not finish")), "{:?}", out[0]);
|
||||
assert!(matches!(&out[1], Err(Error::Failed(m)) if m.contains("no thread")), "{:?}", out[1]);
|
||||
}
|
||||
|
||||
/// A thread stuck past its deadline counts against later loads until its job returns: with
|
||||
/// room for one stuck thread in the process, the load after one that left a thread stuck
|
||||
/// starts no thread and fails its job, and once the stuck job returns a load runs again.
|
||||
#[test]
|
||||
fn stuck_threads_count_across_loads_until_they_end() {
|
||||
let stuck: &'static AtomicUsize = Box::leak(Box::new(AtomicUsize::new(0)));
|
||||
let make = |jobs: Vec<Job<u32>>, clock: Clock| {
|
||||
let mut loads = Loads::with(jobs, 1, Duration::from_secs(10), clock);
|
||||
loads.stuck_threads = stuck;
|
||||
loads.max_stuck = 1;
|
||||
loads.begin();
|
||||
loads
|
||||
};
|
||||
let (started, starts) = sync_channel(1);
|
||||
let (go, held_until) = mpsc::channel();
|
||||
let (ms, clock) = manual();
|
||||
let mut first = make(vec![held(0, started, held_until)], clock);
|
||||
starts.recv().unwrap();
|
||||
ms.store(10_000, Ordering::SeqCst);
|
||||
assert!(first.poll(), "the stuck job failed at its deadline");
|
||||
let results = take_results(&mut first);
|
||||
drop(first);
|
||||
let (_, clock) = manual();
|
||||
let out = make(vec![Job::new(None, || Ok(1))], clock.clone()).wait();
|
||||
assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("no thread")), "{:?}", out[0]);
|
||||
go.send(()).unwrap();
|
||||
assert_eq!(results.recv().map(|done| done.0), Ok(0), "the stuck job returned");
|
||||
assert_eq!(stuck.load(Ordering::SeqCst), 0, "the thread no longer counts as stuck");
|
||||
assert_eq!(make(vec![Job::new(None, || Ok(2))], clock).wait(), vec![Ok(2)]);
|
||||
}
|
||||
|
||||
/// A load dropped while a job runs past its deadline, before anything looked at the job, still
|
||||
/// counts the job's thread as stuck until the job returns.
|
||||
#[test]
|
||||
fn a_dropped_load_counts_a_job_past_its_deadline_as_stuck() {
|
||||
let stuck: &'static AtomicUsize = Box::leak(Box::new(AtomicUsize::new(0)));
|
||||
let (started, starts) = sync_channel(1);
|
||||
let (go, held_until) = mpsc::channel();
|
||||
let (ms, clock) = manual();
|
||||
let mut loads = Loads::with(vec![held(0, started, held_until)], 1, Duration::from_secs(10), clock);
|
||||
loads.stuck_threads = stuck;
|
||||
loads.begin();
|
||||
starts.recv().unwrap();
|
||||
ms.store(10_000, Ordering::SeqCst);
|
||||
let results = take_results(&mut loads);
|
||||
drop(loads);
|
||||
assert_eq!(stuck.load(Ordering::SeqCst), 1, "the stuck thread counts");
|
||||
go.send(()).unwrap();
|
||||
assert_eq!(results.recv().map(|done| done.0), Ok(0), "the stuck job returned");
|
||||
assert_eq!(stuck.load(Ordering::SeqCst), 0, "the thread no longer counts as stuck");
|
||||
}
|
||||
|
||||
/// The launch marker names an item while its job runs, and stops naming it when the job
|
||||
/// returns, a job that panicked included.
|
||||
#[test]
|
||||
fn a_job_names_its_item_until_it_returns_even_when_it_panics() {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let ok = Item::file("test-loader-ok.wasm");
|
||||
let bad = Item::file("test-loader-panics.wasm");
|
||||
let named = |item: &Item| crate::safe_mode::still_loading().iter().any(|i| i.same(item));
|
||||
let (ok2, bad2) = (ok.clone(), bad.clone());
|
||||
let bad_named = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let seen = bad_named.clone();
|
||||
let jobs: Vec<Job<bool>> = vec![
|
||||
Job::new(Some(ok.clone()), move || Ok(named(&ok2))),
|
||||
Job::new(Some(bad.clone()), move || {
|
||||
seen.store(named(&bad2), Ordering::SeqCst);
|
||||
panic!("x")
|
||||
}),
|
||||
];
|
||||
let (_, clock) = manual();
|
||||
let outcomes = Loads::start_with(jobs, 2, LOAD_DEADLINE, clock).wait();
|
||||
assert!(matches!(outcomes.first(), Some(Ok(true))), "named while it runs");
|
||||
assert!(bad_named.load(Ordering::SeqCst), "named while it runs, before it panics");
|
||||
assert!(matches!(outcomes.get(1), Some(Err(Error::Failed(m))) if m.contains("panicked while loading")), "the panic is the job's failure");
|
||||
let running = crate::safe_mode::still_loading();
|
||||
assert!(!running.iter().any(|i| i.same(&bad) || i.same(&ok)), "{running:?}");
|
||||
}
|
||||
}
|
||||
+531
-12
@@ -6,11 +6,14 @@ use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::dialog::ParamUi;
|
||||
use crate::events::{EVENTS_API, Event};
|
||||
use crate::permissions::{self, API_LEVEL, INPUTS_API, PROGRESS_API, Permission};
|
||||
use crate::permissions::{self, API_LEVEL, CONTEXT_API, INPUTS_API, PROGRESS_API, Permission, WRITES_API};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Longest manifest the host reads.
|
||||
pub const MAX_MANIFEST_BYTES: usize = 64 * 1024;
|
||||
/// The name of the custom section a module may carry its manifest in, so the host reads it
|
||||
/// without running any of the module's code.
|
||||
pub const MANIFEST_SECTION: &str = "vc_manifest";
|
||||
/// Most parameters a plug-in may declare.
|
||||
pub const MAX_PARAMS: usize = 256;
|
||||
/// Most parameters outside groups (`group`): a dialog of more is sorted into sections.
|
||||
@@ -32,6 +35,74 @@ pub const MAX_ALLOWED_COMMANDS: usize = 256;
|
||||
/// Longest command id a manifest's `commandAllowlist` names, in bytes.
|
||||
pub const MAX_ALLOWED_ID: usize = 128;
|
||||
|
||||
/// The menus a command's `menu` may name, each as its path of English menu labels. File, Window,
|
||||
/// Help and the application menu are not among them, and neither are the submenus that list
|
||||
/// files, fonts, panels or other plug-ins.
|
||||
pub const MENU_PLACES: &[&[&str]] = &[
|
||||
&["Edit"],
|
||||
&["Edit", "Edit Colors"],
|
||||
&["Object"],
|
||||
&["Object", "Transform"],
|
||||
&["Object", "Arrange"],
|
||||
&["Object", "Path"],
|
||||
&["Object", "Compound Path"],
|
||||
&["Object", "Clipping Mask"],
|
||||
&["Type"],
|
||||
&["Select"],
|
||||
&["Select", "Same"],
|
||||
&["Select", "Object"],
|
||||
&["Effect"],
|
||||
&["View"],
|
||||
];
|
||||
|
||||
/// Where a command's `menu` places it: in the menu at `path` (one of [`MENU_PLACES`]), after the
|
||||
/// built-in item labeled `after` (1 to 64 printable characters), or at the end of that menu when
|
||||
/// `after` is left out or names no built-in item there.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
pub struct MenuPlace {
|
||||
pub path: &'static [&'static str],
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub after: Option<String>,
|
||||
}
|
||||
|
||||
impl MenuPlace {
|
||||
/// Reads a command's `menu` value: `{"path": [label, …], "after"?: label}`.
|
||||
fn read(v: &Value) -> std::result::Result<MenuPlace, String> {
|
||||
let wrong_path = || {
|
||||
let k = "menu.path";
|
||||
let places: Vec<String> =
|
||||
MENU_PLACES.iter().map(|p| format!("[{}]", p.iter().map(|l| format!("{l:?}")).collect::<Vec<_>>().join(", "))).collect();
|
||||
format!("`{k}` must be one of {}", places.join(", "))
|
||||
};
|
||||
let Some(o) = v.as_object() else {
|
||||
let key = "menu";
|
||||
return Err(format!("`{key}` must be an object"));
|
||||
};
|
||||
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "path" | "after")) {
|
||||
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
|
||||
return Err(format!("unknown key `{k}`; the keys here are {}", "path, after"));
|
||||
}
|
||||
let path: Vec<&str> = match o.get("path").and_then(Value::as_array) {
|
||||
Some(path) => path.iter().map(Value::as_str).collect::<Option<_>>().ok_or_else(wrong_path)?,
|
||||
None => return Err(wrong_path()),
|
||||
};
|
||||
let path = *MENU_PLACES.iter().find(|p| **p == path.as_slice()).ok_or_else(wrong_path)?;
|
||||
let key = "menu.after";
|
||||
let after = match o.get("after") {
|
||||
None => None,
|
||||
Some(Value::String(s)) => {
|
||||
let trimmed = s.trim();
|
||||
if trimmed.is_empty() || s.chars().count() > 64 || s.chars().any(char::is_control) {
|
||||
return Err(format!("`{key}` must be 1-64 printable characters"));
|
||||
}
|
||||
Some(trimmed.to_string())
|
||||
}
|
||||
Some(_) => return Err(format!("`{key}` must be a string")),
|
||||
};
|
||||
Ok(MenuPlace { path, after })
|
||||
}
|
||||
}
|
||||
|
||||
/// What a plug-in is.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -94,6 +165,45 @@ impl InputKind {
|
||||
}
|
||||
}
|
||||
|
||||
/// A part of the active document a filter or a plug-in command asks to be given in
|
||||
/// `_context.document`, with or without a selection (its manifest's `context`, plug-in API level 3):
|
||||
/// plain values to read, never objects.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum ContextSection {
|
||||
/// The document's name (never its path), color mode, units, the active artboard's size, the
|
||||
/// bleed and the raster effects resolution.
|
||||
Settings,
|
||||
/// Every artboard's id, name and rectangle, and which one is active.
|
||||
Artboards,
|
||||
/// Every layer and sublayer: name, visibility, lock, nesting, and which one is current.
|
||||
Layers,
|
||||
/// Every swatch, as `swatch.list` lists it.
|
||||
Swatches,
|
||||
}
|
||||
|
||||
impl ContextSection {
|
||||
/// Every section, in the order the docs list them.
|
||||
pub const ALL: [ContextSection; 4] = [ContextSection::Settings, ContextSection::Artboards, ContextSection::Layers, ContextSection::Swatches];
|
||||
|
||||
/// Its name in `context`, which is also its key in `_context.document`.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
ContextSection::Settings => "settings",
|
||||
ContextSection::Artboards => "artboards",
|
||||
ContextSection::Layers => "layers",
|
||||
ContextSection::Swatches => "swatches",
|
||||
}
|
||||
}
|
||||
|
||||
/// The section named `name`.
|
||||
pub fn parse(name: &str) -> Option<ContextSection> {
|
||||
ContextSection::ALL.into_iter().find(|s| s.name() == name)
|
||||
}
|
||||
}
|
||||
|
||||
/// The error of a `context` that is not a list of distinct section names.
|
||||
const CONTEXT_LIST: &str = "`context` must list distinct sections: settings, artboards, layers or swatches";
|
||||
|
||||
/// How much one run of a plug-in may compute.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -115,6 +225,32 @@ impl Budget {
|
||||
}
|
||||
}
|
||||
|
||||
/// What runs a plug-in's code.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Runtime {
|
||||
/// A WebAssembly module ([`crate::Plugin::load`]); the manifest is the module's `vc_manifest`.
|
||||
#[default]
|
||||
Wasm,
|
||||
/// A JavaScript file run on `vectorcraft-js` ([`crate::js`]): an object filter whose manifest
|
||||
/// gives `"runtime": "js"`.
|
||||
Js,
|
||||
}
|
||||
|
||||
impl Runtime {
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Runtime::Wasm => "wasm",
|
||||
Runtime::Js => "js",
|
||||
}
|
||||
}
|
||||
|
||||
/// WebAssembly, which a manifest written back leaves out (`skip_serializing_if`).
|
||||
fn is_wasm(&self) -> bool {
|
||||
*self == Runtime::Wasm
|
||||
}
|
||||
}
|
||||
|
||||
/// One declared parameter.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
@@ -221,9 +357,9 @@ pub struct Param {
|
||||
}
|
||||
|
||||
/// A menu command a plug-in adds (`commands`): the host lists it under Object › Plug-ins › the
|
||||
/// plug-in's name (Effect › Plug-ins for a live effect's), runs it as the command
|
||||
/// `plugin.<plug-in id>.<id>`, and calls the plug-in's `vc_run` with `_context.command` set to
|
||||
/// `id` and the parameters it declares.
|
||||
/// plug-in's name (Effect › Plug-ins for a live effect's), or in the menu its `menu` names, runs it
|
||||
/// as the command `plugin.<plug-in id>.<id>`, and calls the plug-in's `vc_run` with
|
||||
/// `_context.command` set to `id` and the parameters it declares.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Command {
|
||||
/// `[a-z][a-z0-9_]*`, at most [`MAX_COMMAND_ID`] characters, unique within the manifest.
|
||||
@@ -234,6 +370,13 @@ pub struct Command {
|
||||
/// Parameters in declaration (dialog) order, declared as the manifest's own are.
|
||||
#[serde(default, deserialize_with = "ordered_params", serialize_with = "params_as_object")]
|
||||
pub params: Vec<(String, Param)>,
|
||||
/// The menu it is listed in instead of the plug-in's submenu (`menu`, read at
|
||||
/// [`crate::permissions::MENU_API`] and later).
|
||||
#[serde(rename = "menu", skip_deserializing, skip_serializing_if = "Option::is_none")]
|
||||
pub place: Option<MenuPlace>,
|
||||
/// Each `menu` value the manifest gives, until [`Manifest::parse`] reads them.
|
||||
#[serde(skip)]
|
||||
pub(crate) declared_menu: Vec<Value>,
|
||||
}
|
||||
|
||||
impl Command {
|
||||
@@ -242,6 +385,18 @@ impl Command {
|
||||
pub fn shown_label(&self) -> String {
|
||||
crate::permissions::display_text(self.label.trim(), crate::permissions::MAX_SHOWN_NAME)
|
||||
}
|
||||
|
||||
/// The label its menu item shows for plug-in `plugin_name`: [`Command::shown_label`], and for a
|
||||
/// command placed in another menu, followed by the plug-in's name in parentheses.
|
||||
pub fn menu_label(&self, plugin_name: &str) -> String {
|
||||
match self.place {
|
||||
None => self.shown_label(),
|
||||
Some(_) => {
|
||||
let name = crate::permissions::display_text(plugin_name.trim(), crate::permissions::MAX_SHOWN_NAME);
|
||||
format!("{} ({name})", self.shown_label())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ParamSpec> for Param {
|
||||
@@ -300,7 +455,8 @@ impl ParamSpec {
|
||||
}
|
||||
}
|
||||
|
||||
/// The manifest a plug-in returns from `vc_manifest` (UTF-8 JSON).
|
||||
/// The manifest a plug-in carries in its [`MANIFEST_SECTION`] custom section or returns from
|
||||
/// `vc_manifest` (UTF-8 JSON).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Manifest {
|
||||
@@ -327,6 +483,17 @@ pub struct Manifest {
|
||||
/// lists them. Left out or empty, it is given paths and compound paths alone.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "input_names")]
|
||||
pub inputs: Vec<String>,
|
||||
/// The kinds among `inputs` the filter may change, by [`InputKind::name`]: only a filter at
|
||||
/// `api` 3 or later whose `permissions` list `doc.read` and `doc.write` lists them. Left out or
|
||||
/// empty, every kind it reads stays read-only.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "write_names")]
|
||||
pub writes: Vec<String>,
|
||||
/// The parts of the document a run is given in `_context.document`, by
|
||||
/// [`ContextSection::name`]: only a filter, or a live effect with `commands` (for its command
|
||||
/// runs), at `api` 3 or later whose `permissions` list `doc.read` lists them. Left out or empty,
|
||||
/// a run is given none.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "context_names")]
|
||||
pub context: Vec<String>,
|
||||
/// Parameters in declaration (dialog) order; a JSON object `{"name": spec, …}` in the manifest.
|
||||
#[serde(default, deserialize_with = "ordered_params", serialize_with = "params_as_object")]
|
||||
pub params: Vec<(String, Param)>,
|
||||
@@ -334,6 +501,11 @@ pub struct Manifest {
|
||||
/// the one an exporter's files get. Only exporters and importers declare them.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub extensions: Vec<String>,
|
||||
/// An importer whose files File › Place also reads (`file.place`), into the open document as one
|
||||
/// group ([`crate::import::Mode::Place`]): `true` when the manifest has `"place": true`. Only an
|
||||
/// importer sets it.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub place: bool,
|
||||
/// How much a run may compute: only a filter may be [`Budget::Heavy`].
|
||||
#[serde(default, skip_serializing_if = "Budget::is_light")]
|
||||
pub budget: Budget,
|
||||
@@ -354,6 +526,9 @@ pub struct Manifest {
|
||||
/// out or empty, it reacts to none.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "event_names")]
|
||||
pub events: Vec<String>,
|
||||
/// What runs its code: WebAssembly when left out, or `"js"` for a JavaScript filter.
|
||||
#[serde(default, skip_serializing_if = "Runtime::is_wasm")]
|
||||
pub runtime: Runtime,
|
||||
}
|
||||
|
||||
impl Manifest {
|
||||
@@ -363,11 +538,19 @@ impl Manifest {
|
||||
return Err(Error::Manifest(format!("manifest is {} bytes (limit {MAX_MANIFEST_BYTES})", bytes.len())));
|
||||
}
|
||||
let text = std::str::from_utf8(bytes).map_err(|_| Error::Manifest("manifest is not UTF-8".into()))?;
|
||||
Manifest::parse_text(text)
|
||||
}
|
||||
|
||||
/// [`Manifest::parse`] without its size limit, for JSON that holds other keys besides the
|
||||
/// manifest's (a JavaScript plug-in's `source`), whose caller checks the manifest's size. Keys
|
||||
/// the manifest doesn't declare are ignored, and `params` keep the order the text gives them.
|
||||
pub(crate) fn parse_text(text: &str) -> Result<Manifest> {
|
||||
if serde_json::from_str::<Value>(text).is_ok_and(|v| v.get("paintOutput").is_some_and(|p| *p != Value::Bool(true))) {
|
||||
return Err(Error::Manifest("`paintOutput` may only be true".into()));
|
||||
}
|
||||
let man: Manifest = serde_json::from_str(text).map_err(|e| Error::Manifest(format!("manifest: {e}")))?;
|
||||
let mut man: Manifest = serde_json::from_str(text).map_err(|e| Error::Manifest(format!("manifest: {e}")))?;
|
||||
man.validate()?;
|
||||
man.read_places()?;
|
||||
Ok(man)
|
||||
}
|
||||
|
||||
@@ -383,13 +566,17 @@ impl Manifest {
|
||||
api: 1,
|
||||
permissions: None,
|
||||
inputs: Vec::new(),
|
||||
writes: Vec::new(),
|
||||
context: Vec::new(),
|
||||
params: Vec::new(),
|
||||
extensions: Vec::new(),
|
||||
place: false,
|
||||
budget: Budget::Light,
|
||||
paint_output: false,
|
||||
commands: Vec::new(),
|
||||
command_allowlist: Vec::new(),
|
||||
events: Vec::new(),
|
||||
runtime: Runtime::Wasm,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -404,6 +591,31 @@ impl Manifest {
|
||||
self.commands.iter().find(|c| c.id == id)
|
||||
}
|
||||
|
||||
/// Reads each command's `menu` into its [`Command::place`] at
|
||||
/// [`crate::permissions::MENU_API`] and later, and drops it below that level, where the key is
|
||||
/// ignored. A `menu` that names a menu outside [`MENU_PLACES`], has the wrong shape or is given
|
||||
/// twice is refused, and the error names the command.
|
||||
fn read_places(&mut self) -> Result<()> {
|
||||
let reads = self.api >= permissions::MENU_API;
|
||||
for (i, c) in self.commands.iter_mut().enumerate() {
|
||||
let menus = std::mem::take(&mut c.declared_menu);
|
||||
if !reads {
|
||||
continue;
|
||||
}
|
||||
let name = command_name(i, &c.id);
|
||||
let place = match menus.as_slice() {
|
||||
[] => continue,
|
||||
[menu] => MenuPlace::read(menu),
|
||||
_ => {
|
||||
let key = "menu";
|
||||
Err(format!("duplicate field `{key}`"))
|
||||
}
|
||||
};
|
||||
c.place = Some(place.map_err(|e| Error::Manifest(format!("command {name}: {e}")))?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Checks what the module declared: its id, name and text lengths, its extensions, a budget its
|
||||
/// kind may have (only a filter may be heavy), and each parameter and its dialog layout.
|
||||
fn validate(&self) -> Result<()> {
|
||||
@@ -429,10 +641,15 @@ impl Manifest {
|
||||
return Err(Error::Manifest(format!("permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API}")));
|
||||
}
|
||||
self.validate_inputs()?;
|
||||
self.validate_writes()?;
|
||||
self.validate_context()?;
|
||||
if self.paint_output && (self.kind != Kind::Effect || self.api < 2) {
|
||||
return Err(Error::Manifest("`paintOutput` is only for a live effect (`kind` \"effect\") at `api` 2".into()));
|
||||
}
|
||||
self.validate_extensions()?;
|
||||
if self.place && self.kind != Kind::Importer {
|
||||
return Err(Error::Manifest("`place` is only for an importer (`kind` \"importer\")".into()));
|
||||
}
|
||||
match (self.budget, self.kind) {
|
||||
(Budget::Light, _) | (Budget::Heavy, Kind::Filter) => {}
|
||||
(Budget::Heavy, Kind::Effect) => {
|
||||
@@ -448,7 +665,8 @@ impl Manifest {
|
||||
self.validate_params()?;
|
||||
self.validate_commands()?;
|
||||
self.validate_allowlist()?;
|
||||
self.validate_events()
|
||||
self.validate_events()?;
|
||||
self.validate_runtime()
|
||||
}
|
||||
|
||||
/// `events` names each [`Event`] at most once, and a list needs `api` 2 or later and the
|
||||
@@ -485,6 +703,28 @@ impl Manifest {
|
||||
self.events.iter().any(|n| n == event.name())
|
||||
}
|
||||
|
||||
/// A JavaScript plug-in (`"runtime": "js"`) is an object filter, and of the host's permissions
|
||||
/// it lists only `progress`: its realm has no settings, cache or command calls.
|
||||
fn validate_runtime(&self) -> Result<()> {
|
||||
if self.runtime == Runtime::Wasm {
|
||||
return Ok(());
|
||||
}
|
||||
if self.kind != Kind::Filter {
|
||||
let kind = self.kind.name();
|
||||
return Err(Error::Manifest(format!("`runtime` \"js\" is for an object filter (`kind` \"filter\"), not `kind` \"{kind}\"")));
|
||||
}
|
||||
let listed = self.permissions.as_deref().unwrap_or_default();
|
||||
for p in [Permission::Settings, Permission::Cache, Permission::Commands] {
|
||||
if listed.iter().any(|n| n == p.name()) {
|
||||
let name = p.name();
|
||||
return Err(Error::Manifest(format!(
|
||||
"a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress`"
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `commandAllowlist` lists at most [`MAX_ALLOWED_COMMANDS`] distinct command ids
|
||||
/// ([`valid_allowed_id`]), and only a filter with the usual budget lists any: a heavy one runs in
|
||||
/// the background, away from the document its commands would change. A list needs the
|
||||
@@ -560,6 +800,64 @@ impl Manifest {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `writes` names each [`InputKind`] at most once, each one `inputs` lists, and only a filter at
|
||||
/// `api` 3 or later lists any, with a `permissions` list that holds `doc.read` and `doc.write`.
|
||||
fn validate_writes(&self) -> Result<()> {
|
||||
if self.writes.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if self.kind != Kind::Filter {
|
||||
return Err(Error::Manifest("only a filter declares `writes`".into()));
|
||||
}
|
||||
for (i, name) in self.writes.iter().enumerate() {
|
||||
let shown = permissions::display_text(name, permissions::MAX_SHOWN_FIELD);
|
||||
if InputKind::parse(name).is_none() {
|
||||
return Err(Error::Manifest(format!("`writes` names an unknown object kind `{shown}`: use type, image or symbolInstance")));
|
||||
}
|
||||
if self.writes.get(..i).is_some_and(|before| before.contains(name)) {
|
||||
return Err(Error::Manifest(format!("`writes` lists `{shown}` twice")));
|
||||
}
|
||||
if !self.inputs.contains(name) {
|
||||
return Err(Error::Manifest(format!("`writes` lists `{shown}`, which `inputs` doesn't list")));
|
||||
}
|
||||
}
|
||||
if self.api < WRITES_API {
|
||||
return Err(Error::Manifest(format!("`writes` needs `api` {WRITES_API} or later")));
|
||||
}
|
||||
let listed = |p: Permission| self.permissions.as_ref().is_some_and(|names| names.iter().any(|n| n == p.name()));
|
||||
if !listed(Permission::DocWrite) {
|
||||
return Err(Error::Manifest("`writes` needs the permission `doc.write`".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `context` names each [`ContextSection`] at most once, and only a filter, or a live effect
|
||||
/// with commands, at `api` 3 or later lists any, with a `permissions` list that holds
|
||||
/// `doc.read`: installing it then asks the user to grant it ([`Manifest::asks_permissions`]).
|
||||
fn validate_context(&self) -> Result<()> {
|
||||
if self.context.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
for (i, name) in self.context.iter().enumerate() {
|
||||
if ContextSection::parse(name).is_none() || self.context.get(..i).is_some_and(|before| before.contains(name)) {
|
||||
return Err(Error::Manifest(CONTEXT_LIST.into()));
|
||||
}
|
||||
}
|
||||
let runs = self.kind == Kind::Filter || (self.kind == Kind::Effect && !self.commands.is_empty());
|
||||
let reads = self.permissions.as_ref().is_some_and(|p| p.iter().any(|n| n == Permission::DocRead.name()));
|
||||
if !runs || self.api < CONTEXT_API || !reads {
|
||||
return Err(Error::Manifest(
|
||||
"`context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read`".into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The parts of the document it asks to be given (`context`).
|
||||
pub fn context_sections(&self) -> Vec<ContextSection> {
|
||||
self.context.iter().filter_map(|n| ContextSection::parse(n)).collect()
|
||||
}
|
||||
|
||||
/// A filter or a live effect lists at most [`MAX_COMMANDS`] commands, each with a distinct
|
||||
/// id, a printable label and parameters declared as the manifest's own are. A heavy filter
|
||||
/// lists none. The error names the command: its id, or its place in the list.
|
||||
@@ -606,6 +904,11 @@ impl Manifest {
|
||||
self.inputs.iter().filter_map(|n| InputKind::parse(n)).collect()
|
||||
}
|
||||
|
||||
/// The kinds among those it reads that it may change (`writes`).
|
||||
pub fn write_kinds(&self) -> Vec<InputKind> {
|
||||
self.writes.iter().filter_map(|n| InputKind::parse(n)).collect()
|
||||
}
|
||||
|
||||
/// An exporter or an importer lists 1 to [`MAX_EXTENSIONS`] distinct extensions of 1 to 16
|
||||
/// lower-case letters and digits; other kinds list none.
|
||||
fn validate_extensions(&self) -> Result<()> {
|
||||
@@ -775,6 +1078,16 @@ fn input_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Ve
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `writes` as [`input_names`] reads `inputs`.
|
||||
fn write_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<String>, D::Error> {
|
||||
let wrong = || serde::de::Error::custom("`writes` must be a list of object kinds: type, image or symbolInstance");
|
||||
match Value::deserialize(d)? {
|
||||
Value::Null => Ok(Vec::new()),
|
||||
Value::Array(names) => names.into_iter().map(|n| if let Value::String(s) = n { Ok(s) } else { Err(wrong()) }).collect(),
|
||||
_ => Err(wrong()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `events`: a list of names (`null`: none). Anything else is an error that names the key, as
|
||||
/// [`Manifest::validate_events`] names a wrong entry.
|
||||
fn event_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<String>, D::Error> {
|
||||
@@ -786,6 +1099,18 @@ fn event_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Ve
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `context`: a list of names (`null`: none). Anything else is the error
|
||||
/// [`Manifest::validate_context`] gives a wrong entry.
|
||||
fn context_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<String>, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Null => Ok(Vec::new()),
|
||||
Value::Array(names) => {
|
||||
names.into_iter().map(|n| if let Value::String(s) = n { Ok(s) } else { Err(serde::de::Error::custom(CONTEXT_LIST)) }).collect()
|
||||
}
|
||||
_ => Err(serde::de::Error::custom(CONTEXT_LIST)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the `commands` list one entry at a time from the manifest itself, so each command's
|
||||
/// `params` keep their declaration order and a repeated parameter is refused. A malformed entry
|
||||
/// is an error that names it (its id when the id comes before the fault, otherwise its place in
|
||||
@@ -858,7 +1183,7 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu
|
||||
Err(A::Error::custom(self.wrong()))
|
||||
}
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> std::result::Result<Command, A::Error> {
|
||||
let (mut id, mut label, mut params) = (None::<String>, None::<String>, None::<Params>);
|
||||
let (mut id, mut label, mut params, mut menu) = (None::<String>, None::<String>, None::<Params>, Vec::<Value>::new());
|
||||
let named = |id: &Option<String>, e: &dyn std::fmt::Display| {
|
||||
A::Error::custom(format!("command {}: {e}", command_name(self.0, id.as_deref().unwrap_or_default())))
|
||||
};
|
||||
@@ -877,6 +1202,11 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu
|
||||
params = Some(map.next_value().map_err(|e| named(&id, &e))?);
|
||||
false
|
||||
}
|
||||
// A repeated `menu` is refused only where the key is read ([`Manifest::parse`]).
|
||||
"menu" => {
|
||||
menu.push(map.next_value().map_err(|e| named(&id, &e))?);
|
||||
false
|
||||
}
|
||||
"id" | "label" | "params" => true,
|
||||
_ => {
|
||||
map.next_value::<IgnoredAny>()?;
|
||||
@@ -893,7 +1223,7 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu
|
||||
let Some(label) = label else {
|
||||
return Err(named(&Some(id), &"missing field `label`"));
|
||||
};
|
||||
Ok(Command { id, label, params: params.map(|p| p.0).unwrap_or_default() })
|
||||
Ok(Command { id, label, params: params.map(|p| p.0).unwrap_or_default(), place: None, declared_menu: menu })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1103,6 +1433,33 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Only an importer sets `place`, to a boolean, and it asks for no permission beyond
|
||||
/// `import.read`; false, the default, isn't written back.
|
||||
#[test]
|
||||
fn only_an_importer_places_its_files() {
|
||||
let m = Manifest::parse(br#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"place":true}"#).unwrap();
|
||||
assert!(m.place);
|
||||
assert_eq!(m.permissions(), [Permission::ImportRead]);
|
||||
assert_eq!(serde_json::to_value(&m).unwrap()["place"], json!(true));
|
||||
for open_only in [
|
||||
r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"]}"#,
|
||||
r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"place":false}"#,
|
||||
] {
|
||||
let m = Manifest::parse(open_only.as_bytes()).unwrap();
|
||||
assert!(!m.place && serde_json::to_value(&m).unwrap().get("place").is_none(), "{open_only}");
|
||||
}
|
||||
for (bad, says) in [
|
||||
(r#"{"id":"a","name":"x","kind":"filter","place":true}"#, "`place` is only for an importer"),
|
||||
(r#"{"id":"a","name":"x","kind":"exporter","extensions":["plt"],"place":true}"#, "`place` is only for an importer"),
|
||||
(r#"{"id":"a","name":"x","kind":"effect","place":true}"#, "`place` is only for an importer"),
|
||||
(r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"place":"yes"}"#, "invalid type"),
|
||||
(r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"place":1}"#, "invalid type"),
|
||||
] {
|
||||
let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{bad}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A filter may ask for a heavy budget; a live effect runs while the document is drawn and an
|
||||
/// exporter has an export's budget, so they can't. Light, the default, isn't written back.
|
||||
#[test]
|
||||
@@ -1172,7 +1529,7 @@ mod tests {
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":1,"permissions":["progress"]}"#, "`progress` needs plug-in API level 2"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","permissions":["settings"]}"#, "`settings` needs plug-in API level 2"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":1,"permissions":["doc.read","cache"]}"#, "`cache` needs plug-in API level 2"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":3}"#, "`api` is 3"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":4}"#, "`api` is 4; this host implements plug-in API levels 1 to 3"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":0}"#, "`api` is 0"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":-1}"#, "manifest"),
|
||||
] {
|
||||
@@ -1228,6 +1585,109 @@ mod tests {
|
||||
assert!(Manifest::parse(long.as_bytes()).unwrap_err().to_string().contains("twice"));
|
||||
}
|
||||
|
||||
/// A filter at `api` 3 may change the kinds it reads that it lists in `writes`, each once, with
|
||||
/// `doc.read` and `doc.write`. Left out or empty, everything it reads stays read-only and the key
|
||||
/// isn't written back. Anything else is refused naming `writes`.
|
||||
#[test]
|
||||
fn a_filter_at_api_3_lists_the_kinds_it_writes() {
|
||||
let m = Manifest::parse(
|
||||
br#"{"id":"org.example.revise","name":"Revise","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["type","image","symbolInstance"],"writes":["type","image","symbolInstance"]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(m.write_kinds(), InputKind::ALL);
|
||||
assert_eq!(serde_json::to_value(&m).unwrap()["writes"], json!(["type", "image", "symbolInstance"]));
|
||||
let some = Manifest::parse(
|
||||
br#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["image","type"],"writes":["image"]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!((some.input_kinds(), some.write_kinds()), (vec![InputKind::Image, InputKind::Type], vec![InputKind::Image]));
|
||||
for none in [
|
||||
r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"inputs":["type"]}"#,
|
||||
r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"inputs":["type"],"writes":[]}"#,
|
||||
r#"{"id":"a","name":"x","kind":"filter","writes":null}"#,
|
||||
] {
|
||||
let m = Manifest::parse(none.as_bytes()).unwrap();
|
||||
assert!(m.write_kinds().is_empty(), "{none}");
|
||||
assert!(serde_json::to_value(&m).unwrap().get("writes").is_none(), "{none}");
|
||||
}
|
||||
let rw = r#""permissions":["doc.read","doc.write"]"#;
|
||||
for (bad, says) in [
|
||||
(
|
||||
format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":["text"]}}"#),
|
||||
"`writes` names an unknown object kind `text`",
|
||||
),
|
||||
(
|
||||
format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":["type","type"]}}"#),
|
||||
"`writes` lists `type` twice",
|
||||
),
|
||||
(
|
||||
format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":["image"]}}"#),
|
||||
"`writes` lists `image`, which `inputs` doesn't list",
|
||||
),
|
||||
(format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"writes":["image"]}}"#), "which `inputs` doesn't list"),
|
||||
(format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":"type"}}"#), "`writes` must be a list"),
|
||||
(format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":[1]}}"#), "`writes` must be a list"),
|
||||
(format!(r#"{{"id":"a","name":"x","kind":"filter","api":2,{rw},"inputs":["type"],"writes":["type"]}}"#), "`writes` needs `api` 3"),
|
||||
(
|
||||
r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"inputs":["type"],"writes":["type"]}"#.into(),
|
||||
"`writes` needs the permission `doc.write`",
|
||||
),
|
||||
(
|
||||
r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.write"],"inputs":["type"],"writes":["type"]}"#.into(),
|
||||
"`inputs` needs the permission `doc.read`",
|
||||
),
|
||||
(r#"{"id":"a","name":"x","kind":"effect","api":3,"writes":["type"]}"#.into(), "only a filter declares `writes`"),
|
||||
] {
|
||||
let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{bad}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A filter, or a live effect with commands, at `api` 3 may ask for parts of the document
|
||||
/// (`context`), each once, with a `permissions` list holding `doc.read`, so installing it asks
|
||||
/// for approval. Left out or empty, it asks for none and isn't written back. Anything else is
|
||||
/// refused naming `context`.
|
||||
#[test]
|
||||
fn a_level_3_plugin_lists_the_document_context_it_reads() {
|
||||
let m = Manifest::parse(
|
||||
br#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":["settings","artboards","layers","swatches"]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(m.context_sections(), ContextSection::ALL);
|
||||
assert!(m.asks_permissions());
|
||||
assert_eq!(serde_json::to_value(&m).unwrap()["context"], json!(["settings", "artboards", "layers", "swatches"]));
|
||||
let effect = br#"{"id":"a","name":"x","kind":"effect","api":3,"permissions":["doc.read","effect.render"],"context":["layers"],"commands":[{"id":"c","label":"C"}]}"#;
|
||||
assert_eq!(Manifest::parse(effect).unwrap().context_sections(), [ContextSection::Layers]);
|
||||
for none in [r#"{"id":"a","name":"x","kind":"filter","context":[]}"#, r#"{"id":"a","name":"x","kind":"filter","api":3,"context":null}"#] {
|
||||
let m = Manifest::parse(none.as_bytes()).unwrap();
|
||||
assert!(m.context_sections().is_empty(), "{none}");
|
||||
assert!(serde_json::to_value(&m).unwrap().get("context").is_none(), "{none}");
|
||||
}
|
||||
let list = "`context` must list distinct sections";
|
||||
let needs = "`context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read`";
|
||||
for (bad, says) in [
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":["paths"]}"#, list),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":["Layers"]}"#, list),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":["layers","layers"]}"#, list),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":"layers"}"#, list),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":[1]}"#, list),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":{"layers":true}}"#, list),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"context":["layers"]}"#, needs),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","permissions":["doc.read"],"context":["layers"]}"#, needs),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":3,"context":["layers"]}"#, needs),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.write"],"context":["layers"]}"#, needs),
|
||||
(r#"{"id":"a","name":"x","kind":"effect","api":3,"permissions":["doc.read","effect.render"],"context":["layers"]}"#, needs),
|
||||
(
|
||||
r#"{"id":"a","name":"x","kind":"exporter","extensions":["plt"],"api":3,"permissions":["doc.read","export.write"],"context":["layers"]}"#,
|
||||
needs,
|
||||
),
|
||||
(r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"api":3,"permissions":["import.read"],"context":["layers"]}"#, needs),
|
||||
] {
|
||||
let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{bad}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A live effect at `api` 2 may declare `"paintOutput": true`, and only that value; any other
|
||||
/// kind or level, and `false`, `null` or another type, is refused naming the key. Without the
|
||||
/// key, at any level, the effect returns geometry only.
|
||||
@@ -1269,7 +1729,7 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A filter or a live effect lists menu commands with their own parameters; a `menu` key is
|
||||
/// ignored. A malformed entry, a bad or repeated id, a label that isn't printable and too many
|
||||
/// ignored at API level 1. A malformed entry, a bad or repeated id, a label that isn't printable and too many
|
||||
/// commands are refused, and the error names the command.
|
||||
#[test]
|
||||
fn commands_are_checked_and_errors_name_them() {
|
||||
@@ -1291,7 +1751,7 @@ mod tests {
|
||||
assert!(serde_json::to_value(Manifest::parse(br#"{"id":"a","name":"x","kind":"filter"}"#).unwrap()).unwrap().get("commands").is_none());
|
||||
let effect = Manifest::parse(br#"{"id":"a","name":"x","kind":"effect","commands":[{"id":"c","label":"C"}]}"#).unwrap();
|
||||
assert_eq!(effect.commands.len(), 1);
|
||||
let label = |l: &str| Command { id: "c".into(), label: l.into(), params: Vec::new() }.shown_label();
|
||||
let label = |l: &str| Command { id: "c".into(), label: l.into(), params: Vec::new(), place: None, declared_menu: Vec::new() }.shown_label();
|
||||
assert_eq!(label("Flip\u{202E}txt.exe"), "Flip\\u{202E}txt.exe");
|
||||
|
||||
let many: Vec<String> = (0..=MAX_COMMANDS).map(|i| format!(r#"{{"id":"c{i}","label":"C"}}"#)).collect();
|
||||
@@ -1347,6 +1807,65 @@ mod tests {
|
||||
assert!(hidden.unwrap_err().to_string().contains("command `x\\u{202E}`"), "an id in an error is escaped");
|
||||
}
|
||||
|
||||
/// At API level 2 a command's `menu` places it in one of [`MENU_PLACES`], after a named item or
|
||||
/// at the end; a menu outside them (File, Help, Window, Edit › Preferences) or a `menu` of the
|
||||
/// wrong shape is refused and the error names the command. At level 1 the key is ignored.
|
||||
#[test]
|
||||
fn a_command_menu_names_an_allowed_place() {
|
||||
let with = |api: u32, menu: &str| {
|
||||
format!(
|
||||
r#"{{"id":"org.example.low","name":"Low Area","api":{api},"kind":"filter","commands":[{{"id":"low","label":"Low Area Closed Paths","menu":{menu}}}]}}"#
|
||||
)
|
||||
};
|
||||
let m = Manifest::parse(with(2, r#"{"path":["Select"],"after":" Inverse "}"#).as_bytes()).unwrap();
|
||||
let c = &m.commands[0];
|
||||
assert_eq!(c.place, Some(MenuPlace { path: &["Select"], after: Some("Inverse".into()) }));
|
||||
assert_eq!(c.menu_label(&m.name), "Low Area Closed Paths (Low Area)", "a placed item names its plug-in");
|
||||
assert_eq!(serde_json::to_value(&m).unwrap()["commands"][0]["menu"], json!({"path": ["Select"], "after": "Inverse"}));
|
||||
let end = Manifest::parse(with(2, r#"{"path":["Select","Same"]}"#).as_bytes()).unwrap();
|
||||
assert_eq!(end.commands[0].place, Some(MenuPlace { path: &["Select", "Same"], after: None }));
|
||||
|
||||
// API level 1 ignores the key, as hosts before it did: the command stays in the plug-in's submenu.
|
||||
for menu in [r#"{"path":["Select"]}"#, r#""File""#, r#"{"path":["File"]}"#, r#"{"path":["Select"]},"menu":{"path":["Edit"]}"#] {
|
||||
let old = Manifest::parse(with(1, menu).as_bytes()).unwrap();
|
||||
assert_eq!(old.commands[0].place, None, "{menu}");
|
||||
assert_eq!(old.commands[0].menu_label(&old.name), "Low Area Closed Paths");
|
||||
}
|
||||
|
||||
let long = format!(r#"{{"path":["Select"],"after":"{}"}}"#, "x".repeat(65));
|
||||
let padded = format!(r#"{{"path":["Select"],"after":" {} "}}"#, "x".repeat(64));
|
||||
for (menu, says) in [
|
||||
(r#"{"path":["File"]}"#, "`menu.path` must be one of"),
|
||||
(r#"{"path":["Help"]}"#, "`menu.path` must be one of"),
|
||||
(r#"{"path":["Window"]}"#, "`menu.path` must be one of"),
|
||||
(r#"{"path":["VectorCraft"]}"#, "`menu.path` must be one of"),
|
||||
(r#"{"path":["Edit","Preferences"]}"#, "`menu.path` must be one of"),
|
||||
(r#"{"path":["Object","Plug-ins"]}"#, "`menu.path` must be one of"),
|
||||
(r#"{"path":["select"]}"#, "`menu.path` must be one of"),
|
||||
(r#"{"path":[]}"#, "`menu.path` must be one of"),
|
||||
(r#"{"path":"Select"}"#, "`menu.path` must be one of"),
|
||||
(r#"{"path":["Select",1]}"#, "`menu.path` must be one of"),
|
||||
(r#"{"after":"Inverse"}"#, "`menu.path` must be one of"),
|
||||
(r#""Select""#, "`menu` must be an object"),
|
||||
(r#"["Select"]"#, "`menu` must be an object"),
|
||||
(r#"{"path":["Select"],"before":"Inverse"}"#, "unknown key `before`"),
|
||||
(r#"{"path":["Select"],"after":3}"#, "`menu.after` must be a string"),
|
||||
(r#"{"path":["Select"],"after":null}"#, "`menu.after` must be a string"),
|
||||
(r#"{"path":["Select"],"after":" "}"#, "`menu.after` must be 1-64 printable characters"),
|
||||
(r#"{"path":["Select"],"after":"In\u0007verse"}"#, "`menu.after` must be 1-64 printable characters"),
|
||||
(r#"{"path":["Select"],"after":"\nInverse\n"}"#, "`menu.after` must be 1-64 printable characters"),
|
||||
(long.as_str(), "`menu.after` must be 1-64 printable characters"),
|
||||
(padded.as_str(), "`menu.after` must be 1-64 printable characters"),
|
||||
(r#"{"path":["Select"]},"menu":{"path":["Edit"]}"#, "duplicate field `menu`"),
|
||||
] {
|
||||
let e = Manifest::parse(with(2, menu).as_bytes()).unwrap_err().to_string();
|
||||
assert!(e.contains("command `low`") && e.contains(says), "{menu}: {e}");
|
||||
}
|
||||
let twice =
|
||||
r#"{"id":"a","name":"x","api":2,"kind":"filter","commands":[{"id":"x","label":"A","menu":{"path":["Edit"]},"menu":{"path":["Edit"]}}]}"#;
|
||||
assert!(Manifest::parse(twice.as_bytes()).unwrap_err().to_string().contains("duplicate field `menu`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strings_and_number_lists_resolve_like_the_other_types() {
|
||||
let m = Manifest::parse(
|
||||
|
||||
+178
-35
@@ -38,6 +38,8 @@ pub const MITER_LIMIT: std::ops::RangeInclusive<f64> = 1.0..=500.0;
|
||||
pub const MAX_EFFECT_ID: usize = 128;
|
||||
/// Largest data a plug-in may keep with a document (`documentData`), in bytes of JSON.
|
||||
pub const MAX_DOCUMENT_DATA: usize = 1 << 20;
|
||||
/// Most characters of a filter's `notice` as the host shows it, its escapes counted.
|
||||
pub const MAX_NOTICE_CHARS: usize = 200;
|
||||
/// Most text a filter is given of one type object, in bytes of UTF-8 over all its runs: longer
|
||||
/// type comes with `truncated` and no runs or paragraphs.
|
||||
pub const MAX_INPUT_TEXT: usize = 256 * 1024;
|
||||
@@ -80,6 +82,10 @@ pub struct OutObject {
|
||||
/// A read-only input object (type, an image or a symbol instance) returned as it was given:
|
||||
/// it stays as it is, and new objects listed after it go above it.
|
||||
pub kept: bool,
|
||||
/// A type object, an image or a symbol instance of a kind the filter may change (`writes`)
|
||||
/// returned with changes: the fields it changes, by their names in the input, checked when
|
||||
/// they are applied ([`apply_output`]).
|
||||
pub edit: Option<serde_json::Map<String, Value>>,
|
||||
}
|
||||
|
||||
/// One stroke of an [`OutObject`]. `None` fields keep the stroke's value (a new stroke's
|
||||
@@ -293,7 +299,7 @@ fn affine_json(xf: Affine) -> Value {
|
||||
/// paragraphs: [style]}` with the native character and paragraph attributes, one paragraph style
|
||||
/// for each paragraph, and `truncated`: true, with no runs or paragraphs, past [`MAX_INPUT_TEXT`]
|
||||
/// or [`MAX_INPUT_RUNS`];
|
||||
/// - an image (`"image"`): `pixelSize: [w, h]`, `colorMode: "rgb"|"cmyk"|"gray"|"unknown"`,
|
||||
/// - an image (`"image"`): `opacity` (0 to 1), `pixelSize: [w, h]`, `colorMode: "rgb"|"cmyk"|"gray"|"unknown"`,
|
||||
/// `linked`, `pixelsOmitted`, and for an embedded image of at most [`MAX_INPUT_PIXELS`]
|
||||
/// `pixelsBase64`: straight RGBA, 8 bits a channel, row by row from the top (a CMYK image's inks
|
||||
/// through the working CMYK profile, as sRGB). A linked image's file and path are never read or
|
||||
@@ -330,6 +336,7 @@ fn encode_read_only_within(doc: &Document, n: &Node, symbols: &SymbolBoxes, left
|
||||
if let Some(q) = n.image_quad() {
|
||||
o["corners"] = json!(q.map(|p| [p.x, p.y]));
|
||||
}
|
||||
o["opacity"] = json!(n.opacity);
|
||||
o["pixelSize"] = json!([im.width, im.height]);
|
||||
o["colorMode"] = json!(doc.image_blob(im).map_or("unknown", color_mode));
|
||||
o["linked"] = json!(im.link.is_some());
|
||||
@@ -670,6 +677,15 @@ fn decode_paint(v: &Value, at: &str) -> Result<Paint> {
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// An object's name from plug-in output (`null`: no name), without control characters and at most
|
||||
/// 256 of them.
|
||||
fn decode_name(n: &Value, at: &str) -> Result<String> {
|
||||
Ok(match n {
|
||||
Value::Null => String::new(),
|
||||
n => n.as_str().ok_or_else(|| out_err(at, "`name` must be a string"))?.chars().filter(|c| !c.is_control()).take(256).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
fn opt<'a>(o: &'a serde_json::Map<String, Value>, key: &str) -> Option<&'a Value> {
|
||||
o.get(key).filter(|v| !v.is_null())
|
||||
}
|
||||
@@ -691,11 +707,7 @@ fn decode_object(v: &Value, at: &str, anchors: &mut usize) -> Result<OutObject>
|
||||
});
|
||||
}
|
||||
if let Some(n) = o.get("name") {
|
||||
let name = match n {
|
||||
Value::Null => String::new(),
|
||||
n => n.as_str().ok_or_else(|| out_err(at, "`name` must be a string"))?.chars().filter(|c| !c.is_control()).take(256).collect(),
|
||||
};
|
||||
out.name = Some(name);
|
||||
out.name = Some(decode_name(n, at)?);
|
||||
}
|
||||
if let Some(p) = opt(o, "path") {
|
||||
out.path = Some(decode_path(p, &format!("{at}.path"), anchors)?);
|
||||
@@ -794,10 +806,12 @@ pub struct Output {
|
||||
/// (what the plug-in keeps stays as it is), `Some(None)` for `null` (it forgets it), else what
|
||||
/// it keeps from now on, at most [`MAX_DOCUMENT_DATA`] bytes of JSON.
|
||||
pub document_data: Option<Option<Value>>,
|
||||
/// `notice`, the run's report for the status bar, as [`decode_notice`] reads it.
|
||||
pub notice: Option<String>,
|
||||
}
|
||||
|
||||
/// Parses a filter's output: `{"objects": [...], "documentData"?: …}`, or `{"error": "message"}`
|
||||
/// when the plug-in declined (the message reaches the user).
|
||||
/// Parses a filter's output: `{"objects": [...], "documentData"?: …, "notice"?: "…"}`, or
|
||||
/// `{"error": "message"}` when the plug-in declined (the message reaches the user).
|
||||
pub fn decode_output(bytes: &[u8]) -> Result<Output> {
|
||||
decode_output_with(bytes, &[], &HashMap::new())
|
||||
}
|
||||
@@ -809,8 +823,18 @@ pub fn decode_output(bytes: &[u8]) -> Result<Output> {
|
||||
/// differs, before anything changes. Each object is parsed from `input` only to compare it, one at
|
||||
/// a time, and an object that can't be read from there is an error.
|
||||
pub fn decode_output_with(bytes: &[u8], input: &[u8], read_only: &ReadOnlySpans) -> Result<Output> {
|
||||
decode_output_writing(bytes, input, read_only, &[])
|
||||
}
|
||||
|
||||
/// [`decode_output_with`] for a filter that may change the objects of kinds `writes` among them
|
||||
/// (its manifest's `writes`): such an object is still listed exactly once, and an entry for it may
|
||||
/// leave fields out, which keep their values, and give its name, its transform, and type's
|
||||
/// `text.runs` and `text.paragraphs`, an image's `opacity` or an instance's `symbolId` changed.
|
||||
/// Such an entry is [`OutObject::edit`] with the fields it changes; one that changes nothing is
|
||||
/// [`OutObject::kept`]. Any other field must be as given, and the error names the first that isn't.
|
||||
pub fn decode_output_writing(bytes: &[u8], input: &[u8], read_only: &ReadOnlySpans, writes: &[InputKind]) -> Result<Output> {
|
||||
let mut v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?;
|
||||
let objects = decode_objects(&v, input, read_only)?;
|
||||
let objects = decode_objects(&v, input, read_only, writes)?;
|
||||
let document_data = match v.get_mut("documentData").map(Value::take) {
|
||||
None => None,
|
||||
Some(Value::Null) => Some(None),
|
||||
@@ -822,19 +846,82 @@ pub fn decode_output_with(bytes: &[u8], input: &[u8], read_only: &ReadOnlySpans)
|
||||
Some(Some(data))
|
||||
}
|
||||
};
|
||||
Ok(Output { objects, document_data })
|
||||
let notice = decode_notice(&v)?;
|
||||
Ok(Output { objects, document_data, notice })
|
||||
}
|
||||
|
||||
/// The `notice` of output `v`: `None` when it has none (or `null`), else its text without the
|
||||
/// white space around it, as [`crate::permissions::display_text`] shows plug-in text (control,
|
||||
/// bidirectional formatting and separator characters escaped) and at most [`MAX_NOTICE_CHARS`]
|
||||
/// characters. A `notice` that is not a string, or whose shown part has no character besides white
|
||||
/// space, control characters and the default-ignorable characters the host does not escape, is an
|
||||
/// error.
|
||||
pub fn decode_notice(v: &Value) -> Result<Option<String>> {
|
||||
match v.get("notice") {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(s)) if shown_part_is_visible(s.trim()) => Ok(Some(crate::permissions::display_text(s.trim(), MAX_NOTICE_CHARS))),
|
||||
Some(_) => Err(Error::Output("`notice` must be a string with visible text".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Does the part of notice `s` that [`crate::permissions::display_text`] keeps within
|
||||
/// [`MAX_NOTICE_CHARS`], escapes counted and room left for the `…` when it cuts, hold a character
|
||||
/// that draws something?
|
||||
fn shown_part_is_visible(s: &str) -> bool {
|
||||
let shows = |c: char| !c.is_whitespace() && !c.is_control() && !draws_nothing(c);
|
||||
let width = |c: char| crate::permissions::display_text(c.encode_utf8(&mut [0; 4]), usize::MAX).chars().count();
|
||||
// Characters written through the end of `c`, and through the first visible character.
|
||||
let mut used = 0;
|
||||
let mut visible_by = None;
|
||||
for c in s.chars() {
|
||||
used += width(c);
|
||||
if visible_by.is_none() && shows(c) {
|
||||
visible_by = Some(used);
|
||||
}
|
||||
if used > MAX_NOTICE_CHARS {
|
||||
break;
|
||||
}
|
||||
}
|
||||
visible_by.is_some_and(|end| used <= MAX_NOTICE_CHARS || end < MAX_NOTICE_CHARS)
|
||||
}
|
||||
|
||||
/// Is `c` one of Unicode's default-ignorable characters (soft hyphen, zero-width and invisible
|
||||
/// characters, fillers, variation selectors, tags) that [`crate::permissions::display_text`] keeps
|
||||
/// as it is, so it draws nothing? The bidirectional ones it escapes are not among them.
|
||||
fn draws_nothing(c: char) -> bool {
|
||||
matches!(
|
||||
c,
|
||||
'\u{00AD}'
|
||||
| '\u{034F}'
|
||||
| '\u{115F}'
|
||||
| '\u{1160}'
|
||||
| '\u{17B4}'
|
||||
| '\u{17B5}'
|
||||
| '\u{180B}'..='\u{180F}'
|
||||
| '\u{200B}'..='\u{200D}'
|
||||
| '\u{2060}'..='\u{2065}'
|
||||
| '\u{206A}'..='\u{206F}'
|
||||
| '\u{3164}'
|
||||
| '\u{FE00}'..='\u{FE0F}'
|
||||
| '\u{FEFF}'
|
||||
| '\u{FFA0}'
|
||||
| '\u{FFF0}'..='\u{FFF8}'
|
||||
| '\u{1BCA0}'..='\u{1BCA3}'
|
||||
| '\u{1D173}'..='\u{1D17A}'
|
||||
| '\u{E0000}'..='\u{E0FFF}'
|
||||
)
|
||||
}
|
||||
|
||||
/// Parses a plug-in's objects: `{"objects": [...]}`, or `{"error": "message"}` when the plug-in
|
||||
/// declined (the message reaches the user). A live effect's other keys don't matter.
|
||||
pub fn decode(bytes: &[u8]) -> Result<Vec<OutObject>> {
|
||||
let v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?;
|
||||
decode_objects(&v, &[], &HashMap::new())
|
||||
decode_objects(&v, &[], &HashMap::new(), &[])
|
||||
}
|
||||
|
||||
/// The objects of output `v`, or its decline; entries for `read_only` objects as
|
||||
/// [`decode_output_with`] reads them.
|
||||
fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans) -> Result<Vec<OutObject>> {
|
||||
/// [`decode_output_writing`] reads them, those of kinds `writes` changeable.
|
||||
fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans, writes: &[InputKind]) -> Result<Vec<OutObject>> {
|
||||
if let Some(e) = declined(v) {
|
||||
return Err(e);
|
||||
}
|
||||
@@ -843,6 +930,8 @@ fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans) -> Result<
|
||||
return Err(Error::Output(format!("{} objects (limit {MAX_OBJECTS})", objects.len())));
|
||||
}
|
||||
let mut anchors = 0;
|
||||
// Bytes of type text the output writes, over all its objects.
|
||||
let mut text = 0;
|
||||
let mut returned: HashSet<NodeId> = HashSet::new();
|
||||
let out = objects
|
||||
.iter()
|
||||
@@ -853,12 +942,19 @@ fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans) -> Result<
|
||||
if !returned.insert(id) {
|
||||
return Err(out_err(&at, "is listed twice"));
|
||||
}
|
||||
let kept = OutObject { id: Some(id), kept: true, ..OutObject::default() };
|
||||
// `{"id": …}` alone keeps the object, so there is nothing to compare it with.
|
||||
if o.as_object().is_none_or(|m| m.len() != 1) {
|
||||
let given = serde_json::from_slice(input.get(span.clone()).unwrap_or_default()).map_err(|e| Error::Io(e.to_string()))?;
|
||||
let Some(entry) = o.as_object().filter(|m| m.len() != 1) else { return Ok(kept) };
|
||||
let given: Value = serde_json::from_slice(input.get(span.clone()).unwrap_or_default()).map_err(|e| Error::Io(e.to_string()))?;
|
||||
let kind = given.get("type").and_then(Value::as_str).and_then(InputKind::parse).filter(|k| writes.contains(k));
|
||||
let Some(kind) = kind else {
|
||||
check_unchanged(o, &given, &at)?;
|
||||
}
|
||||
Ok(OutObject { id: Some(id), kept: true, ..OutObject::default() })
|
||||
return Ok(kept);
|
||||
};
|
||||
Ok(match writes::changes(entry, &given, kind, &at, &mut text)? {
|
||||
Some(edit) => OutObject { id: Some(id), edit: Some(edit), ..OutObject::default() },
|
||||
None => kept,
|
||||
})
|
||||
}
|
||||
None => decode_object(o, &format!("objects[{i}]"), &mut anchors),
|
||||
})
|
||||
@@ -884,28 +980,40 @@ fn output_id(o: &Value) -> Option<NodeId> {
|
||||
/// numbers compared by value. Otherwise the error names the first field that differs
|
||||
/// (`text.runs[0].text`): a field the entry gives before one it leaves out, shown as
|
||||
/// [`crate::permissions::display_text`] shows a manifest string, since the entry's keys are the
|
||||
/// plug-in's.
|
||||
/// plug-in's. An image's `opacity`, which filters are given from plug-in API level 3, may be left
|
||||
/// out, so an entry that a filter built for level 2 writes as it was given there still matches.
|
||||
fn check_unchanged(o: &Value, given: &Value, at: &str) -> Result<()> {
|
||||
let changed = match (o, given) {
|
||||
(Value::Object(x), Value::Object(y)) => {
|
||||
let mut keys: Vec<&String> = x.keys().collect();
|
||||
keys.sort();
|
||||
keys.into_iter().find_map(|k| match y.get(k) {
|
||||
Some(q) => first_difference(&x[k], q, k),
|
||||
None => Some(k.clone()),
|
||||
})
|
||||
keys.into_iter()
|
||||
.find_map(|k| match y.get(k) {
|
||||
Some(q) => first_difference(&x[k], q, k),
|
||||
None => Some(k.clone()),
|
||||
})
|
||||
.or_else(|| {
|
||||
let image = y.get("type").and_then(Value::as_str) == Some(InputKind::Image.name());
|
||||
let mut missing: Vec<&String> = y.keys().filter(|k| !x.contains_key(*k) && !(image && *k == "opacity")).collect();
|
||||
missing.sort();
|
||||
missing.first().map(|k| (*k).clone())
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
_ => first_difference(o, given, ""),
|
||||
};
|
||||
match changed.or_else(|| first_difference(o, given, "")) {
|
||||
match changed {
|
||||
None => Ok(()),
|
||||
Some(field) => {
|
||||
let field = crate::permissions::display_text(&field, crate::permissions::MAX_SHOWN_FIELD);
|
||||
Err(out_err(at, format!("read-only field '{field}' changed")))
|
||||
}
|
||||
Some(field) => Err(read_only_changed(at, &field)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The error for an entry at `at` that changes read-only `field`, which is shown as
|
||||
/// [`crate::permissions::display_text`] shows a manifest string.
|
||||
fn read_only_changed(at: &str, field: &str) -> Error {
|
||||
let field = crate::permissions::display_text(field, crate::permissions::MAX_SHOWN_FIELD);
|
||||
out_err(at, format!("read-only field '{field}' changed"))
|
||||
}
|
||||
|
||||
/// The path of the first place `a` and `b` differ (`""`: they differ as a whole), `None` when they
|
||||
/// are the same JSON with numbers compared by value.
|
||||
fn first_difference(a: &Value, b: &Value, at: &str) -> Option<String> {
|
||||
@@ -1031,12 +1139,40 @@ fn members(doc: &mut Document, old: &[Arc<Node>], path: PathData) -> Vec<Arc<Nod
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether `returned`, a path from plug-in output, is `current` as it was: output has its empty
|
||||
/// subpaths dropped, so `current`'s are left out of the comparison.
|
||||
fn same_geometry(returned: &PathData, current: &PathData) -> bool {
|
||||
returned.subpaths.iter().eq(current.subpaths.iter().filter(|sp| !sp.anchors.is_empty()))
|
||||
}
|
||||
|
||||
/// Refuses an output that replaces the members of compound path `n` while one of them isn't a path
|
||||
/// (plug-ins aren't given its geometry), or is hidden, locked or (unless the output sets `guide`) a
|
||||
/// guide.
|
||||
fn check_members_replaceable(n: &Node, children: &[Arc<Node>], sets_guide: bool, at: &str) -> Result<()> {
|
||||
let id = n.id.0;
|
||||
if children.iter().any(|c| c.path_data().is_none()) {
|
||||
return Err(out_err(at, format!("compound path {id} has a member that isn't a path, so its members can't be replaced")));
|
||||
}
|
||||
if children.iter().any(|c| !c.visible || c.locked || (!sets_guide && is_guide(c))) {
|
||||
return Err(out_err(at, format!("compound path {id} has a hidden, locked or guide member, so its members can't be replaced")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes `o` into `n` (an input object, or a fresh node for a new one); its effect records once
|
||||
/// `admit` lets them in.
|
||||
fn write(doc: &mut Document, n: &mut Node, o: OutObject, at: &str, admit: AdmitEffects) -> Result<()> {
|
||||
let (cur_path, cur_rule, cur_compound) = geometry(n).unwrap_or((PathData::default(), FillRule::NonZero, false));
|
||||
let compound = o.compound.unwrap_or(cur_compound);
|
||||
let rule = o.rule.unwrap_or(cur_rule);
|
||||
// A compound path handed back with its path as it was keeps its members as they are.
|
||||
let same_members = cur_compound && o.path.as_ref().is_none_or(|p| same_geometry(p, &cur_path));
|
||||
if let NodeKind::Compound { children, .. } = &n.kind
|
||||
&& (!same_members || !compound)
|
||||
{
|
||||
let at = if compound { format!("{at}.path") } else { format!("{at}.type") };
|
||||
check_members_replaceable(n, children, o.guide.is_some(), &at)?;
|
||||
}
|
||||
match (&mut n.kind, compound) {
|
||||
(NodeKind::Path { path, rule: r, live, .. }, false) => {
|
||||
// A path handed back as it was stays the live shape it was.
|
||||
@@ -1047,7 +1183,7 @@ fn write(doc: &mut Document, n: &mut Node, o: OutObject, at: &str, admit: AdmitE
|
||||
*r = rule;
|
||||
}
|
||||
(NodeKind::Compound { children, rule: r }, true) => {
|
||||
if let Some(p) = o.path {
|
||||
if let Some(p) = o.path.filter(|_| !same_members) {
|
||||
*children = members(doc, children, p);
|
||||
}
|
||||
*r = rule;
|
||||
@@ -1233,7 +1369,9 @@ impl Plan {
|
||||
/// input object, just below the first one listed after them (at the first input object's place
|
||||
/// when the output keeps none; on top of `parent` when there were no inputs). Input objects missing
|
||||
/// from the output are deleted. An object's effect records replace its own once `admit` lets them
|
||||
/// in. Returns the resulting objects in output order (to select).
|
||||
/// in. Type, images and symbol instances stay as they are, or take the changes of their
|
||||
/// [`OutObject::edit`] once each value is checked. Returns the resulting objects in output order
|
||||
/// (to select).
|
||||
pub fn apply_output(doc: &mut Document, inputs: &[NodeId], out: Vec<OutObject>, parent: Option<NodeId>, admit: AdmitEffects) -> Result<Vec<NodeId>> {
|
||||
let wanted: HashSet<NodeId> = inputs.iter().copied().collect();
|
||||
let mut originals: HashMap<NodeId, Node> = HashMap::new();
|
||||
@@ -1258,12 +1396,15 @@ pub fn apply_output(doc: &mut Document, inputs: &[NodeId], out: Vec<OutObject>,
|
||||
out_err(&at, format!("{} is not the id of an input object", id.0))
|
||||
}
|
||||
})?;
|
||||
// Type, images and symbol instances are only read: writing one would make it a path.
|
||||
if input_kind(&n).is_some() && !o.kept {
|
||||
return Err(out_err(&at, format!("{} is read-only", id.0)));
|
||||
}
|
||||
// Type, images and symbol instances change only through the fields a filter that
|
||||
// may write them returns: writing one as a path would make it a path.
|
||||
let kept = o.kept;
|
||||
if !kept {
|
||||
if input_kind(&n).is_some() && !kept {
|
||||
let Some(edit) = &o.edit else { return Err(out_err(&at, format!("{} is read-only", id.0))) };
|
||||
writes::apply(doc, &mut n, edit, &format!("{at} (id {})", id.0))?;
|
||||
} else if o.edit.is_some() {
|
||||
return Err(out_err(&at, format!("{} is not type, an image or a symbol instance", id.0)));
|
||||
} else if !kept {
|
||||
write(doc, &mut n, o, &at, admit)?;
|
||||
}
|
||||
if !run.is_empty() {
|
||||
@@ -1320,5 +1461,7 @@ pub fn output_geometry(objects: Vec<OutObject>) -> PathData {
|
||||
PathData::new(objects.into_iter().filter_map(|o| o.path).flat_map(|p| p.subpaths).collect())
|
||||
}
|
||||
|
||||
mod writes;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1066,7 +1066,8 @@ fn a_changed_field_is_named_escaped_and_short() {
|
||||
}
|
||||
|
||||
/// A filter given read-only objects returns each one as `{"id": …}` or exactly as given (numbers by
|
||||
/// value), and they stay as they are, new objects listed after one going just above it. Any change,
|
||||
/// value; an image may leave out its `opacity`), and they stay as they are, new objects listed
|
||||
/// after one going just above it. Any change,
|
||||
/// an object left out or listed twice, and a new object of such a kind are refused before anything
|
||||
/// changes.
|
||||
#[test]
|
||||
@@ -1087,6 +1088,14 @@ fn read_only_kind_field_and_omission_refuse() {
|
||||
let mut echo = input.clone();
|
||||
echo["objects"][3]["transform"] = json!([1, 0, 0, 1, 5, 50]);
|
||||
assert!(decode_output_with(echo.to_string().as_bytes(), &bytes, &read_only).is_ok());
|
||||
// An image without `opacity`, as plug-in API level 2 gave it, is the image as given.
|
||||
let mut echo = input.clone();
|
||||
for i in [4, 5] {
|
||||
assert_eq!(echo["objects"][i]["type"], json!("image"));
|
||||
echo["objects"][i].as_object_mut().unwrap().remove("opacity");
|
||||
}
|
||||
let out = decode_output_with(echo.to_string().as_bytes(), &bytes, &read_only).unwrap();
|
||||
assert_eq!(out.objects.iter().filter(|o| o.kept).count(), 5);
|
||||
// So is an id written as a float; a fractional one names no object.
|
||||
let id = input["objects"][3]["id"].as_u64().unwrap();
|
||||
let mut echo = input.clone();
|
||||
@@ -1151,6 +1160,486 @@ fn read_only_kind_field_and_omission_refuse() {
|
||||
assert_eq!(d, before);
|
||||
}
|
||||
|
||||
/// [`mixed`] with a second symbol, "Moon", and its targets and input for a filter that reads and may
|
||||
/// change every kind.
|
||||
fn writable() -> (Document, Vec<NodeId>, Vec<u8>, ReadOnlySpans, [NodeId; 5]) {
|
||||
let (mut d, _, layer, extra) = mixed();
|
||||
let art = Arc::new(Node::path(d.alloc_id(), square(5.0), Appearance::default()));
|
||||
d.symbols.push(vectorcraft_doc::Symbol { name: "Moon".into(), art, dynamic: false });
|
||||
let targets = filter_targets_with(&d, &[layer], &InputKind::ALL);
|
||||
let (bytes, read_only) = encode_input_with(&d, &targets, &InputKind::ALL, usize::MAX).unwrap();
|
||||
(d, targets, bytes, read_only, extra)
|
||||
}
|
||||
|
||||
/// Decodes `out` for [`writable`]'s input with `writes` and applies it to `d`.
|
||||
fn write_out(
|
||||
d: &mut Document,
|
||||
targets: &[NodeId],
|
||||
bytes: &[u8],
|
||||
read_only: &ReadOnlySpans,
|
||||
writes: &[InputKind],
|
||||
out: &Value,
|
||||
) -> Result<Vec<NodeId>> {
|
||||
let out = decode_output_writing(out.to_string().as_bytes(), bytes, read_only, writes)?;
|
||||
apply_output(d, targets, out.objects, None, &keep)
|
||||
}
|
||||
|
||||
/// A filter that may write type, images and symbol instances changes type's runs and character
|
||||
/// attributes, an image's transform and opacity, and the symbol and transform of an instance,
|
||||
/// with entries that give only the fields they change. What it writes reads back the same. An
|
||||
/// exact echo, `{"id": …}` alone and fields given as they were (numbers by value) change nothing.
|
||||
#[test]
|
||||
fn writable_kinds_take_type_runs_image_placement_and_instance_symbols() {
|
||||
use vectorcraft_doc::{CharStyle, ParaStyle};
|
||||
let (mut d, targets, bytes, read_only, [text, embedded, linked, star, ghost]) = writable();
|
||||
let before = d.clone();
|
||||
let all = &InputKind::ALL;
|
||||
let echo = decode_output_writing(&bytes, &bytes, &read_only, all).unwrap();
|
||||
assert!(echo.objects.iter().all(|o| o.edit.is_none()));
|
||||
apply_output(&mut d, &targets, echo.objects, None, &keep).unwrap();
|
||||
assert_eq!(d, before, "an exact echo changes nothing");
|
||||
let ro = |id: NodeId| json!({"id": id.0});
|
||||
let paths: Vec<Value> = targets.iter().filter(|id| !read_only.contains_key(id)).map(|id| ro(*id)).collect();
|
||||
let with = |entries: Vec<Value>| {
|
||||
let objects = [paths.clone(), entries].concat();
|
||||
json!({ "objects": objects })
|
||||
};
|
||||
let same = with(vec![
|
||||
json!({"id": text.0, "transform": [1, 0, 0, 1, 5, 50], "name": "T"}),
|
||||
json!({"id": embedded.0, "opacity": 1}),
|
||||
ro(linked),
|
||||
json!({"id": star.0, "symbolId": "Star"}),
|
||||
ro(ghost),
|
||||
]);
|
||||
let out = decode_output_writing(same.to_string().as_bytes(), &bytes, &read_only, all).unwrap();
|
||||
assert!(out.objects.iter().all(|o| o.edit.is_none()));
|
||||
assert_eq!(out.objects.iter().filter(|o| o.kept).count(), 5, "fields given as they were change nothing");
|
||||
// The changes, each entry giving only what it changes.
|
||||
let big = CharStyle { size: 24.0, ..CharStyle::default() };
|
||||
let runs = json!([{"text": "Bye\n", "style": CharStyle::default()}, {"text": "now", "style": big}]);
|
||||
let out = with(vec![
|
||||
json!({"id": text.0, "name": "Renamed", "text": {"runs": runs}}),
|
||||
json!({"id": embedded.0, "transform": [1, 0, 0, 1, 10, 20], "opacity": 0.5}),
|
||||
ro(linked),
|
||||
json!({"id": star.0, "symbolId": "Moon", "transform": [1, 0, 0, 1, 50, 0]}),
|
||||
ro(ghost),
|
||||
]);
|
||||
let made = write_out(&mut d, &targets, &bytes, &read_only, all, &out).unwrap();
|
||||
assert_eq!(made.len(), targets.len());
|
||||
let node = |id: NodeId| d.node(id).unwrap().clone();
|
||||
let NodeKind::Text(t) = &node(text).kind else { panic!("type") };
|
||||
assert_eq!((t.plain_text().as_str(), t.runs[1].style.size), ("Bye\nnow", 24.0));
|
||||
assert_eq!(t.para_at(1).space_before, 6.0, "paragraphs keep their styles");
|
||||
assert_eq!(t.para_at(0), &ParaStyle::default());
|
||||
assert_eq!(node(text).name.as_deref(), Some("Renamed"));
|
||||
let NodeKind::Image(im) = &node(embedded).kind else { panic!("image") };
|
||||
assert_eq!((im.xf, node(embedded).opacity), (Affine::new([1.0, 0.0, 0.0, 1.0, 10.0, 20.0]), 0.5));
|
||||
assert_eq!(node(star).kind, NodeKind::SymbolInstance { symbol: "Moon".into(), xf: Affine::translate((50.0, 0.0)) });
|
||||
for id in [linked, ghost] {
|
||||
assert_eq!(d.node(id), before.node(id), "objects returned by id stay as they were");
|
||||
}
|
||||
// Read again, the changed objects give what was written.
|
||||
let read = |id: NodeId| encode_read_only(&d, d.node(id).unwrap()).unwrap();
|
||||
assert_eq!(read(text)["text"]["runs"], runs);
|
||||
assert_eq!((&read(embedded)["transform"], &read(embedded)["opacity"]), (&json!([1.0, 0.0, 0.0, 1.0, 10.0, 20.0]), &json!(0.5)));
|
||||
assert_eq!((&read(star)["symbolId"], &read(star)["transform"]), (&json!("Moon"), &json!([1.0, 0.0, 0.0, 1.0, 50.0, 0.0])));
|
||||
assert!(read(star).get("missing").is_none());
|
||||
// An instance of a symbol the document lacks can point to one it has.
|
||||
let mut d = before.clone();
|
||||
let out = with(vec![ro(text), ro(embedded), ro(linked), ro(star), json!({"id": ghost.0, "symbolId": "Star"})]);
|
||||
write_out(&mut d, &targets, &bytes, &read_only, all, &out).unwrap();
|
||||
assert!(matches!(&d.node(ghost).unwrap().kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Star"));
|
||||
}
|
||||
|
||||
/// An entry that changes a field its kind can't change, a kind the manifest doesn't list in
|
||||
/// `writes`, or gives a value out of range is refused naming the object and the field, before
|
||||
/// anything changes.
|
||||
#[test]
|
||||
fn bad_writes_are_refused_naming_the_object_and_the_field() {
|
||||
use vectorcraft_doc::CharStyle;
|
||||
let (d, targets, bytes, read_only, [text, embedded, linked, star, ghost]) = writable();
|
||||
let input: Value = serde_json::from_slice(&bytes).unwrap();
|
||||
let at = |id: NodeId| input["objects"].as_array().unwrap().iter().position(|o| o["id"] == json!(id.0)).unwrap();
|
||||
let style = serde_json::to_value(CharStyle::default()).unwrap();
|
||||
let styled = |f: &dyn Fn(&mut Value)| {
|
||||
let mut s = style.clone();
|
||||
f(&mut s);
|
||||
json!([{"text": "Hi\nthere", "style": s}])
|
||||
};
|
||||
let (t, e, l, s) = (text.0, embedded.0, linked.0, star.0);
|
||||
let (ti, ei, si) = (at(text), at(embedded), at(star));
|
||||
let cases: Vec<(NodeId, Value, &[InputKind], String)> = vec![
|
||||
(text, json!({"text": {"kind": "area"}}), &InputKind::ALL, format!("objects[{ti}] (id {t}): read-only field 'text.kind' changed")),
|
||||
(text, json!({"text": {"x": 1}}), &InputKind::ALL, format!("(id {t}): read-only field 'text.x' changed")),
|
||||
(text, json!({"bounds": [0, 0, 1, 1]}), &InputKind::ALL, format!("(id {t}): read-only field 'bounds[0]' changed")),
|
||||
(text, json!({"opacity": 0.5}), &InputKind::ALL, format!("(id {t}): read-only field 'opacity' changed")),
|
||||
(text, json!({"text": {"runs": []}}), &InputKind::ALL, "text.runs: type needs at least one run".into()),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["fontSzie"] = json!(9))}}),
|
||||
&InputKind::ALL,
|
||||
"text.runs[0].style: unknown key 'fontSzie'".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["size"] = json!(5000))}}),
|
||||
&InputKind::ALL,
|
||||
"text.runs[0].style.size: `size` must be from 0.1 to 1296".into(),
|
||||
),
|
||||
(text, json!({"text": {"runs": styled(&|s| s["size"] = json!("big"))}}), &InputKind::ALL, "text.runs[0].style:".into()),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["font_family"] = json!(" "))}}),
|
||||
&InputKind::ALL,
|
||||
"font_family: must be 1-256 printable characters".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["font_family"] = json!(format!(" {}", "a".repeat(256))))}}),
|
||||
&InputKind::ALL,
|
||||
"font_family: must be 1-256 printable characters".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["fill"] = json!({"type": "solid", "color": s["fill"]["color"], "tintt": 0.5}))}}),
|
||||
&InputKind::ALL,
|
||||
"text.runs[0].style.fill: unknown key 'tintt'".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["stroke"] = json!({"type": "none", "pattern": "Dots"}))}}),
|
||||
&InputKind::ALL,
|
||||
"text.runs[0].style.stroke: unknown key 'pattern'".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": [{"text": "A\nB\nC", "style": style}], "paragraphs": input["objects"][at(text)]["text"]["paragraphs"]}}),
|
||||
&InputKind::ALL,
|
||||
"text.paragraphs: expected 3 paragraph styles, one per paragraph".into(),
|
||||
),
|
||||
(text, json!({"text": {"runs": [{"text": "Hi", "style": style, "color": 1}]}}), &InputKind::ALL, "text.runs[0]: unknown key 'color'".into()),
|
||||
(text, json!({"text": 5}), &InputKind::ALL, format!("objects[{ti}] (id {t}): `text` must be an object")),
|
||||
(text, json!({"text": {"runs": [{"text": 5, "style": style}]}}), &InputKind::ALL, "text.runs[0]: `text` must be a string".into()),
|
||||
(text, json!({"text": {"runs": [{"text": "Hi", "style": 5}]}}), &InputKind::ALL, "text.runs[0]: `style` must be an object".into()),
|
||||
(text, json!({"text": {"paragraphs": [5, {}]}}), &InputKind::ALL, "text: `paragraphs[0]` must be an object".into()),
|
||||
(text, json!({"text": {"paragraphs": [{"spaceBefor": 1}, {}]}}), &InputKind::ALL, "text.paragraphs[0]: unknown key 'spaceBefor'".into()),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"paragraphs": [{"hyphenation": {"wordLongerThen": 3}}, {}]}}),
|
||||
&InputKind::ALL,
|
||||
"text.paragraphs[0].hyphenation: unknown key 'wordLongerThen'".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"paragraphs": [{"justification": {"wordSpacng": [80, 100, 133]}}, {}]}}),
|
||||
&InputKind::ALL,
|
||||
"text.paragraphs[0].justification: unknown key 'wordSpacng'".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"paragraphs": [{}, {"tabs": [{"position": 36}, {"position": 72, "aling": "center"}]}]}}),
|
||||
&InputKind::ALL,
|
||||
"text.paragraphs[1].tabs[1]: unknown key 'aling'".into(),
|
||||
),
|
||||
(text, json!({"text": {"paragraphs": [{"list": {"levl": 2}}, {}]}}), &InputKind::ALL, "text.paragraphs[0].list: unknown key 'levl'".into()),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["stroke_dash"] = json!({"pattern": [2, 2], "ofset": 1}))}}),
|
||||
&InputKind::ALL,
|
||||
"text.runs[0].style.stroke_dash: unknown key 'ofset'".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": [{"text": "Hi\u{FFFC}", "style": style}]}}),
|
||||
&InputKind::ALL,
|
||||
"holds the character of an inline graphic".into(),
|
||||
),
|
||||
(text, json!({"text": {"paragraphs": [{}]}}), &InputKind::ALL, "text.paragraphs: expected 2 paragraph styles, one per paragraph".into()),
|
||||
(text, json!({"transform": [1, 0, 0, 0, 0, 0]}), &InputKind::ALL, format!("objects[{ti}] (id {t}).transform: flattens the object")),
|
||||
(text, json!({"transform": [1, 0, 0, 1, 1e9, 0]}), &InputKind::ALL, "transform: a number is out of range".into()),
|
||||
(text, json!({"transform": [1, 0, null, 0, 1, 10, 20]}), &InputKind::ALL, "transform: must be a list of 6 numbers".into()),
|
||||
(text, json!({"transform": [1, 0, 0, 1, 10]}), &InputKind::ALL, "transform: must be a list of 6 numbers".into()),
|
||||
(text, json!({"transform": [1, 0, 0, 1]}), &InputKind::ALL, "transform: must be a list of 6 numbers".into()),
|
||||
(embedded, json!({"pixelSize": [3, 1]}), &InputKind::ALL, format!("(id {e}): read-only field 'pixelSize[0]' changed")),
|
||||
(embedded, json!({"opacity": 2}), &InputKind::ALL, format!("objects[{ei}] (id {e}).opacity: must be a number from 0 to 1")),
|
||||
(embedded, json!({"opacity": "half"}), &InputKind::ALL, "opacity: must be a number from 0 to 1".into()),
|
||||
(linked, json!({"linked": false}), &InputKind::ALL, format!("(id {l}): read-only field 'linked' changed")),
|
||||
(embedded, json!({"opacity": 0.5}), &[InputKind::Type, InputKind::SymbolInstance], format!("(id {e}): read-only field 'opacity' changed")),
|
||||
(
|
||||
star,
|
||||
json!({"symbolId": "Nowhere"}),
|
||||
&InputKind::ALL,
|
||||
format!("objects[{si}] (id {s}).symbolId: 'Nowhere' is not a symbol in this document"),
|
||||
),
|
||||
(star, json!({"symbolId": 7}), &InputKind::ALL, "symbolId: must be the name of a symbol".into()),
|
||||
(star, json!({"overrides": {"a": 1}}), &InputKind::ALL, format!("(id {s}): read-only field 'overrides.a' changed")),
|
||||
(ghost, json!({"missing": false}), &InputKind::ALL, "read-only field 'missing' changed".into()),
|
||||
(star, json!({"symbolId": "Moon"}), &[InputKind::Type], format!("(id {s}): read-only field 'symbolId' changed")),
|
||||
];
|
||||
for (id, entry, writes, says) in cases {
|
||||
let mut out = input.clone();
|
||||
let mut e = entry.clone();
|
||||
e["id"] = json!(id.0);
|
||||
out["objects"][at(id)] = e;
|
||||
let mut doc = d.clone();
|
||||
let err = write_out(&mut doc, &targets, &bytes, &read_only, writes, &out).unwrap_err().to_string();
|
||||
assert!(err.contains(&says), "{entry}: {says}: {err}");
|
||||
assert_eq!(doc, d, "{entry}: nothing changed");
|
||||
}
|
||||
// Leaving a writable object out is still refused: it isn't deleted.
|
||||
let mut out = input.clone();
|
||||
out["objects"].as_array_mut().unwrap().remove(at(star));
|
||||
let e = write_out(&mut d.clone(), &targets, &bytes, &read_only, &InputKind::ALL, &out).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("objects (id {s}): a read-only object was left out")), "{e}");
|
||||
}
|
||||
|
||||
/// The text a filter writes to one type object is held to [`MAX_INPUT_TEXT`] bytes and
|
||||
/// [`MAX_INPUT_RUNS`] runs and paragraphs, as the text it is given; type given as `truncated`
|
||||
/// keeps its text, though it can still move.
|
||||
#[test]
|
||||
fn written_text_is_held_to_the_input_limits_and_truncated_type_keeps_its_text() {
|
||||
use vectorcraft_doc::{CharStyle, TextObject};
|
||||
let (mut d, _, layer, [text, ..]) = mixed();
|
||||
let long = Node::new(
|
||||
d.alloc_id(),
|
||||
NodeKind::Text(Box::new(TextObject::point(Point::new(0.0, 0.0), &"x".repeat(MAX_INPUT_TEXT + 1), CharStyle::default()))),
|
||||
);
|
||||
let long = d.insert(Some(layer), usize::MAX, long).unwrap();
|
||||
let targets = filter_targets_with(&d, &[layer], &[InputKind::Type]);
|
||||
let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap();
|
||||
let input: Value = serde_json::from_slice(&bytes).unwrap();
|
||||
let at = |id: NodeId| input["objects"].as_array().unwrap().iter().position(|o| o["id"] == json!(id.0)).unwrap();
|
||||
assert_eq!(input["objects"][at(long)]["truncated"], json!(true));
|
||||
let style = serde_json::to_value(CharStyle::default()).unwrap();
|
||||
let run = |s: String| json!({"text": s, "style": style});
|
||||
let writes = &[InputKind::Type];
|
||||
for (id, text_v, says) in [
|
||||
(text, json!({"runs": [run("x".repeat(MAX_INPUT_TEXT + 1))]}), format!("bytes of text (limit {MAX_INPUT_TEXT})")),
|
||||
(text, json!({"runs": vec![run("x".into()); MAX_INPUT_RUNS + 1]}), format!("must be a list of at most {MAX_INPUT_RUNS} entries")),
|
||||
(text, json!({"runs": [run("\n".repeat(MAX_INPUT_RUNS))]}), format!("{} paragraphs (limit {MAX_INPUT_RUNS})", MAX_INPUT_RUNS + 1)),
|
||||
(text, json!({"paragraphs": vec![json!({}); MAX_INPUT_RUNS + 1]}), format!("must be a list of at most {MAX_INPUT_RUNS} entries")),
|
||||
(long, json!({"runs": [run("short".into())]}), "the text of type given as `truncated` can't be changed".to_string()),
|
||||
] {
|
||||
let mut out = input.clone();
|
||||
out["objects"][at(id)] = json!({"id": id.0, "text": text_v});
|
||||
let mut doc = d.clone();
|
||||
let e = write_out(&mut doc, &targets, &bytes, &read_only, writes, &out).unwrap_err().to_string();
|
||||
assert!(e.contains(&says), "{says}: {e}");
|
||||
assert_eq!(doc, d);
|
||||
}
|
||||
// At the limit the text is written; truncated type still moves.
|
||||
let mut out = input.clone();
|
||||
out["objects"][at(text)] = json!({"id": text.0, "text": {"runs": [run("x".repeat(MAX_INPUT_TEXT))]}});
|
||||
out["objects"][at(long)] = json!({"id": long.0, "transform": [1, 0, 0, 1, 3, 4]});
|
||||
write_out(&mut d, &targets, &bytes, &read_only, writes, &out).unwrap();
|
||||
assert!(matches!(&d.node(text).unwrap().kind, NodeKind::Text(t) if t.plain_text().len() == MAX_INPUT_TEXT));
|
||||
assert!(
|
||||
matches!(&d.node(long).unwrap().kind, NodeKind::Text(t) if t.xf == Affine::translate((3.0, 4.0)) && t.plain_text().len() == MAX_INPUT_TEXT + 1)
|
||||
);
|
||||
}
|
||||
|
||||
/// An inline graphic in type stays as it was, in its place among the inline graphics: the runs
|
||||
/// around it can change, and adding, removing or changing one is refused.
|
||||
#[test]
|
||||
fn inline_graphics_in_written_type_stay_as_they_were() {
|
||||
use vectorcraft_doc::{CharStyle, InlineArt, TextObject, TextRun};
|
||||
let (mut d, _, layer, _) = mixed();
|
||||
let mut t = TextObject::point(Point::new(0.0, 0.0), "A", CharStyle::default());
|
||||
t.runs = vec![
|
||||
TextRun::new("A", CharStyle::default()),
|
||||
TextRun::inline(InlineArt::new("Star"), CharStyle::default()),
|
||||
TextRun::new("B", CharStyle::default()),
|
||||
];
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
let id = d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
let targets = vec![id];
|
||||
let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap();
|
||||
let input: Value = serde_json::from_slice(&bytes).unwrap();
|
||||
let runs = input["objects"][0]["text"]["runs"].clone();
|
||||
let writes = &[InputKind::Type];
|
||||
let with = |runs: Value| json!({"objects": [{"id": id.0, "text": {"runs": runs}}]});
|
||||
let mut changed = runs.clone();
|
||||
changed[0]["text"] = json!("Before ");
|
||||
changed[2]["text"] = json!(" after");
|
||||
let mut doc = d.clone();
|
||||
write_out(&mut doc, &targets, &bytes, &read_only, writes, &with(changed)).unwrap();
|
||||
let NodeKind::Text(t) = &doc.node(id).unwrap().kind else { panic!("type") };
|
||||
assert_eq!(t.plain_text(), "Before \u{FFFC} after");
|
||||
assert_eq!(t.runs[1].inline.as_ref().map(|a| a.symbol.as_str()), Some("Star"));
|
||||
let mut moved = runs.clone();
|
||||
moved[1]["inline"]["symbol"] = json!("Moon");
|
||||
let without = json!([runs[0], runs[2]]);
|
||||
let doubled = json!([runs[0], runs[1], runs[1], runs[2]]);
|
||||
for bad in [moved, without, doubled] {
|
||||
let mut doc = d.clone();
|
||||
let e = write_out(&mut doc, &targets, &bytes, &read_only, writes, &with(bad.clone())).unwrap_err().to_string();
|
||||
assert!(e.contains("inline graphics can't be added, removed, reordered or changed"), "{bad}: {e}");
|
||||
assert_eq!(doc, d);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs written without `paragraphs` keep each paragraph's style when the number of paragraphs
|
||||
/// stays the same, and otherwise the styles follow the paragraphs' text: a paragraph whose text
|
||||
/// stays keeps its style, also when changes are made at two places, a paragraph added at the start
|
||||
/// takes the style of the next one and one added later the style of the one before it, and joining
|
||||
/// two paragraphs keeps the first one's style.
|
||||
#[test]
|
||||
fn written_runs_without_paragraphs_keep_each_paragraph_s_style() {
|
||||
use vectorcraft_doc::{CharStyle, Justify, ParaStyle, TextObject};
|
||||
let (mut d, _, layer, _) = mixed();
|
||||
let mut t = TextObject::point(Point::new(0.0, 0.0), "A\nB\nC", CharStyle::default());
|
||||
let styled = |justify| ParaStyle { justify, ..ParaStyle::default() };
|
||||
t.set_paragraph_styles(vec![styled(Justify::Left), styled(Justify::Center), styled(Justify::Right)]);
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
let id = d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
let targets = vec![id];
|
||||
let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap();
|
||||
let justified = |text: &str| {
|
||||
let out = json!({"objects": [{"id": id.0, "text": {"runs": [{"text": text, "style": CharStyle::default()}]}}]});
|
||||
let mut doc = d.clone();
|
||||
write_out(&mut doc, &targets, &bytes, &read_only, &[InputKind::Type], &out).unwrap();
|
||||
let NodeKind::Text(t) = &doc.node(id).unwrap().kind else { panic!("type") };
|
||||
assert_eq!(t.plain_text(), text);
|
||||
(0..t.paragraph_count()).map(|i| t.para_at(i).justify).collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(justified("X\nA\nB\nC"), [Justify::Left, Justify::Left, Justify::Center, Justify::Right]);
|
||||
assert_eq!(justified("A\nBé\nC"), [Justify::Left, Justify::Center, Justify::Right]);
|
||||
assert_eq!(justified("One\nTwo\nThree"), [Justify::Left, Justify::Center, Justify::Right]);
|
||||
assert_eq!(justified("AB\nC"), [Justify::Left, Justify::Right]);
|
||||
assert_eq!(justified("A\nB\nC\nD"), [Justify::Left, Justify::Center, Justify::Right, Justify::Right]);
|
||||
// Two separate changes: B and C keep their styles.
|
||||
assert_eq!(justified("X\nA\nB\nC\nY"), [Justify::Left, Justify::Left, Justify::Center, Justify::Right, Justify::Right]);
|
||||
assert_eq!(justified("A\nX\nB\nC\nY"), [Justify::Left, Justify::Left, Justify::Center, Justify::Right, Justify::Right]);
|
||||
// A changed paragraph takes the style of the one it replaces; the one added after it, that style.
|
||||
assert_eq!(justified("A\nB2\nB3\nC"), [Justify::Left, Justify::Center, Justify::Center, Justify::Right]);
|
||||
assert_eq!(justified("A2\nC"), [Justify::Left, Justify::Right]);
|
||||
}
|
||||
|
||||
/// A paragraph that a change adds next to a numbered one takes its style without the number, and
|
||||
/// the numbered paragraph keeps it.
|
||||
#[test]
|
||||
fn written_runs_give_an_added_paragraph_no_list_number() {
|
||||
use vectorcraft_doc::text::ParaList;
|
||||
use vectorcraft_doc::{CharStyle, ParaStyle, TextObject};
|
||||
let (mut d, _, layer, _) = mixed();
|
||||
let mut t = TextObject::point(Point::new(0.0, 0.0), "A\nB", CharStyle::default());
|
||||
let numbered = ParaStyle { list: Some(ParaList { start: Some(5), ..ParaList::default() }), ..ParaStyle::default() };
|
||||
t.set_paragraph_styles(vec![ParaStyle::default(), numbered]);
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
let id = d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
let targets = vec![id];
|
||||
let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap();
|
||||
let out = json!({"objects": [{"id": id.0, "text": {"runs": [{"text": "X\nA\nB\nY", "style": CharStyle::default()}]}}]});
|
||||
write_out(&mut d, &targets, &bytes, &read_only, &[InputKind::Type], &out).unwrap();
|
||||
let NodeKind::Text(t) = &d.node(id).unwrap().kind else { panic!("type") };
|
||||
let starts: Vec<_> = (0..t.paragraph_count()).map(|i| t.para_at(i).list.map(|l| l.start)).collect();
|
||||
assert_eq!(starts, [None, None, Some(Some(5)), Some(None)]);
|
||||
}
|
||||
|
||||
/// Past 262,144 pairs of old and new paragraphs to compare, the paragraphs are paired in order.
|
||||
#[test]
|
||||
fn written_runs_pair_paragraphs_in_order_past_the_compare_limit() {
|
||||
use vectorcraft_doc::{CharStyle, Justify, ParaStyle, TextObject};
|
||||
let (mut d, _, layer, _) = mixed();
|
||||
let paras: Vec<String> = (0..600).map(|i| format!("p{i}")).collect();
|
||||
let mut t = TextObject::point(Point::new(0.0, 0.0), ¶s.join("\n"), CharStyle::default());
|
||||
let styled = |i: usize| ParaStyle { justify: if i.is_multiple_of(2) { Justify::Left } else { Justify::Right }, ..ParaStyle::default() };
|
||||
t.set_paragraph_styles((0..600).map(styled).collect());
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
let id = d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
let targets = vec![id];
|
||||
let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap();
|
||||
// 600 old paragraphs times 602 new ones: none starts or ends both texts.
|
||||
let text = format!("X\n{}\nY", paras.join("\n"));
|
||||
let out = json!({"objects": [{"id": id.0, "text": {"runs": [{"text": text, "style": CharStyle::default()}]}}]});
|
||||
write_out(&mut d, &targets, &bytes, &read_only, &[InputKind::Type], &out).unwrap();
|
||||
let NodeKind::Text(t) = &d.node(id).unwrap().kind else { panic!("type") };
|
||||
assert_eq!(t.paragraph_count(), 602);
|
||||
let got: Vec<_> = (0..602).map(|i| t.para_at(i).justify).collect();
|
||||
let want: Vec<_> = (0..602).map(|i| styled(i.min(599)).justify).collect();
|
||||
assert_eq!(got, want);
|
||||
}
|
||||
|
||||
/// Every number in the character and paragraph styles a filter writes is checked against the range
|
||||
/// the style commands keep it to, in a style of the filter's own and in one the type already has,
|
||||
/// and a custom Kinsoku set must be one of the document's. Each bad value is refused naming the
|
||||
/// object and the field, and the document stays as it was. A set of the document's, given by
|
||||
/// name, takes the document's characters.
|
||||
#[test]
|
||||
fn written_style_numbers_are_checked_even_in_a_style_the_type_has() {
|
||||
use vectorcraft_doc::{CharStyle, KinsokuSet, ParaStyle, TabAlign, TabStop, TextObject};
|
||||
let (mut d, _, layer, _) = mixed();
|
||||
d.kinsoku_sets.push(KinsokuSet { name: "Mine".into(), cannot_start: vec!['、'], ..KinsokuSet::default() });
|
||||
let stop = TabStop { position: 10.0, align: TabAlign::Left, leader: String::new(), align_on: '.' };
|
||||
let outside = KinsokuSet { name: "Elsewhere".into(), ..KinsokuSet::default() };
|
||||
let bad_chars: [(&str, CharStyle, &str); 5] = [
|
||||
("leading 1e9", CharStyle { leading: Some(1e9), ..CharStyle::default() }, "style.leading: `leading` must be from 0.1 to 5000"),
|
||||
("scale 0", CharStyle { h_scale: 0.0, ..CharStyle::default() }, "style.h_scale: `h_scale` must be from 1 to 10000"),
|
||||
("baseline shift", CharStyle { baseline_shift: 1e9, ..CharStyle::default() }, "style.baseline_shift: `baseline_shift` must be from"),
|
||||
("tracking", CharStyle { tracking: -5000.0, ..CharStyle::default() }, "style.tracking: `tracking` must be from -1000 to 10000"),
|
||||
("aki", CharStyle { aki_left: 2000.0, ..CharStyle::default() }, "style.akiLeft: `akiLeft` must be from 0 to 1000"),
|
||||
];
|
||||
let hard = |set: KinsokuSet| ParaStyle { kinsoku: vectorcraft_doc::Kinsoku::Hard, kinsoku_set: Some(Arc::new(set)), ..ParaStyle::default() };
|
||||
let bad_paras: [(&str, ParaStyle, &str); 4] = [
|
||||
("100000 tabs", ParaStyle { tabs: vec![stop.clone(); 100_000], ..ParaStyle::default() }, "paragraphs[0].tabs: at most 256 tab stops"),
|
||||
("indent", ParaStyle { left_indent: 1e9, ..ParaStyle::default() }, "paragraphs[0].left_indent: `left_indent` must be from -1296 to 1296"),
|
||||
(
|
||||
"hyphenation",
|
||||
ParaStyle { hyphenation: vectorcraft_doc::HyphenationOptions { after_first: 0, ..Default::default() }, ..ParaStyle::default() },
|
||||
"paragraphs[0].hyphenation.after_first",
|
||||
),
|
||||
("unknown kinsoku set", hard(outside.clone()), "paragraphs[0].kinsoku_set: the document has no Kinsoku set named 'Elsewhere'"),
|
||||
];
|
||||
// `own`: the type already has the bad style, and the filter changes only its other run or
|
||||
// paragraph; otherwise the bad style is the filter's own.
|
||||
let run = |id: NodeId, own: bool, bad: &CharStyle| {
|
||||
let mut t = TextObject::point(Point::new(0.0, 0.0), "A\nB", CharStyle::default());
|
||||
if own {
|
||||
t.runs = vec![vectorcraft_doc::TextRun::new("A\n", bad.clone()), vectorcraft_doc::TextRun::new("B", CharStyle::default())];
|
||||
}
|
||||
let mut doc = d.clone();
|
||||
let n = Node::new(id, NodeKind::Text(Box::new(t)));
|
||||
let id = doc.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
(doc, id)
|
||||
};
|
||||
let check = |doc: &Document, id: NodeId, entry: Value, says: &str, what: &str| {
|
||||
let (bytes, read_only) = encode_input_with(doc, &[id], &[InputKind::Type], usize::MAX).unwrap();
|
||||
let mut entry = entry;
|
||||
entry["id"] = json!(id.0);
|
||||
let mut changed = doc.clone();
|
||||
let e = write_out(&mut changed, &[id], &bytes, &read_only, &[InputKind::Type], &json!({"objects": [entry]})).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("(id {}).text.", id.0)) && e.contains(says), "{what}: {says}: {e}");
|
||||
assert_eq!(&changed, doc, "{what}: nothing changed");
|
||||
};
|
||||
let fresh = d.clone().alloc_id();
|
||||
for (what, bad, says) in &bad_chars {
|
||||
let (doc, id) = run(fresh, false, bad);
|
||||
let runs = json!([{"text": "A\n", "style": bad}, {"text": "B", "style": CharStyle::default()}]);
|
||||
check(&doc, id, json!({"text": {"runs": runs}}), says, what);
|
||||
let (doc, id) = run(fresh, true, bad);
|
||||
let runs = json!([{"text": "A\n", "style": bad}, {"text": "Be", "style": CharStyle::default()}]);
|
||||
check(&doc, id, json!({"text": {"runs": runs}}), says, &format!("{what}, a style the type has"));
|
||||
}
|
||||
let centered = ParaStyle { justify: vectorcraft_doc::Justify::Center, ..ParaStyle::default() };
|
||||
for (what, bad, says) in &bad_paras {
|
||||
let (doc, id) = run(fresh, false, &CharStyle::default());
|
||||
check(&doc, id, json!({"text": {"paragraphs": [bad, ParaStyle::default()]}}), says, what);
|
||||
let mut doc = doc;
|
||||
if let Some(Node { kind: NodeKind::Text(t), .. }) = doc.node_mut(id) {
|
||||
t.set_paragraph_styles(vec![bad.clone(), ParaStyle::default()]);
|
||||
}
|
||||
check(&doc, id, json!({"text": {"paragraphs": [bad, centered]}}), says, &format!("{what}, a style the type has"));
|
||||
}
|
||||
// A set the document has, by name, takes the document's characters.
|
||||
let (mut doc, id) = run(fresh, false, &CharStyle::default());
|
||||
let (bytes, read_only) = encode_input_with(&doc, &[id], &[InputKind::Type], usize::MAX).unwrap();
|
||||
let named = hard(KinsokuSet { name: "Mine".into(), cannot_start: vec!['x'; 3], ..KinsokuSet::default() });
|
||||
let out = json!({"objects": [{"id": id.0, "text": {"paragraphs": [named, ParaStyle::default()]}}]});
|
||||
write_out(&mut doc, &[id], &bytes, &read_only, &[InputKind::Type], &out).unwrap();
|
||||
let NodeKind::Text(t) = &doc.node(id).unwrap().kind else { panic!("type") };
|
||||
assert_eq!(t.para_at(0).kinsoku_set.as_deref().map(|s| s.cannot_start.clone()), Some(vec!['、']));
|
||||
}
|
||||
|
||||
/// A filter's `documentData`: absent keeps what the plug-in keeps, `null` forgets it, any other JSON
|
||||
/// of at most [`MAX_DOCUMENT_DATA`] bytes is kept, and more refuses the whole output.
|
||||
#[test]
|
||||
@@ -1172,3 +1661,52 @@ fn document_data_is_kept_forgotten_or_refused() {
|
||||
// A decline is still a decline.
|
||||
assert!(matches!(decode_output(br#"{"error": "No pens.", "documentData": 1}"#), Err(Error::Failed(_))));
|
||||
}
|
||||
|
||||
/// A filter's `notice`: absent or `null` is none; a string is trimmed, its control, bidirectional
|
||||
/// and separator characters escaped, and cut at [`MAX_NOTICE_CHARS`] with an ellipsis; anything
|
||||
/// else, and text with nothing visible, refuses the whole output.
|
||||
#[test]
|
||||
fn notice_is_escaped_capped_and_checked() {
|
||||
let out = |notice: Option<Value>| {
|
||||
let mut v = json!({"objects": []});
|
||||
if let Some(n) = notice {
|
||||
v["notice"] = n;
|
||||
}
|
||||
decode_output(v.to_string().as_bytes()).map(|o| o.notice)
|
||||
};
|
||||
assert_eq!(out(None).unwrap(), None);
|
||||
assert_eq!(out(Some(Value::Null)).unwrap(), None);
|
||||
assert_eq!(out(Some(json!(" Selected 12 objects \n"))).unwrap().as_deref(), Some("Selected 12 objects"));
|
||||
let shown = out(Some(json!("Saved\u{202E}txt.exe\nError: disk full\u{7}"))).unwrap().unwrap_or_default();
|
||||
assert_eq!(shown, "Saved\\u{202E}txt.exe\\u{000A}Error: disk full\\u{0007}");
|
||||
let long = out(Some(json!("y".repeat(10_000)))).unwrap().unwrap_or_default();
|
||||
assert_eq!(long.chars().count(), MAX_NOTICE_CHARS);
|
||||
assert!(long.ends_with('…'));
|
||||
// Escapes count toward the limit, so a notice of right-to-left overrides stays within it too.
|
||||
let escaped = out(Some(json!("\u{202E}".repeat(10_000)))).unwrap().unwrap_or_default();
|
||||
assert!(escaped.chars().count() <= MAX_NOTICE_CHARS && !escaped.contains('\u{202E}'), "{escaped}");
|
||||
for bad in [
|
||||
json!(""),
|
||||
json!(" \t\n "),
|
||||
json!("\u{200B}\u{FEFF}"),
|
||||
json!("\u{034F}"),
|
||||
json!("\u{3164}\u{FE0F}\u{E0041}"),
|
||||
// The visible text comes after the cut, so the status bar would show only the `…`.
|
||||
json!(format!("{}AB", "\u{200B}".repeat(MAX_NOTICE_CHARS - 1))),
|
||||
json!(format!("{}A", "\u{7}".repeat(MAX_NOTICE_CHARS / 8))),
|
||||
json!(12),
|
||||
json!(["a"]),
|
||||
json!({"text": "a"}),
|
||||
json!(true),
|
||||
] {
|
||||
assert!(matches!(out(Some(bad.clone())), Err(Error::Output(ref e)) if e.contains("`notice`")), "{bad}");
|
||||
}
|
||||
// Text with a visible character keeps the invisible ones, and its bidirectional ones escaped.
|
||||
assert_eq!(out(Some(json!("\u{2067}Done\u{034F}"))).unwrap().as_deref(), Some("\\u{2067}Done\u{034F}"));
|
||||
// A visible character in the last place the limit shows, whole or before the `…`, is enough.
|
||||
let pad = "\u{200B}".repeat(MAX_NOTICE_CHARS - 2);
|
||||
assert_eq!(out(Some(json!(format!("{pad}\u{200B}A")))).unwrap(), Some(format!("{pad}\u{200B}A")));
|
||||
assert_eq!(out(Some(json!(format!("{pad}ABC")))).unwrap(), Some(format!("{pad}A…")));
|
||||
// A decline is still a decline.
|
||||
assert!(matches!(decode_output(br#"{"error": "No pens.", "notice": "Done"}"#), Err(Error::Failed(_))));
|
||||
}
|
||||
@@ -0,0 +1,526 @@
|
||||
//! What a filter whose manifest lists `writes` may change about the type, images and symbol
|
||||
//! instances it was given: each one's name and transform; type's runs, with their character
|
||||
//! attributes, and its paragraph styles; an image's opacity; and the symbol an instance shows.
|
||||
//! Every other field stays read-only, and every value is checked before anything changes.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::{Map, Value};
|
||||
use vectorcraft_doc::text::{AttrRangeError, INLINE_CHAR};
|
||||
use vectorcraft_doc::{CharStyle, Document, JustificationOptions, KinsokuSet, Node, NodeKind, ParaStyle, TextObject, TextRun};
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
use super::{
|
||||
MAX_COORD, MAX_INPUT_RUNS, MAX_INPUT_TEXT, MAX_INPUT_TEXT_TOTAL, admit_paint, decode_name, decode_paint, first_difference, out_err,
|
||||
read_only_changed,
|
||||
};
|
||||
use crate::{Error, InputKind, Result};
|
||||
|
||||
/// The longest font family name a filter may set, in characters.
|
||||
const MAX_FAMILY: usize = 256;
|
||||
/// The smallest determinant a transform a filter sets may have: a smaller one flattens the object.
|
||||
const MIN_DETERMINANT: f64 = 1e-12;
|
||||
/// The most pairs of an old and a new paragraph, past those both texts start and end with, that a
|
||||
/// change of the paragraph count compares by their text ([`moved_para_styles`]).
|
||||
const MAX_MATCHED_PAIRS: usize = 1 << 18;
|
||||
|
||||
/// The fields of an object of `kind` a filter that lists the kind in `writes` may change.
|
||||
fn writable(kind: InputKind) -> &'static [&'static str] {
|
||||
match kind {
|
||||
InputKind::Type => &["name", "transform", "text"],
|
||||
InputKind::Image => &["name", "transform", "opacity"],
|
||||
InputKind::SymbolInstance => &["name", "transform", "symbolId"],
|
||||
}
|
||||
}
|
||||
|
||||
/// The changes entry `o` of a filter's output makes to object `given` of `kind` (as the input gave
|
||||
/// it), `None` when it changes nothing. Fields it leaves out keep their values; a field it gives
|
||||
/// that isn't [`writable`] must be as given. Changed type text counts toward `text`, the bytes of
|
||||
/// text written over the whole output. The changes are keyed `name`, `transform`, `opacity`,
|
||||
/// `symbolId`, `runs` and `paragraphs`; their values are checked when they are applied ([`apply`]).
|
||||
pub(super) fn changes(o: &Map<String, Value>, given: &Value, kind: InputKind, at: &str, text: &mut usize) -> Result<Option<Map<String, Value>>> {
|
||||
let mut keys: Vec<&String> = o.keys().filter(|k| *k != "id").collect();
|
||||
keys.sort();
|
||||
let mut out = Map::new();
|
||||
for k in keys {
|
||||
let v = &o[k];
|
||||
let was = given.get(k);
|
||||
if !writable(kind).contains(&k.as_str()) {
|
||||
if let Some(field) = was.map_or_else(|| Some(k.clone()), |w| first_difference(v, w, k)) {
|
||||
return Err(read_only_changed(at, &field));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match (k.as_str(), was) {
|
||||
("text", Some(was)) => text_changes(k, v, was, given.get("truncated") == Some(&Value::Bool(true)), at, text, &mut out)?,
|
||||
("name", None) if v.is_null() => {}
|
||||
(_, Some(was)) if first_difference(v, was, "").is_none() => {}
|
||||
_ => {
|
||||
out.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((!out.is_empty()).then_some(out))
|
||||
}
|
||||
|
||||
/// The `runs` and `paragraphs` of type text `v`, the output's field `key`, that differ from `was`
|
||||
/// (the text the input gave), into `out`; its other fields must be as given, and type given as
|
||||
/// `truncated` keeps its text. A changed list is held to [`MAX_INPUT_RUNS`] entries, and changed
|
||||
/// runs to [`MAX_INPUT_TEXT`] bytes of text, which count toward `total`, held to
|
||||
/// [`MAX_INPUT_TEXT_TOTAL`], and to [`MAX_INPUT_RUNS`] paragraphs. With changed runs, `paragraphs`
|
||||
/// given as they were go into `out` too, to be checked against the new paragraphs.
|
||||
fn text_changes(key: &str, v: &Value, was: &Value, truncated: bool, at: &str, total: &mut usize, out: &mut Map<String, Value>) -> Result<()> {
|
||||
let t = v.as_object().ok_or_else(|| out_err(at, format!("`{key}` must be an object")))?;
|
||||
let mut keys: Vec<&String> = t.keys().collect();
|
||||
keys.sort();
|
||||
for k in keys {
|
||||
let field = format!("{key}.{k}");
|
||||
let given = was.get(k);
|
||||
let differs = given.is_none_or(|g| first_difference(&t[k], g, "").is_some());
|
||||
if !matches!(k.as_str(), "runs" | "paragraphs") {
|
||||
if differs {
|
||||
let shown = given.and_then(|g| first_difference(&t[k], g, &field)).unwrap_or_else(|| field.clone());
|
||||
return Err(read_only_changed(at, &shown));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !differs {
|
||||
continue;
|
||||
}
|
||||
if truncated {
|
||||
return Err(out_err(&format!("{at}.{field}"), "the text of type given as `truncated` can't be changed"));
|
||||
}
|
||||
let list = t[k].as_array().filter(|l| l.len() <= MAX_INPUT_RUNS);
|
||||
let list = list.ok_or_else(|| out_err(&format!("{at}.{field}"), format!("must be a list of at most {MAX_INPUT_RUNS} entries")))?;
|
||||
if k == "runs" {
|
||||
if list.is_empty() {
|
||||
return Err(out_err(&format!("{at}.{field}"), "type needs at least one run"));
|
||||
}
|
||||
let bytes = list.iter().fold(0usize, |n, r| n.saturating_add(r.get("text").and_then(Value::as_str).map_or(0, str::len)));
|
||||
if bytes > MAX_INPUT_TEXT {
|
||||
return Err(out_err(&format!("{at}.{field}"), format!("{bytes} bytes of text (limit {MAX_INPUT_TEXT})")));
|
||||
}
|
||||
// Each paragraph gets a paragraph style; the text holds at most as many paragraphs as runs.
|
||||
let breaks = |r: &Value| r.get("text").and_then(Value::as_str).map_or(0, |s| s.bytes().filter(|&b| b == b'\n').count());
|
||||
let paragraphs = list.iter().fold(1usize, |n, r| n.saturating_add(breaks(r)));
|
||||
if paragraphs > MAX_INPUT_RUNS {
|
||||
return Err(out_err(&format!("{at}.{field}"), format!("{paragraphs} paragraphs (limit {MAX_INPUT_RUNS})")));
|
||||
}
|
||||
*total = total.saturating_add(bytes);
|
||||
if *total > MAX_INPUT_TEXT_TOTAL {
|
||||
return Err(out_err(&format!("{at}.{field}"), format!("more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output")));
|
||||
}
|
||||
}
|
||||
out.insert(k.clone(), t[k].clone());
|
||||
}
|
||||
// Paragraph styles given as they were still need one per paragraph of the new runs.
|
||||
if out.contains_key("runs")
|
||||
&& !out.contains_key("paragraphs")
|
||||
&& let Some(p) = t.get("paragraphs")
|
||||
{
|
||||
out.insert("paragraphs".into(), p.clone());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every attribute name `T` reads, including those its JSON leaves out at their defaults: the field
|
||||
/// names serde's derive hands `deserialize_struct`.
|
||||
fn attr_names<T: DeserializeOwned>() -> &'static [&'static str] {
|
||||
use serde::de::{Error as _, Visitor, value::Error};
|
||||
|
||||
struct Names<'a>(&'a mut &'static [&'static str]);
|
||||
impl<'de> serde::Deserializer<'de> for Names<'_> {
|
||||
type Error = Error;
|
||||
fn deserialize_any<V: Visitor<'de>>(self, _: V) -> std::result::Result<V::Value, Error> {
|
||||
Err(Error::custom("not a struct"))
|
||||
}
|
||||
fn deserialize_struct<V: Visitor<'de>>(self, _: &'static str, fields: &'static [&'static str], _: V) -> std::result::Result<V::Value, Error> {
|
||||
*self.0 = fields;
|
||||
Err(Error::custom("field names only"))
|
||||
}
|
||||
serde::forward_to_deserialize_any! {
|
||||
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf option unit
|
||||
unit_struct newtype_struct seq tuple tuple_struct map enum identifier ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
let mut fields: &'static [&'static str] = &[];
|
||||
// Always an error: the probe only records the names.
|
||||
let _ = T::deserialize(Names(&mut fields));
|
||||
fields
|
||||
}
|
||||
|
||||
/// `v`, the field `key` of the entry at `parent`, as a `T` whose attributes are all ones `T` reads:
|
||||
/// a value that isn't an object is an error at `parent`, and an unknown key, as an ill-typed value,
|
||||
/// an error at `parent.key`.
|
||||
fn strict<T: DeserializeOwned>(v: &Value, parent: &str, key: &str) -> Result<T> {
|
||||
let o = v.as_object().ok_or_else(|| out_err(parent, format!("`{key}` must be an object")))?;
|
||||
let at = format!("{parent}.{key}");
|
||||
let names = attr_names::<T>();
|
||||
if let Some(k) = o.keys().find(|k| !names.contains(&k.as_str())) {
|
||||
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
|
||||
return Err(out_err(&at, format!("unknown key '{k}'")));
|
||||
}
|
||||
serde_json::from_value(v.clone()).map_err(|e| out_err(&at, e))
|
||||
}
|
||||
|
||||
/// The field `key` of `v`, the style at `at`, holds only attributes `T` reads: an object, or each
|
||||
/// object of a list. An unknown key is an error at `at.key` (or `at.key[i]`); other values are left
|
||||
/// to the style's own checks.
|
||||
fn known_keys<T: DeserializeOwned>(v: &Value, at: &str, key: &str) -> Result<()> {
|
||||
let names = attr_names::<T>();
|
||||
let check = |o: &Map<String, Value>, at: &str| match o.keys().find(|k| !names.contains(&k.as_str())) {
|
||||
Some(k) => {
|
||||
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
|
||||
Err(out_err(at, format!("unknown key '{k}'")))
|
||||
}
|
||||
None => Ok(()),
|
||||
};
|
||||
match v.get(key) {
|
||||
Some(Value::Object(o)) => check(o, &format!("{at}.{key}")),
|
||||
Some(Value::Array(list)) => list.iter().enumerate().try_for_each(|(i, e)| match e {
|
||||
Value::Object(o) => check(o, &format!("{at}.{key}[{i}]")),
|
||||
_ => Ok(()),
|
||||
}),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A transform from a filter's output: six finite numbers, each within ±[`MAX_COORD`], that don't
|
||||
/// flatten the object.
|
||||
fn decode_transform(v: &Value, at: &str) -> Result<Affine> {
|
||||
let c: Option<Vec<f64>> = v.as_array().and_then(|a| a.iter().map(Value::as_f64).collect());
|
||||
let c: [f64; 6] = c.and_then(|c| c.try_into().ok()).ok_or_else(|| out_err(at, "must be a list of 6 numbers"))?;
|
||||
if !c.iter().all(|x| x.is_finite() && x.abs() <= MAX_COORD) {
|
||||
return Err(out_err(at, format!("a number is out of range (limit ±{MAX_COORD})")));
|
||||
}
|
||||
let xf = Affine::new(c);
|
||||
if xf.determinant().abs() < MIN_DETERMINANT {
|
||||
return Err(out_err(at, "flattens the object to a line or a point"));
|
||||
}
|
||||
Ok(xf)
|
||||
}
|
||||
|
||||
/// The transform object `n` is given with: type's and an instance's own, an image's (for a
|
||||
/// distorted image, the placement nearest its corners at its middle).
|
||||
fn given_transform(n: &Node) -> Option<Affine> {
|
||||
match &n.kind {
|
||||
NodeKind::Text(t) => Some(t.xf),
|
||||
NodeKind::Image(im) => Some(vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf)),
|
||||
NodeKind::SymbolInstance { xf, .. } => Some(*xf),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies `changes` ([`changes`]) to `n`, an input object of `doc`; `at` names it in errors. Each
|
||||
/// value is checked first, and an error leaves `n` to be dropped.
|
||||
pub(super) fn apply(doc: &Document, n: &mut Node, changes: &Map<String, Value>, at: &str) -> Result<()> {
|
||||
if let Some(v) = changes.get("transform") {
|
||||
let at = format!("{at}.transform");
|
||||
let new = decode_transform(v, &at)?;
|
||||
let old = given_transform(n).filter(|xf| xf.determinant().abs() >= MIN_DETERMINANT);
|
||||
let old = old.ok_or_else(|| out_err(&at, "an object flattened to a line or a point can't be placed again"))?;
|
||||
// Everything the object carries moves with it: a distorted image's corners, its gradients.
|
||||
n.transform(new * old.inverse(), false);
|
||||
let distorted = n.is_distorted_image();
|
||||
match &mut n.kind {
|
||||
NodeKind::Text(t) => t.xf = new,
|
||||
NodeKind::SymbolInstance { xf, .. } => *xf = new,
|
||||
NodeKind::Image(im) if !distorted => im.xf = new,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(v) = changes.get("opacity") {
|
||||
let op = v.as_f64().filter(|o| (0.0..=1.0).contains(o));
|
||||
n.opacity = op.ok_or_else(|| out_err(&format!("{at}.opacity"), "must be a number from 0 to 1"))? as f32;
|
||||
}
|
||||
if let Some(v) = changes.get("symbolId") {
|
||||
let at = format!("{at}.symbolId");
|
||||
let name = v.as_str().ok_or_else(|| out_err(&at, "must be the name of a symbol"))?;
|
||||
if !doc.symbols.iter().any(|s| s.name == name) {
|
||||
let shown = crate::permissions::display_text(name, crate::permissions::MAX_SHOWN_FIELD);
|
||||
return Err(out_err(&at, format!("'{shown}' is not a symbol in this document")));
|
||||
}
|
||||
let other = matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbol != name);
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &mut n.kind {
|
||||
*symbol = name.to_string();
|
||||
}
|
||||
// An edited part's path names an object of the old symbol's art, as Replace Symbol finds.
|
||||
if other && !n.extras().symbol_overrides.is_empty() {
|
||||
n.extras_mut().symbol_overrides.clear();
|
||||
}
|
||||
}
|
||||
if changes.contains_key("runs") || changes.contains_key("paragraphs") {
|
||||
let story = doc.story_of(n.id).len();
|
||||
let NodeKind::Text(t) = &mut n.kind else { return Err(read_only_changed(at, "text")) };
|
||||
set_text(doc, t, story > 1, changes.get("runs"), changes.get("paragraphs"), at)?;
|
||||
}
|
||||
if let Some(v) = changes.get("name") {
|
||||
n.name = Some(decode_name(v, at)?).filter(|s| !s.trim().is_empty());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Gives type `t` the runs `runs` and paragraph styles `paragraphs` a filter returned (`threaded`:
|
||||
/// it is a frame of a story that flows through others). Each run has `text`, `style` and, for an
|
||||
/// inline graphic, `inline`; each attribute is one the type reads. Inline graphics stay as they
|
||||
/// were, in the same order, and the characters of threaded type or type with ruby stay as they
|
||||
/// were. Every number of every run's style is in the range the character style commands keep it
|
||||
/// to ([`CharStyle::check_ranges`]), and a run whose style isn't one of the type's own has a font
|
||||
/// family, and its paints are checked as an object's are. Paragraph styles are one per paragraph
|
||||
/// ([`para_style`]). With runs alone, each paragraph keeps its style when the number of paragraphs stays
|
||||
/// the same, and otherwise the styles follow the paragraphs' text ([`moved_para_styles`]).
|
||||
fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Value>, paragraphs: Option<&Value>, at: &str) -> Result<()> {
|
||||
if let Some(runs) = runs {
|
||||
let at = format!("{at}.text.runs");
|
||||
let list = runs.as_array().map(Vec::as_slice).unwrap_or_default();
|
||||
// The type's own styles, as JSON text, to look each run's style up once.
|
||||
let own: HashSet<String> = t.runs.iter().filter_map(|r| serde_json::to_string(&r.style).ok()).collect();
|
||||
let mut new = Vec::with_capacity(list.len());
|
||||
for (i, v) in list.iter().enumerate() {
|
||||
let at = format!("{at}[{i}]");
|
||||
let o = v.as_object().ok_or_else(|| out_err(&at, "a run must be {\"text\", \"style\", \"inline\"?}"))?;
|
||||
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "text" | "style" | "inline")) {
|
||||
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
|
||||
return Err(out_err(&at, format!("unknown key '{k}'")));
|
||||
}
|
||||
let key = "text";
|
||||
let text = o.get(key).and_then(Value::as_str).ok_or_else(|| out_err(&at, format!("`{key}` must be a string")))?;
|
||||
let style_v = o.get("style").unwrap_or(&Value::Null);
|
||||
let mut style: CharStyle = strict(style_v, &at, "style")?;
|
||||
known_keys::<vectorcraft_doc::Dash>(style_v, &format!("{at}.style"), "stroke_dash")?;
|
||||
let inline = match o.get("inline") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => Some(serde_json::from_value(v.clone()).map_err(|e| out_err(&format!("{at}.inline"), e))?),
|
||||
};
|
||||
if inline.is_none() {
|
||||
if text.contains(INLINE_CHAR) {
|
||||
return Err(out_err(&at, "`text` holds the character of an inline graphic"));
|
||||
}
|
||||
// Every number goes to the layout, so it is checked even in a style the type has.
|
||||
style.check_ranges(|_| true).map_err(|e| range_err(&format!("{at}.style"), &e))?;
|
||||
for key in ["fill", "stroke"] {
|
||||
if let Some(p) = style_v.get(key) {
|
||||
check_paint_keys(p, &format!("{at}.style.{key}"))?;
|
||||
}
|
||||
}
|
||||
if !serde_json::to_string(&style).is_ok_and(|s| own.contains(&s)) {
|
||||
check_style(doc, &mut style, t.runs.get(i).map(|r| &r.style), &format!("{at}.style"))?;
|
||||
}
|
||||
}
|
||||
new.push(TextRun { text: text.to_string(), style, inline });
|
||||
}
|
||||
// Inline graphics are compared as saved (their measured bounds aren't), and keep those.
|
||||
let saved = |r: &&TextRun| serde_json::to_value(r).ok();
|
||||
let old_inline: Vec<&TextRun> = t.runs.iter().filter(|r| r.inline.is_some()).collect();
|
||||
let new_inline: Vec<&TextRun> = new.iter().filter(|r| r.inline.is_some()).collect();
|
||||
if old_inline.len() != new_inline.len() || old_inline.iter().zip(&new_inline).any(|(a, b)| saved(a) != saved(b)) {
|
||||
return Err(out_err(&at, "inline graphics can't be added, removed, reordered or changed"));
|
||||
}
|
||||
let mut kept = old_inline.into_iter().cloned().collect::<Vec<_>>().into_iter();
|
||||
for r in new.iter_mut().filter(|r| r.inline.is_some()) {
|
||||
if let Some(old) = kept.next() {
|
||||
*r = old;
|
||||
}
|
||||
}
|
||||
let plain: String = new.iter().map(|r| r.text.as_str()).collect();
|
||||
let old = t.plain_text();
|
||||
let mut moved = None;
|
||||
if plain != old {
|
||||
if threaded {
|
||||
return Err(out_err(&at, "the characters of threaded type can't be changed"));
|
||||
}
|
||||
if !t.ruby.is_empty() {
|
||||
return Err(out_err(&at, "the characters of type with ruby can't be changed"));
|
||||
}
|
||||
let breaks = |s: &str| s.bytes().filter(|&b| b == b'\n').count();
|
||||
if paragraphs.is_none() && breaks(&plain) != breaks(&old) {
|
||||
// Paragraphs added or joined: the styles follow the paragraphs' text. With as many
|
||||
// paragraphs as before, each keeps its style.
|
||||
moved = Some(moved_para_styles(&t.paragraph_styles(), &old, &plain));
|
||||
}
|
||||
}
|
||||
t.runs = new;
|
||||
if let Some(styles) = moved {
|
||||
t.set_paragraph_styles(styles);
|
||||
}
|
||||
}
|
||||
match paragraphs {
|
||||
Some(v) => {
|
||||
let text = format!("{at}.text");
|
||||
let list = v.as_array().map(Vec::as_slice).unwrap_or_default();
|
||||
let count = t.paragraph_count();
|
||||
if list.len() != count {
|
||||
return Err(out_err(&format!("{text}.paragraphs"), format!("expected {count} paragraph styles, one per paragraph")));
|
||||
}
|
||||
let styles = list.iter().enumerate().map(|(i, p)| para_style(doc, p, &text, &format!("paragraphs[{i}]"))).collect::<Result<_>>()?;
|
||||
t.set_paragraph_styles(styles);
|
||||
}
|
||||
None => t.normalize_paras(),
|
||||
}
|
||||
// The layout is measured again before the type is drawn.
|
||||
t.cached_bounds = None;
|
||||
t.cached_baselines.clear();
|
||||
t.cached_ink = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The paragraph styles of text `new` that replaced `old`, whose paragraphs had `styles` (one per
|
||||
/// paragraph). The paragraphs, split at `\n`, are matched as a longest common subsequence of their
|
||||
/// texts after the paragraphs both start and end with are set aside; when the paragraphs left in
|
||||
/// the old text times those left in the new pass [`MAX_MATCHED_PAIRS`], they are paired in order
|
||||
/// instead. A
|
||||
/// matched paragraph keeps its style. Between two matched paragraphs, the changed ones take the
|
||||
/// styles of the old paragraphs there in order, and the last of those past their count; paragraphs
|
||||
/// added where there were none take the style of the paragraph before them, or of the next one at
|
||||
/// the start. A style copied to a paragraph that was not there loses its list number
|
||||
/// ([`vectorcraft_doc::text::ParaList::start`]).
|
||||
fn moved_para_styles(styles: &[ParaStyle], old: &str, new: &str) -> Vec<ParaStyle> {
|
||||
let a: Vec<&str> = old.split('\n').collect();
|
||||
let b: Vec<&str> = new.split('\n').collect();
|
||||
let pre = a.iter().zip(&b).take_while(|(x, y)| x == y).count();
|
||||
let (a_rest, b_rest) = (a.get(pre..).unwrap_or_default(), b.get(pre..).unwrap_or_default());
|
||||
let suf = a_rest.iter().rev().zip(b_rest.iter().rev()).take_while(|(x, y)| x == y).count();
|
||||
// `matched[j]`: the old paragraph that new paragraph `j` is, if any.
|
||||
let mut matched: Vec<Option<usize>> = vec![None; b.len()];
|
||||
for (j, m) in matched.iter_mut().enumerate().take(pre) {
|
||||
*m = Some(j);
|
||||
}
|
||||
for k in 0..suf {
|
||||
if let Some(m) = matched.get_mut(b.len() - 1 - k) {
|
||||
*m = Some(a.len() - 1 - k);
|
||||
}
|
||||
}
|
||||
let (am, bm) = (a_rest.get(..a_rest.len() - suf).unwrap_or_default(), b_rest.get(..b_rest.len() - suf).unwrap_or_default());
|
||||
if !am.is_empty() && !bm.is_empty() && am.len().saturating_mul(bm.len()) <= MAX_MATCHED_PAIRS {
|
||||
let mut ids = std::collections::HashMap::new();
|
||||
let mut id = |s: &str| {
|
||||
let next = ids.len();
|
||||
*ids.entry(s.to_string()).or_insert(next)
|
||||
};
|
||||
let ai: Vec<usize> = am.iter().map(|s| id(s)).collect();
|
||||
let bi: Vec<usize> = bm.iter().map(|s| id(s)).collect();
|
||||
// `len[i * w + j]`: the length of the longest common subsequence of `ai[i..]` and `bi[j..]`.
|
||||
let w = bi.len() + 1;
|
||||
let mut len = vec![0u32; (ai.len() + 1) * w];
|
||||
for i in (0..ai.len()).rev() {
|
||||
for j in (0..bi.len()).rev() {
|
||||
let at = |i: usize, j: usize| len.get(i * w + j).copied().unwrap_or(0);
|
||||
let v = if ai.get(i) == bi.get(j) { at(i + 1, j + 1) + 1 } else { at(i + 1, j).max(at(i, j + 1)) };
|
||||
if let Some(c) = len.get_mut(i * w + j) {
|
||||
*c = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
let at = |i: usize, j: usize| len.get(i * w + j).copied().unwrap_or(0);
|
||||
let (mut i, mut j) = (0, 0);
|
||||
while i < ai.len() && j < bi.len() {
|
||||
if ai.get(i) == bi.get(j) {
|
||||
if let Some(m) = matched.get_mut(pre + j) {
|
||||
*m = Some(pre + i);
|
||||
}
|
||||
(i, j) = (i + 1, j + 1);
|
||||
} else if at(i + 1, j) >= at(i, j + 1) {
|
||||
i += 1;
|
||||
} else {
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let style = |i: usize, numbered: bool| {
|
||||
let mut s = styles.get(i).or(styles.last()).cloned().unwrap_or_default();
|
||||
if !numbered && let Some(l) = s.list.as_mut() {
|
||||
l.start = None;
|
||||
}
|
||||
s
|
||||
};
|
||||
let mut out = Vec::with_capacity(b.len());
|
||||
let (mut next_old, mut j) = (0, 0);
|
||||
while j < b.len() {
|
||||
if let Some(&Some(i)) = matched.get(j) {
|
||||
out.push(style(i, true));
|
||||
(next_old, j) = (i + 1, j + 1);
|
||||
continue;
|
||||
}
|
||||
// New paragraphs `j..end` stand where old paragraphs `next_old..old_end` were.
|
||||
let end = (j..b.len()).find(|&k| matched.get(k).is_some_and(Option::is_some)).unwrap_or(b.len());
|
||||
let old_end = matched.get(end).copied().flatten().unwrap_or(a.len());
|
||||
for g in 0..end - j {
|
||||
out.push(if next_old < old_end {
|
||||
style((next_old + g).min(old_end - 1), next_old + g < old_end)
|
||||
} else {
|
||||
style(next_old.checked_sub(1).unwrap_or(old_end), false)
|
||||
});
|
||||
}
|
||||
j = end;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An attribute of the style at `at` out of its range, naming the attribute.
|
||||
fn range_err(at: &str, e: &AttrRangeError) -> Error {
|
||||
out_err(&format!("{at}.{}", e.key), &e.message)
|
||||
}
|
||||
|
||||
/// Paragraph style `v` from a filter's output, the entry `key` of the text at `parent`: each
|
||||
/// attribute one a paragraph reads, each number in the range the paragraph style commands keep it
|
||||
/// to ([`ParaStyle::check_ranges`], the Justification options as given), and a custom Kinsoku set
|
||||
/// one of `doc`'s, by name, whose characters it takes.
|
||||
fn para_style(doc: &Document, v: &Value, parent: &str, key: &str) -> Result<ParaStyle> {
|
||||
let mut st: ParaStyle = strict(v, parent, key)?;
|
||||
let at = format!("{parent}.{key}");
|
||||
known_keys::<vectorcraft_doc::HyphenationOptions>(v, &at, "hyphenation")?;
|
||||
known_keys::<JustificationOptions>(v, &at, "justification")?;
|
||||
known_keys::<vectorcraft_doc::TabStop>(v, &at, "tabs")?;
|
||||
known_keys::<vectorcraft_doc::text::ParaList>(v, &at, "list")?;
|
||||
let justification = match v.get("justification") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(j) => Some(serde_json::from_value::<JustificationOptions>(j.clone()).map_err(|e| out_err(&format!("{at}.justification"), e))?),
|
||||
};
|
||||
st.check_ranges(justification.as_ref(), &[], |_, _| true).map_err(|e| range_err(&at, &e))?;
|
||||
if let Some(set) = &st.kinsoku_set {
|
||||
let found = KinsokuSet::named(&doc.kinsoku_sets, &set.name).ok_or_else(|| {
|
||||
let shown = crate::permissions::display_text(&set.name, crate::permissions::MAX_SHOWN_FIELD);
|
||||
out_err(&format!("{at}.kinsoku_set"), format!("the document has no Kinsoku set named '{shown}'"))
|
||||
})?;
|
||||
st.kinsoku_set = Some(std::sync::Arc::new(found.clone()));
|
||||
}
|
||||
Ok(st)
|
||||
}
|
||||
|
||||
/// Checks character style `s`, a filter's own (`was`: the style of the run in its place before):
|
||||
/// its font family is 1 to [`MAX_FAMILY`] printable characters, counted as given, and its fill and
|
||||
/// stroke are admitted as an object's paints are. Its numbers and its paints' keys are checked for
|
||||
/// every run ([`set_text`]).
|
||||
fn check_style(doc: &Document, s: &mut CharStyle, was: Option<&CharStyle>, at: &str) -> Result<()> {
|
||||
let family = s.font_family.trim();
|
||||
if family.is_empty() || s.font_family.chars().count() > MAX_FAMILY || s.font_family.chars().any(char::is_control) {
|
||||
return Err(out_err(&format!("{at}.font_family"), format!("must be 1-{MAX_FAMILY} printable characters")));
|
||||
}
|
||||
let paint = |p: &vectorcraft_color::Paint, was: Option<&vectorcraft_color::Paint>, key: &str| {
|
||||
let at = format!("{at}.{key}");
|
||||
let v = serde_json::to_value(p).map_err(|e| out_err(&at, e))?;
|
||||
admit_paint(doc, decode_paint(&v, &at)?, was, &at)
|
||||
};
|
||||
s.fill = paint(&s.fill, was.map(|w| &w.fill), "fill")?;
|
||||
s.stroke = paint(&s.stroke, was.map(|w| &w.stroke), "stroke")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Checks that paint `v` of a style, at `at`, has no key besides `type` and those its `type`
|
||||
/// reads; a key of another paint, or an unknown one, is an error naming it.
|
||||
fn check_paint_keys(v: &Value, at: &str) -> Result<()> {
|
||||
let Some(o) = v.as_object() else { return Ok(()) };
|
||||
let known: &[&str] = match o.get("type").and_then(Value::as_str) {
|
||||
Some("solid") => &["color", "swatch", "tint"],
|
||||
Some("gradient") => attr_names::<vectorcraft_color::GradientPaint>(),
|
||||
Some("pattern") => &["pattern", "xf"],
|
||||
_ => &[],
|
||||
};
|
||||
if let Some(k) = o.keys().find(|k| *k != "type" && !known.contains(&k.as_str())) {
|
||||
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
|
||||
return Err(out_err(at, format!("unknown key '{k}'")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -47,8 +47,8 @@ pub enum Scope {
|
||||
}
|
||||
|
||||
/// Parses and checks a painted result: `{"objects": [...]}`, or `{"error": "message"}` when the
|
||||
/// plug-in declined. `rule` is the fill rule a piece without `fillRule` takes. Any other top-level
|
||||
/// key, an unknown key in a piece, stroke or paint, a list or count past its limit, a number out of
|
||||
/// plug-in declined. `rule` is the fill rule a piece without `fillRule` takes. A top-level `notice`
|
||||
/// is ignored. Any other top-level key, an unknown key in a piece, stroke or paint, a list or count past its limit, a number out of
|
||||
/// range or a paint of the wrong form refuses the whole result, naming the field.
|
||||
pub fn decode(bytes: &[u8], scope: Scope, rule: FillRule) -> Result<Vec<Piece>> {
|
||||
let v: Value = serde_json::from_slice(bytes).map_err(|e| out_err("output", format!("not JSON: {e}")))?;
|
||||
@@ -56,8 +56,8 @@ pub fn decode(bytes: &[u8], scope: Scope, rule: FillRule) -> Result<Vec<Piece>>
|
||||
return Err(e);
|
||||
}
|
||||
let top = v.as_object().ok_or_else(|| out_err("output", "expected {\"objects\": [...]}"))?;
|
||||
if let Some(k) = top.keys().find(|k| !matches!(k.as_str(), "objects" | "error")) {
|
||||
return Err(out_err(k, "a painted live effect returns only `objects`"));
|
||||
if let Some(k) = top.keys().find(|k| !matches!(k.as_str(), "objects" | "error" | "notice")) {
|
||||
return Err(out_err(k, "a painted live effect returns only `objects` and `notice`"));
|
||||
}
|
||||
let objects = top.get("objects").and_then(Value::as_array).ok_or_else(|| out_err("objects", "expected {\"objects\": [...]}"))?;
|
||||
if objects.len() > MAX_OBJECTS {
|
||||
|
||||
@@ -154,6 +154,21 @@ fn faults_refuse_the_whole_result_by_field() {
|
||||
assert_eq!(declined, Error::Failed("nothing to do".into()));
|
||||
}
|
||||
|
||||
/// A top-level `notice` is ignored, as a filter-only key a live effect may hand back; other
|
||||
/// unknown top-level keys still refuse the result.
|
||||
#[test]
|
||||
fn a_notice_is_ignored_and_other_top_level_keys_refused() {
|
||||
let ok = json!({"path": square(), "fills": [red()]});
|
||||
let decode_top = |top: Value| decode(&serde_json::to_vec(&top).unwrap(), Scope::Object, FillRule::NonZero);
|
||||
let pieces = decode_top(json!({"objects": [ok], "notice": "Done"})).unwrap();
|
||||
assert_eq!(pieces.len(), 1);
|
||||
assert_eq!(decode_top(json!({"objects": [ok], "notice": 12})).unwrap().len(), 1);
|
||||
for key in ["note", "notices", "message"] {
|
||||
let e = decode_top(json!({"objects": [ok], key: "Done"})).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("{key}:")) && e.contains("returns only `objects` and `notice`"), "{key}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A key a paint does not have, at any level of it, refuses the result and is named; it is not
|
||||
/// dropped.
|
||||
#[test]
|
||||
|
||||
@@ -16,8 +16,9 @@ use crate::{Error, Kind, Result};
|
||||
|
||||
/// The plug-in API level this host implements. A manifest's `api` (1 when left out) may be at most
|
||||
/// this. Level 2 adds the host imports ([`PROGRESS_API`]) and a live effect's `paintOutput`
|
||||
/// ([`crate::painted`]).
|
||||
pub const API_LEVEL: u32 = 2;
|
||||
/// ([`crate::painted`]); level 3 adds a filter's `writes` ([`WRITES_API`]) and a manifest's
|
||||
/// `context` ([`CONTEXT_API`]).
|
||||
pub const API_LEVEL: u32 = 3;
|
||||
|
||||
/// The API level that adds the host imports ([`crate::host::IMPORTS`]) and the `progress`,
|
||||
/// `settings`, `cache` and `commands` permissions they need.
|
||||
@@ -26,6 +27,17 @@ pub const PROGRESS_API: u32 = 2;
|
||||
/// The API level that adds a filter's `inputs` ([`crate::InputKind`]).
|
||||
pub const INPUTS_API: u32 = 2;
|
||||
|
||||
/// The API level that adds a filter's `writes`: the kinds among its `inputs` it may change.
|
||||
pub const WRITES_API: u32 = 3;
|
||||
|
||||
/// The API level that reads a command's `menu` ([`crate::manifest::MenuPlace`]); below it the key
|
||||
/// is ignored.
|
||||
pub const MENU_API: u32 = 2;
|
||||
|
||||
/// The API level that adds a manifest's `context` ([`crate::ContextSection`]): the document's
|
||||
/// settings, artboards, layers and swatches, given to a run with or without a selection.
|
||||
pub const CONTEXT_API: u32 = 3;
|
||||
|
||||
/// Most permissions a manifest may list.
|
||||
pub const MAX_PERMISSIONS: usize = 16;
|
||||
|
||||
@@ -43,7 +55,8 @@ pub const RESERVED: &[&str] = &["ui.panel", "ui.tool"];
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub enum Permission {
|
||||
/// Read the objects the host hands it: a filter's selected paths, the object a live effect is
|
||||
/// on, the document an exporter writes.
|
||||
/// on, the document an exporter writes; and the document information a manifest's `context`
|
||||
/// asks for ([`crate::ContextSection`]).
|
||||
#[serde(rename = "doc.read")]
|
||||
DocRead,
|
||||
/// Change, add and delete objects (a filter's output), as one undo step.
|
||||
|
||||
+818
-58
@@ -65,23 +65,138 @@ pub fn approved(plugin: &Plugin) -> bool {
|
||||
!m.asks_permissions() || granted(&m.id).is_some_and(|g| g.covers(&m.id, plugin.hash(), &m.permissions()))
|
||||
}
|
||||
|
||||
/// Tests: what runs before an install waits for the plug-ins, given the plug-in's id.
|
||||
#[cfg(test)]
|
||||
type InstallHook = Arc<dyn Fn(&str) + Send + Sync>;
|
||||
|
||||
/// Tests: runs right before [`install`] waits for the plug-ins' write lock.
|
||||
#[cfg(test)]
|
||||
static BEFORE_INSTALL_LOCK: Mutex<Option<InstallHook>> = Mutex::new(None);
|
||||
|
||||
/// Installs `plugin`, replacing one with the same id, when it is [`approved`]: a module that lists
|
||||
/// permissions no recorded grant gives this very module is refused ([`Error::NeedsApproval`]), and
|
||||
/// the plug-in installed under its id, the grants and the revision stay as they were.
|
||||
pub fn install(mut plugin: Plugin) -> Result<Arc<Plugin>> {
|
||||
pub fn install(plugin: Plugin) -> Result<Arc<Plugin>> {
|
||||
// The revision moves while the write lock is held, so a cache that reads the new revision and
|
||||
// then the plug-ins finds the new plug-in among them. The approval is checked while it is held
|
||||
// too.
|
||||
#[cfg(test)]
|
||||
{
|
||||
let hook = BEFORE_INSTALL_LOCK.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
if let Some(hook) = hook {
|
||||
hook(plugin.id());
|
||||
}
|
||||
}
|
||||
let mut plugins = PLUGINS.write().unwrap_or_else(|e| e.into_inner());
|
||||
if !approved(&plugin) {
|
||||
return Err(Error::NeedsApproval(crate::permissions::names(&plugin.manifest().permissions()).join(", ")));
|
||||
}
|
||||
Ok(insert(&mut plugins, plugin))
|
||||
}
|
||||
|
||||
/// Installs `plugin` in `plugins`, which the plug-ins' write lock holds, with the next revision.
|
||||
fn insert(plugins: &mut BTreeMap<String, Arc<Plugin>>, mut plugin: Plugin) -> Arc<Plugin> {
|
||||
plugin.set_serial(REVISION.fetch_add(1, Ordering::Relaxed) + 1);
|
||||
note_change(plugin.id(), plugin.serial());
|
||||
let p = Arc::new(plugin);
|
||||
plugins.insert(p.id().to_string(), p.clone());
|
||||
Ok(p)
|
||||
p
|
||||
}
|
||||
|
||||
/// [`install`] for a load that installs plug-ins one by one, recording `grant` first when it is
|
||||
/// given: while the plug-ins' write lock is held, a plug-in whose id was installed or removed
|
||||
/// elsewhere since the load started ([`LoadChanges::superseded`]) is not installed (`Ok(None)`), and
|
||||
/// neither the plug-ins nor the grants change. A grant that doesn't give this very module every
|
||||
/// permission it lists is refused ([`Error::NeedsApproval`]) and not recorded. Otherwise `attach`
|
||||
/// runs, then the grant is recorded and the plug-in installed. `attach` runs while the plug-ins are
|
||||
/// held, so it may call [`set_storage`] but no function that reads or changes the plug-ins or grants.
|
||||
pub fn install_for_load(plugin: Plugin, changes: &LoadChanges, grant: Option<GrantToken>, attach: impl FnOnce()) -> Result<Option<Arc<Plugin>>> {
|
||||
let mut plugins = PLUGINS.write().unwrap_or_else(|e| e.into_inner());
|
||||
if changes.superseded(plugin.id()) {
|
||||
return Ok(None);
|
||||
}
|
||||
let m = plugin.manifest();
|
||||
let approved = match &grant {
|
||||
Some(token) => !m.asks_permissions() || token.grant().covers(&m.id, plugin.hash(), &m.permissions()),
|
||||
None => approved(&plugin),
|
||||
};
|
||||
if !approved {
|
||||
return Err(Error::NeedsApproval(crate::permissions::names(&m.permissions()).join(", ")));
|
||||
}
|
||||
attach();
|
||||
if let Some(token) = grant {
|
||||
let g = token.grant().clone();
|
||||
GRANTS.write().unwrap_or_else(|e| e.into_inner()).insert(g.id.clone(), g);
|
||||
}
|
||||
Ok(Some(insert(&mut plugins, plugin)))
|
||||
}
|
||||
|
||||
/// Forgets the grant for `id` when the plug-in installed under it is the one that took the revision
|
||||
/// `serial` ([`Plugin::serial`]), checked while the plug-ins are held, so a plug-in installed in its
|
||||
/// place meanwhile keeps the grant recorded for it → whether a grant was forgotten.
|
||||
pub fn revoke_if_installed(id: &str, serial: u64) -> bool {
|
||||
// The same order as `install`, which reads the grants while it holds the plug-ins.
|
||||
let plugins = PLUGINS.read().unwrap_or_else(|e| e.into_inner());
|
||||
plugins.get(id).is_some_and(|p| p.serial() == serial) && GRANTS.write().unwrap_or_else(|e| e.into_inner()).remove(id).is_some()
|
||||
}
|
||||
|
||||
/// The [`revision`] of each id's last install or removal ([`changed_since`]).
|
||||
static CHANGED: RwLock<BTreeMap<String, u64>> = RwLock::new(BTreeMap::new());
|
||||
|
||||
/// Records that `id` was installed or removed at revision `rev`; called while the plug-ins' write
|
||||
/// lock is held.
|
||||
fn note_change(id: &str, rev: u64) {
|
||||
CHANGED.write().unwrap_or_else(|e| e.into_inner()).insert(id.to_string(), rev);
|
||||
}
|
||||
|
||||
/// Whether plug-in `id` was installed or removed after [`revision`] gave `rev`.
|
||||
pub fn changed_since(id: &str, rev: u64) -> bool {
|
||||
CHANGED.read().unwrap_or_else(|e| e.into_inner()).get(id).is_some_and(|&r| r > rev)
|
||||
}
|
||||
|
||||
/// What a load that installs plug-ins one by one has to check, so that a module it loaded before
|
||||
/// another session installed or removed the same id doesn't undo that change: the [`revision`] when
|
||||
/// the load listed its files, and the revision of each id it, or a load of the same session that
|
||||
/// ended before it, installed.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct LoadChanges {
|
||||
since: Option<u64>,
|
||||
own: BTreeMap<String, u64>,
|
||||
}
|
||||
|
||||
impl LoadChanges {
|
||||
/// Marks the load as started now, unless it started already. A load calls it as it lists its
|
||||
/// files, so a change made between the listing and the loads counts as one made elsewhere.
|
||||
pub fn start(&mut self) {
|
||||
self.since.get_or_insert_with(revision);
|
||||
}
|
||||
|
||||
/// Whether `id` was installed or removed since the load started, other than by the load itself
|
||||
/// or a load it [adopted](LoadChanges::adopt).
|
||||
pub fn superseded(&self, id: &str) -> bool {
|
||||
self.since.is_some_and(|since| changed_since(id, since.max(self.own.get(id).copied().unwrap_or(0))))
|
||||
}
|
||||
|
||||
/// Records that the load installed `plugin`.
|
||||
pub fn installed(&mut self, plugin: &Plugin) {
|
||||
self.own.insert(plugin.id().to_string(), plugin.serial());
|
||||
}
|
||||
|
||||
/// Counts what `earlier`, a load of the same session queued before this one that has ended,
|
||||
/// installed as this load's own: a module this load installs after it then replaces it, as it
|
||||
/// would have with the loads run one after the other.
|
||||
pub fn adopt(&mut self, earlier: &LoadChanges) {
|
||||
for (id, &serial) in &earlier.own {
|
||||
let own = self.own.entry(id.clone()).or_default();
|
||||
*own = (*own).max(serial);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a load reports for a module it skips because the plug-in under its id was installed or
|
||||
/// removed elsewhere while it loaded ([`LoadChanges`]).
|
||||
pub const SUPERSEDED: &str = "skipped: the plug-in with its id was installed or removed elsewhere while it loaded";
|
||||
|
||||
/// What [`install_checked`] does to the grant recorded for the plug-in's id.
|
||||
pub enum GrantUpdate {
|
||||
/// Records this grant, replacing an earlier one for the id ([`grant`]).
|
||||
@@ -128,6 +243,7 @@ pub fn install_checked<E>(
|
||||
}
|
||||
}
|
||||
plugin.set_serial(REVISION.fetch_add(1, Ordering::Relaxed) + 1);
|
||||
note_change(&id, plugin.serial());
|
||||
let p = Arc::new(plugin);
|
||||
plugins.insert(id, p.clone());
|
||||
Ok(p)
|
||||
@@ -154,7 +270,7 @@ pub fn remove(id: &str) -> bool {
|
||||
let mut plugins = PLUGINS.write().unwrap_or_else(|e| e.into_inner());
|
||||
let gone = plugins.remove(id).is_some();
|
||||
if gone {
|
||||
REVISION.fetch_add(1, Ordering::Relaxed);
|
||||
note_change(id, REVISION.fetch_add(1, Ordering::Relaxed) + 1);
|
||||
}
|
||||
gone
|
||||
}
|
||||
@@ -178,14 +294,73 @@ pub fn intern(s: &str) -> &'static str {
|
||||
v
|
||||
}
|
||||
|
||||
/// Reads a `.wasm` file (refusing anything that isn't a regular file or exceeds the module limit)
|
||||
/// Reads a `.wasm` file (refusing anything that isn't a regular file or exceeds the module limit),
|
||||
/// or a JavaScript plug-in's `.vcplugin` manifest and the script it names ([`read_js_package`]),
|
||||
/// and loads it.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn load_file(path: &std::path::Path, limits: Limits) -> Result<Plugin> {
|
||||
let bytes = read_module(path, &limits, || {})?;
|
||||
load_file_where(path, limits, &|_| Ok(()))
|
||||
}
|
||||
|
||||
/// [`load_file`], reading a JavaScript plug-in's script only when `allow` accepts its path.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn load_file_where(path: &std::path::Path, limits: Limits, allow: &dyn Fn(&std::path::Path) -> std::result::Result<(), String>) -> Result<Plugin> {
|
||||
let bytes = if is_js_package(path) { read_js_package(path, allow)? } else { read_module(path, &limits, || {})? };
|
||||
Ok(Plugin::load(&bytes, limits)?.with_source(path.display().to_string()))
|
||||
}
|
||||
|
||||
/// Does `path` name a JavaScript plug-in's manifest file: is its extension `.vcplugin`?
|
||||
pub fn is_js_package(path: &std::path::Path) -> bool {
|
||||
path.extension().is_some_and(|x| x.eq_ignore_ascii_case(crate::js::PACKAGE_EXT))
|
||||
}
|
||||
|
||||
/// The JavaScript plug-in whose manifest file is `path`, as the one JSON object [`Plugin::load`]
|
||||
/// reads: the manifest, with the text of the script its `script` names in `source`. The manifest
|
||||
/// file must give `"runtime": "js"` and `script`, a `.js` file in the same folder, and no `source`.
|
||||
/// Each file is refused before it is read when it isn't a regular file or is larger than its limit
|
||||
/// ([`crate::manifest::MAX_MANIFEST_BYTES`], [`crate::js::MAX_SCRIPT_BYTES`]); the script is read
|
||||
/// only when `allow` accepts its path, and must be UTF-8.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn read_js_package(path: &std::path::Path, allow: &dyn Fn(&std::path::Path) -> std::result::Result<(), String>) -> Result<Vec<u8>> {
|
||||
read_js_package_with(path, allow, || {})
|
||||
}
|
||||
|
||||
/// [`read_js_package`], with `opening` run between the script's size check and its open.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn read_js_package_with(
|
||||
path: &std::path::Path,
|
||||
allow: &dyn Fn(&std::path::Path) -> std::result::Result<(), String>,
|
||||
opening: impl FnOnce(),
|
||||
) -> Result<Vec<u8>> {
|
||||
use serde_json::Value;
|
||||
let manifest_limits = Limits { max_module_bytes: crate::manifest::MAX_MANIFEST_BYTES, ..Limits::default() };
|
||||
let bytes = read_module(path, &manifest_limits, || {})?;
|
||||
let map: serde_json::Map<String, Value> = serde_json::from_slice(&bytes).map_err(|e| Error::Manifest(format!("{}: {e}", path.display())))?;
|
||||
if !crate::js::is_js(&map) {
|
||||
return Err(Error::Manifest(crate::js::NOT_JS.into()));
|
||||
}
|
||||
if map.contains_key("source") {
|
||||
return Err(Error::Manifest(crate::js::SOURCE_RULE.into()));
|
||||
}
|
||||
let name = crate::js::script_name(map.get("script").ok_or_else(crate::js::no_script)?)?;
|
||||
let file = path.parent().unwrap_or(std::path::Path::new("")).join(&name);
|
||||
allow(&file).map_err(Error::Io)?;
|
||||
let script_limits = Limits { max_module_bytes: crate::js::MAX_SCRIPT_BYTES, ..Limits::default() };
|
||||
let source = read_module(&file, &script_limits, opening)?;
|
||||
let source = String::from_utf8(source).map_err(|_| Error::Module("the script is not UTF-8 text".into()))?;
|
||||
// `source` is added to the manifest's own text, so its keys keep their order. The text parsed as
|
||||
// an object that has `runtime`, so its last character other than white space is its closing `}`.
|
||||
let end = bytes.iter().rposition(|b| !b.is_ascii_whitespace()).filter(|&i| bytes[i] == b'}');
|
||||
let end = end.ok_or_else(|| Error::Manifest(format!("{}: not a JSON object", path.display())))?;
|
||||
let source = serde_json::to_vec(&Value::String(source)).map_err(|e| Error::Manifest(e.to_string()))?;
|
||||
let mut out = Vec::with_capacity(bytes.len() + source.len() + 12);
|
||||
out.extend_from_slice(&bytes[..end]);
|
||||
out.extend_from_slice(b",\"source\":");
|
||||
out.extend_from_slice(&source);
|
||||
out.push(b'}');
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The bytes of the module file at `path`. A path that doesn't name a regular file is refused
|
||||
/// before it is opened, and so is one over the module limit. On Unix the file is opened without
|
||||
/// waiting, so a named pipe put in its place after that check doesn't hold the load until something
|
||||
@@ -228,7 +403,7 @@ fn open_module(path: &std::path::Path) -> std::io::Result<std::fs::File> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_FOLDER_FILES: usize = 1000;
|
||||
|
||||
/// The first [`MAX_FOLDER_FILES`] `*.wasm` paths directly in `dir` by file name, sorted, and how
|
||||
/// The first [`MAX_FOLDER_FILES`] `*.wasm` and `*.vcplugin` paths directly in `dir` by file name, sorted, and how
|
||||
/// many more there are. Only that many paths are held while the folder is listed. An error while
|
||||
/// the folder is listed is returned, as one opening it is.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -239,7 +414,7 @@ fn folder_files(dir: &std::path::Path) -> Result<(Vec<std::path::PathBuf>, usize
|
||||
let mut more = 0;
|
||||
for entry in rd {
|
||||
let p = entry.map_err(io)?.path();
|
||||
if !p.extension().is_some_and(|x| x.eq_ignore_ascii_case("wasm")) {
|
||||
if !p.extension().is_some_and(|x| x.eq_ignore_ascii_case("wasm")) && !is_js_package(&p) {
|
||||
continue;
|
||||
}
|
||||
kept.push(p);
|
||||
@@ -267,20 +442,25 @@ pub struct FolderReport {
|
||||
/// found in a file, which is now disabled too ([`crate::safe_mode::disable_file_of`]). The app
|
||||
/// saves the list again.
|
||||
pub disabled_changed: bool,
|
||||
/// A file failed because no loader thread was left to load it ([`crate::loader::NO_THREAD`]):
|
||||
/// loading the folder again may load it.
|
||||
pub no_thread: bool,
|
||||
}
|
||||
|
||||
/// Installs every `*.wasm` directly in `dir` (not recursive), in file-name order, up to the first
|
||||
/// Installs every `*.wasm` and `*.vcplugin` ([`read_js_package`]) directly in `dir` (not recursive), in file-name order, up to the first
|
||||
/// 1,000 by file name; the report counts the files left out ([`FolderReport::left_out`]). Anything
|
||||
/// that isn't a regular file, such as a named pipe, is reported and skipped without waiting on it
|
||||
/// ([`load_file`]). A bad module is reported and skipped, the others still load; so is a heavy one
|
||||
/// ([`crate::Budget::Heavy`]), which installs only once the user agrees, and one that lists
|
||||
/// permissions the user has not granted this very module ([`approved`]).
|
||||
/// ([`load_file`]). The modules load on worker threads ([`FolderLoad`]) and install in file-name
|
||||
/// order. A bad module is reported and skipped, the others still load; so is one whose load panics
|
||||
/// or doesn't finish in time ([`crate::loader`]), a heavy one ([`crate::Budget::Heavy`]), which
|
||||
/// installs only once the user agrees, and one that lists permissions the user has not granted this
|
||||
/// very module ([`approved`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn load_folder(dir: &std::path::Path) -> Result<FolderReport> {
|
||||
load_folder_where(dir, |_| Ok(()), approved)
|
||||
}
|
||||
|
||||
/// [`load_folder`], loading only the files `allow` accepts, and of the plug-ins that list
|
||||
/// [`load_folder`], loading only the files `allow` accepts (a JavaScript plug-in's script too), and of the plug-ins that list
|
||||
/// permissions only those `approve` accepts and a recorded grant covers ([`install`]); the others
|
||||
/// are reported as failed with the reason. A plug-in the user disabled ([`crate::safe_mode::skipped`]) is reported and
|
||||
/// skipped, by its file before it loads or by its id after (its file is then disabled too, so the
|
||||
@@ -291,54 +471,255 @@ pub fn load_folder(dir: &std::path::Path) -> Result<FolderReport> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn load_folder_where(
|
||||
dir: &std::path::Path,
|
||||
allow: impl Fn(&std::path::Path) -> std::result::Result<(), String>,
|
||||
allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static,
|
||||
approve: impl Fn(&Plugin) -> bool,
|
||||
) -> Result<FolderReport> {
|
||||
use crate::safe_mode::{self, Item};
|
||||
safe_mode::check()?;
|
||||
let (files, left_out) = folder_files(dir)?;
|
||||
let mut report = FolderReport { left_out, ..FolderReport::default() };
|
||||
for f in files {
|
||||
if let Err(why) = allow(&f) {
|
||||
report.failed.push((f.display().to_string(), why));
|
||||
continue;
|
||||
let mut load = FolderLoad::begin(dir, allow)?;
|
||||
while !load.done() {
|
||||
load.wait();
|
||||
load.install_ready(&approve);
|
||||
}
|
||||
Ok(load.finish())
|
||||
}
|
||||
|
||||
/// Tests: what runs before a folder module loads, given its path.
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
type FileHook = std::sync::Arc<dyn Fn(&std::path::Path) + Send + Sync>;
|
||||
|
||||
/// Tests: runs on the worker thread before the module at the path it is given loads.
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
pub(crate) static BEFORE_FOLDER_FILE: Mutex<Option<FileHook>> = Mutex::new(None);
|
||||
|
||||
/// A [`load_folder_where`] whose modules load on worker threads ([`crate::loader`]) while the
|
||||
/// caller goes on: [`FolderLoad::begin`] lists the folder and starts the loads,
|
||||
/// [`FolderLoad::install_ready`] installs what loaded so far in file-name order, whatever order the
|
||||
/// loads finish in, and [`FolderLoad::finish`] ends the load once [`FolderLoad::done`]. A module
|
||||
/// whose load panics or doesn't finish in time is reported as failed, and the others still install.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub struct FolderLoad {
|
||||
/// Each file in file-name order, with why it was refused before loading, if it was.
|
||||
files: Vec<(std::path::PathBuf, Option<String>)>,
|
||||
loads: crate::loader::Loads<Plugin>,
|
||||
/// Outcomes taken from `loads` and not installed yet, in order.
|
||||
loaded: std::collections::VecDeque<Result<Plugin>>,
|
||||
/// The next file to install or report.
|
||||
next: usize,
|
||||
report: FolderReport,
|
||||
/// Installs and removals elsewhere since the folder was listed, which a module loaded before
|
||||
/// them doesn't undo.
|
||||
changes: LoadChanges,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl FolderLoad {
|
||||
/// Lists `dir` and starts loading the files `allow` accepts and the user didn't disable. Each
|
||||
/// file is checked with `allow` again on its worker thread, right before it is read. In Safe
|
||||
/// Mode nothing loads ([`Error::SafeMode`]); an error listing the folder is returned.
|
||||
pub fn begin(
|
||||
dir: &std::path::Path,
|
||||
allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static,
|
||||
) -> Result<FolderLoad> {
|
||||
let mut load = Self::list_on(dir, allow, None)?;
|
||||
load.start();
|
||||
Ok(load)
|
||||
}
|
||||
|
||||
/// [`FolderLoad::begin`] without starting the loads: [`FolderLoad::start`] starts them, and
|
||||
/// so does waiting for them.
|
||||
pub fn list(
|
||||
dir: &std::path::Path,
|
||||
allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static,
|
||||
) -> Result<FolderLoad> {
|
||||
Self::list_on(dir, allow, None)
|
||||
}
|
||||
|
||||
/// Starts the loads, unless they started already.
|
||||
pub fn start(&mut self) {
|
||||
self.changes.start();
|
||||
self.loads.begin();
|
||||
}
|
||||
|
||||
/// [`FolderLoad::list`] for `workers` threads (`None`: as many as [`crate::loader::Loads::start`]
|
||||
/// starts).
|
||||
fn list_on(
|
||||
dir: &std::path::Path,
|
||||
allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static,
|
||||
workers: Option<usize>,
|
||||
) -> Result<FolderLoad> {
|
||||
use crate::loader::{Job, Loads};
|
||||
use crate::safe_mode::{self, Item};
|
||||
safe_mode::check()?;
|
||||
// A change made elsewhere once the folder starts being listed is one the load doesn't undo.
|
||||
let mut changes = LoadChanges::default();
|
||||
changes.start();
|
||||
let (found, left_out) = folder_files(dir)?;
|
||||
let allow = std::sync::Arc::new(allow);
|
||||
let mut files = Vec::with_capacity(found.len());
|
||||
let mut jobs = Vec::new();
|
||||
for f in found {
|
||||
let item = Item::file(f.display().to_string());
|
||||
let refused = match allow(&f) {
|
||||
Err(why) => Some(why),
|
||||
Ok(()) if safe_mode::skipped(&item) => Some(DISABLED.to_string()),
|
||||
Ok(()) => None,
|
||||
};
|
||||
if refused.is_none() {
|
||||
let (path, allow) = (f.clone(), allow.clone());
|
||||
jobs.push(Job::new(Some(item), move || {
|
||||
allow(&path).map_err(Error::Io)?;
|
||||
#[cfg(test)]
|
||||
{
|
||||
let hook = BEFORE_FOLDER_FILE.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
if let Some(hook) = hook {
|
||||
hook(&path);
|
||||
}
|
||||
}
|
||||
load_file_where(&path, Limits::default(), &*allow)
|
||||
}));
|
||||
}
|
||||
files.push((f, refused));
|
||||
}
|
||||
let item = Item::file(f.display().to_string());
|
||||
if safe_mode::skipped(&item) {
|
||||
report.failed.push((f.display().to_string(), DISABLED.into()));
|
||||
continue;
|
||||
}
|
||||
let token = safe_mode::loading(&item);
|
||||
let loaded = load_file(&f, Limits::default());
|
||||
safe_mode::loaded(token);
|
||||
match loaded {
|
||||
Ok(p) if safe_mode::skipped(&Item::of(&p)) => {
|
||||
report.disabled_changed |= safe_mode::disable_file_of(&Item::of(&p));
|
||||
report.failed.push((f.display().to_string(), DISABLED.into()));
|
||||
}
|
||||
// A heavy plug-in installs once the user agrees, which loading a folder doesn't ask.
|
||||
Ok(p) if p.manifest().budget == crate::Budget::Heavy => {
|
||||
report.failed.push((f.display().to_string(), "asks for a heavy budget, which the user allows when installing it on its own".into()));
|
||||
}
|
||||
Ok(p) if p.manifest().asks_permissions() && !approve(&p) => {
|
||||
let asked = crate::permissions::names(&p.manifest().permissions()).join(", ");
|
||||
report.failed.push((f.display().to_string(), Error::NeedsApproval(asked).to_string()));
|
||||
}
|
||||
// `approve` only narrows what installs: `install` still refuses a module that no
|
||||
// recorded grant covers.
|
||||
Ok(p) => match install(p) {
|
||||
Ok(p) => report.loaded.push(p.id().to_string()),
|
||||
Err(e) => report.failed.push((f.display().to_string(), e.to_string())),
|
||||
},
|
||||
Err(e) => report.failed.push((f.display().to_string(), e.to_string())),
|
||||
let loads = match workers {
|
||||
Some(n) => Loads::deferred_on(jobs, n),
|
||||
None => Loads::deferred(jobs),
|
||||
};
|
||||
let report = FolderReport { left_out, ..FolderReport::default() };
|
||||
Ok(FolderLoad { files, loads, loaded: Default::default(), next: 0, report, changes })
|
||||
}
|
||||
|
||||
/// The installs and removals the load checks its modules against ([`LoadChanges`]).
|
||||
pub fn changes(&self) -> &LoadChanges {
|
||||
&self.changes
|
||||
}
|
||||
|
||||
/// [`FolderLoad::changes`], to [adopt](LoadChanges::adopt) an earlier load's.
|
||||
pub fn changes_mut(&mut self) -> &mut LoadChanges {
|
||||
&mut self.changes
|
||||
}
|
||||
|
||||
/// Whether every file has been installed or reported.
|
||||
pub fn done(&self) -> bool {
|
||||
self.next == self.files.len()
|
||||
}
|
||||
|
||||
/// Whether [`FolderLoad::install_ready`] has something to install or report now, without
|
||||
/// waiting (or nothing is left).
|
||||
pub fn ready(&mut self) -> bool {
|
||||
match self.files.get(self.next) {
|
||||
None => true,
|
||||
Some((_, Some(_))) => true,
|
||||
Some((_, None)) => !self.loaded.is_empty() || self.loads.next_ready(),
|
||||
}
|
||||
}
|
||||
for id in &report.loaded {
|
||||
if get(id).is_some_and(|p| !p.manifest().asks_permissions()) {
|
||||
revoke(id);
|
||||
|
||||
/// Waits until [`FolderLoad::ready`], starting the loads first ([`FolderLoad::start`]).
|
||||
pub fn wait(&mut self) {
|
||||
self.start();
|
||||
while !self.ready() && !self.loads.taken() {
|
||||
self.loads.wait_next();
|
||||
}
|
||||
}
|
||||
Ok(report)
|
||||
|
||||
/// Installs the plug-ins that loaded, and reports the files that failed, in file-name order up
|
||||
/// to the first file still loading, as [`load_folder_where`] does: those that list permissions
|
||||
/// only when `approve` accepts them and a recorded grant covers them → the ids it installed.
|
||||
pub fn install_ready(&mut self, approve: impl Fn(&Plugin) -> bool) -> Vec<String> {
|
||||
use crate::safe_mode::{self, Item};
|
||||
self.loaded.extend(self.loads.ready());
|
||||
let mut installed = Vec::new();
|
||||
while let Some((f, refused)) = self.files.get(self.next) {
|
||||
let name = f.display().to_string();
|
||||
if let Some(why) = refused {
|
||||
self.report.failed.push((name, why.clone()));
|
||||
self.next += 1;
|
||||
continue;
|
||||
}
|
||||
let Some(loaded) = self.loaded.pop_front() else { break };
|
||||
self.loads.release(1);
|
||||
self.next += 1;
|
||||
let report = &mut self.report;
|
||||
match loaded {
|
||||
Ok(p) if safe_mode::skipped(&Item::of(&p)) => {
|
||||
report.disabled_changed |= safe_mode::disable_file_of(&Item::of(&p));
|
||||
report.failed.push((name, DISABLED.into()));
|
||||
}
|
||||
// A heavy plug-in installs once the user agrees, which loading a folder doesn't ask.
|
||||
Ok(p) if p.manifest().budget == crate::Budget::Heavy => {
|
||||
report.failed.push((name, "asks for a heavy budget, which the user allows when installing it on its own".into()));
|
||||
}
|
||||
// The very module installed elsewhere meanwhile (another session loading the same
|
||||
// folder) counts as loaded. `approve` may record a grant, so it is asked only for
|
||||
// that module: a module another session replaced or removed changes no grant.
|
||||
Ok(p) if self.changes.superseded(p.id()) => match get(p.id()) {
|
||||
Some(q) if q.hash() == p.hash() && (!p.manifest().asks_permissions() || approve(&p)) => report.loaded.push(p.id().to_string()),
|
||||
Some(q) if q.hash() == p.hash() => {
|
||||
let asked = crate::permissions::names(&p.manifest().permissions()).join(", ");
|
||||
report.failed.push((name, Error::NeedsApproval(asked).to_string()));
|
||||
}
|
||||
_ => report.failed.push((name, SUPERSEDED.into())),
|
||||
},
|
||||
Ok(p) if p.manifest().asks_permissions() && !approve(&p) => {
|
||||
let asked = crate::permissions::names(&p.manifest().permissions()).join(", ");
|
||||
report.failed.push((name, Error::NeedsApproval(asked).to_string()));
|
||||
}
|
||||
// `approve` only narrows what installs: `install_for_load` still refuses a module that
|
||||
// no recorded grant covers, and one whose id changed elsewhere since the check above.
|
||||
Ok(p) => match install_for_load(p, &self.changes, None, || {}) {
|
||||
Ok(Some(p)) => {
|
||||
self.changes.installed(&p);
|
||||
report.loaded.push(p.id().to_string());
|
||||
installed.push(p.id().to_string());
|
||||
}
|
||||
Ok(None) => report.failed.push((name, SUPERSEDED.into())),
|
||||
Err(e) => report.failed.push((name, e.to_string())),
|
||||
},
|
||||
Err(e) => {
|
||||
report.no_thread |= matches!(&e, Error::Failed(m) if m == crate::loader::NO_THREAD);
|
||||
report.failed.push((name, e.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
installed
|
||||
}
|
||||
|
||||
/// Whether [`FolderLoad::install_ready`] turned off the file of a disabled plug-in it matched by
|
||||
/// id ([`crate::safe_mode::disable_file_of`]) since the list of disabled plug-ins was last saved
|
||||
/// ([`FolderLoad::disabled_saved`]).
|
||||
pub fn disabled_changed(&self) -> bool {
|
||||
self.report.disabled_changed
|
||||
}
|
||||
|
||||
/// The list of disabled plug-ins was saved: [`FolderLoad::disabled_changed`] is false until the
|
||||
/// load changes it again.
|
||||
pub fn disabled_saved(&mut self) {
|
||||
self.report.disabled_changed = false;
|
||||
}
|
||||
|
||||
/// Drops the loads not taken yet: jobs not started don't start, and running ones are given
|
||||
/// until their deadline ([`crate::loader::Loads`]). What was installed stays, and the load is
|
||||
/// [`FolderLoad::done`].
|
||||
pub fn cancel(&mut self) {
|
||||
self.loads = crate::loader::Loads::deferred(Vec::new());
|
||||
self.loaded.clear();
|
||||
self.next = self.files.len();
|
||||
}
|
||||
|
||||
/// Ends the load → its report. When the module the load installed under an id lists no
|
||||
/// permissions and is still installed, the process's grant for that id is forgotten. Files not
|
||||
/// installed or reported yet ([`FolderLoad::done`] false) are left out.
|
||||
pub fn finish(self) -> FolderReport {
|
||||
let FolderLoad { report, changes, .. } = self;
|
||||
for id in &report.loaded {
|
||||
// The serial is checked again while the grant is removed, so a module installed in its
|
||||
// place meanwhile keeps its grant.
|
||||
if let Some(&serial) = changes.own.get(id)
|
||||
&& get(id).is_some_and(|p| p.serial() == serial && !p.manifest().asks_permissions())
|
||||
{
|
||||
revoke_if_installed(id, serial);
|
||||
}
|
||||
}
|
||||
report
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -352,15 +733,24 @@ mod tests {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let plugin = Plugin::load(include_bytes!("../tests/fixtures/desaturate.wasm"), Limits::default()).unwrap();
|
||||
let id = plugin.id().to_string();
|
||||
let (waits, install_waits) = std::sync::mpsc::channel();
|
||||
let ours = id.clone();
|
||||
*BEFORE_INSTALL_LOCK.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(move |p: &str| {
|
||||
if p == ours {
|
||||
let _ = waits.send(());
|
||||
}
|
||||
}));
|
||||
let held = PLUGINS.read().unwrap_or_else(|e| e.into_inner());
|
||||
let before = revision();
|
||||
let installing = std::thread::spawn(move || install(plugin));
|
||||
let moved = (0..1_000_000).any(|_| {
|
||||
std::thread::yield_now();
|
||||
revision() != before
|
||||
});
|
||||
// The install has done everything it does before it waits for the set, which the test holds.
|
||||
let reached = install_waits.recv();
|
||||
let moved = revision() != before;
|
||||
drop(held);
|
||||
installing.join().unwrap().unwrap();
|
||||
let installed = installing.join();
|
||||
*BEFORE_INSTALL_LOCK.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
installed.unwrap().unwrap();
|
||||
assert!(reached.is_ok(), "the install never asked for the set");
|
||||
assert!(!moved, "the revision changed while the install waited for the set");
|
||||
assert!(revision() > before && remove(&id));
|
||||
}
|
||||
@@ -578,6 +968,104 @@ mod tests {
|
||||
assert!(matches!(&read, Err(Error::Module(e)) if e.contains("limit 16")), "{read:?}");
|
||||
}
|
||||
|
||||
/// A JavaScript plug-in's manifest file and its script, in `dir`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_js(dir: &std::path::Path, id: &str, manifest: serde_json::Value, script: Option<&str>) -> std::path::PathBuf {
|
||||
let mut m = serde_json::json!({"id": id, "name": "JS", "kind": "filter", "runtime": "js", "script": "f.js"});
|
||||
if let (Some(m), serde_json::Value::Object(extra)) = (m.as_object_mut(), manifest) {
|
||||
m.extend(extra);
|
||||
}
|
||||
let path = dir.join(format!("{id}.vcplugin"));
|
||||
std::fs::write(&path, serde_json::to_vec(&m).unwrap()).unwrap();
|
||||
if let Some(script) = script {
|
||||
std::fs::write(dir.join("f.js"), script).unwrap();
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
/// A `.vcplugin` in a folder installs with its script, and its SHA-256 is the one an install of
|
||||
/// the same package by bytes gets.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_folder_installs_a_javascript_plugin() {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = test_dir("js");
|
||||
let id = "test.registry.js";
|
||||
write_js(&dir, id, serde_json::json!({}), Some("function run(i) { return i; }"));
|
||||
let r = load_folder_where(&dir, |_| Ok(()), |_| false).unwrap();
|
||||
let bytes = read_js_package(&dir.join(format!("{id}.vcplugin")), &|_| Ok(())).unwrap();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert_eq!(r.loaded, vec![id.to_string()], "{r:?}");
|
||||
let p = get(id).unwrap();
|
||||
assert_eq!((p.script(), p.hash()), (Some("f.js"), crate::permissions::sha256_hex(&bytes).as_str()));
|
||||
assert!(remove(id));
|
||||
}
|
||||
|
||||
/// A manifest with `"runtime": "js"` and no `script` is refused, and the error names the key;
|
||||
/// so is one that names a script `allow` refuses or that isn't there.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_javascript_manifest_needs_its_script() {
|
||||
let dir = test_dir("js-script");
|
||||
let no_key = write_js(&dir, "a", serde_json::json!({"script": null}), None);
|
||||
let mut m: serde_json::Value = serde_json::from_slice(&std::fs::read(&no_key).unwrap()).unwrap();
|
||||
m.as_object_mut().unwrap().remove("script");
|
||||
std::fs::write(&no_key, serde_json::to_vec(&m).unwrap()).unwrap();
|
||||
let missing = write_js(&dir, "b", serde_json::json!({}), None);
|
||||
let inline = write_js(&dir, "c", serde_json::json!({"source": "function run(i) { return i; }"}), None);
|
||||
let not_js = write_js(&dir, "d", serde_json::json!({"runtime": "wasm"}), None);
|
||||
let refused = read_js_package(&missing, &|p| Err(format!("{} is outside", p.display())));
|
||||
let results = [
|
||||
read_js_package(&no_key, &|_| Ok(())),
|
||||
read_js_package(&missing, &|_| Ok(())),
|
||||
read_js_package(&inline, &|_| Ok(())),
|
||||
read_js_package(¬_js, &|_| Ok(())),
|
||||
];
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert!(matches!(&results[0], Err(Error::Manifest(e)) if e.starts_with("`runtime` \"js\" needs `script`")), "{:?}", results[0]);
|
||||
assert!(matches!(&results[1], Err(Error::Io(e)) if e.contains("f.js")), "{:?}", results[1]);
|
||||
assert!(matches!(&results[2], Err(Error::Manifest(e)) if e.contains("`source`")), "{:?}", results[2]);
|
||||
assert!(matches!(&results[3], Err(Error::Manifest(e)) if e == crate::js::NOT_JS), "{:?}", results[3]);
|
||||
assert!(matches!(&refused, Err(Error::Io(e)) if e.ends_with("is outside")), "{refused:?}");
|
||||
}
|
||||
|
||||
/// A script larger than the limit is refused by its size before it is opened.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn an_oversized_script_is_refused_before_it_is_read() {
|
||||
let dir = test_dir("js-big");
|
||||
let path = write_js(&dir, "big", serde_json::json!({}), Some(""));
|
||||
std::fs::File::options().write(true).open(dir.join("f.js")).unwrap().set_len(crate::js::MAX_SCRIPT_BYTES as u64 + 1).unwrap();
|
||||
let opened = std::cell::Cell::new(false);
|
||||
let read = read_js_package_with(&path, &|_| Ok(()), || opened.set(true));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert!(matches!(&read, Err(Error::Module(e)) if e.contains(&format!("limit {}", crate::js::MAX_SCRIPT_BYTES))), "{read:?}");
|
||||
assert!(!opened.get(), "the script was opened");
|
||||
}
|
||||
|
||||
/// A manifest file's parameters keep their declaration order through the package it is read
|
||||
/// into, which is its own text with `source` added.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_javascript_package_keeps_the_manifest_s_order() {
|
||||
let dir = test_dir("js-order");
|
||||
let num = r#"{"type": "number", "min": 0, "max": 10, "default": 1}"#;
|
||||
let text = format!(
|
||||
"{{\"id\": \"order\", \"name\": \"JS\", \"kind\": \"filter\", \"runtime\": \"js\", \"script\": \"f.js\", \"params\": {{\"z\": {num}, \"a\": {num}}}}}\n"
|
||||
);
|
||||
let path = dir.join("order.vcplugin");
|
||||
std::fs::write(&path, &text).unwrap();
|
||||
std::fs::write(dir.join("f.js"), "function run(i) { return i; }").unwrap();
|
||||
let bytes = read_js_package(&path, &|_| Ok(()));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
let bytes = bytes.unwrap();
|
||||
let expected = format!("{},\"source\":\"function run(i) {{ return i; }}\"}}", text.trim_end().strip_suffix('}').unwrap());
|
||||
assert_eq!(String::from_utf8_lossy(&bytes), expected);
|
||||
let (manifest, _) = crate::js::read_bundle(&bytes).unwrap();
|
||||
assert_eq!(manifest.params.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>(), ["z", "a"]);
|
||||
}
|
||||
|
||||
/// A folder load reports a subfolder, a named pipe and a link to a named pipe with `.wasm`
|
||||
/// names as not files, and goes on.
|
||||
#[cfg(unix)]
|
||||
@@ -618,4 +1106,276 @@ mod tests {
|
||||
let first: Vec<String> = (0..MAX_FOLDER_FILES).map(|i| dir.join(format!("{i:05}.wasm")).display().to_string()).collect();
|
||||
assert_eq!(tried, first, "the first files by name, in that order");
|
||||
}
|
||||
|
||||
/// Clears [`BEFORE_FOLDER_FILE`] when a test ends, failed or not.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
struct Hooked;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Hooked {
|
||||
fn set(hook: impl Fn(&std::path::Path) + Send + Sync + 'static) -> Hooked {
|
||||
*BEFORE_FOLDER_FILE.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::sync::Arc::new(hook));
|
||||
Hooked
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Drop for Hooked {
|
||||
fn drop(&mut self) {
|
||||
*BEFORE_FOLDER_FILE.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// The plug-ins of a folder install in file-name order, and take their revisions in that order,
|
||||
/// when the first file's load finishes after the others.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_folder_installs_in_file_name_order_whatever_order_the_loads_finish_in() {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = test_dir("order");
|
||||
let ids = ["test.registry.order.a", "test.registry.order.b", "test.registry.order.c"];
|
||||
for (n, id) in ["a", "b", "c"].iter().zip(ids) {
|
||||
std::fs::write(dir.join(format!("{n}.wasm")), module(id, None, 11)).unwrap();
|
||||
}
|
||||
let first = dir.join("a.wasm");
|
||||
let (go, a_waits) = std::sync::mpsc::channel::<()>();
|
||||
let a_waits = Mutex::new(a_waits);
|
||||
let (reached, a_reached) = std::sync::mpsc::channel::<()>();
|
||||
let held = first.clone();
|
||||
let _hook = Hooked::set(move |p| {
|
||||
if p == held {
|
||||
let _ = reached.send(());
|
||||
let _ = a_waits.lock().unwrap_or_else(|e| e.into_inner()).recv();
|
||||
}
|
||||
});
|
||||
// Two workers, so the other files load while the first one waits.
|
||||
let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2)).unwrap();
|
||||
load.start();
|
||||
// Bound after `load`, so a failing assertion lets the first file go before dropping `load`
|
||||
// waits for it.
|
||||
let go = go;
|
||||
a_reached.recv().unwrap();
|
||||
// The other two files load on the other worker while the first one waits: their outcomes
|
||||
// come in, and the launch marker no longer names them.
|
||||
let others = [load.loads.record_next(), load.loads.record_next()];
|
||||
let all = ["a", "b", "c"].map(|n| dir.join(format!("{n}.wasm")));
|
||||
let named = |p: &std::path::Path| {
|
||||
let item = crate::safe_mode::Item::file(p.display().to_string());
|
||||
crate::safe_mode::still_loading().iter().any(|i| i.same(&item))
|
||||
};
|
||||
assert!(others == [Some(1), Some(2)] && !named(&all[1]) && !named(&all[2]), "the other files didn't load meanwhile: {others:?}");
|
||||
let early = load.install_ready(|_| false);
|
||||
assert!(!load.done(), "the load ended while the first file waited");
|
||||
assert!(early.is_empty() && ids.iter().all(|id| get(id).is_none()), "nothing installs before the first file has loaded");
|
||||
go.send(()).unwrap();
|
||||
while !load.done() {
|
||||
load.wait();
|
||||
load.install_ready(|_| false);
|
||||
}
|
||||
let r = load.finish();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert_eq!(r.loaded, ids.to_vec(), "{r:?}");
|
||||
let serials: Vec<u64> = ids.iter().map(|id| get(id).unwrap().serial()).collect();
|
||||
assert!(serials.windows(2).all(|w| w[0] < w[1]), "installed in file-name order: {serials:?}");
|
||||
for id in ids {
|
||||
assert!(remove(id));
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder module that loaded before something else installed or removed the same id, while
|
||||
/// an earlier file still loaded, doesn't undo that change: it is reported as skipped, and the
|
||||
/// plug-in installed meanwhile stays, as does the removal.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_folder_module_doesnt_undo_a_change_made_while_it_waited() {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = test_dir("superseded");
|
||||
let ids = ["test.registry.superseded.a", "test.registry.superseded.b", "test.registry.superseded.c"];
|
||||
// b's file asks for a permission: asking whether it may install could record a grant.
|
||||
for (n, id) in ["a", "b", "c"].iter().zip(ids) {
|
||||
let asks = (*n == "b").then_some(r#"["doc.read"]"#);
|
||||
std::fs::write(dir.join(format!("{n}.wasm")), module(id, asks, 13)).unwrap();
|
||||
}
|
||||
install_bytes(&module(ids[2], None, 14)).unwrap();
|
||||
let first = dir.join("a.wasm");
|
||||
let (go, a_waits) = std::sync::mpsc::channel::<()>();
|
||||
let a_waits = Mutex::new(a_waits);
|
||||
let (reached, a_reached) = std::sync::mpsc::channel::<()>();
|
||||
let held = first.clone();
|
||||
let _hook = Hooked::set(move |p| {
|
||||
if p == held {
|
||||
let _ = reached.send(());
|
||||
let _ = a_waits.lock().unwrap_or_else(|e| e.into_inner()).recv();
|
||||
}
|
||||
});
|
||||
let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2)).unwrap();
|
||||
load.start();
|
||||
a_reached.recv().unwrap();
|
||||
// Elsewhere, while the first file still loads: `b` is installed and `c` removed.
|
||||
let theirs = install_bytes(&module(ids[1], None, 15)).unwrap().serial();
|
||||
assert!(remove(ids[2]));
|
||||
go.send(()).unwrap();
|
||||
let asked = Mutex::new(Vec::new());
|
||||
while !load.done() {
|
||||
load.wait();
|
||||
load.install_ready(|p| {
|
||||
asked.lock().unwrap_or_else(|e| e.into_inner()).push(p.id().to_string());
|
||||
false
|
||||
});
|
||||
}
|
||||
let r = load.finish();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert_eq!(r.loaded, vec![ids[0]], "{r:?}");
|
||||
assert!(r.failed.iter().all(|(_, why)| why == SUPERSEDED) && r.failed.len() == 2, "{r:?}");
|
||||
assert!(asked.lock().unwrap_or_else(|e| e.into_inner()).is_empty(), "no grant is asked for a superseded module");
|
||||
assert_eq!(get(ids[1]).map(|p| p.serial()), Some(theirs), "the plug-in installed meanwhile stays");
|
||||
assert!(get(ids[2]).is_none(), "the removal stays");
|
||||
for id in &ids[..2] {
|
||||
assert!(remove(id));
|
||||
}
|
||||
}
|
||||
|
||||
/// A plug-in installed elsewhere after the folder was listed and before its loads started
|
||||
/// stays: the folder's module with its id is skipped. One a load of the same session installed
|
||||
/// before it ([`LoadChanges::adopt`]) is replaced.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_folder_module_doesnt_undo_a_change_made_before_its_loads_started() {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = test_dir("superseded-listed");
|
||||
let ids = ["test.registry.listed.a", "test.registry.listed.b"];
|
||||
for (n, id) in ["a", "b"].iter().zip(ids) {
|
||||
std::fs::write(dir.join(format!("{n}.wasm")), module(id, None, 13)).unwrap();
|
||||
}
|
||||
let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2)).unwrap();
|
||||
// Before the loads start: another session installs `a`, and an earlier load of this
|
||||
// session installs `b`.
|
||||
let theirs = install_bytes(&module(ids[0], None, 14)).unwrap().serial();
|
||||
let mut earlier = LoadChanges::default();
|
||||
earlier.start();
|
||||
earlier.installed(&install_bytes(&module(ids[1], None, 15)).unwrap());
|
||||
load.changes_mut().adopt(&earlier);
|
||||
load.start();
|
||||
while !load.done() {
|
||||
load.wait();
|
||||
load.install_ready(|_| false);
|
||||
}
|
||||
let r = load.finish();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert_eq!(r.loaded, vec![ids[1]], "{r:?}");
|
||||
assert!(r.failed.iter().all(|(_, why)| why == SUPERSEDED) && r.failed.len() == 1, "{r:?}");
|
||||
assert_eq!(get(ids[0]).map(|p| p.serial()), Some(theirs), "the plug-in installed elsewhere stays");
|
||||
for id in ids {
|
||||
assert!(remove(id));
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder whose second module panics while it loads reports it as failed and installs the
|
||||
/// others.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_folder_module_that_panics_while_loading_fails_alone() {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = test_dir("panics");
|
||||
let ids = ["test.registry.panics.a", "test.registry.panics.b", "test.registry.panics.c"];
|
||||
for (n, id) in ["a", "b", "c"].iter().zip(ids) {
|
||||
std::fs::write(dir.join(format!("{n}.wasm")), module(id, None, 12)).unwrap();
|
||||
}
|
||||
let broken = dir.join("b.wasm");
|
||||
let hooked = broken.clone();
|
||||
let hook = Hooked::set(move |p| {
|
||||
if p == hooked {
|
||||
panic!("a defect while loading");
|
||||
}
|
||||
});
|
||||
let r = load_folder_where(&dir, |_| Ok(()), |_| false);
|
||||
drop(hook);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
let item = crate::safe_mode::Item::file(broken.display().to_string());
|
||||
let marked = crate::safe_mode::still_loading().iter().any(|i| i.same(&item));
|
||||
let r = r.unwrap();
|
||||
assert_eq!(r.loaded, vec![ids[0], ids[2]], "{r:?}");
|
||||
assert_eq!(r.failed.len(), 1, "{r:?}");
|
||||
assert!(r.failed[0].0 == broken.display().to_string() && r.failed[0].1.contains("panicked"), "{r:?}");
|
||||
assert!(!marked, "the launch marker stops naming the module whose load failed");
|
||||
for id in [ids[0], ids[2]] {
|
||||
assert!(remove(id));
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder module isn't installed over a plug-in installed elsewhere with its id while the load
|
||||
/// asked whether it may install: that plug-in stays, and the module is reported as skipped.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_folder_module_doesnt_replace_one_installed_while_it_was_approved() {
|
||||
use crate::permissions::Permission::DocRead;
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = test_dir("approving");
|
||||
let id = "test.registry.approving";
|
||||
let asking = module(id, Some(r#"["doc.read"]"#), 17);
|
||||
std::fs::write(dir.join("a.wasm"), &asking).unwrap();
|
||||
grant(GrantToken::after_engine_approval(grant_for(id, &asking, vec![DocRead])));
|
||||
let theirs = std::cell::Cell::new(None);
|
||||
let r = load_folder_where(
|
||||
&dir,
|
||||
|_| Ok(()),
|
||||
|_| {
|
||||
theirs.set(Some(install_bytes(&module(id, None, 18)).unwrap().serial()));
|
||||
true
|
||||
},
|
||||
);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
let now = get(id).map(|p| p.serial());
|
||||
assert!(remove(id));
|
||||
revoke(id);
|
||||
let r = r.unwrap();
|
||||
assert_eq!(now, theirs.get(), "the plug-in installed meanwhile was replaced: {r:?}");
|
||||
assert!(r.loaded.is_empty() && r.failed.len() == 1 && r.failed[0].1 == SUPERSEDED, "{r:?}");
|
||||
}
|
||||
|
||||
/// A grant is forgotten only while the plug-in that took the given revision is installed under
|
||||
/// its id: a plug-in installed in its place keeps the grant recorded for it.
|
||||
#[test]
|
||||
fn a_grant_is_revoked_only_for_the_plugin_still_installed() {
|
||||
use crate::permissions::Permission::DocRead;
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let id = "test.registry.revokeinstalled";
|
||||
let first = install_bytes(&module(id, None, 19)).unwrap().serial();
|
||||
let asking = module(id, Some(r#"["doc.read"]"#), 20);
|
||||
grant(GrantToken::after_engine_approval(grant_for(id, &asking, vec![DocRead])));
|
||||
let second = install_bytes(&asking).unwrap().serial();
|
||||
assert!(!revoke_if_installed(id, first), "the grant of the plug-in installed in its place was forgotten");
|
||||
assert!(granted(id).is_some());
|
||||
assert!(revoke_if_installed(id, second));
|
||||
assert!(granted(id).is_none() && remove(id));
|
||||
}
|
||||
|
||||
/// A folder file that no loader thread was left to load fails with that reason, and the report
|
||||
/// says a file found no thread ([`FolderReport::no_thread`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_folder_file_no_thread_was_left_to_load_is_reported() {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = test_dir("nothread");
|
||||
let id = "test.registry.nothread";
|
||||
std::fs::write(dir.join("a.wasm"), module(id, None, 16)).unwrap();
|
||||
let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(1)).unwrap();
|
||||
load.loads.refuse_threads = true;
|
||||
load.start();
|
||||
while !load.done() {
|
||||
load.wait();
|
||||
load.install_ready(|_| false);
|
||||
}
|
||||
let r = load.finish();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert!(get(id).is_none(), "{r:?}");
|
||||
assert_eq!(r.failed.len(), 1, "{r:?}");
|
||||
assert!(r.no_thread && r.failed[0].1.contains(crate::loader::NO_THREAD), "{r:?}");
|
||||
}
|
||||
}
|
||||
+235
-42
@@ -1,13 +1,13 @@
|
||||
//! The wasmi host: loading, instantiating and calling a plug-in under resource limits.
|
||||
|
||||
use wasmi::{
|
||||
Config, CustomFuelCosts, EnforcedLimits, Engine, Instance, Memory, Module, Store, StoreLimitsBuilder, TypedFunc, TypedResumableCall, Val,
|
||||
WasmParams, WasmResults,
|
||||
Config, CustomFuelCosts, EnforcedLimits, Engine, ExternType, Instance, Memory, Module, Store, StoreLimitsBuilder, TypedFunc, TypedResumableCall,
|
||||
Val, ValType, WasmParams, WasmResults,
|
||||
};
|
||||
use wasmparser::{Validator, WasmFeatures};
|
||||
use wasmparser::{CompositeInnerType, Parser, Payload, Validator, WasmFeatures};
|
||||
|
||||
use crate::host::{self, Bridge, Deadline, Host, Report, Run};
|
||||
use crate::manifest::{MAX_MANIFEST_BYTES, Manifest};
|
||||
use crate::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES, Manifest, Runtime};
|
||||
use crate::permissions::Permission;
|
||||
use crate::{Error, Kind, Result};
|
||||
|
||||
@@ -42,12 +42,46 @@ const WASM_FEATURES: WasmFeatures = WasmFeatures::MUTABLE_GLOBAL
|
||||
.union(WasmFeatures::EXTENDED_CONST)
|
||||
.union(WasmFeatures::FLOATS);
|
||||
|
||||
/// The most parameters or results a function type may have: the limit `EnforcedLimits::strict()`
|
||||
/// sets in wasmi 2.0.0.
|
||||
const MAX_FUNC_TYPE_VALUES: usize = 32;
|
||||
|
||||
/// Validates `bytes` with only [`WASM_FEATURES`] on, before wasmi reads the module. A module that
|
||||
/// uses any other proposal is refused with the validator's error, which names the proposal.
|
||||
/// uses any other proposal is refused with the validator's error, which names the proposal. A
|
||||
/// function type with more than [`MAX_FUNC_TYPE_VALUES`] parameters or results is refused before
|
||||
/// any function body is validated.
|
||||
fn check_features(bytes: &[u8]) -> Result<()> {
|
||||
check_func_types(bytes)?;
|
||||
Validator::new_with_features(WASM_FEATURES).validate_all(bytes).map(|_| ()).map_err(|e| Error::Module(e.to_string()))
|
||||
}
|
||||
|
||||
/// Refuses a function type in the type section with more than [`MAX_FUNC_TYPE_VALUES`] parameters
|
||||
/// or results, with wasmi's message. Reading stops at the code section. A section that doesn't
|
||||
/// parse is left to the validator, which reports it.
|
||||
fn check_func_types(bytes: &[u8]) -> Result<()> {
|
||||
for payload in Parser::new(0).parse_all(bytes) {
|
||||
let types = match payload {
|
||||
Ok(Payload::TypeSection(types)) => types,
|
||||
Ok(Payload::CodeSectionStart { .. }) | Err(_) => return Ok(()),
|
||||
Ok(_) => continue,
|
||||
};
|
||||
for group in types {
|
||||
let Ok(group) = group else { return Ok(()) };
|
||||
for ty in group.types() {
|
||||
if let CompositeInnerType::Func(f) = &ty.composite_type.inner {
|
||||
if f.params().len() > MAX_FUNC_TYPE_VALUES {
|
||||
return Err(Error::Module(format!("a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters")));
|
||||
}
|
||||
if f.results().len() > MAX_FUNC_TYPE_VALUES {
|
||||
return Err(Error::Module(format!("a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results")));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sets each WebAssembly proposal that wasmi's `Config` has a setter for in this build on or off,
|
||||
/// to match [`WASM_FEATURES`].
|
||||
fn set_features(config: &mut Config) -> &mut Config {
|
||||
@@ -135,12 +169,17 @@ impl Default for Limits {
|
||||
}
|
||||
}
|
||||
|
||||
/// A plug-in's code: a WebAssembly module, or a JavaScript file ([`crate::js`]).
|
||||
enum Code {
|
||||
Wasm { engine: Engine, module: Module },
|
||||
Js(crate::js::Script),
|
||||
}
|
||||
|
||||
/// A loaded, validated plug-in. Cheap to share (`Arc`) and safe to run from several threads:
|
||||
/// every run gets its own store and instance.
|
||||
/// every run gets its own store and instance, or for a JavaScript plug-in its own realm.
|
||||
pub struct Plugin {
|
||||
manifest: Manifest,
|
||||
engine: Engine,
|
||||
module: Module,
|
||||
code: Code,
|
||||
limits: Limits,
|
||||
size: usize,
|
||||
hash: String,
|
||||
@@ -222,15 +261,109 @@ type RunArgs = (i32, i32, i32, i32);
|
||||
/// `vc_event(event_ptr, event_len) -> 0` (anything else: the handler failed).
|
||||
type EventArgs = (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>> {
|
||||
let mut sections = module.custom_sections().filter(|s| s.name() == MANIFEST_SECTION);
|
||||
let Some(section) = sections.next() else {
|
||||
return Ok(None);
|
||||
};
|
||||
if sections.next().is_some() {
|
||||
return Err(Error::Manifest(format!("the module has more than one `{MANIFEST_SECTION}` custom section")));
|
||||
}
|
||||
let manifest = Manifest::parse(section.data())?;
|
||||
// `Manifest::parse` has checked that the section is UTF-8 JSON of at most `MAX_MANIFEST_BYTES`.
|
||||
let abi = serde_json::from_slice::<serde_json::Value>(section.data()).ok().and_then(|v| v.get("abi").and_then(serde_json::Value::as_i64));
|
||||
if abi != Some(i64::from(ABI_VERSION)) {
|
||||
return Err(Error::Abi(format!(
|
||||
"the manifest in the `{MANIFEST_SECTION}` custom section must give `abi` as {ABI_VERSION}, the ABI version this host implements"
|
||||
)));
|
||||
}
|
||||
Ok(Some(manifest))
|
||||
}
|
||||
|
||||
/// Most tables a module may define: the store an instance runs in holds no more.
|
||||
const MAX_TABLES: u64 = 4;
|
||||
/// Most elements a table may hold: the store an instance runs in holds no more.
|
||||
const MAX_TABLE_ELEMENTS: u64 = 100_000;
|
||||
|
||||
/// The number of tables the module in `bytes` defines and the largest initial size among them,
|
||||
/// from its table section, or `None` when its sections can't be read. `bytes` is a module
|
||||
/// [`check_features`] has validated.
|
||||
fn table_sizes(bytes: &[u8]) -> Option<(u64, u64)> {
|
||||
for payload in wasmparser::Parser::new(0).parse_all(bytes) {
|
||||
if let wasmparser::Payload::TableSection(reader) = payload.ok()? {
|
||||
let count = u64::from(reader.count());
|
||||
let mut largest = 0;
|
||||
for table in reader {
|
||||
largest = largest.max(table.ok()?.ty.initial);
|
||||
}
|
||||
return Some((count, largest));
|
||||
}
|
||||
}
|
||||
Some((0, 0))
|
||||
}
|
||||
|
||||
/// Checks the tables the module in `bytes` defines against the store's limits ([`MAX_TABLES`]
|
||||
/// tables of at most [`MAX_TABLE_ELEMENTS`] elements), which instantiating it checks. The host
|
||||
/// offers no tables to import, so the module defines every table it has.
|
||||
fn check_tables(bytes: &[u8]) -> Result<()> {
|
||||
let Some((count, largest)) = table_sizes(bytes) else {
|
||||
return Err(Error::Module("the module's table section could not be read".into()));
|
||||
};
|
||||
if count > MAX_TABLES || largest > MAX_TABLE_ELEMENTS {
|
||||
return Err(Error::Limit(format!(
|
||||
"table budget (the module defines {count} tables, the largest with {largest} elements; limit {MAX_TABLES} tables of {MAX_TABLE_ELEMENTS} elements)"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Checks the exports a run needs without instantiating `module`: its memory as `memory`, whose
|
||||
/// initial size fits in `max_memory_bytes`, and `vc_alloc` and `vc_run` with the ABI's types.
|
||||
fn check_exports(module: &Module, max_memory_bytes: usize) -> Result<()> {
|
||||
use ValType::{I32, I64};
|
||||
let export = |name: &str| module.exports().find(|e| e.name() == name).map(|e| e.ty().clone());
|
||||
let Some(ExternType::Memory(memory)) = export("memory") else {
|
||||
return Err(Error::Abi("the module must export its linear memory as `memory`".into()));
|
||||
};
|
||||
// Pages are 64 KiB: the engine's configuration leaves custom page sizes off.
|
||||
let initial = memory.minimum().saturating_mul(1 << 16);
|
||||
if initial > max_memory_bytes as u64 {
|
||||
return Err(Error::Limit(format!("memory budget (the module's initial memory is {initial} bytes, limit {max_memory_bytes})")));
|
||||
}
|
||||
let wanted: [(&str, &[ValType], &[ValType], &str); 2] =
|
||||
[("vc_alloc", &[I32], &[I32], "(param i32) (result i32)"), ("vc_run", &[I32, I32, I32, I32], &[I64], "(param i32 i32 i32 i32) (result i64)")];
|
||||
for (name, params, results, signature) in wanted {
|
||||
if !matches!(export(name), Some(ExternType::Func(f)) if f.params() == params && f.results() == results) {
|
||||
return Err(Error::Abi(format!("the module must export `{name}` with the type {signature}")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Plugin {
|
||||
/// Validates and loads a module: checks the ABI version, the exports and reads the manifest, and
|
||||
/// checks that each host import it asks for is one the host offers ([`crate::host::IMPORTS`])
|
||||
/// and its manifest allows. In Safe Mode nothing is loaded ([`Error::SafeMode`]).
|
||||
/// Validates and loads a module: reads the manifest, checks that each host import it asks for
|
||||
/// is one the host offers ([`crate::host::IMPORTS`]) and its manifest allows, and checks the
|
||||
/// exports. A module that carries its manifest in a [`MANIFEST_SECTION`] custom section is
|
||||
/// checked without being instantiated, so none of its code runs; one without that section is
|
||||
/// instantiated to call `vc_abi_version` and `vc_manifest`. Bytes that hold a JSON object with
|
||||
/// `"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> {
|
||||
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)));
|
||||
}
|
||||
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 };
|
||||
p.heavy_limits();
|
||||
return Ok(p);
|
||||
}
|
||||
if !bytes.starts_with(b"\0asm") {
|
||||
return Err(Error::Module("not a WebAssembly binary (missing \\0asm header)".into()));
|
||||
}
|
||||
@@ -245,39 +378,85 @@ 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 mut p = Plugin { manifest: Manifest::placeholder(), engine, module, limits, size: bytes.len(), hash, source: None, serial: 0 };
|
||||
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 section = section_manifest(&module)?;
|
||||
let mut p = Plugin {
|
||||
manifest: Manifest::placeholder(),
|
||||
code: Code::Wasm { engine, module: module.clone() },
|
||||
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()));
|
||||
}
|
||||
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)?;
|
||||
host::check_granted(&p.manifest, &imports)?;
|
||||
// A heavy filter's runs get the larger budget the host allows for one, which the host
|
||||
// lets the user allow or refuse before installing it.
|
||||
if p.manifest.budget == crate::Budget::Heavy {
|
||||
p.limits.fuel_base = p.limits.fuel_base.max(p.limits.heavy_fuel);
|
||||
p.limits.wall_time_ms = p.limits.wall_time_ms.max(p.limits.heavy_wall_time_ms);
|
||||
}
|
||||
p.heavy_limits();
|
||||
// The other exports must exist with the right types.
|
||||
live.func::<i32, i32>("vc_alloc")?;
|
||||
live.func::<RunArgs, i64>("vc_run")?;
|
||||
if !p.manifest.events.is_empty() {
|
||||
live.func::<EventArgs, i32>("vc_event")?;
|
||||
match live {
|
||||
Some(live) => {
|
||||
live.func::<i32, i32>("vc_alloc")?;
|
||||
live.func::<RunArgs, i64>("vc_run")?;
|
||||
if !p.manifest.events.is_empty() {
|
||||
live.func::<EventArgs, i32>("vc_event")?;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
check_exports(&module, p.limits.max_memory_bytes)?;
|
||||
check_tables(bytes)?;
|
||||
}
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// A heavy filter's runs get the larger budget the host allows for one, which the host lets the
|
||||
/// user allow or refuse before installing it.
|
||||
fn heavy_limits(&mut self) {
|
||||
if self.manifest.budget == crate::Budget::Heavy {
|
||||
self.limits.fuel_base = self.limits.fuel_base.max(self.limits.heavy_fuel);
|
||||
self.limits.wall_time_ms = self.limits.wall_time_ms.max(self.limits.heavy_wall_time_ms);
|
||||
}
|
||||
}
|
||||
|
||||
/// What runs its code ([`Manifest::runtime`]).
|
||||
pub fn runtime(&self) -> Runtime {
|
||||
self.manifest.runtime
|
||||
}
|
||||
|
||||
/// A JavaScript plug-in's script file name; `None` for a WebAssembly module.
|
||||
pub fn script(&self) -> Option<&str> {
|
||||
match &self.code {
|
||||
Code::Js(script) => Some(&script.name),
|
||||
Code::Wasm { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn manifest(&self) -> &Manifest {
|
||||
&self.manifest
|
||||
}
|
||||
@@ -327,15 +506,21 @@ impl Plugin {
|
||||
/// [`Plugin::instantiate`] with the start function given at most `start_fuel` instructions;
|
||||
/// the instance's store holds what it left.
|
||||
fn instantiate_with(&self, run: Run, granted: &[Permission], report: &mut Report, start_fuel: u64) -> Result<Live> {
|
||||
let limits =
|
||||
StoreLimitsBuilder::new().memory_size(self.limits.max_memory_bytes).memories(1).tables(4).table_elements(100_000).instances(1).build();
|
||||
let mut store = Store::new(&self.engine, Host { limits, run });
|
||||
let Code::Wasm { engine, module } = &self.code else { return Err(Error::Module("not a WebAssembly binary (missing \\0asm header)".into())) };
|
||||
let limits = StoreLimitsBuilder::new()
|
||||
.memory_size(self.limits.max_memory_bytes)
|
||||
.memories(1)
|
||||
.tables(MAX_TABLES as usize)
|
||||
.table_elements(MAX_TABLE_ELEMENTS as usize)
|
||||
.instances(1)
|
||||
.build();
|
||||
let mut store = Store::new(engine, Host { limits, run });
|
||||
store.limiter(|h| &mut h.limits);
|
||||
// The start function (if any) runs on one slice of fuel: it runs before `call` can check
|
||||
// the deadline or a cancel between slices, so a heavy budget would let it run for minutes.
|
||||
store.set_fuel(start_fuel.min(FUEL_SLICE)).map_err(wasm_err)?;
|
||||
let linker = host::linker(&self.engine, granted);
|
||||
let instance = match linker.instantiate_and_start(&mut store, &self.module) {
|
||||
let linker = host::linker(engine, granted);
|
||||
let instance = match linker.instantiate_and_start(&mut store, module) {
|
||||
Ok(instance) => instance,
|
||||
Err(e) => {
|
||||
*report = std::mem::take(&mut store.data_mut().run.report);
|
||||
@@ -483,6 +668,14 @@ impl Plugin {
|
||||
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));
|
||||
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()));
|
||||
}
|
||||
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 mut live = self.instantiate(run, &m.permissions(), report)?;
|
||||
// Calls can be made from `vc_run` on, not from the start function.
|
||||
if bridge.is_some() {
|
||||
|
||||
+177
-84
@@ -14,16 +14,16 @@
|
||||
//!
|
||||
//! **Launch marker** (native builds): a small file in a folder the app picks, written before the
|
||||
//! stored plug-ins load, updated before and after each module load and each live effect's first
|
||||
//! evaluation (and each evaluation that starts while one of those is running) to name the oldest
|
||||
//! item still loading (several threads can load at once), and removed
|
||||
//! when the app quits ([`begin_launch`], [`loading`], [`loaded`], [`end_launch`]). A launch that
|
||||
//! ends while an item is still loading (a panic the app caught while a plug-in loaded) keeps its
|
||||
//! marker naming that item. A marker left behind by a
|
||||
//! launch that is no longer running names the item that was loading when it stopped, which may or
|
||||
//! may not be what stopped it. Until the user
|
||||
//! chooses what to do about that item ([`forget_previous`]), the next launch's marker names it too
|
||||
//! and stays when that launch quits, so a launch that asks nothing (`--safe-mode`) or one closed in
|
||||
//! Safe Mode leaves the choice to the launch after it. Each launch has
|
||||
//! evaluation (and each evaluation that starts while one of those is running) to name every item
|
||||
//! still loading, oldest first (several threads can load at once; at most [`MAX_MARKER_ITEMS`]),
|
||||
//! and removed when the app quits ([`begin_launch`], [`loading`], [`loaded`], [`end_launch`]). A
|
||||
//! launch that ends while an item is still loading (a panic the app caught outside a load job
|
||||
//! while a plug-in loaded) keeps its marker naming that item. A marker left behind by a launch
|
||||
//! that is no longer running names the items that were loading when it stopped; any one of them,
|
||||
//! or none, may be what stopped it. Until the user chooses what to do about those items
|
||||
//! ([`forget_previous`]), the next launch's marker names them too and stays when that launch
|
||||
//! quits, so a launch that asks nothing (`--safe-mode`) or one closed in Safe Mode leaves the
|
||||
//! choice to the launch after it. Each launch has
|
||||
//! its own marker and holds a lock on a file beside it, so a launch that is still running (a second
|
||||
//! window) is never taken for one that stopped. A marker that is missing, empty, unreadable,
|
||||
//! malformed, larger than [`MAX_MARKER_BYTES`] or of another version names nothing.
|
||||
@@ -41,8 +41,11 @@ const MAX_FIELD_CHARS: usize = 1024;
|
||||
/// The most bytes one stored item takes in JSON: three fields of [`MAX_FIELD_CHARS`] characters,
|
||||
/// each written in at most 6 bytes (`\u001f`), plus keys, quotes and indentation.
|
||||
const MAX_ITEM_JSON_BYTES: usize = 3 * MAX_FIELD_CHARS * 6 + 256;
|
||||
/// The largest launch marker read, in bytes: room for one stored item.
|
||||
pub const MAX_MARKER_BYTES: u64 = (MAX_ITEM_JSON_BYTES + 256) as u64;
|
||||
/// The most items a launch marker names.
|
||||
pub const MAX_MARKER_ITEMS: usize = 16;
|
||||
/// The largest launch marker read, in bytes: room for [`MAX_MARKER_ITEMS`] stored items, and the
|
||||
/// first of them again as `item`.
|
||||
pub const MAX_MARKER_BYTES: u64 = ((MAX_MARKER_ITEMS + 1) * MAX_ITEM_JSON_BYTES + 256) as u64;
|
||||
/// The longest name an item is shown with, in characters (longer ones end with "…").
|
||||
pub const MAX_NAME_CHARS: usize = 64;
|
||||
/// The most disabled items kept.
|
||||
@@ -413,18 +416,19 @@ pub fn read_disabled_file(bytes: &[u8]) -> Option<Vec<Item>> {
|
||||
)
|
||||
}
|
||||
|
||||
/// The item the launch before this one was loading when it stopped, once [`begin_launch`] read it.
|
||||
static PREVIOUS: Mutex<Option<Item>> = Mutex::new(None);
|
||||
/// The items the launch before this one was loading when it stopped, once [`begin_launch`] read
|
||||
/// them.
|
||||
static PREVIOUS: Mutex<Vec<Item>> = Mutex::new(Vec::new());
|
||||
|
||||
/// The item the launch before this one was loading when it stopped ([`begin_launch`]); `None` once
|
||||
/// the user chose what to do about it ([`forget_previous`]).
|
||||
pub fn previous() -> Option<Item> {
|
||||
/// The items the launch before this one was loading when it stopped, oldest first
|
||||
/// ([`begin_launch`]); none once the user chose what to do about them ([`forget_previous`]).
|
||||
pub fn previous() -> Vec<Item> {
|
||||
PREVIOUS.lock().unwrap_or_else(|e| e.into_inner()).clone()
|
||||
}
|
||||
|
||||
/// The user chose what to do about [`previous`]: this launch's marker stops naming it.
|
||||
/// The user chose what to do about [`previous`]: this launch's marker stops naming them.
|
||||
pub fn forget_previous() {
|
||||
*PREVIOUS.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
PREVIOUS.lock().unwrap_or_else(|e| e.into_inner()).clear();
|
||||
refresh();
|
||||
}
|
||||
|
||||
@@ -437,9 +441,19 @@ struct Running {
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Running {
|
||||
/// The item this launch's marker names: the oldest item still loading, else [`previous`].
|
||||
fn pending(&self) -> Option<Item> {
|
||||
self.items.first().map(|(_, i)| i.clone()).or_else(previous)
|
||||
/// The items this launch's marker names: the items still loading, oldest first, each plug-in
|
||||
/// once, at most [`MAX_MARKER_ITEMS`]; with none loading, [`previous`].
|
||||
fn pending(&self) -> Vec<Item> {
|
||||
let mut items: Vec<Item> = Vec::new();
|
||||
for (_, item) in &self.items {
|
||||
if items.len() == MAX_MARKER_ITEMS {
|
||||
break;
|
||||
}
|
||||
if !items.iter().any(|i| i.same(item)) {
|
||||
items.push(item.clone());
|
||||
}
|
||||
}
|
||||
if items.is_empty() { previous() } else { items }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -450,22 +464,33 @@ static LOADING: Mutex<Running> = Mutex::new(Running { next: 0, items: Vec::new()
|
||||
#[derive(Debug)]
|
||||
pub struct Loading(u64);
|
||||
|
||||
/// Writes this launch's marker naming the item [`Running::pending`] gives, while holding the lock
|
||||
/// Writes this launch's marker naming the items [`Running::pending`] gives, while holding the lock
|
||||
/// on the items still loading, so two threads' writes land in the order of their changes.
|
||||
fn refresh() {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
marker::write(LOADING.lock().unwrap_or_else(|e| e.into_inner()).pending().as_ref());
|
||||
marker::write(&LOADING.lock().unwrap_or_else(|e| e.into_inner()).pending());
|
||||
}
|
||||
|
||||
/// The marker's content naming `item`, cut as a stored item is (none: nothing is loading).
|
||||
/// The marker's content naming `items` (none: nothing is loading), each cut as a stored item is,
|
||||
/// at most [`MAX_MARKER_ITEMS`]: the first as `item`, and all of them as `items` when there are
|
||||
/// several.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn marker_bytes(item: Option<&Item>) -> Vec<u8> {
|
||||
let item = item.cloned().and_then(Item::bounded);
|
||||
serde_json::to_vec(&json!({"format": MARKER_FORMAT, "version": MARKER_VERSION, "item": item})).unwrap_or_default()
|
||||
fn marker_bytes(items: &[Item]) -> Vec<u8> {
|
||||
let items: Vec<Item> = items.iter().cloned().filter_map(Item::bounded).take(MAX_MARKER_ITEMS).collect();
|
||||
let mut v = json!({"format": MARKER_FORMAT, "version": MARKER_VERSION, "item": items.first()});
|
||||
if items.len() > 1 {
|
||||
v["items"] = json!(items);
|
||||
}
|
||||
serde_json::to_vec(&v).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The item a marker's content names; `None` when it names none or isn't a marker of this version.
|
||||
pub fn parse_marker(bytes: &[u8]) -> Option<Item> {
|
||||
/// The items a marker's content names, oldest first: its `items` when it has them, else its
|
||||
/// `item`; none when it names none or isn't a marker of this version.
|
||||
pub fn parse_marker(bytes: &[u8]) -> Vec<Item> {
|
||||
read_marker(bytes).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn read_marker(bytes: &[u8]) -> Option<Vec<Item>> {
|
||||
if bytes.len() as u64 > MAX_MARKER_BYTES {
|
||||
return None;
|
||||
}
|
||||
@@ -473,31 +498,44 @@ pub fn parse_marker(bytes: &[u8]) -> Option<Item> {
|
||||
if v["format"] != MARKER_FORMAT || v["version"] != MARKER_VERSION {
|
||||
return None;
|
||||
}
|
||||
serde_json::from_value::<Item>(v.get("item").filter(|i| i.is_object())?.clone()).ok()?.bounded()
|
||||
let item = |i: &Value| serde_json::from_value::<Item>(i.clone()).ok()?.bounded();
|
||||
let mut items: Vec<Item> = Vec::new();
|
||||
for i in v["items"].as_array().into_iter().flatten().filter(|i| i.is_object()) {
|
||||
if items.len() == MAX_MARKER_ITEMS {
|
||||
break;
|
||||
}
|
||||
if let Some(i) = item(i).filter(|i| !items.iter().any(|e| e.same(i))) {
|
||||
items.push(i);
|
||||
}
|
||||
}
|
||||
if items.is_empty() {
|
||||
items.extend(v.get("item").filter(|i| i.is_object()).and_then(item));
|
||||
}
|
||||
Some(items)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use marker::{begin_launch, end_launch};
|
||||
|
||||
/// Adds `item` to the items still loading and writes this launch's marker naming the oldest of
|
||||
/// them (no marker: only the list changes) → the [`Loading`] to give to [`loaded`] when it is done.
|
||||
/// Adds `item` to the items still loading and writes this launch's marker naming them (no marker:
|
||||
/// only the list changes) → the [`Loading`] to give to [`loaded`] when it is done.
|
||||
pub fn loading(item: &Item) -> Loading {
|
||||
let mut running = LOADING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let token = running.next;
|
||||
running.next = running.next.wrapping_add(1);
|
||||
running.items.push((token, item.clone()));
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
marker::write(running.pending().as_ref());
|
||||
marker::write(&running.pending());
|
||||
Loading(token)
|
||||
}
|
||||
|
||||
/// Removes the item `token` names from the items still loading and writes this launch's marker
|
||||
/// naming the oldest one left; with none left, the item of [`previous`] or nothing.
|
||||
/// naming the ones left; with none left, the items of [`previous`] or nothing.
|
||||
pub fn loaded(token: Loading) {
|
||||
let mut running = LOADING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
running.items.retain(|(t, _)| *t != token.0);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
marker::write(running.pending().as_ref());
|
||||
marker::write(&running.pending());
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -551,12 +589,12 @@ mod marker {
|
||||
(bytes.len() as u64 <= MAX_MARKER_BYTES).then_some(bytes)
|
||||
}
|
||||
|
||||
/// Starts this launch's marker in `dir` → the item a launch that is no longer running was
|
||||
/// loading when it stopped, if one was (its marker is then removed, and this launch's marker
|
||||
/// names the item until [`super::forget_previous`]). A folder that can't be written leaves this
|
||||
/// launch without a marker; it still starts.
|
||||
pub fn begin_launch(dir: &Path) -> Option<Item> {
|
||||
let mut previous = None;
|
||||
/// Starts this launch's marker in `dir` → the items a launch that is no longer running was
|
||||
/// loading when it stopped, if it was loading any (its marker is then removed, and this
|
||||
/// launch's marker names the items until [`super::forget_previous`]). A folder that can't be
|
||||
/// written leaves this launch without a marker; it still starts.
|
||||
pub fn begin_launch(dir: &Path) -> Vec<Item> {
|
||||
let mut previous = Vec::new();
|
||||
let mut tokens: Vec<String> = std::fs::read_dir(dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
@@ -569,8 +607,8 @@ mod marker {
|
||||
if running(dir, &token) {
|
||||
continue;
|
||||
}
|
||||
if previous.is_none() {
|
||||
previous = read(&json_path(dir, &token)).as_deref().and_then(parse_marker);
|
||||
if previous.is_empty() {
|
||||
previous = read(&json_path(dir, &token)).as_deref().map(parse_marker).unwrap_or_default();
|
||||
}
|
||||
for path in [json_path(dir, &token), tmp_path(dir, &token), lock_path(dir, &token)] {
|
||||
let _ = std::fs::remove_file(path);
|
||||
@@ -588,32 +626,32 @@ mod marker {
|
||||
previous
|
||||
}
|
||||
|
||||
/// Replaces this launch's marker with one naming `item`: written to a temporary file first,
|
||||
/// Replaces this launch's marker with one naming `items`: written to a temporary file first,
|
||||
/// then renamed over the marker, so a reader finds the old marker or the new one. A write that
|
||||
/// fails leaves the marker as it was.
|
||||
pub(super) fn write(item: Option<&Item>) {
|
||||
pub(super) fn write(items: &[Item]) {
|
||||
let current = CURRENT.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Some(c) = current.as_ref() else { return };
|
||||
let tmp = tmp_path(&c.dir, &c.token);
|
||||
let _ = File::create(&tmp)
|
||||
.and_then(|mut f| f.write_all(&marker_bytes(item)).and_then(|()| f.sync_all()))
|
||||
.and_then(|mut f| f.write_all(&marker_bytes(items)).and_then(|()| f.sync_all()))
|
||||
.and_then(|()| std::fs::rename(&tmp, json_path(&c.dir, &c.token)));
|
||||
}
|
||||
|
||||
/// Removes this launch's marker: the app is quitting normally. While an item is still loading
|
||||
/// ([`super::loading`] without [`super::loaded`]), the marker stays, naming the oldest one;
|
||||
/// otherwise, while the user has not chosen what to do about [`super::previous`], the marker
|
||||
/// stays, naming that, so the next launch asks.
|
||||
/// ([`super::loading`] without [`super::loaded`]), the marker stays, naming the items still
|
||||
/// loading; otherwise, while the user has not chosen what to do about [`super::previous`], the
|
||||
/// marker stays, naming those, so the next launch asks.
|
||||
pub fn end_launch() {
|
||||
let running = LOADING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let pending = running.pending();
|
||||
if pending.is_some() {
|
||||
write(pending.as_ref());
|
||||
if !pending.is_empty() {
|
||||
write(&pending);
|
||||
}
|
||||
let Some(c) = CURRENT.lock().unwrap_or_else(|e| e.into_inner()).take() else { return };
|
||||
let Current { dir, token, _lock } = c;
|
||||
drop(_lock);
|
||||
let marker = pending.is_none().then(|| json_path(&dir, &token));
|
||||
let marker = pending.is_empty().then(|| json_path(&dir, &token));
|
||||
for path in marker.into_iter().chain([tmp_path(&dir, &token), lock_path(&dir, &token)]) {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
@@ -629,6 +667,12 @@ mod marker {
|
||||
#[cfg(test)]
|
||||
pub(crate) static TEST_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Tests: the items still loading, oldest first.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn still_loading() -> Vec<Item> {
|
||||
LOADING.lock().unwrap_or_else(|e| e.into_inner()).items.iter().map(|(_, i)| i.clone()).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -683,11 +727,18 @@ mod tests {
|
||||
assert_eq!(Item::file("C:\\Plug-ins\\x.wasm").label(), "x.wasm");
|
||||
}
|
||||
|
||||
/// The items the marker at `path` names.
|
||||
fn marker_at(path: &std::path::Path) -> Vec<Item> {
|
||||
std::fs::read(path).ok().as_deref().map(parse_marker).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_marker_of_this_version_names_an_item() {
|
||||
let item = Item { id: Some("org.example.x".into()), file: Some("/p/x.wasm".into()), name: None };
|
||||
assert_eq!(parse_marker(&marker_bytes(Some(&item))), Some(item));
|
||||
assert_eq!(parse_marker(&marker_bytes(None)), None, "nothing was loading");
|
||||
assert_eq!(parse_marker(&marker_bytes(std::slice::from_ref(&item))), std::slice::from_ref(&item));
|
||||
assert_eq!(parse_marker(&marker_bytes(&[])), [], "nothing was loading");
|
||||
// A marker naming one item has no `items`, as before markers named several.
|
||||
assert!(!String::from_utf8(marker_bytes(std::slice::from_ref(&item))).unwrap().contains("\"items\""));
|
||||
for bad in [
|
||||
&b""[..],
|
||||
b"{",
|
||||
@@ -698,13 +749,28 @@ mod tests {
|
||||
br#"{"format":"vectorcraft-launch","version":1,"item":{}}"#,
|
||||
br#"{"format":"vectorcraft-launch","version":1,"item":{"id":"x""#,
|
||||
] {
|
||||
assert_eq!(parse_marker(bad), None, "{}", String::from_utf8_lossy(bad));
|
||||
assert_eq!(parse_marker(bad), [], "{}", String::from_utf8_lossy(bad));
|
||||
}
|
||||
let mut big =
|
||||
format!(r#"{{"format":"vectorcraft-launch","version":1,"item":{{"id":"{}"}}}}"#, "y".repeat(MAX_MARKER_BYTES as usize)).into_bytes();
|
||||
assert_eq!(parse_marker(&big), None, "larger than the limit");
|
||||
assert_eq!(parse_marker(&big), [], "larger than the limit");
|
||||
big.truncate(10);
|
||||
assert_eq!(parse_marker(&big), None, "cut short");
|
||||
assert_eq!(parse_marker(&big), [], "cut short");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_marker_names_every_item_up_to_its_limit() {
|
||||
let field = |i: usize, tag: &str| format!("{tag}{i:04}{}", "\u{1}".repeat(MAX_FIELD_CHARS));
|
||||
let items: Vec<Item> =
|
||||
(0..MAX_MARKER_ITEMS + 3).map(|i| Item { id: Some(field(i, "i")), file: Some(field(i, "f")), name: Some(field(i, "n")) }).collect();
|
||||
let bytes = marker_bytes(&items);
|
||||
assert!(bytes.len() as u64 <= MAX_MARKER_BYTES, "{} bytes", bytes.len());
|
||||
let read = parse_marker(&bytes);
|
||||
assert_eq!(read.len(), MAX_MARKER_ITEMS);
|
||||
assert!(read.iter().zip(&items).all(|(r, i)| r.same(i)), "oldest first");
|
||||
// A marker whose `items` names nothing readable falls back to its `item`.
|
||||
let x = br#"{"format":"vectorcraft-launch","version":1,"item":{"id":"x"},"items":[{},"y"]}"#;
|
||||
assert_eq!(parse_marker(x), [Item { id: Some("x".into()), ..Item::default() }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -714,23 +780,23 @@ mod tests {
|
||||
// A launch that stopped while loading x: its marker without a held lock, and a stray
|
||||
// temporary file from a write it didn't finish.
|
||||
let x = Item { id: Some("org.example.x".into()), file: None, name: Some("X".into()) };
|
||||
std::fs::write(dir.join("launch-1-a.json"), marker_bytes(Some(&x))).unwrap();
|
||||
std::fs::write(dir.join("launch-1-a.json"), marker_bytes(std::slice::from_ref(&x))).unwrap();
|
||||
std::fs::write(dir.join("launch-1-a.json.tmp"), b"{\"format\":\"vectorcr").unwrap();
|
||||
assert_eq!(begin_launch(&dir), Some(x.clone()));
|
||||
assert_eq!(previous(), Some(x.clone()));
|
||||
assert_eq!(begin_launch(&dir), std::slice::from_ref(&x));
|
||||
assert_eq!(previous(), std::slice::from_ref(&x));
|
||||
assert!(!dir.join("launch-1-a.json").exists() && !dir.join("launch-1-a.json.tmp").exists(), "read once");
|
||||
let mine = marker::path_of_current().unwrap();
|
||||
assert_eq!(std::fs::read(&mine).ok().as_deref().and_then(parse_marker), Some(x.clone()), "named until the user chooses");
|
||||
assert_eq!(marker_at(&mine), std::slice::from_ref(&x), "named until the user chooses");
|
||||
forget_previous();
|
||||
assert_eq!(std::fs::read(&mine).ok().as_deref().and_then(parse_marker), None);
|
||||
assert_eq!(marker_at(&mine), []);
|
||||
let token = loading(&x);
|
||||
assert_eq!(std::fs::read(&mine).ok().as_deref().and_then(parse_marker), Some(x.clone()));
|
||||
assert_eq!(marker_at(&mine), std::slice::from_ref(&x));
|
||||
assert!(!mine.with_extension("json.tmp").exists(), "the temporary file is renamed over the marker");
|
||||
loaded(token);
|
||||
assert_eq!(std::fs::read(&mine).ok().as_deref().and_then(parse_marker), None);
|
||||
assert_eq!(marker_at(&mine), []);
|
||||
end_launch();
|
||||
assert!(!mine.exists(), "a normal quit removes the marker");
|
||||
assert_eq!(begin_launch(&dir), None, "nothing left behind");
|
||||
assert_eq!(begin_launch(&dir), [], "nothing left behind");
|
||||
end_launch();
|
||||
forget_previous();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
@@ -741,13 +807,13 @@ mod tests {
|
||||
let _f = fresh();
|
||||
let dir = temp_dir("pending");
|
||||
let x = Item { id: Some("org.example.x".into()), file: None, name: Some("X".into()) };
|
||||
std::fs::write(dir.join("launch-1-a.json"), marker_bytes(Some(&x))).unwrap();
|
||||
assert_eq!(begin_launch(&dir), Some(x.clone()));
|
||||
std::fs::write(dir.join("launch-1-a.json"), marker_bytes(std::slice::from_ref(&x))).unwrap();
|
||||
assert_eq!(begin_launch(&dir), std::slice::from_ref(&x));
|
||||
end_launch();
|
||||
assert_eq!(begin_launch(&dir), Some(x.clone()), "asked again");
|
||||
assert_eq!(begin_launch(&dir), std::slice::from_ref(&x), "asked again");
|
||||
forget_previous();
|
||||
end_launch();
|
||||
assert_eq!(begin_launch(&dir), None, "once the user chose");
|
||||
assert_eq!(begin_launch(&dir), [], "once the user chose");
|
||||
end_launch();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -757,15 +823,15 @@ mod tests {
|
||||
let _f = fresh();
|
||||
let dir = temp_dir("ends-loading");
|
||||
let x = Item { id: Some("org.example.x".into()), file: None, name: Some("X".into()) };
|
||||
assert_eq!(begin_launch(&dir), None);
|
||||
assert_eq!(begin_launch(&dir), []);
|
||||
let token = loading(&x);
|
||||
// A panic the app caught while x loaded: the app quits without `loaded`.
|
||||
end_launch();
|
||||
loaded(token);
|
||||
assert_eq!(begin_launch(&dir), Some(x.clone()), "the next launch asks");
|
||||
assert_eq!(begin_launch(&dir), std::slice::from_ref(&x), "the next launch asks");
|
||||
forget_previous();
|
||||
end_launch();
|
||||
assert_eq!(begin_launch(&dir), None);
|
||||
assert_eq!(begin_launch(&dir), []);
|
||||
end_launch();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -776,22 +842,49 @@ mod tests {
|
||||
let dir = temp_dir("two-loading");
|
||||
let a = Item { id: Some("org.example.a".into()), file: None, name: Some("A".into()) };
|
||||
let b = Item { id: Some("org.example.b".into()), file: None, name: Some("B".into()) };
|
||||
assert_eq!(begin_launch(&dir), None);
|
||||
assert_eq!(begin_launch(&dir), []);
|
||||
let mine = marker::path_of_current().unwrap();
|
||||
let marker = || std::fs::read(&mine).ok().as_deref().and_then(parse_marker);
|
||||
// Two threads run their plug-ins' first evaluations at once.
|
||||
let ta = loading(&a);
|
||||
let tb = loading(&b);
|
||||
assert_eq!(marker(), Some(a.clone()), "the oldest item still loading");
|
||||
assert_eq!(marker_at(&mine), [a.clone(), b.clone()], "both items still loading, oldest first");
|
||||
loaded(ta);
|
||||
assert_eq!(marker(), Some(b.clone()), "b is still loading");
|
||||
assert_eq!(marker_at(&mine), std::slice::from_ref(&b), "b is still loading");
|
||||
// The app stops while b loads.
|
||||
end_launch();
|
||||
loaded(tb);
|
||||
assert_eq!(begin_launch(&dir), Some(b.clone()), "the next launch offers b");
|
||||
assert_eq!(begin_launch(&dir), std::slice::from_ref(&b), "the next launch offers b");
|
||||
forget_previous();
|
||||
end_launch();
|
||||
assert_eq!(begin_launch(&dir), None);
|
||||
assert_eq!(begin_launch(&dir), []);
|
||||
end_launch();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A launch that stops while two plug-ins load offers both at the next launch, until the user
|
||||
/// chooses, however many launches that takes.
|
||||
#[test]
|
||||
fn a_launch_that_stops_while_two_plug_ins_load_offers_both() {
|
||||
let _f = fresh();
|
||||
let dir = temp_dir("two-stopped");
|
||||
let a = Item { id: Some("org.example.a".into()), file: None, name: Some("A".into()) };
|
||||
let b = Item { id: Some("org.example.b".into()), file: None, name: Some("B".into()) };
|
||||
assert_eq!(begin_launch(&dir), []);
|
||||
let ta = loading(&a);
|
||||
let tb = loading(&b);
|
||||
// The same plug-in loading twice is named once.
|
||||
let ta2 = loading(&a);
|
||||
end_launch();
|
||||
for t in [ta, tb, ta2] {
|
||||
loaded(t);
|
||||
}
|
||||
assert_eq!(begin_launch(&dir), [a.clone(), b.clone()], "the next launch offers both");
|
||||
assert_eq!(previous(), [a.clone(), b.clone()]);
|
||||
end_launch();
|
||||
assert_eq!(begin_launch(&dir), [a.clone(), b.clone()], "asked again");
|
||||
forget_previous();
|
||||
end_launch();
|
||||
assert_eq!(begin_launch(&dir), []);
|
||||
end_launch();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -802,11 +895,11 @@ mod tests {
|
||||
let dir = temp_dir("long-path");
|
||||
// Each character written as 6 or 2 bytes, so the item is far larger in JSON than in characters.
|
||||
let long = format!("C:\\{}\\x.wasm", "\u{1}é".repeat(700));
|
||||
assert_eq!(begin_launch(&dir), None);
|
||||
assert_eq!(begin_launch(&dir), []);
|
||||
let token = loading(&Item::file(long.clone()));
|
||||
end_launch();
|
||||
loaded(token);
|
||||
let stopped = begin_launch(&dir).expect("the marker names the module");
|
||||
let stopped = begin_launch(&dir).into_iter().next().expect("the marker names the module");
|
||||
assert!(stopped.same(&Item::file(long.clone())), "the stored item matches the full path");
|
||||
disable(stopped);
|
||||
assert!(skipped(&Item::file(long.clone())), "Disable and Continue skips it");
|
||||
@@ -891,14 +984,14 @@ mod tests {
|
||||
let _f = fresh();
|
||||
let dir = temp_dir("running");
|
||||
let x = Item { id: Some("org.example.x".into()), file: None, name: None };
|
||||
std::fs::write(dir.join("launch-9-b.json"), marker_bytes(Some(&x))).unwrap();
|
||||
std::fs::write(dir.join("launch-9-b.json"), marker_bytes(std::slice::from_ref(&x))).unwrap();
|
||||
let lock = std::fs::File::create(dir.join("launch-9-b.lock")).unwrap();
|
||||
lock.try_lock().unwrap();
|
||||
assert_eq!(begin_launch(&dir), None, "that launch is still running");
|
||||
assert_eq!(begin_launch(&dir), [], "that launch is still running");
|
||||
assert!(dir.join("launch-9-b.json").exists());
|
||||
end_launch();
|
||||
drop(lock);
|
||||
assert_eq!(begin_launch(&dir), Some(x), "once it stopped");
|
||||
assert_eq!(begin_launch(&dir), [x], "once it stopped");
|
||||
end_launch();
|
||||
forget_previous();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
@@ -7,12 +7,26 @@ const OUTPUT_AT: usize = 0x1_0000;
|
||||
/// `s` as the body of a WAT string literal (every byte that isn't a letter, digit or space
|
||||
/// escaped).
|
||||
pub fn string(s: &str) -> String {
|
||||
s.bytes().map(|b| if b.is_ascii_alphanumeric() || b == b' ' { char::from(b).to_string() } else { format!("\\{b:02x}") }).collect()
|
||||
bytes(s.as_bytes())
|
||||
}
|
||||
|
||||
/// `data` as the body of a WAT string literal, every byte that isn't an ASCII letter, digit or
|
||||
/// space escaped (so it may hold any bytes, UTF-8 or not).
|
||||
pub fn bytes(data: &[u8]) -> String {
|
||||
data.iter().map(|&b| if b.is_ascii_alphanumeric() || b == b' ' { char::from(b).to_string() } else { format!("\\{b:02x}") }).collect()
|
||||
}
|
||||
|
||||
/// `vc_alloc`, which grows memory by whole pages, so its blocks never overlap data segments.
|
||||
const ALLOC: &str = r#"(func (export "vc_alloc") (param $n i32) (result i32) (local $old i32)
|
||||
(local.set $old (memory.grow (i32.shr_u (i32.add (local.get $n) (i32.const 65535)) (i32.const 16))))
|
||||
(if (result i32) (i32.eq (local.get $old) (i32.const -1)) (then (i32.const 0)) (else (i32.mul (local.get $old) (i32.const 65536)))))"#;
|
||||
|
||||
/// A plug-in module: `manifest` (JSON), a `vc_run` whose body is `run` (parameters `$in $il $pp
|
||||
/// $pl`, result i64), extra module fields `extra` and `pages` of initial memory. `vc_alloc` grows
|
||||
/// memory by whole pages, so its blocks never overlap data segments.
|
||||
/// $pl`, result i64), extra module fields `extra` and `pages` of initial memory (at least 1: with
|
||||
/// none, the first `vc_alloc` block would start at 0, which the host refuses). `vc_alloc` grows
|
||||
/// memory by whole pages, so its blocks never overlap data segments. The manifest comes from the
|
||||
/// `vc_manifest` export, which the host calls when it loads the module ([`sectioned`] carries it in
|
||||
/// a custom section instead).
|
||||
pub fn module(manifest: &str, run: &str, extra: &str, pages: u32) -> String {
|
||||
format!(
|
||||
r#"(module
|
||||
@@ -21,16 +35,50 @@ pub fn module(manifest: &str, run: &str, extra: &str, pages: u32) -> String {
|
||||
(data (i32.const 16) "{data}")
|
||||
(func (export "vc_abi_version") (result i32) (i32.const 1))
|
||||
(func (export "vc_manifest") (result i64) (i64.or (i64.shl (i64.const {len}) (i64.const 32)) (i64.const 16)))
|
||||
(func (export "vc_alloc") (param $n i32) (result i32) (local $old i32)
|
||||
(local.set $old (memory.grow (i32.shr_u (i32.add (local.get $n) (i32.const 65535)) (i32.const 16))))
|
||||
(if (result i32) (i32.eq (local.get $old) (i32.const -1)) (then (i32.const 0)) (else (i32.mul (local.get $old) (i32.const 65536)))))
|
||||
{ALLOC}
|
||||
(func (export "vc_run") (param $in i32) (param $il i32) (param $pp i32) (param $pl i32) (result i64)
|
||||
{run}))"#,
|
||||
pages = pages.max(1),
|
||||
data = string(manifest),
|
||||
len = manifest.len(),
|
||||
)
|
||||
}
|
||||
|
||||
/// A custom section named `name` holding `data`, as a module field.
|
||||
pub fn custom_section(name: &str, data: &[u8]) -> String {
|
||||
format!(r#"(@custom "{}" "{}")"#, string(name), bytes(data))
|
||||
}
|
||||
|
||||
/// A plug-in module like [`module`] that carries `manifest` in its `vc_manifest` custom section
|
||||
/// ([`crate::manifest::MANIFEST_SECTION`]) and exports only `memory`, `vc_alloc` and `vc_run`: the
|
||||
/// host reads the manifest without running any of its code. The host loads it only when `manifest`
|
||||
/// gives `"abi": 1`. It has `pages` of initial memory, at least 1, as [`module`] has.
|
||||
pub fn sectioned(manifest: &str, run: &str, extra: &str, pages: u32) -> String {
|
||||
format!(
|
||||
r#"(module
|
||||
{section}
|
||||
{extra}
|
||||
(memory (export "memory") {pages})
|
||||
{ALLOC}
|
||||
(func (export "vc_run") (param $in i32) (param $il i32) (param $pp i32) (param $pl i32) (result i64)
|
||||
{run}))"#,
|
||||
section = custom_section(crate::manifest::MANIFEST_SECTION, manifest.as_bytes()),
|
||||
pages = pages.max(1),
|
||||
)
|
||||
}
|
||||
|
||||
/// `module` (a module in WebAssembly text that starts with `(module`, after any white space) with
|
||||
/// the module field `field` added first, after the module's `$name` when it has one, such as a
|
||||
/// [`custom_section`]; `None` when `module` does not start with `(module`.
|
||||
pub fn with_field(module: &str, field: &str) -> Option<String> {
|
||||
let rest = module.trim_start().strip_prefix("(module")?;
|
||||
let Some(id) = rest.trim_start().strip_prefix('$') else {
|
||||
return Some(format!("(module\n {field}{rest}"));
|
||||
};
|
||||
let (name, rest) = id.split_at(id.find(|c: char| c.is_whitespace() || c == '(' || c == ')').unwrap_or(id.len()));
|
||||
Some(format!("(module ${name}\n {field}{rest}"))
|
||||
}
|
||||
|
||||
/// A `vc_run` body returning the input unchanged.
|
||||
pub const ECHO: &str = "(i64.or (i64.shl (i64.extend_i32_u (local.get $il)) (i64.const 32)) (i64.extend_i32_u (local.get $in)))";
|
||||
|
||||
|
||||
Reference in new issue
Block a user