Merge pull request #9139 from dotCooCoo/feat/plugin-api-events

Plug-ins: react to selection, layer, open and save events
This commit is contained in:
.CooCoo
2026-12-02 11:15:23 -08:00
committed by GitHub
34 changed files with 2880 additions and 29 deletions
+5
View File
@@ -18,13 +18,16 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
// A drag or typing still in progress is a step of its own, as before Undo: the batch's steps
// would otherwise run inside it and take its baseline as theirs (#1697).
if s.active().is_some() && !s.previewing {
let open = s.holds_interaction() || s.docs.iter().any(|d| d.interaction.is_some());
super::super::edit::settle_interaction(s)?;
s.plugin_events_batch_settled(open);
}
let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone());
// The documents as they are now, whole: what a failed step brings back. Their art, history,
// file, format and saved state share their data with the open ones until a step changes them.
let start = s.docs.clone();
let active = s.active;
let opens = s.plugin_events_mark();
s.batch_stash = Some(vec![]);
let mut grouped = Vec::with_capacity(cmds.len());
// The Type tool keeps what the steps' Undo and Redo change in it, to put back on a rollback.
@@ -39,6 +42,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
}
Err(e) => {
roll_back(s, start, &stash);
// The documents the steps opened are closed again: plug-ins are not told of them.
s.forget_plugin_opens_since(opens);
s.notify_text_tool("batch.rollBack");
s.active = active;
s.sync_front_profiles();
+2 -1
View File
@@ -1060,7 +1060,8 @@ fn open_loaded(
st.import_losses = losses;
st.links_from = read_from;
let opened = &s.documents()[index];
let (title, file_info_title) = (opened.title(), opened.doc.info_title().to_string());
let (title, file_info_title, uid) = (opened.title(), opened.doc.info_title().to_string(), opened.uid);
s.note_plugin_event(vectorcraft_plugins::Event::DocumentOpened, uid);
Ok(super::merge(
json!({ "index": index, "title": title, "fileInfoTitle": file_info_title, "format": format.id, "warnings": warnings, "restored": restored }),
links.to_json(),
+2
View File
@@ -1219,6 +1219,8 @@ impl SaveJob {
}
if saved {
crate::cmd::recovery::forget(s, uid);
// Also when the document closed while its file was being written.
s.note_plugin_event(vectorcraft_plugins::Event::DocumentSaved, uid);
}
if let Some(path) = written {
if native {
+13 -3
View File
@@ -134,6 +134,9 @@ pub fn describe(p: &Plugin) -> Value {
if m.appearance_output {
v["appearanceOutput"] = json!(true);
}
if !m.events.is_empty() {
v["events"] = json!(m.events);
}
if let Some(script) = p.script() {
v["runtime"] = json!(m.runtime.name());
v["script"] = json!(script);
@@ -1546,6 +1549,7 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
s.store_disabled_plugins_in(&turn);
}
drop(turn);
s.plugins_changed_for_events();
let mut v = describe_installed(&installed);
if !unknown.is_empty() {
v["unknownCommands"] = json!(unknown);
@@ -2313,12 +2317,17 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"changed": changed, "saved": saved, "disabled": safe_mode::disabled().iter().map(shown_item).collect::<Vec<_>>()}))
}
fn info(_: &mut Session, p: &Value) -> Result<Value> {
fn info(s: &mut Session, p: &Value) -> Result<Value> {
let plugin = plugin_by_id("plugin.info", p)?;
let mut v = describe_installed(&plugin);
v["manifest"] = serde_json::to_value(plugin.manifest()).unwrap_or(Value::Null);
v["defaults"] = Value::Object(plugin.manifest().defaults());
v["lastError"] = json!(effect::last_error(plugin.id()));
if !plugin.manifest().events.is_empty() {
let (off, last) = s.plugin_event_status(&plugin);
v["eventsOff"] = json!(off);
v["lastEventError"] = json!(last);
}
Ok(v)
}
@@ -2389,6 +2398,7 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
if !stored && !module && (!installed || !registry::remove(id)) {
return Err(err(vectorcraft_plugins::Error::NotFound(id.into())));
}
s.plugins_changed_for_events();
Ok(json!({"removed": id}))
}
@@ -2418,7 +2428,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List Plug-ins",
[],
None,
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\"|\"generator\" (a generator draws art from its parameters, see plugin.generate), author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), outputKinds?: [\"type\"|\"image\"|\"layer\"|\"artboard\"] (what an importer at API level 4 returns besides paths, see docs/plugins.md), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 to 4), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path?: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there), context?: [{menu: \"canvas\"|\"layers\", when?: \"selection\"|\"oneObject\"|\"typeObject\"|\"layerRow\"}] (the context menus that also list it)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\"|\"generator\" (a generator draws art from its parameters, see plugin.generate), author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), outputKinds?: [\"type\"|\"image\"|\"layer\"|\"artboard\"] (what an importer at API level 4 returns besides paths, see docs/plugins.md), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md; events: it reacts to the events it names, see events), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 to 4), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), events?: [\"selection.changed\"|\"document.opened\"|\"document.saved\"|\"layer.changed\"] (the events its vc_event handler is given after each change of that kind, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path?: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there), context?: [{menu: \"canvas\"|\"layers\", when?: \"selection\"|\"oneObject\"|\"typeObject\"|\"layerRow\"}] (the context menus that also list it)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
always,
list
),
@@ -2427,7 +2437,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Plug-in Info",
[],
None,
"{id} → plugin.list's entry plus {manifest, defaults, lastError (a live effect's last failure, null; for a live effect with paintOutput, its name and the refused field, such as objects[1].strokes[0].width)}",
"{id} → plugin.list's entry plus {manifest, defaults, lastError (a live effect's last failure, null; for a live effect with paintOutput, its name and the refused field, such as objects[1].strokes[0].width), eventsOff? (with events: true once 3 handlers in a row failed, until the app starts again or a module is installed with its id again, the same module included), lastEventError? (with events: its handler's last failure, null)}",
always,
info
),
+122
View File
@@ -463,6 +463,82 @@ pub(crate) fn call(s: &mut Session, run: &Calls, id: &str, args: &Value) -> std:
Ok(value)
}
/// The commands a plug-in's event handler may call ([`event_call`]), in order: each one only reads
/// the document and returns what it found. Every other command is refused before it runs.
pub(crate) const EVENT_READS: &[&str] = &[
"dataset.list",
"graphicStyle.list",
"guide.list",
"image.info",
"object.blend.info",
"swatch.list",
"symbol.list",
"text.getRange",
"transparency.info",
"variable.list",
];
/// Makes call `id` with `args` from a plug-in's handler of event `event` ([`crate::plugin_events`])
/// as [`call`] does, for a command in [`EVENT_READS`]; any other command is refused before it runs,
/// with an error that names the event. The call runs inside [`read_only`]: every document and the
/// session state the commands a plug-in may call change go back to how they were afterwards, and a
/// call that changed a document, its selection, current layer or layer rows, or which document is
/// active, is refused.
pub(crate) fn event_call(s: &mut Session, run: &Calls, event: &str, id: &str, args: &Value) -> std::result::Result<Value, CallFailure> {
if super::find_command(id).is_none() {
return Err(CallFailure { code: CALL_UNKNOWN_COMMAND, why: super::params::unknown_command(id).to_string() });
}
if !EVENT_READS.contains(&id) {
return Err(CallFailure { code: CALL_DENIED_COMMAND, why: format!("a {event} handler only reads: `{id}` is not a command it may call") });
}
let (r, changed) = read_only(s, |s| call(s, run, id, args));
if changed {
return Err(CallFailure { code: CALL_DENIED_COMMAND, why: format!("a {event} handler only reads: `{id}` changed the document") });
}
r
}
/// Runs `f` and then puts every open document (its art, selection, current layer, rows and
/// history), which document is active and the session state the commands a plug-in may call change
/// ([`Saved`]) back to how they were → `f`'s result, and whether `f` changed a document, its
/// selection, current layer or layer rows, opened or closed one, or changed which one is active.
/// A document `f` changed is given a newer revision, so it redraws.
fn read_only<R>(s: &mut Session, f: impl FnOnce(&mut Session) -> R) -> (R, bool) {
let saved = Saved::of(s);
let pending_paint = s.pending_paint.clone();
let start = s.docs.clone();
let active = s.active;
// A panic in `f` still puts everything back before it carries on.
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(s)));
let now = std::mem::replace(&mut s.docs, start);
let mut changed = s.active != active || now.len() != s.docs.len();
for st in &mut s.docs {
let Some(n) = now.iter().find(|d| d.uid == st.uid) else {
changed = true;
continue;
};
if n.revision != st.revision
|| !Arc::ptr_eq(&n.doc, &st.doc)
|| n.selection != st.selection
|| n.active_layer != st.active_layer
|| n.layer_rows != st.layer_rows
{
st.revision = st.revision.max(n.revision).saturating_add(1);
changed = true;
}
}
s.active = active;
saved.restore(s);
s.pending_paint = pending_paint;
if changed {
s.sync_front_profiles();
}
match r {
Ok(r) => (r, changed),
Err(payload) => std::panic::resume_unwind(payload),
}
}
/// Runs command `id` with `args` in `s` with no file or folder readable or writable: every path the
/// command reaches through the checked file access ([`crate::file_access`]) is refused, whatever
/// param carries it.
@@ -952,4 +1028,50 @@ mod tests {
assert!(!names_key("{pathData: 1}", "path"));
assert!(names_key("path: x", "path"));
}
/// Each command an event handler may call is one a plug-in may call and one the journal does
/// not record, listed once, in order.
#[test]
fn event_reads_are_reviewed_reads() {
for id in EVENT_READS {
let Some(spec) = crate::cmd::find_command(id) else { panic!("no command {id}") };
assert_eq!(denied(spec), None, "{id} is refused to every plug-in");
assert!(!spec.journal, "{id} is journaled");
}
assert!(EVENT_READS.windows(2).all(|w| w[0] < w[1]), "in order, once each");
}
/// [`read_only`] puts back what its function changed: the document, its selection, the
/// preferences and the paint defaults, and says that the document changed; a function that
/// changes nothing is no change.
#[test]
fn read_only_puts_everything_back() {
use serde_json::json;
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].clone();
s.execute("select.none", &json!({})).unwrap();
let st = s.doc().unwrap();
let (doc, revision, history) = (st.doc.clone(), st.revision, st.history.undo.len());
let (prefs, paint) = (s.prefs.history_states, s.paint.clone());
let ((), changed) = read_only(&mut s, |s| {
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap();
s.prefs.history_states += 1;
s.paint.stroke_width += 3.0;
});
assert!(changed);
let st = s.doc().unwrap();
assert!(Arc::ptr_eq(&st.doc, &doc), "the same document");
assert!(st.selection.objects.is_empty(), "the selection as it was");
assert_eq!(st.history.undo.len(), history, "no undo step");
assert!(st.revision > revision, "a newer revision, so it redraws");
assert_eq!((s.prefs.history_states, &s.paint), (prefs, &paint));
let revision = st.revision;
let ((), changed) = read_only(&mut s, |s| {
s.execute("variable.list", &json!({})).unwrap();
});
assert!(!changed, "a read changes nothing");
assert_eq!(s.doc().unwrap().revision, revision);
}
}
+8
View File
@@ -14,6 +14,7 @@ pub mod journal;
pub mod link_watch;
#[cfg(not(target_arch = "wasm32"))]
pub mod packs;
pub mod plugin_events;
pub mod schemas;
pub mod steps;
pub mod store;
@@ -407,6 +408,13 @@ pub struct Session {
/// While the active tool's actions run: their commands aren't "a command from outside the
/// tool" ([`Session::after_command`]).
pub(crate) in_tool_actions: bool,
/// The events plug-ins react to that wait for delivery, and how the documents were at the last
/// check ([`plugin_events`]).
pub(crate) plugin_events: plugin_events::PluginEvents,
/// The frontend delivers plug-in events by the frame ([`Session::deliver_plugin_events`]). Off,
/// each top-level command delivers them when it ends. When on, the frontend calls
/// [`Session::begin_plugin_event_frame`] once before each frame's deliveries.
pub plugin_event_frames: bool,
/// The warnings of the previews that settling an interaction applied, while a top-level command
/// or the tool's actions collect them ([`Session::collect_settled_warnings`]).
settled_warnings: Option<Vec<String>>,
+872
View File
@@ -0,0 +1,872 @@
//! Events plug-ins react to ([`vectorcraft_plugins::events`]): the session notices a changed
//! selection, current layer or set of layers by comparing each open document with how it was at the
//! last check, and hears of each successful open and save ([`Session::note_plugin_event`]). It then
//! calls the `vc_event` handler of each installed plug-in whose manifest names the event, after the
//! change has finished and outside any undo step.
//!
//! - A check runs after each top-level command, or when a frontend that sets
//! [`Session::plugin_event_frames`] delivers ([`Session::deliver_plugin_events`]), by the frame.
//! Changes between two checks are one event: a burst of selection changes is one
//! `selection.changed` with the final selection. No check or delivery runs while an interaction
//! is open (a drag being previewed); waiting events wait for it to end. A document opened or
//! created since the last check is compared with how it was when it was added
//! ([`Session::plugin_events_see_new_documents`]).
//! A check after commit or cancel records the settled state for plug-ins installed during the interaction.
//! - At most [`MAX_PENDING`] events wait; past that the oldest is dropped. An event raised while a
//! handler runs waits for the next delivery: handlers never run inside one another.
//! A frontend frame runs at most [`MAX_FRAME_HANDLERS`] handlers across all its deliveries,
//! after [`Session::begin_plugin_event_frame`] resets the budget. Runnable recipients still
//! waiting request another frame through the delivery's return value.
//! - A handler only reads. The host applies nothing it returns, and it may call only the commands
//! in [`super::cmd::plugin_call::EVENT_READS`]; any other call is refused with an error that names
//! the event, and what a call changes is put back ([`super::cmd::plugin_call::event_call`]).
//! - A handler that fails is reported once a streak; after
//! [`vectorcraft_plugins::events::MAX_EVENT_FAILURES`] failures in a row the plug-in's events stop
//! until the session ends, or until a module is installed under its id again.
//! - When no installed plug-in reacts to events, a check returns before comparing anything.
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::hash::Hash;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, NodeId, NodeKind, Selection};
use vectorcraft_plugins::events::{Event, MAX_EVENT_FAILURES, MAX_EVENT_IDS};
use vectorcraft_plugins::permissions::Permission;
use vectorcraft_plugins::{LogLevel, Plugin, registry};
use crate::Session;
/// Most events that wait for delivery.
pub const MAX_PENDING: usize = 32;
/// Most events kept after the queue dropped them for room, until the next delivery, for a
/// rollback to put back.
const MAX_EVICTED: usize = 1024;
/// Most handlers called across all deliveries in one frontend frame.
pub const MAX_FRAME_HANDLERS: usize = 4;
/// Most notices kept for the frontend to show; older ones are dropped.
pub const MAX_NOTICES: usize = 64;
/// The reasons a `layer.changed` event gives, in the order it lists them.
pub const LAYER_REASONS: [&str; 5] = ["current", "added", "deleted", "reordered", "options"];
/// A document as the last check saw it.
struct Seen {
uid: u64,
doc: Arc<Document>,
selection: Selection,
layer: Option<NodeId>,
}
/// A plug-in an event is for: its id, the hash of its module and its installation
/// ([`Plugin::serial`]), so a module removed and installed again is another recipient.
type Recipient = (String, String, u64);
#[cfg(test)]
std::thread_local! {
pub(crate) static RECIPIENT_IDENTITIES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The recipient `p` is.
fn recipient(p: &Plugin) -> Recipient {
#[cfg(test)]
RECIPIENT_IDENTITIES.with(|count| count.set(count.get() + 1));
(p.id().to_string(), p.hash().to_string(), p.serial())
}
/// An event waiting for delivery: what changed, in which document, and the plug-ins it is for
/// (those installed when it happened), each with the reasons of a `layer.changed` it was given.
#[derive(Clone, Debug, PartialEq)]
struct Pending {
event: Event,
document: u64,
to: Vec<(Recipient, Vec<&'static str>)>,
/// When it was queued ([`PluginEvents::queued`] then).
seq: u64,
/// The event this enqueue pushed out of the waiting queue.
displaced: Option<u64>,
/// Queued by a command of the running script, whose run has not ended yet
/// ([`Session::plugin_events_script_ended`]).
by_script: bool,
}
impl Pending {
/// Whether this event is for `r`.
#[cfg(test)]
fn is_for(&self, r: &Recipient) -> bool {
self.to.iter().any(|(x, _)| x == r)
}
/// The reasons of a `layer.changed` that `r` is given.
#[cfg(test)]
fn reasons_for(&self, r: &Recipient) -> &[&'static str] {
self.to.iter().find(|(x, _)| x == r).map_or(&[], |(_, reasons)| reasons.as_slice())
}
}
/// One plug-in's failed handlers in a row, for the installation `serial` of the module with `hash`.
#[derive(Clone, Debug, Default)]
struct Failures {
hash: String,
serial: u64,
count: u32,
disabled: bool,
last_error: Option<String>,
}
/// A line a handler wrote with `vc_log`, or a handler's failure, for the frontend to show.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Notice {
/// The plug-in's id and name.
pub plugin: String,
pub name: String,
/// The event its handler was given.
pub event: &'static str,
pub level: LogLevel,
/// The text, in English for a failure.
pub text: String,
/// For a failure, what failed, for the frontend to word in the interface language; `None` for
/// a line the handler wrote.
pub failure: Option<Failure>,
}
/// A failure a [`Notice`] reports.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Failure {
/// A handler failed with `error`, the first time in a row.
Handler { error: String },
/// The plug-in's events stopped after `count` failed handlers in a row.
EventsOff { count: u32 },
}
impl Failure {
/// The English message with `{event}`, `{error}` and `{n}` placeholders, `one` or `other` by
/// the count.
pub const HANDLER: &'static str = "its {event} handler failed: {error}";
pub const EVENTS_OFF_ONE: &'static str =
"its events are off until it is installed again or VectorCraft starts again, after {n} failed handler in a row";
pub const EVENTS_OFF_OTHER: &'static str =
"its events are off until it is installed again or VectorCraft starts again, after {n} failed handlers in a row";
}
/// The session's plug-in event state.
#[derive(Default)]
pub struct PluginEvents {
seen: Vec<Seen>,
/// The plug-ins that reacted to events when `seen` was taken.
seen_by: Vec<Recipient>,
pending: VecDeque<Pending>,
/// The events dropped from `pending` since the last delivery, oldest first, which
/// [`Session::forget_plugin_opens_since`] puts back when a rollback frees room.
evicted: VecDeque<Pending>,
/// How many events have been queued as their own entry.
queued: u64,
dispatching: bool,
frame_handlers: usize,
interaction_ended: bool,
failures: BTreeMap<String, Failures>,
notices: VecDeque<Notice>,
/// The installed plug-ins that react to events, as of a registry revision.
subscribers: Option<(u64, Vec<Arc<Plugin>>)>,
#[cfg(test)]
pub(crate) test_subscribers: Option<Vec<Arc<Plugin>>>,
}
impl PluginEvents {
/// The installed plug-ins that react to events (none in Safe Mode).
fn subscribers(&mut self) -> Vec<Arc<Plugin>> {
#[cfg(test)]
if let Some(subs) = &self.test_subscribers {
return subs.clone();
}
if vectorcraft_plugins::safe_mode::active() {
return Vec::new();
}
let revision = registry::revision();
if let Some((at, subs)) = &self.subscribers
&& *at == revision
{
return subs.clone();
}
let subs: Vec<Arc<Plugin>> = registry::list().into_iter().filter(|p| !p.manifest().events.is_empty()).collect();
self.subscribers = Some((revision, subs.clone()));
subs
}
/// Queues `event` for document `uid`, for the plug-ins `to`, with the reasons of a
/// `layer.changed`. A `selection.changed` or `layer.changed` already waiting for that document
/// takes it in: each plug-in in `to` is added, or adds the new reasons to the ones it was given,
/// so a plug-in is given only the reasons of the changes it was given. Past [`MAX_PENDING`] the
/// oldest event is dropped.
fn queue(&mut self, event: Event, uid: u64, reasons: Vec<&'static str>, to: Vec<Recipient>) {
if matches!(event, Event::SelectionChanged | Event::LayerChanged)
&& let Some(p) = self.pending.iter_mut().find(|p| p.event == event && p.document == uid)
{
for r in to {
let i = match p.to.iter().position(|(x, _)| *x == r) {
Some(i) => i,
None => {
p.to.push((r, Vec::new()));
p.to.len() - 1
}
};
let given = &mut p.to[i].1;
for reason in &reasons {
if !given.contains(reason) {
given.push(*reason);
}
}
given.sort_by_key(|r| LAYER_REASONS.iter().position(|x| x == r));
}
return;
}
let mut displaced = None;
if self.pending.len() >= MAX_PENDING
&& let Some(dropped) = self.pending.pop_front()
{
displaced = Some(dropped.seq);
log::warn!("plug-in events: dropped a waiting {} event, past {MAX_PENDING} waiting", dropped.event.name());
// Kept until the next delivery, in case a rollback frees room for it again.
// When that store is full, an open goes first, since only opens are rolled back.
if self.evicted.len() >= MAX_EVICTED {
let at = self.evicted.iter().position(|p| p.event == Event::DocumentOpened).unwrap_or(0);
self.evicted.remove(at);
}
self.evicted.push_back(dropped);
}
let to = to.into_iter().map(|r| (r, reasons.clone())).collect();
self.pending.push_back(Pending { event, document: uid, to, seq: self.queued, displaced, by_script: false });
self.queued += 1;
}
fn notice(&mut self, n: Notice) {
if self.notices.len() >= MAX_NOTICES {
self.notices.pop_front();
}
self.notices.push_back(n);
}
/// The failures of plug-in `p`, started again when a module was installed under its id since
/// they were recorded, the same module again included.
fn failures_of(&mut self, p: &Plugin) -> &mut Failures {
let f = self.failures.entry(p.id().to_string()).or_default();
if !f.is_of(p) {
*f = Failures { hash: p.hash().to_string(), serial: p.serial(), ..Failures::default() };
}
f
}
}
impl Failures {
/// Whether these are the failures of `p` as it is installed now.
fn is_of(&self, p: &Plugin) -> bool {
self.hash == p.hash() && self.serial == p.serial()
}
}
/// A layer or sublayer: its id, its parent (`None` at the top), the layer itself without its
/// contents (for comparing its options) and the ids of the rows directly in it, in order.
type LayerRow<Id = NodeId> = (Id, Option<Id>, vectorcraft_doc::Node, Vec<Id>);
/// Each layer and sublayer of `doc`, in order.
fn layer_rows(doc: &Document) -> Vec<LayerRow> {
let mut out = Vec::new();
let mut stack: Vec<(&Arc<vectorcraft_doc::Node>, Option<NodeId>)> = doc.layers.iter().rev().map(|l| (l, None)).collect();
while let Some((n, parent)) = stack.pop() {
let NodeKind::Layer { children, .. } = &n.kind else { continue };
stack.extend(children.iter().rev().filter(|c| c.is_layer()).map(|c| (c, Some(n.id))));
let rows = children.iter().map(|c| c.id).collect();
let mut bare = (**n).clone();
if let Some(c) = bare.children_mut() {
c.clear();
}
out.push((n.id, parent, bare, rows));
}
out
}
/// Whether a layer's place among the rows beside it differs between `old` (of `before`) and `new`
/// (of `after`), counting only the rows on both sides, so an object added or deleted next to a
/// sublayer is not a move.
fn layers_moved_among_rows(before: &Document, old: &[LayerRow], after: &Document, new: &[LayerRow]) -> bool {
use std::collections::{HashMap, HashSet};
let layers: HashSet<NodeId> = old.iter().map(|r| r.0).collect();
let lists = |doc: &Document, rows: &[LayerRow]| {
let mut m: HashMap<Option<NodeId>, Vec<NodeId>> = rows.iter().map(|r| (Some(r.0), r.3.clone())).collect();
m.insert(None, doc.layers.iter().map(|l| l.id).collect());
m
};
let (a, b) = (lists(before, old), lists(after, new));
a.iter().any(|(parent, xs)| {
let Some(ys) = b.get(parent) else { return false };
let (in_x, in_y): (HashSet<NodeId>, HashSet<NodeId>) = (xs.iter().copied().collect(), ys.iter().copied().collect());
let places = |list: &[NodeId], other: &HashSet<NodeId>| {
list.iter().filter(|id| other.contains(id)).enumerate().filter(|(_, id)| layers.contains(id)).map(|(i, id)| (i, *id)).collect::<Vec<_>>()
};
places(xs, &in_y) != places(ys, &in_x)
})
}
/// Why the layers of `after` (with current layer `layer_after`) differ from those of `before`
/// (with `layer_before`), in [`LAYER_REASONS`] order; empty when they don't.
fn layer_reasons(before: &Arc<Document>, layer_before: Option<NodeId>, after: &Arc<Document>, layer_after: Option<NodeId>) -> Vec<&'static str> {
let mut reasons = Vec::new();
if layer_before != layer_after {
reasons.push("current");
}
if Arc::ptr_eq(before, after) {
return reasons;
}
let (old, new) = (layer_rows(before), layer_rows(after));
reasons.extend(layer_row_reasons(&old, &new, || layers_moved_among_rows(before, &old, after, &new)));
reasons
}
/// Compares layer membership, order and options by id.
fn layer_row_reasons<Id: Copy + Eq + Hash>(old: &[LayerRow<Id>], new: &[LayerRow<Id>], moved: impl FnOnce() -> bool) -> Vec<&'static str> {
let mut reasons = Vec::new();
let old_by_id: HashMap<Id, &LayerRow<Id>> = old.iter().map(|r| (r.0, r)).collect();
let new_by_id: HashMap<Id, &LayerRow<Id>> = new.iter().map(|r| (r.0, r)).collect();
if new.iter().any(|r| !old_by_id.contains_key(&r.0)) {
reasons.push("added");
}
if old.iter().any(|r| !new_by_id.contains_key(&r.0)) {
reasons.push("deleted");
}
let kept = |rows: &[LayerRow<Id>], other: &HashMap<Id, &LayerRow<Id>>| {
rows.iter().filter(|r| other.contains_key(&r.0)).map(|r| (r.0, r.1)).collect::<Vec<_>>()
};
if kept(old, &new_by_id) != kept(new, &old_by_id) || moved() {
reasons.push("reordered");
}
if old.iter().any(|r| new_by_id.get(&r.0).is_some_and(|o| o.2 != r.2)) {
reasons.push("options");
}
reasons
}
impl Session {
/// Hears that `event` (`document.opened` or `document.saved`) happened to document `uid`, which
/// the next delivery hands the plug-ins that react to it. Nothing is kept when none does.
pub(crate) fn note_plugin_event(&mut self, event: Event, uid: u64) {
let to: Vec<Recipient> = self.plugin_events.subscribers().iter().filter(|p| p.manifest().reacts_to(event)).map(|p| recipient(p)).collect();
if to.is_empty() {
return;
}
self.plugin_events.queue(event, uid, Vec::new(), to);
// An open or a save is queued as its own entry, the newest.
if self.script_in_run
&& let Some(p) = self.plugin_events.pending.back_mut()
{
p.by_script = true;
}
}
/// At the end of a script's run. The opens and saves its commands queued wait until then, also
/// through deliveries between its slices ([`Session::deliver_plugin_events`]). When the run
/// failed (`kept` false), drops the waiting `document.opened` events its commands queued, since
/// the documents they opened were discarded with its working copy. Its saves stay, since the
/// files they wrote stay written, and so do the events of documents a frontend opened while the
/// run was paused. The next delivery gives what is left in the order it was queued.
pub(crate) fn plugin_events_script_ended(&mut self, kept: bool) {
let events = &mut self.plugin_events;
if !kept {
events.pending.retain(|p| !(p.by_script && p.event == Event::DocumentOpened));
events.evicted.retain(|p| !(p.by_script && p.event == Event::DocumentOpened));
}
for p in events.pending.iter_mut().chain(events.evicted.iter_mut()) {
p.by_script = false;
}
}
/// A mark for [`Session::forget_plugin_opens_since`]: the events queued so far.
pub(crate) fn plugin_events_mark(&self) -> u64 {
self.plugin_events.queued
}
/// Drops the waiting `document.opened` events queued since `mark`, for opens that a rollback
/// undid (a failed `command.batch`, or a failed command of a script or a plug-in call). The
/// saves stay, since the files they wrote stay written.
/// Events displaced by those opens return in their original order, ahead of the events still
/// waiting, while there is room.
pub(crate) fn forget_plugin_opens_since(&mut self, mark: u64) {
let events = &mut self.plugin_events;
let undone = |p: &Pending| p.event == Event::DocumentOpened && p.seq >= mark;
let displaced: Vec<_> = events.pending.iter().chain(&events.evicted).filter(|p| undone(p)).filter_map(|p| p.displaced).collect();
events.pending.retain(|p| !undone(p));
events.evicted.retain(|p| !undone(p));
while events.pending.len() < MAX_PENDING
&& let Some(at) = events.evicted.iter().rposition(|p| displaced.contains(&p.seq))
&& let Some(p) = events.evicted.remove(at)
{
events.pending.push_front(p);
}
}
/// Compares each open document with how the last check saw it and queues the events its changes
/// give the installed plug-ins: `selection.changed` and `layer.changed`. A document neither the
/// last check nor [`Session::plugin_events_see_new_documents`] saw gives none, and a plug-in
/// installed since the last check is given none: the
/// change may have come before it. A waiting event is no longer for a plug-in that is not
/// installed now, so a module removed and installed again is not given it. Nothing is compared
/// while an interaction is open, nor when no plug-in reacts to events.
fn check_plugin_events(&mut self, interaction_ended: bool) {
if self.script_in_run {
return;
}
let subs = self.plugin_events.subscribers();
if subs.is_empty() {
self.plugin_events.seen.clear();
self.plugin_events.seen_by.clear();
self.plugin_events.pending.clear();
self.plugin_events.evicted.clear();
return;
}
let installed: Vec<Recipient> = subs.iter().map(|p| recipient(p)).collect();
self.plugin_events.pending.retain_mut(|p| {
p.to.retain(|(r, _)| installed.contains(r));
!p.to.is_empty()
});
if self.holds_interaction() || (self.in_tool_actions && !interaction_ended) || self.docs.iter().any(|d| d.interaction.is_some()) {
return;
}
let mut events = std::mem::take(&mut self.plugin_events);
let before = std::mem::take(&mut events.seen);
let before_by = std::mem::take(&mut events.seen_by);
let to = |e: Event| -> Vec<Recipient> {
subs.iter().filter(|p| p.manifest().reacts_to(e)).map(|p| recipient(p)).filter(|r| before_by.contains(r)).collect()
};
let (selection, layers) = (to(Event::SelectionChanged), to(Event::LayerChanged));
let mut seen = Vec::with_capacity(self.docs.len());
for st in &self.docs {
if let Some(old) = before.iter().find(|s| s.uid == st.uid) {
if !selection.is_empty() && old.selection != st.selection {
events.queue(Event::SelectionChanged, st.uid, Vec::new(), selection.clone());
}
if !layers.is_empty() {
let reasons = layer_reasons(&old.doc, old.layer, &st.doc, st.active_layer);
if !reasons.is_empty() {
events.queue(Event::LayerChanged, st.uid, reasons, layers.clone());
}
}
}
seen.push(Seen { uid: st.uid, doc: st.doc.clone(), selection: st.selection.clone(), layer: st.active_layer });
}
events.seen = seen;
events.seen_by = subs.iter().map(|p| recipient(p)).collect();
events.pending.retain(|p| p.event.outlives_document() || self.docs.iter().any(|d| d.uid == p.document));
self.plugin_events = events;
}
/// Resets the handler budget for a frontend frame. Call once before the frame's deliveries,
/// including background work and all UI passes, when [`Session::plugin_event_frames`] is on.
pub fn begin_plugin_event_frame(&mut self) {
self.plugin_events.frame_handlers = 0;
}
/// Checks the open documents for changes ([`Session::check_plugin_events`]) and calls the
/// handlers of the events waiting, oldest first, one handler at a time. While a handler runs,
/// this returns at once: what the handler's calls change waits for the next delivery. While an
/// interaction is open, the events wait for the first delivery after it ends.
/// A set-aside interaction also holds events. A frontend frame calls at most
/// [`MAX_FRAME_HANDLERS`] handlers across all deliveries since [`Session::begin_plugin_event_frame`]
/// and keeps the remaining recipients for later frames. Returns whether runnable handlers
/// remain queued, so the frontend can request another frame even when no handler wrote a notice.
pub fn deliver_plugin_events(&mut self) -> bool {
if self.plugin_events.dispatching {
return false;
}
self.check_plugin_events(false);
if self.plugin_events.pending.is_empty()
|| self.holds_interaction()
|| self.in_tool_actions
|| self.docs.iter().any(|d| d.interaction.is_some())
{
return false;
}
let subs: HashMap<Recipient, Arc<Plugin>> = self.plugin_events.subscribers().into_iter().map(|p| (recipient(&p), p)).collect();
self.plugin_events.dispatching = true;
self.plugin_events.evicted.clear();
// A handler's calls are checked as calls from outside, also when the command that ended
// played saved steps ([`Session::replay`] puts its flag back only after this delivery).
let replaying = self.set_replaying(false);
// The commands a handler calls run nested, never journaled; a panic in one leaves the depth
// as it was found.
let depth = self.depth;
self.depth += 1;
// An open or a save a running script queued waits for the end of the run
// ([`Session::plugin_events_script_ended`]), also when a frontend delivers between its
// slices: a run that fails discards the documents it opened.
let mut held = VecDeque::new();
let mut budget = if self.plugin_event_frames { MAX_FRAME_HANDLERS.saturating_sub(self.plugin_events.frame_handlers) } else { usize::MAX };
let waiting = self.plugin_events.pending.len();
for _ in 0..waiting {
let Some(mut p) = self.plugin_events.pending.pop_front() else { break };
if p.by_script {
held.push_back(p);
continue;
}
if !p.event.outlives_document() && !self.docs.iter().any(|d| d.uid == p.document) {
continue;
}
let mut served = 0;
for (i, (r, reasons)) in p.to.iter().enumerate() {
let Some(plugin) = subs.get(r).filter(|s| s.manifest().reacts_to(p.event)) else {
served = i + 1;
continue;
};
if self.plugin_events.failures_of(plugin).disabled {
served = i + 1;
continue;
}
if budget == 0 {
break;
}
self.run_handler(plugin, &p, reasons);
served = i + 1;
budget -= 1;
if self.plugin_event_frames {
self.plugin_events.frame_handlers += 1;
}
}
p.to.drain(..served);
if !p.to.is_empty() {
held.push_back(p);
}
if budget == 0 {
break;
}
}
// The held events are older than any a handler's calls queued meanwhile.
while let Some(p) = held.pop_back() {
self.plugin_events.pending.push_front(p);
}
self.depth = depth;
self.set_replaying(replaying);
self.plugin_events.dispatching = false;
self.plugin_events.pending.iter().any(|p| {
!p.by_script
&& (p.event.outlives_document() || self.docs.iter().any(|d| d.uid == p.document))
&& p.to.iter().any(|(r, _)| subs.get(r).is_some_and(|plugin| !self.plugin_event_status(plugin).0))
})
}
/// The JSON event `p` as plug-in `plugin` is given it: the selected object ids of a
/// `selection.changed` only with `doc.read`, and `reasons`, the reasons of a `layer.changed`
/// it was given.
fn event_json(&self, plugin: &Plugin, p: &Pending, reasons: &[&'static str]) -> Value {
let mut v = json!({ "type": p.event.name(), "document": p.document });
let Some(st) = self.docs.iter().find(|d| d.uid == p.document) else { return v };
match p.event {
Event::SelectionChanged => {
let objects = &st.selection.objects;
v["count"] = json!(objects.len());
v["truncated"] = json!(false);
v["ids"] = Value::Null;
if plugin.manifest().permissions().contains(&Permission::DocRead) {
v["ids"] = json!(objects.iter().take(MAX_EVENT_IDS).map(|i| i.0).collect::<Vec<_>>());
v["truncated"] = json!(objects.len() > MAX_EVENT_IDS);
}
}
Event::LayerChanged => {
v["layer"] = json!(st.active_layer.map(|l| l.0));
v["reasons"] = json!(reasons);
}
Event::DocumentOpened | Event::DocumentSaved => {}
}
v
}
/// Calls `plugin`'s handler with event `p`, given `reasons`, and records what it wrote and
/// whether it failed.
fn run_handler(&mut self, plugin: &Arc<Plugin>, p: &Pending, reasons: &[&'static str]) {
let event = p.event.name();
let text = serde_json::to_vec(&self.event_json(plugin, p, reasons)).unwrap_or_default();
let m = plugin.manifest();
let may = m.permissions();
let (r, report) = if may.contains(&Permission::Commands) && !m.command_allowlist.is_empty() {
let calls = crate::cmd::plugin_call::Calls::of(self, may.contains(&Permission::DocRead), false);
let mut bridge = |id: &str, args: &Value| crate::cmd::plugin_call::event_call(self, &calls, event, id, args);
plugin.run_event(&text, Some(&mut bridge))
} else {
plugin.run_event(&text, None)
};
let (id, name) = (plugin.id().to_string(), m.name.clone());
for line in report.lines {
self.plugin_events.notice(Notice { plugin: id.clone(), name: name.clone(), event, level: line.level, text: line.text, failure: None });
}
let failures = self.plugin_events.failures_of(plugin);
let e = match r {
Ok(()) => {
failures.count = 0;
return;
}
Err(e) => e.to_string(),
};
failures.count += 1;
failures.last_error = Some(e.clone());
let (count, first) = (failures.count, failures.count == 1);
log::warn!("plug-in {id}: its {event} handler failed: {e}");
if first {
let text = Failure::HANDLER.replace("{event}", event).replace("{error}", &e);
let failure = Some(Failure::Handler { error: e });
self.plugin_events.notice(Notice { plugin: id.clone(), name: name.clone(), event, level: LogLevel::Error, text, failure });
}
if count >= MAX_EVENT_FAILURES {
self.plugin_events.failures_of(plugin).disabled = true;
let text = if count == 1 { Failure::EVENTS_OFF_ONE } else { Failure::EVENTS_OFF_OTHER }.replace("{n}", &count.to_string());
let failure = Some(Failure::EventsOff { count });
self.plugin_events.notice(Notice { plugin: id, name, event, level: LogLevel::Error, text, failure });
}
}
/// Takes each open document the last check didn't see, one opened or created since, as it is
/// now, so the next check compares it with this state: a change made to it before the next
/// delivery gives its event. Called when a document is added and after each top-level command.
/// When no check has seen a plug-in that reacts to events, the first check runs now for the
/// plug-ins installed. Nothing is kept when none is installed, nor for a document in an
/// interaction.
pub(crate) fn plugin_events_see_new_documents(&mut self) {
if self.plugin_events.seen_by.is_empty() {
// No check has run since plug-ins that react to events were installed: one now takes
// every open document as it is, for the plug-ins installed now.
if !self.plugin_events.subscribers().is_empty() {
self.check_plugin_events(false);
}
return;
}
for st in &self.docs {
if st.interaction.is_none() && !self.plugin_events.seen.iter().any(|s| s.uid == st.uid) {
self.plugin_events.seen.push(Seen { uid: st.uid, doc: st.doc.clone(), selection: st.selection.clone(), layer: st.active_layer });
}
}
}
/// Delivers the events of a top-level command that just ended, unless the frontend delivers
/// them once a frame ([`Session::plugin_event_frames`]) or a script is running.
pub(crate) fn plugin_events_after_command(&mut self) {
self.plugin_events_see_new_documents();
if std::mem::take(&mut self.plugin_events.interaction_ended) {
self.plugin_events_interaction_ended();
}
if !self.plugin_event_frames && !self.script_in_run {
self.deliver_plugin_events();
}
}
/// After a plug-in was installed or removed, compares the open documents with the last check
/// ([`Session::check_plugin_events`]): what changed before is given only to the plug-ins that
/// were installed then, and what changes from now on to every plug-in installed now, also
/// before the next delivery.
pub(crate) fn plugins_changed_for_events(&mut self) {
if !self.plugin_events.dispatching {
self.check_plugin_events(false);
}
}
/// Before a batch's steps run: checks the documents when the batch settled an interaction
/// (`settled`), or when the installed plug-ins differ from the last check's, so that a plug-in
/// installed since then is given the batch's changes. Otherwise the last check stays the
/// baseline.
pub(crate) fn plugin_events_batch_settled(&mut self, settled: bool) {
if self.plugin_events.dispatching || self.batch_stash.is_some() || self.script_in_run {
return;
}
if !settled {
let installed: Vec<Recipient> = self.plugin_events.subscribers().iter().map(|p| recipient(p)).collect();
if installed == self.plugin_events.seen_by {
// Events for plug-ins removed, or for documents closed, since then still leave the
// queue first.
let set: HashSet<&Recipient> = installed.iter().collect();
let docs = &self.docs;
self.plugin_events.pending.retain_mut(|p| {
p.to.retain(|(r, _)| set.contains(r));
!p.to.is_empty() && (p.event.outlives_document() || docs.iter().any(|d| d.uid == p.document))
});
self.plugin_events.seen.retain(|s| docs.iter().any(|d| d.uid == s.uid));
return;
}
}
self.check_plugin_events(true);
}
/// Records the settled document state after an interaction ends, including subscribers
/// installed during its previews. Tool actions may still be finishing; handlers wait for them.
pub(crate) fn plugin_events_interaction_ended(&mut self) {
if !self.plugin_events.dispatching {
if self.depth == 0 {
self.check_plugin_events(true);
} else {
self.plugin_events.interaction_ended = true;
}
}
}
/// The handlers' log lines and failures since the last call, oldest first.
pub fn take_plugin_event_notices(&mut self) -> Vec<Notice> {
self.plugin_events.notices.drain(..).collect()
}
/// Whether this session stopped delivering events to plug-in `p` after its handlers failed, and
/// the last failure's error.
pub fn plugin_event_status(&self, p: &Plugin) -> (bool, Option<String>) {
match self.plugin_events.failures.get(p.id()).filter(|f| f.is_of(p)) {
Some(f) => (f.disabled, f.last_error.clone()),
None => (false, None),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn layer_comparison_indexes_ids_instead_of_scanning_each_snapshot() {
use std::cell::Cell;
use std::hash::Hasher;
#[derive(Clone, Copy)]
struct Counted<'a> {
value: u64,
comparisons: &'a Cell<usize>,
}
impl PartialEq for Counted<'_> {
fn eq(&self, other: &Self) -> bool {
self.comparisons.set(self.comparisons.get() + 1);
self.value == other.value
}
}
impl Eq for Counted<'_> {}
impl Hash for Counted<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.value.hash(state);
}
}
let comparisons = Cell::new(0);
let doc = Document::new(100.0, 100.0);
let node = (*doc.layers[0]).clone();
let old: Vec<LayerRow<Counted<'_>>> =
(0..1024).map(|value| (Counted { value, comparisons: &comparisons }, None, node.clone(), Vec::new())).collect();
let mut new = old.clone();
new.last_mut().unwrap().2.name = Some("Notes".into());
assert_eq!(layer_row_reasons(&old, &new, || false), ["options"]);
assert!(comparisons.get() < old.len() * 32, "{} id comparisons for {} layers", comparisons.get(), old.len());
}
/// Waiting selection and layer events of a document merge; each plug-in keeps the reasons of
/// the changes it was given.
#[test]
fn waiting_selection_and_layer_events_of_a_document_merge() {
let (a, b): (Recipient, Recipient) = (("a".into(), "1".into(), 1), ("b".into(), "2".into(), 2));
let mut e = PluginEvents::default();
e.queue(Event::SelectionChanged, 1, vec![], vec![a.clone()]);
e.queue(Event::LayerChanged, 1, vec!["options"], vec![a.clone()]);
e.queue(Event::SelectionChanged, 1, vec![], vec![a.clone()]);
e.queue(Event::LayerChanged, 1, vec!["current", "options"], vec![a.clone()]);
e.queue(Event::LayerChanged, 1, vec!["deleted", "current"], vec![a.clone(), b.clone()]);
e.queue(Event::SelectionChanged, 2, vec![], vec![a.clone()]);
e.queue(Event::DocumentSaved, 1, vec![], vec![a.clone()]);
e.queue(Event::DocumentSaved, 1, vec![], vec![a.clone()]);
let got: Vec<(Event, u64, Vec<&str>)> = e.pending.iter().map(|p| (p.event, p.document, p.reasons_for(&a).to_vec())).collect();
assert_eq!(
got,
[
(Event::SelectionChanged, 1, vec![]),
(Event::LayerChanged, 1, vec!["current", "deleted", "options"]),
(Event::SelectionChanged, 2, vec![]),
(Event::DocumentSaved, 1, vec![]),
(Event::DocumentSaved, 1, vec![]),
]
);
assert_eq!(e.pending[1].reasons_for(&b), ["current", "deleted"], "only the change it was given");
assert!(!e.pending[0].is_for(&b));
}
/// While a handler runs, a delivery returns at once; the change waits for the next one, which
/// hands it over once.
#[test]
fn an_event_raised_while_a_handler_runs_waits_for_the_next_delivery() {
use serde_json::json;
use vectorcraft_plugins::wat as tpl;
let id = "test.events.nested";
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
s.allow_plugin_grants_from_requests();
let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].clone();
s.execute("select.none", &json!({})).unwrap();
let manifest =
format!(r#"{{"id":"{id}","name":"Test","kind":"filter","api":2,"permissions":["progress","events"],"events":["selection.changed"]}}"#);
let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap();
let grant = json!(["progress", "events"]);
s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap();
s.plugin_event_frames = true;
let given = |s: &mut Session| s.take_plugin_event_notices().into_iter().filter(|n| n.plugin == id).count();
s.plugin_events.dispatching = true;
s.execute("select.set", &json!({"ids": [r]})).unwrap();
s.deliver_plugin_events();
assert_eq!(given(&mut s), 0, "not inside the running handler");
s.plugin_events.dispatching = false;
s.deliver_plugin_events();
assert_eq!(given(&mut s), 1);
s.deliver_plugin_events();
assert_eq!(given(&mut s), 0, "once");
s.execute("plugin.remove", &json!({"id": id})).unwrap();
}
#[test]
fn at_most_32_events_wait() {
let mut e = PluginEvents::default();
for uid in 0..(MAX_PENDING as u64 + 5) {
e.queue(Event::DocumentOpened, uid, vec![], vec![]);
}
assert_eq!(e.pending.len(), MAX_PENDING);
assert_eq!(e.pending.front().map(|p| p.document), Some(5), "the oldest are dropped");
}
#[test]
fn a_rollback_of_opens_brings_back_the_events_they_pushed_out() {
let mut s = Session::new();
let r: Recipient = ("a".into(), "h".into(), 1);
for uid in 1..=3 {
s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![r.clone()]);
}
let mark = s.plugin_events_mark();
for uid in 0..(2 * MAX_PENDING) as u64 {
s.plugin_events.queue(Event::DocumentOpened, 100 + uid, vec![], vec![r.clone()]);
}
assert!(s.plugin_events.pending.iter().all(|p| p.event == Event::DocumentOpened), "the save was pushed out");
s.plugin_events.queue(Event::DocumentSaved, 999, vec![], vec![r]);
s.forget_plugin_opens_since(mark);
let left: Vec<_> = s.plugin_events.pending.iter().map(|p| (p.event.name(), p.document)).collect();
assert_eq!(
left,
[
(Event::DocumentSaved.name(), 1),
(Event::DocumentSaved.name(), 2),
(Event::DocumentSaved.name(), 3),
(Event::DocumentSaved.name(), 999)
]
);
}
#[test]
fn a_rollback_of_an_open_that_displaced_nothing_does_not_restore_an_earlier_save() {
let mut s = Session::new();
for uid in 0..=MAX_PENDING as u64 {
s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![]);
}
assert_eq!(s.plugin_events.evicted.front().unwrap().document, 0);
s.plugin_events.pending.pop_front();
let waiting = s.plugin_events.pending.clone();
let mark = s.plugin_events_mark();
s.plugin_events.queue(Event::DocumentOpened, 100, vec![], vec![]);
s.forget_plugin_opens_since(mark);
assert_eq!(s.plugin_events.pending, waiting);
assert_eq!(s.plugin_events.evicted.front().unwrap().document, 0);
}
}
+9
View File
@@ -664,6 +664,8 @@ pub(crate) struct Savepoint {
pending_paint: Option<crate::Paint>,
choices: Choices,
journal: usize,
/// The plug-in events queued before the command ([`Session::plugin_events_mark`]).
plugin_events: u64,
}
impl Savepoint {
@@ -698,6 +700,7 @@ impl Savepoint {
pending_paint: s.pending_paint.clone(),
choices: Choices::of(s),
journal: s.journal.len(),
plugin_events: s.plugin_events_mark(),
}
}
@@ -750,6 +753,8 @@ impl Savepoint {
s.pending_paint = self.pending_paint;
self.choices.put(s);
s.journal.truncate(self.journal);
// The documents the command opened are closed again: plug-ins are not told of them.
s.forget_plugin_opens_since(self.plugin_events);
s.sync_front_profiles();
exact
}
@@ -2202,6 +2207,8 @@ impl Session {
lost
});
drop(lost);
// The job's working copy went with it, with the documents the run opened.
self.plugin_events_script_ended(false);
raise_ids(self);
self.script_stop.clear();
self.reset_tool();
@@ -2597,6 +2604,7 @@ impl Session {
let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left));
close_run(self, &job.host, &mut report, ending(&e.kind));
self.end_job(job, e.kind == RunErrorKind::Internal);
self.plugin_events_script_ended(false);
raise_ids(self);
self.script_stop.clear();
self.reset_tool();
@@ -2701,6 +2709,7 @@ impl Session {
close_run(self, host, &mut report, console::Ending::Finished);
let tool = host.dom.chosen_tool();
self.end_job(job, false);
self.plugin_events_script_ended(true);
// The tool `app.selectTool` chose last becomes the current tool, as a choice on the
// toolbar makes it; the run's changes are kept when the tool cannot be chosen.
if let Some(id) = tool
+3
View File
@@ -151,6 +151,8 @@ impl Session {
screens_hand_off: None,
recovery: Default::default(),
in_tool_actions: false,
plugin_events: Default::default(),
plugin_event_frames: false,
settled_warnings: None,
held_interaction: None,
previewing: false,
@@ -423,6 +425,7 @@ impl Session {
{
self.begin_named_undo_group(label);
}
self.plugin_events_see_new_documents();
i
}
+9
View File
@@ -665,10 +665,15 @@ impl Session {
// The interaction is taken below, so its starting state is read first: the commit is what
// the previews that came before it changed.
let before = (self.depth == 0).then(|| self.active().and_then(|st| st.interaction.as_ref().map(|it| st.layers_view_before(it)))).flatten();
// Plug-in events wait for an open interaction only: a commit with none open ends nothing.
let open = self.in_interaction() || self.holds_interaction();
let r = self.commit_interaction_unwatched();
if let Some(before) = before {
self.reveal_since(&before);
}
if r.is_ok() && open {
self.plugin_events_interaction_ended();
}
r
}
@@ -774,6 +779,7 @@ impl Session {
}
pub fn cancel_interaction(&mut self) -> Result<()> {
let open = self.in_interaction() || self.holds_interaction();
self.put_back_interaction();
self.restore_preview_appearance_item();
self.clear_deferred_overlay_cache();
@@ -811,6 +817,9 @@ impl Session {
if !used_defaults_only {
self.inherit_new_art();
}
if open {
self.plugin_events_interaction_ended();
}
Ok(())
}
+3
View File
@@ -132,6 +132,9 @@ impl Session {
if self.script_in_run && self.depth > 0 && r.is_ok() {
crate::script::note_style_lists(self);
}
if self.depth == 0 {
self.plugin_events_after_command();
}
r
}
+2
View File
@@ -1319,11 +1319,13 @@ impl Session {
}
/// Installs what `load` has loaded so far, without waiting, in `turn`.
/// Records the installed plug-ins' event baseline now, or after an open interaction ends.
fn install_plugin_load(&mut self, load: &mut PluginLoad, turn: &StoreTurn) {
match load {
PluginLoad::Stored(load) => self.install_stored_plugins(load, turn),
PluginLoad::Folder(load) => crate::cmd::plugin::install_folder(self, load, turn),
}
self.plugins_changed_for_events();
}
/// Ends `load` once [`PluginLoad::done`], in `turn` → its report.
+1
View File
@@ -154,6 +154,7 @@ mod perspgrid;
mod pixelalign;
mod place;
mod placed_document;
mod plugin_events;
mod plugins;
mod prefs;
mod prefs_file;
File diff suppressed because it is too large Load Diff
+2
View File
@@ -1823,6 +1823,7 @@ impl Session {
}
/// Apply tool actions. Errors from previews are reported but keep the interaction alive.
/// Headless sessions deliver plug-in events after the outer actions finish.
pub fn apply_actions(&mut self, acts: Vec<Action>) -> Result<Vec<UiRequest>> {
// The tool acts on its own interaction, which a command from outside it may have set aside.
if !acts.is_empty() {
@@ -1851,6 +1852,7 @@ impl Session {
self.back_to_painter = outer_painter;
if !outer && self.depth == 0 {
self.trim_histories();
self.plugin_events_after_command();
}
r
}
+94
View File
@@ -0,0 +1,94 @@
//! Events a plug-in may react to, from plug-in API level 2 on: its manifest's `events` names them
//! ([`Event`]) and lists the `events` permission, and the module exports
//! `vc_event(event_ptr: i32, event_len: i32) -> i32`. After a change has finished, the host calls
//! `vc_event` in a fresh instance with a small JSON object that names the event and the document
//! ([`crate::Plugin::run_event`]). A handler only reads: the host applies nothing it returns, and
//! a command call that would change a document is refused ([`crate::host`]).
//!
//! The limits are VectorCraft's own values: [`EVENT_FUEL`] instructions and
//! [`EVENT_WALL_TIME_MS`] for one handler, an event of at most [`MAX_EVENT_BYTES`], and
//! [`MAX_EVENT_IDS`] selected ids in a `selection.changed` event.
/// The plug-in API level that adds `events`, the `events` permission and `vc_event`.
pub const EVENTS_API: u32 = 2;
/// Instructions one handler may use, or the plug-in's own budget when that is smaller.
pub const EVENT_FUEL: u64 = 5_000_000;
/// Wall-clock budget of one handler, in milliseconds, or the plug-in's own when that is shorter.
pub const EVENT_WALL_TIME_MS: u64 = 200;
/// Largest event JSON the host hands a handler, in bytes.
pub const MAX_EVENT_BYTES: usize = 64 * 1024;
/// Most selected object ids a `selection.changed` event lists; a larger selection sends the first
/// ones with `truncated: true` and its whole `count`. That many ids of the largest value still fit
/// in [`MAX_EVENT_BYTES`].
pub const MAX_EVENT_IDS: usize = 2048;
/// Failed handlers in a row after which the host stops calling a plug-in's handler until the app
/// starts again.
pub const MAX_EVENT_FAILURES: u32 = 3;
/// One thing a plug-in may react to.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Event {
/// The selection in a document changed: other objects, anchors or segments, or nothing.
SelectionChanged,
/// A file opened as a document (File › Open, a recent file, New from Template).
DocumentOpened,
/// A document was saved to its own file (Save, Save As).
DocumentSaved,
/// The current layer changed, or a layer was added, deleted, moved or given other options.
LayerChanged,
}
impl Event {
/// Every event, in the order the docs list them.
pub const ALL: [Event; 4] = [Event::SelectionChanged, Event::DocumentOpened, Event::DocumentSaved, Event::LayerChanged];
/// Its name in a manifest's `events`, which is also the event's `type`.
pub fn name(self) -> &'static str {
match self {
Event::SelectionChanged => "selection.changed",
Event::DocumentOpened => "document.opened",
Event::DocumentSaved => "document.saved",
Event::LayerChanged => "layer.changed",
}
}
/// The event named `name`.
pub fn parse(name: &str) -> Option<Event> {
Event::ALL.into_iter().find(|e| e.name() == name)
}
/// Whether the event is still delivered when its document has closed before the delivery:
/// an open or a save is, a selection or layer change is not.
pub fn outlives_document(self) -> bool {
matches!(self, Event::DocumentOpened | Event::DocumentSaved)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names_round_trip() {
for e in Event::ALL {
assert_eq!(Event::parse(e.name()), Some(e));
}
assert_eq!(Event::parse("selection.change"), None);
assert_eq!(Event::parse(""), None);
}
/// A `selection.changed` event that lists the most ids, each of the largest value, fits in the
/// largest event a handler is given.
#[test]
fn the_largest_selection_event_fits() {
let ids = vec![u64::MAX; MAX_EVENT_IDS];
let event = serde_json::json!({"type": "selection.changed", "document": u64::MAX, "count": u64::MAX, "ids": ids, "truncated": true});
let len = serde_json::to_vec(&event).unwrap().len();
assert!(len <= MAX_EVENT_BYTES, "{len} bytes");
}
}
+2
View File
@@ -460,6 +460,8 @@ mod tests {
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.events", ok, json!({"api": 2, "permissions": ["events"], "events": ["selection.changed"]})));
assert!(matches!(&e, Error::Manifest(why) if why.contains("can't list the permission `events`")), "{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"})));
+5 -2
View File
@@ -34,8 +34,9 @@
//! the set of [`permissions`] its manifest lists, which the user approves when it is installed. A
//! filter or a live effect may also add menu commands of its own ([`Command`]), which the host
//! runs through `vc_run` with the command's id in `_context`. Its name, command labels and
//! parameter text may come in other languages too ([`translations`]). The web build checks modules and
//! runs filters in a worker of its own ([`worker`]).
//! parameter text may come in other languages too ([`translations`]). Any kind may also react to the
//! [`events`] its manifest names, through `vc_event`, without changing the document. The web
//! build checks modules and runs filters in a worker of its own ([`worker`]).
//!
//! An object filter may also be written in JavaScript ([`js`]): its manifest gives
//! `"runtime": "js"` and names a `.js` file, which runs in a fresh `vectorcraft-js` realm for each
@@ -45,6 +46,7 @@
pub mod deferred;
pub mod dialog;
pub mod effect;
pub mod events;
pub mod export;
pub mod generate;
pub mod host;
@@ -66,6 +68,7 @@ pub mod wat;
pub mod worker;
pub use dialog::ParamUi;
pub use events::Event;
pub use host::{LogLevel, LogLine, Report};
pub use manifest::{
Budget, Command, ContextMenu, ContextPlace, ContextSection, ContextWhen, InputKind, Kind, Manifest, MenuPlace, OutputKind, Param, ParamSpec,
+101 -2
View File
@@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use crate::dialog::ParamUi;
use crate::events::{EVENTS_API, Event};
use crate::permissions::{self, API_LEVEL, APPEARANCE_API, CONTEXT_API, INPUTS_API, OUTPUT_KINDS_API, PROGRESS_API, Permission, WRITES_API};
use crate::translations::Translations;
use crate::{Error, Result};
@@ -723,6 +724,11 @@ pub struct Manifest {
/// lists any ([`Manifest::validate`]).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub command_allowlist: Vec<String>,
/// The events it reacts to, by [`Event::name`]: only a module at `api` 2 or later whose
/// `permissions` list `events` lists any, and it exports `vc_event` ([`crate::events`]). Left
/// 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,
@@ -783,6 +789,7 @@ impl Manifest {
appearance_output: false,
commands: Vec::new(),
command_allowlist: Vec::new(),
events: Vec::new(),
runtime: Runtime::Wasm,
translations: Translations::default(),
}
@@ -897,12 +904,47 @@ impl Manifest {
self.validate_params()?;
self.validate_commands()?;
self.validate_allowlist()?;
self.validate_events()?;
self.validate_translations()?;
self.validate_runtime()
}
/// `events` names each [`Event`] at most once, and a list needs `api` 2 or later and the
/// permission `events`, which needs a list.
fn validate_events(&self) -> Result<()> {
for (i, name) in self.events.iter().enumerate() {
let shown = permissions::display_text(name, permissions::MAX_SHOWN_FIELD);
if Event::parse(name).is_none() {
return Err(Error::Manifest(format!(
"`events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed"
)));
}
if self.events.get(..i).is_some_and(|before| before.contains(name)) {
return Err(Error::Manifest(format!("`events` lists `{shown}` twice")));
}
}
let listed = self.permissions.as_ref().is_some_and(|p| p.iter().any(|n| n == Permission::Events.name()));
if self.events.is_empty() == listed {
return Err(Error::Manifest("`events` needs the permission `events`, and `events` needs a list of `events`".into()));
}
if listed && self.api < EVENTS_API {
return Err(Error::Manifest(format!("`events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API}")));
}
Ok(())
}
/// The events it reacts to (`events`).
pub fn event_kinds(&self) -> Vec<Event> {
self.events.iter().filter_map(|n| Event::parse(n)).collect()
}
/// Does it react to `event`?
pub fn reacts_to(&self, event: Event) -> bool {
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.
/// it lists only `progress`: its realm has no settings, cache, command calls or `vc_event`.
fn validate_runtime(&self) -> Result<()> {
if self.runtime == Runtime::Wasm {
return Ok(());
@@ -912,7 +954,7 @@ impl Manifest {
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] {
for p in [Permission::Settings, Permission::Cache, Permission::Commands, Permission::Events] {
if listed.iter().any(|n| n == p.name()) {
let name = p.name();
return Err(Error::Manifest(format!(
@@ -1326,6 +1368,17 @@ fn write_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Ve
}
}
/// 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> {
let wrong = || serde::de::Error::custom("`events` must be a list of event names, such as selection.changed");
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 `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> {
@@ -2359,6 +2412,52 @@ mod tests {
assert!(Manifest::parse(manifest(MAX_PARAMS + 1, MAX_PARAMS).as_bytes()).is_err(), "too many in all");
}
/// Any kind at `api` 2 that lists the permission `events` names the events it reacts to; an
/// unknown or repeated name, a list without the permission or the permission without a list,
/// and a list at `api` 1 are refused, and the error names the fault.
#[test]
fn events_are_listed_with_their_permission_at_api_2() {
let m = Manifest::parse(
br#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":["layer.changed","selection.changed"]}"#,
)
.unwrap();
assert_eq!(m.event_kinds(), [Event::LayerChanged, Event::SelectionChanged]);
assert!(m.reacts_to(Event::SelectionChanged) && !m.reacts_to(Event::DocumentSaved));
assert_eq!(m.permissions(), [Permission::Events]);
assert_eq!(serde_json::to_value(&m).unwrap()["events"], json!(["layer.changed", "selection.changed"]));
let effect =
br#"{"id":"a","name":"x","kind":"effect","api":2,"permissions":["doc.read","effect.render","events"],"events":["document.saved"]}"#;
assert_eq!(Manifest::parse(effect).unwrap().event_kinds(), [Event::DocumentSaved]);
let importer =
br#"{"id":"a","name":"x","kind":"importer","api":2,"extensions":["q"],"permissions":["import.read","events"],"events":["document.opened"]}"#;
assert!(Manifest::parse(importer).is_ok());
let plain = Manifest::parse(br#"{"id":"a","name":"x","kind":"filter","events":null}"#).unwrap();
assert!(plain.events.is_empty() && serde_json::to_value(&plain).unwrap().get("events").is_none());
for (bad, says) in [
(
r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":["selection.change"]}"#,
"unknown event `selection.change`",
),
(
r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":["layer.changed","layer.changed"]}"#,
"lists `layer.changed` twice",
),
(r#"{"id":"a","name":"x","kind":"filter","api":2,"events":["layer.changed"]}"#, "needs the permission `events`"),
(
r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"events":["layer.changed"]}"#,
"needs the permission `events`",
),
(r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"]}"#, "needs the permission `events`"),
(r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":[]}"#, "needs the permission `events`"),
(r#"{"id":"a","name":"x","kind":"filter","permissions":["events"],"events":["layer.changed"]}"#, "needs plug-in API level 2"),
(r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":"layer.changed"}"#, "must be a list"),
(r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":[1]}"#, "must be a list"),
] {
let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string();
assert!(e.contains(says), "{bad}: {e}");
}
}
#[test]
fn rejects_bad_manifests() {
for bad in [
+12 -4
View File
@@ -7,7 +7,8 @@
//! `permissions` gets the ones its kind implies ([`Permission::implied`]): what every plug-in of
//! that kind could do before manifests listed them. `progress`, `settings`, `cache` and `commands`,
//! which let a plug-in use the host imports of API level 2 ([`crate::host`]), are never implied: a
//! manifest lists them.
//! manifest lists them. Nor is `events`, which lets a plug-in of any kind react to the events its
//! manifest names ([`crate::events`]).
use serde::{Deserialize, Serialize};
@@ -96,10 +97,14 @@ pub enum Permission {
/// ([`crate::host::IMPORTS`]): a filter only.
#[serde(rename = "commands")]
Commands,
/// Run on its own after the changes its manifest's `events` names ([`crate::events`]), with
/// `vc_event`: any kind.
#[serde(rename = "events")]
Events,
}
/// Every permission this host grants, in the order prompts list them.
pub const ALL: [Permission; 10] = [
pub const ALL: [Permission; 11] = [
Permission::DocRead,
Permission::DocWrite,
Permission::State,
@@ -110,6 +115,7 @@ pub const ALL: [Permission; 10] = [
Permission::Settings,
Permission::Cache,
Permission::Commands,
Permission::Events,
];
/// The permissions of the host imports, which any kind may list and none implies; each needs plug-in
@@ -131,6 +137,7 @@ impl Permission {
Permission::Settings => "settings",
Permission::Cache => "cache",
Permission::Commands => "commands",
Permission::Events => "events",
}
}
@@ -152,13 +159,14 @@ impl Permission {
Permission::Settings => "Keep settings of its own",
Permission::Cache => "Keep a cache of its own, which you can clear",
Permission::Commands => "Run these commands",
Permission::Events => "Run on its own when the selection, a document or a layer changes",
}
}
/// May a plug-in of `kind` that declares `commands` or not list it: one [`Permission::allowed`]
/// gives it, or one of the host imports' ([`HOST`]), which any kind may list.
/// gives it, one of the host imports' ([`HOST`]) or `events`, which any kind may list.
pub fn applies(self, kind: Kind, commands: bool) -> bool {
HOST.contains(&self) || Permission::allowed(kind, commands).contains(&self)
self == Permission::Events || HOST.contains(&self) || Permission::allowed(kind, commands).contains(&self)
}
/// The permissions a manifest of `kind` without `permissions` gets. A manifest may also list
+126 -4
View File
@@ -333,6 +333,9 @@ fn wasm_err(e: wasmi::Error) -> Error {
/// `vc_run(input_ptr, input_len, params_ptr, params_len) -> len << 32 | ptr` (negative: error).
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
@@ -395,8 +398,9 @@ fn check_tables(bytes: &[u8]) -> Result<()> {
}
/// 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<()> {
/// initial size fits in `max_memory_bytes`, and `vc_alloc` and `vc_run` with the ABI's types, and
/// `vc_event` with its type when `events` is set (the manifest lists events).
fn check_exports(module: &Module, max_memory_bytes: usize, events: bool) -> 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 {
@@ -414,6 +418,9 @@ fn check_exports(module: &Module, max_memory_bytes: usize) -> Result<()> {
return Err(Error::Abi(format!("the module must export `{name}` with the type {signature}")));
}
}
if events && !matches!(export("vc_event"), Some(ExternType::Func(f)) if f.params() == [I32, I32] && f.results() == [I32]) {
return Err(Error::Abi("the module lists `events`, so it must export `vc_event` with the type (param i32 i32) (result i32)".into()));
}
Ok(())
}
@@ -449,6 +456,9 @@ impl Plugin {
// 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")?;
}
Ok(p)
}
@@ -475,6 +485,10 @@ impl Plugin {
return Err(Error::Abi("the module must export its linear memory as `memory`".into()));
}
p.read(manifest.to_vec(), &imports)?;
if !p.manifest.events.is_empty() {
let Code::Wasm { module, .. } = &p.code else { return Ok(p) };
exports_func(module, "vc_event", &[ValType::I32; 2], &[ValType::I32])?;
}
Ok(p)
}
@@ -498,7 +512,7 @@ impl Plugin {
return Ok(false);
};
self.take(manifest, text, imports)?;
check_exports(&module, self.limits.max_memory_bytes)?;
check_exports(&module, self.limits.max_memory_bytes, !self.manifest.events.is_empty())?;
check_tables(bytes)?;
Ok(true)
}
@@ -646,6 +660,12 @@ impl Plugin {
/// A new instance for `run`, with the host imports of the permissions `granted` linked. When the
/// module's start function fails, what it reported through the host imports goes to `report`.
fn instantiate(&self, run: Run, granted: &[Permission], report: &mut Report) -> Result<Live> {
self.instantiate_with(run, granted, report, self.limits.fuel_base)
}
/// [`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 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)
@@ -658,7 +678,7 @@ impl Plugin {
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(self.limits.fuel_base.min(FUEL_SLICE)).map_err(wasm_err)?;
store.set_fuel(start_fuel.min(FUEL_SLICE)).map_err(wasm_err)?;
let linker = host::linker(engine, granted);
let instance = match linker.instantiate_and_start(&mut store, module) {
Ok(instance) => instance,
@@ -703,6 +723,37 @@ impl Plugin {
slice(live, left, start)
}
/// Calls `f` on at most `budget` instructions, which holds what the call left unused when it
/// returns `Ok`, for the next call to share. With `bridge`, each command call `vc_call` asks
/// for is made with it while the call waits ([`Plugin::answer`]); without it one fails the call.
fn call_budget<P: WasmParams, R: WasmResults>(
live: &mut Live,
f: &TypedFunc<P, R>,
params: P,
budget: &mut u64,
deadline: &Deadline,
mut bridge: Option<&mut Bridge<'_>>,
) -> Result<R> {
let mut call = Self::first_slice(live, budget, |store| f.call_resumable(store, params))?;
loop {
match Self::drive(live, budget, deadline, call)? {
Driven::Finished(r) => {
*budget = budget.saturating_add(live.store.get_fuel().map_err(wasm_err)?);
return Ok(r);
}
Driven::Call(command, args, paused) => {
let Some(bridge) = bridge.as_deref_mut() else {
return Err(Error::Trap("unexpected host trap".into()));
};
// A panic making the call fails the handler, as one in the runtime does.
let answer = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| bridge(&command, &args)))
.map_err(|_| Error::Trap("the runtime panicked".into()))?;
call = Self::answer(live, budget, deadline, &command, answer, paused)?;
}
}
}
}
/// Goes on with `call` slice by slice ([`Plugin::call`]) until it finishes or pauses for a
/// command call that `vc_call` asked for ([`host::Run::pending`]). Each command call costs
/// [`host::CALL_FUEL`] instructions and one for every 64 bytes of its arguments, and the deadline
@@ -937,4 +988,75 @@ impl Plugin {
}
live.read_packed(packed, "the output", limits.max_output_bytes)
}
/// Its limits for one event handler: at most [`crate::events::EVENT_FUEL`] instructions and
/// [`crate::events::EVENT_WALL_TIME_MS`], or its own budgets when they are smaller, and every
/// other limit as it is.
pub fn event_limits(&self) -> Limits {
Limits {
fuel_base: self.limits.fuel_base.min(crate::events::EVENT_FUEL),
wall_time_ms: self.limits.wall_time_ms.min(crate::events::EVENT_WALL_TIME_MS),
..self.limits.clone()
}
}
/// Calls `vc_event` with `event` (the event JSON) in a fresh instance under
/// [`Plugin::event_limits`] → `Ok` when it returned 0, and what it reported through the host
/// imports. With `bridge`, each `vc_call` of a command its `commandAllowlist` names is made with
/// it; a failed call fails the handler. A module that doesn't react to events, an event past
/// [`crate::events::MAX_EVENT_BYTES`] and Safe Mode run nothing.
pub fn run_event(&self, event: &[u8], bridge: Option<&mut Bridge<'_>>) -> (Result<()>, Report) {
let mut report = Report::default();
if let Err(e) = crate::safe_mode::check() {
return (Err(e), report);
}
if self.manifest.events.is_empty() {
return (Err(Error::Abi("the module reacts to no events".into())), report);
}
if event.len() > crate::events::MAX_EVENT_BYTES {
let (len, max) = (event.len(), crate::events::MAX_EVENT_BYTES);
return (Err(Error::Limit(format!("event size ({len} bytes, limit {max})"))), report);
}
let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.event_inner(event, &mut report, bridge)));
(run.map_err(|_| Error::Trap("the runtime panicked".into())).and_then(|r| r), report)
}
fn event_inner(&self, event: &[u8], report: &mut Report, bridge: Option<&mut Bridge<'_>>) -> Result<()> {
let limits = self.event_limits();
let deadline = Deadline::new(limits.wall_time_ms);
let m = &self.manifest;
let run = Run::new(&m.id, false, true, deadline).with_storage(crate::registry::storage(&m.id));
let mut live = self.instantiate_with(run, &m.permissions(), report, limits.fuel_base)?;
// The start function, `vc_alloc` and `vc_event` share the one budget.
let mut budget = live.store.get_fuel().map_err(wasm_err)?;
if bridge.is_some() {
live.store.data_mut().run.allow_calls(m.command_allowlist.clone());
}
let out = (|| {
let alloc: TypedFunc<i32, i32> = live.func("vc_alloc")?;
let handler: TypedFunc<EventArgs, i32> = live.func("vc_event")?;
// The start function may have used the time: neither call runs past it.
deadline.check()?;
let ptr = Self::call_budget(&mut live, &alloc, event.len().max(1) as i32, &mut budget, &deadline, None)? as u32 as usize;
if ptr == 0 {
return Err(Error::Failed("vc_alloc returned 0 (out of memory)".into()));
}
let outside = || Error::Abi("vc_alloc returned a block outside memory".into());
let end = ptr.checked_add(event.len()).ok_or_else(outside)?;
live.memory.data_mut(&mut live.store).get_mut(ptr..end).ok_or_else(outside)?.copy_from_slice(event);
deadline.check()?;
let code = Self::call_budget(&mut live, &handler, (ptr as i32, event.len() as i32), &mut budget, &deadline, bridge)?;
deadline.check()?;
if code != 0 {
return Err(Error::Failed(format!("vc_event returned {code}")));
}
Ok(())
})();
let state = &mut live.store.data_mut().run;
*report = std::mem::take(&mut state.report);
match (state.call_failure.take(), out) {
(Some(e), _) => Err(e),
(None, out) => out,
}
}
}
+12
View File
@@ -82,6 +82,18 @@ pub fn with_field(module: &str, field: &str) -> Option<String> {
/// 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)))";
/// A plug-in that reacts to events ([`crate::events`]): `manifest` (JSON that lists `events`), the
/// module fields `imports` before the others, a `vc_event` whose body is `handler` (parameters
/// `$ep $el`, result i32) and a `vc_run` that returns its input.
pub fn reacting(manifest: &str, imports: &str, handler: &str) -> String {
let extra = format!(r#"{imports} (func (export "vc_event") (param $ep i32) (param $el i32) (result i32) {handler})"#);
module(manifest, ECHO, &extra, 1)
}
/// A `vc_event` body that writes the event it is given as an information log line (with
/// [`HOST_IMPORTS`]) and returns 0.
pub const LOG_EVENT: &str = "(drop (call $vc_log (i32.const 2) (local.get $ep) (local.get $el))) (i32.const 0)";
/// A plug-in that always returns `output` (whatever it is given).
pub fn returning(manifest: &str, output: &str) -> String {
then_returning(manifest, "", output)
+90
View File
@@ -1247,6 +1247,96 @@ fn a_plugin_reaches_only_its_own_storage() {
registry::set_storage("test.storage.theirs", None);
}
/// The manifest of an event plug-in `id` that writes log lines and reacts to `events` (JSON list).
fn reacting_manifest(id: &str, events: &str) -> String {
format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":["progress","events"],"events":{events}}}"#)
}
/// A module that lists `events` needs a `vc_event` export of the right type; one that lists none
/// may leave it out.
#[test]
fn an_event_plugin_exports_vc_event() {
let manifest = reacting_manifest("test.events.export", r#"["selection.changed"]"#);
let e = Plugin::load(&build(&tpl::reporting(&manifest, "", INPUT)), Limits::default()).unwrap_err();
assert!(e.to_string().contains("vc_event"), "{e}");
let wrong = format!(r#"{} (func (export "vc_event") (param i32) (result i32) (i32.const 0))"#, tpl::HOST_IMPORTS);
let e = Plugin::load(&build(&tpl::module(&manifest, tpl::ECHO, &wrong, 1)), Limits::default()).unwrap_err();
assert!(e.to_string().contains("vc_event"), "{e}");
assert!(Plugin::load(&build(&tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)), Limits::default()).is_ok());
assert!(Plugin::load(&ok_module(tpl::ECHO), Limits::default()).is_ok(), "no events, no vc_event");
// A module whose manifest is in its custom section is checked without being instantiated.
let section =
r#"{"id":"test.events.section","name":"T","kind":"filter","api":2,"permissions":["events"],"events":["selection.changed"],"abi":1}"#;
let e = Plugin::load(&build(&tpl::sectioned(section, tpl::ECHO, "", 1)), Limits::default()).unwrap_err();
assert!(e.to_string().contains("vc_event"), "{e}");
let one_param = r#"(func (export "vc_event") (param i32) (result i32) (i32.const 0))"#;
let e = Plugin::load(&build(&tpl::sectioned(section, tpl::ECHO, one_param, 1)), Limits::default()).unwrap_err();
assert!(e.to_string().contains("vc_event"), "{e}");
let handler = r#"(func (export "vc_event") (param i32 i32) (result i32) (i32.const 0))"#;
assert!(Plugin::load(&build(&tpl::sectioned(section, tpl::ECHO, handler, 1)), Limits::default()).is_ok());
}
/// `vc_event` is given the event JSON in its own memory and returns 0; anything else, a trap and a
/// handler past its instruction budget fail it. A module without events runs no handler.
#[test]
fn vc_event_is_given_the_event_and_its_code_is_checked() {
let manifest = reacting_manifest("test.events.run", r#"["layer.changed"]"#);
let p = Plugin::load(&build(&tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)), Limits::default()).unwrap();
let event = br#"{"type":"layer.changed","document":7}"#;
let (r, report) = p.run_event(event, None);
r.unwrap();
assert_eq!(report.lines.iter().map(|l| l.text.as_str()).collect::<Vec<_>>(), [std::str::from_utf8(event).unwrap()]);
for (handler, says) in [
("(i32.const 3)", "vc_event returned 3"),
("unreachable", "trapped"),
// The instruction budget, or the time budget on a loaded machine.
("(loop $l (br $l)) (i32.const 0)", "budget"),
] {
let p = Plugin::load(&build(&tpl::reacting(&manifest, tpl::HOST_IMPORTS, handler)), Limits::default()).unwrap();
let e = p.run_event(event, None).0.unwrap_err().to_string();
assert!(e.contains(says), "{handler}: {e}");
}
let e = p.run_event(&vec![b' '; vectorcraft_plugins::events::MAX_EVENT_BYTES + 1], None).0.unwrap_err();
assert!(e.to_string().contains("event size"), "{e}");
let plain = Plugin::load(&ok_module(tpl::ECHO), Limits::default()).unwrap();
assert!(plain.run_event(event, None).0.is_err());
let limits = p.event_limits();
assert_eq!((limits.fuel_base, limits.wall_time_ms), (vectorcraft_plugins::events::EVENT_FUEL, vectorcraft_plugins::events::EVENT_WALL_TIME_MS));
}
/// The start function, `vc_alloc` and `vc_event` share one event budget: work that fits it in the
/// handler alone fits it no longer when the start function has done as much first. The budget is
/// 200,000 instructions, which run in far less than the 200 ms an event is given, so the run that
/// fails is stopped by its instruction budget.
#[test]
fn a_handler_and_its_start_function_share_the_event_budget() {
let manifest = reacting_manifest("test.events.shared", r#"["layer.changed"]"#);
let burn = r#"(func $burn (param $k i32) (block $b (loop $l
(br_if $b (i32.eqz (local.get $k)))
(local.set $k (i32.sub (local.get $k) (i32.const 1)))
(br $l))))"#;
let plugin = |start: u32, handler: u32| {
let imports = format!("{} {burn} (func $s (call $burn (i32.const {start}))) (start $s)", tpl::HOST_IMPORTS);
let body = format!("(call $burn (i32.const {handler})) (i32.const 0)");
Plugin::load(&build(&tpl::reacting(&manifest, &imports, &body)), Limits { fuel_base: 200_000, ..Limits::default() }).unwrap()
};
let event = br#"{"type":"layer.changed","document":1}"#;
// The most loop turns, doubling, that fit the budget in the handler alone: twice as many run out
// of instructions.
let mut k = 1u32 << 8;
let e = loop {
match plugin(0, k * 2).run_event(event, None).0 {
Ok(()) => k *= 2,
Err(e) => break e.to_string(),
}
assert!(k < 1 << 30, "a handler that never runs out of its budget");
};
assert!(e.contains("instruction budget"), "{e}");
assert!(plugin(0, k).run_event(event, None).0.is_ok());
let e = plugin(k, k).run_event(event, None).0.unwrap_err().to_string();
assert!(e.contains("instruction budget"), "{e}");
}
/// A heavy filter installs once the user agrees, which loading a folder doesn't ask: it is skipped
/// and reported.
#[test]
+80 -5
View File
@@ -61,6 +61,12 @@ fn now_secs() -> f64 {
monotonic_ms() / 1000.0
}
#[cfg(test)]
std::thread_local! {
/// The notices [`VectorcraftApp::deliver_plugin_events`] took on this thread.
static TAKEN_EVENT_NOTICES: std::cell::RefCell<Vec<vectorcraft_engine::plugin_events::Notice>> = const { std::cell::RefCell::new(Vec::new()) };
}
impl VectorcraftApp {
/// The app around `session`, reaching the platform through `services` (the clipboard, files
/// and the like). It registers the app's icon sets, starts cataloguing the installed fonts at
@@ -79,6 +85,9 @@ impl VectorcraftApp {
session.place_cursor_requests = true;
// A script runs a slice per frame, so the window keeps drawing and Stop can be pressed.
session.script_frames = true;
// Plug-in events are delivered by the frame: after the work that finished in the
// background, and at the end of the UI pass ([`VectorcraftApp::deliver_plugin_events`]).
session.plugin_event_frames = true;
let views = session.documents().iter().map(View::of).collect();
let view_uids = session.documents().iter().map(|d| d.uid).collect();
let known = session.documents().iter().map(|d| d.uid).collect();
@@ -362,10 +371,11 @@ impl VectorcraftApp {
/// Applies the work that finished off the UI thread. It stays pending while a script runs, since
/// every change to the documents ends in a busy error until the script ends. Plug-in worker runs
/// are still read then, so Cancel and their time budgets still end them ([`plugin_runs::poll`]).
pub(crate) fn poll_finished_work(&mut self) {
/// Returns whether plug-in event delivery needs a repaint.
pub(crate) fn poll_finished_work(&mut self) -> bool {
if self.session.script_running() {
plugin_runs::poll(self);
return;
return false;
}
background::poll(self);
opening::poll(self);
@@ -373,6 +383,46 @@ impl VectorcraftApp {
trace_runs::poll(self);
placing::poll(self);
retype_runs::poll(self);
// The handlers' time counts toward the frame-time sample, as the delivery after the UI
// pass does.
let t0 = monotonic_ms();
let pending = self.deliver_plugin_events();
self.perf.early_events_ms += monotonic_ms() - t0;
pending
}
/// The plug-in event notices this thread's apps took, for tests that check a handler ran in a
/// pass ([`Self::deliver_plugin_events`] takes them from the session).
#[cfg(test)]
pub(crate) fn take_event_notices_taken() -> Vec<vectorcraft_engine::plugin_events::Notice> {
TAKEN_EVENT_NOTICES.with(|taken| std::mem::take(&mut *taken.borrow_mut()))
}
/// Hands the plug-ins that react to events the changes of this frame
/// ([`vectorcraft_engine::Session::deliver_plugin_events`]). The last warning or error a handler
/// wrote, or the last handler failure, shows in the status bar after the plug-in's name.
/// Returns whether the status bar changed or runnable handlers remain queued.
fn deliver_plugin_events(&mut self) -> bool {
let pending = self.session.deliver_plugin_events();
let notices = self.session.take_plugin_event_notices();
#[cfg(test)]
TAKEN_EVENT_NOTICES.with(|taken| taken.borrow_mut().extend(notices.iter().cloned()));
let shown = notices.into_iter().rev().find(|n| matches!(n.level, vectorcraft_plugins::LogLevel::Error | vectorcraft_plugins::LogLevel::Warn));
let Some(mut n) = shown else { return pending };
let name = vectorcraft_plugins::permissions::display_text(&n.name, vectorcraft_plugins::permissions::MAX_SHOWN_NAME);
// The status is kept in English and translated when the status bar shows it, with the
// plug-in's name kept as it is; a line the handler wrote is kept whole.
let status = format!("{name}: {}", n.text);
self.status(status.clone());
if n.failure.is_some() {
n.name = name;
self.ui.status_plugin_event = Some((status, n));
self.ui.status_kept = None;
} else {
self.ui.status_plugin_event = None;
self.ui.status_kept = Some((String::new(), status, String::new()));
}
true
}
/// The language the UI is drawn in: the Preferences window's choice while it is open (so a
@@ -467,6 +517,10 @@ impl VectorcraftApp {
/// [`Self::tick`]'s work.
fn tick_frame(&mut self, ctx: &egui::Context) {
self.ticked_pass = Some(ctx.cumulative_pass_nr());
if ctx.current_pass_index() == 0 {
self.perf.early_events_ms = 0.0;
self.session.begin_plugin_event_frame();
}
let lang = self.ui_language();
i18n::set_current(lang);
// The engine gives new type the Japanese defaults while the UI is in Japanese.
@@ -515,12 +569,17 @@ impl VectorcraftApp {
// them, even if the worker below finishes them during this same tick.
ctx.data_mut(|d| d.insert_temp(egui::Id::unique("clipboard.pending-at-tick"), self.clipboard_publishing.is_pending()));
screen_color::tick(self, ctx);
let script_was_running = self.session.script_running();
// Once a frame: work that finishes during a frame's first pass is applied in the next frame, not in a second
// pass of this one.
if ctx.current_pass_index() == 0 {
self.poll_finished_work();
if ctx.current_pass_index() == 0 && self.poll_finished_work() {
ctx.request_repaint();
}
crate::script_runs::poll(self);
// Apply the work that waited for the script in the frame it ended in.
if script_was_running && !self.session.script_running() && self.poll_finished_work() {
ctx.request_repaint();
}
// A panel's, a dialog's or the text input's commit journaled in the frame before.
crate::panels::actions::after_journaled_edit(self);
crate::scripts_menu::poll(self, ctx);
@@ -652,6 +711,9 @@ impl VectorcraftApp {
/// input to the automation roots and turns a panic into an error message.
pub fn ui(&mut self, ui: &mut egui::Ui) {
let ctx = ui.ctx().clone();
if ctx.current_pass_index() == 0 && self.ticked_pass != Some(ctx.cumulative_pass_nr()) {
self.perf.early_events_ms = 0.0;
}
self.adopt_context(&ctx);
let confined = self.automation_scope(&ctx);
if let Err(msg) = file_access::confine(confined.as_ref(), || {
@@ -659,6 +721,19 @@ impl VectorcraftApp {
self.handle_input(&ctx);
self.ui_frame(ui);
self.window_keys(&ctx);
// What the canvas, a panel, a dialog or a window key changed in this pass reaches
// the plug-ins that react to it now, since an idle app draws no further frame; a
// line a handler wrote shows in the next one. The handlers' time counts toward the
// frame-time sample of a pass egui presents.
let t0 = monotonic_ms();
if !self.session.script_running() && self.deliver_plugin_events() {
ctx.request_repaint();
}
if !ctx.will_discard() {
self.perf.frame_ms += monotonic_ms() - t0;
} else {
self.perf.early_events_ms += monotonic_ms() - t0;
}
})
}) {
self.session.set_replaying(false);
@@ -753,7 +828,7 @@ impl VectorcraftApp {
// A pass egui will discard and rerun is not a presented frame: it must not become the
// frame-time sample, and it must not issue a capture of what it drew.
if !ctx.will_discard() {
self.perf.frame_ms = monotonic_ms() - t0;
self.perf.frame_ms = monotonic_ms() - t0 + std::mem::take(&mut self.perf.early_events_ms);
self.issue_captures(&ctx);
// A hidden window's pass shows nothing, so the step waits for a pass the user sees.
if step_held && !self.viewport_hidden(&ctx) {
+2
View File
@@ -409,4 +409,6 @@ pub struct Perf {
pub frame_ms: f64,
pub render_ms: f64,
pub fps: f64,
/// Time plug-in event handlers took before the frame's UI pass, added to its `frame_ms`.
pub early_events_ms: f64,
}
+14
View File
@@ -771,6 +771,20 @@ fn date_time_now() -> (String, u64) {
/// it are translated.
pub(crate) fn status_message(app: &VectorcraftApp) -> String {
let status = app.ui.status.as_str();
if let Some((original, notice)) = &app.ui.status_plugin_event
&& original == status
{
use vectorcraft_engine::plugin_events::Failure;
let text = match &notice.failure {
Some(Failure::Handler { error }) => crate::i18n::fmt(&crate::i18n::msg(Failure::HANDLER), &[("event", notice.event), ("error", error)]),
Some(Failure::EventsOff { count }) => {
let template = if *count == 1 { Failure::EVENTS_OFF_ONE } else { Failure::EVENTS_OFF_OTHER };
crate::i18n::fmt(&crate::i18n::msg(template), &[("n", &count.to_string())])
}
None => notice.text.clone(),
};
return format!("{}: {text}", notice.name);
}
let is = |before: &str, kept: &str, after: &str| status.strip_prefix(before).and_then(|rest| rest.strip_suffix(after)) == Some(kept);
if let Some((before, kept, after)) = app.session.script_authored_failure()
&& is(&before, kept, &after)
+1 -1
View File
@@ -631,7 +631,7 @@ fn the_status_bar_stands_still_while_its_readouts_change() {
] {
let (x_value, y_value) = {
let mut app = bar.app();
app.perf = crate::Perf { render_ms: render, frame_ms: frame, fps };
app.perf = crate::Perf { render_ms: render, frame_ms: frame, fps, ..Default::default() };
app.hover_doc = Some(vectorcraft_geom::Point::new(x, y));
(app.session.general_unit().readout(x), app.session.general_unit().readout(y))
};
+1
View File
@@ -294,6 +294,7 @@ fn permission_words(name: &str, commands: &[String], context: bool) -> String {
Some(permissions::Permission::Progress) => tl!("Show its progress, see Cancel and write log lines"),
Some(permissions::Permission::Settings) => tl!("Keep settings of its own"),
Some(permissions::Permission::Cache) => tl!("Keep a cache of its own, which you can clear"),
Some(permissions::Permission::Events) => tl!("Run on its own when the selection, a document or a layer changes"),
None => return permissions::display_text(name, permissions::MAX_SHOWN_FIELD),
};
words.to_string()
+4
View File
@@ -747,6 +747,9 @@ pub struct UiState {
/// as they are ([`crate::plugin_runs::show_notice`]). Not saved.
#[serde(skip)]
pub status_kept: Option<(String, String, String)>,
/// The status and structured plug-in event failure translated when shown. Not saved.
#[serde(skip)]
pub status_plugin_event: Option<(String, vectorcraft_engine::plugin_events::Notice)>,
pub palette_open: bool,
pub palette_query: String,
/// Set when the palette's shortcut, its command or the search icon opens or closes the palette,
@@ -1530,6 +1533,7 @@ impl Default for UiState {
status_notes: None,
startup_notes: Vec::new(),
status_kept: None,
status_plugin_event: None,
palette_open: false,
palette_query: String::new(),
palette_toggled: false,
+77
View File
@@ -1055,6 +1055,83 @@ fn opening_a_javascript_manifest_by_path_does_not_read_it_first() {
app.run("plugin.remove", json!({"id": id})).unwrap();
}
/// A selection made in the UI pass, after the frame's background work (as a click on the canvas or
/// a panel makes it), reaches a plug-in that reacts to `selection.changed` before that pass ends:
/// nothing is left for a later delivery.
#[test]
fn a_change_made_in_a_ui_pass_is_delivered_in_that_pass() {
let mut app = app();
app.session.allow_plugin_grants_from_requests();
let id = "test.UI.ui_pass_events";
let grant = json!(["progress", "events"]);
let manifest = format!(r#"{{"id":"{id}","name":"Pass Events","kind":"filter","api":2,"permissions":{grant},"events":["selection.changed"]}}"#);
// The handler writes the event as an information line, which the status bar does not show, so
// the plug-in leaves the status bar of other tests' sessions alone.
let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap();
app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap();
let r = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone();
app.run("select.none", json!({})).unwrap();
let ctx = crate::testing::ui_context();
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0));
let pass = |app: &mut VectorcraftApp, select: bool| {
crate::testing::part_frame(app, &ctx, egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |app, ui| {
app.tick(ui.ctx());
if select {
app.session.execute("select.set", &json!({"ids": [r]})).unwrap();
}
app.ui(ui);
});
};
// The window lays itself out in the first two passes.
pass(&mut app, false);
pass(&mut app, false);
let _ = VectorcraftApp::take_event_notices_taken();
pass(&mut app, true);
let ran = VectorcraftApp::take_event_notices_taken().into_iter().filter(|n| n.plugin == id && n.event == "selection.changed").count();
assert_eq!(ran, 1, "the handler ran in the pass that made the change");
app.session.deliver_plugin_events();
let left: Vec<String> = app.session.take_plugin_event_notices().into_iter().filter(|n| n.plugin == id).map(|n| n.text).collect();
assert!(left.is_empty(), "delivered in the pass that made the change, not later: {left:?}");
assert_eq!(app.session.doc().unwrap().selection.objects.len(), 1, "the selection was made");
app.run("plugin.remove", json!({"id": id})).unwrap();
}
/// Escape leaving isolation mode restores the selection from before entry after the window's
/// panels and dialogs are drawn; the plug-in that reacts to `selection.changed` is still given the
/// change in that pass.
#[test]
fn a_selection_a_window_key_changes_is_delivered_in_that_pass() {
let mut app = app();
app.session.allow_plugin_grants_from_requests();
let id = "test.UI.window_key_events";
let grant = json!(["progress", "events"]);
let manifest = format!(r#"{{"id":"{id}","name":"Key Events","kind":"filter","api":2,"permissions":{grant},"events":["selection.changed"]}}"#);
let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap();
app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap();
let a = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone();
let b = app.run("shape.rectangle", json!({"x": 40, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone();
app.run("select.set", json!({"ids": [a, b]})).unwrap();
let g = app.run("object.group", json!({})).unwrap()["id"].clone();
app.run("object.isolate", json!({"id": g})).unwrap();
app.run("select.set", json!({"ids": [a]})).unwrap();
let ctx = crate::testing::ui_context();
super::synthetic::key_frame(&mut app, &ctx, vec![]);
super::synthetic::key_frame(&mut app, &ctx, vec![]);
app.session.deliver_plugin_events();
let _ = app.session.take_plugin_event_notices();
let _ = VectorcraftApp::take_event_notices_taken();
let before = app.session.doc().unwrap().selection.objects.clone();
let esc = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
super::synthetic::key_frame(&mut app, &ctx, vec![esc]);
assert_ne!(app.session.doc().unwrap().selection.objects, before, "Escape left isolation and restored the selection");
let ran = VectorcraftApp::take_event_notices_taken().into_iter().filter(|n| n.plugin == id && n.event == "selection.changed").count();
assert_eq!(ran, 1, "the handler ran in the pass of the key");
app.session.deliver_plugin_events();
let left: Vec<String> = app.session.take_plugin_event_notices().into_iter().filter(|n| n.plugin == id).map(|n| n.text).collect();
assert!(left.is_empty(), "delivered in the pass of the key, not later: {left:?}");
app.run("plugin.remove", json!({"id": id})).unwrap();
}
/// The approval names a plug-in whose manifest translates its name in the UI language and also
/// gives the manifest's own name, both escaped; a language without a translation shows the
/// manifest's name alone. What OK installs stays bound to the id and hash shown.
+45
View File
@@ -321,6 +321,51 @@ fn finished_background_work_waits_for_the_run_to_end() {
assert!(app.opening.activate.is_empty());
}
/// The selection a script changes reaches a plug-in that reacts to `selection.changed` in the
/// frame the script ends in: once it has ended, nothing asks for another frame.
#[test]
fn a_finished_run_delivers_its_plugin_events_in_the_frame_it_ends() {
use vectorcraft_plugins::wat as tpl;
/// Removes the plug-in when the test ends, failed or not: the registry serves every session in
/// the process.
struct Remove(&'static str);
impl Drop for Remove {
fn drop(&mut self) {
vectorcraft_plugins::registry::remove(self.0);
}
}
let mut app = app();
app.session.prefs.show_external_script_warning = false;
app.session.allow_plugin_grants_from_requests();
let id = "test.UI.script_run_events";
let _remove = Remove(id);
let grant = json!(["progress", "events"]);
let manifest = format!(r#"{{"id":"{id}","name":"Run Events","kind":"filter","api":2,"permissions":{grant},"events":["selection.changed"]}}"#);
// The handler writes the event as an information line, which the status bar does not show, so
// the plug-in leaves the status bar of other tests' sessions alone; this thread's app keeps
// what it took ([`VectorcraftApp::take_event_notices_taken`]).
let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap();
app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap();
app.poll_finished_work();
let _ = crate::VectorcraftApp::take_event_notices_taken();
let source = format!("{DRAW} vc.run('select.all', {{}});");
menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap();
let ctx = egui::Context::default();
for _ in 0..10_000 {
if !app.session.script_running() {
break;
}
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx()));
out.textures_delta.clear();
}
assert!(!app.session.script_running(), "the script did not end");
let ran: Vec<String> = crate::VectorcraftApp::take_event_notices_taken().into_iter().filter(|n| n.plugin == id).map(|n| n.text).collect();
assert_eq!(ran.len(), 1, "{ran:?}");
assert!(ran[0].contains("selection.changed"), "{ran:?}");
}
#[test]
fn quitting_asks_to_stop_and_stop_undoes_the_run() {
let mut app = app();
+10 -1
View File
@@ -15572,7 +15572,16 @@ while it runs, through `vc_call`: the calls and its output are one undo step, an
fails leaves the documents, selections and history as they were. Without `doc.read` every call fails. A command that
reads or writes files, uses the clipboard, changes preferences or the view, runs a script, an action or a plug-in,
switches documents or undoes is never called; `plugin.install` refuses a manifest that lists one, and `plugin.inspect` lists such ids as
`refusedCommands` and ids no command has as `unknownCommands` (`plugin.install` lists those too). A live-effect plug-in is an effect with
`refusedCommands` and ids no command has as `unknownCommands`; `plugin.install` also lists the `unknownCommands`. A plug-in
at API level 2 whose manifest lists the `events` permission and `events` (in its `plugin.list` entry) is given the events
of the kinds its `events` list names, from `selection.changed`, `document.opened`, `document.saved` and `layer.changed`,
through `vc_event` once the change has finished. Headless tool gestures deliver events after their actions finish.
An open drag, including one temporarily set aside by a command, holds events until it ends. Documents created or
opened in a batch are compared with their state when added, and background plug-in loads record the event baseline
when they install, or after the drag ends if one is open. Each UI frame calls at most four event handlers across
background delivery and all UI passes; runnable recipients still queued request another frame, even without notices.
The handler only reads, and `plugin.info` gives `eventsOff` and `lastEventError` (see `docs/plugins.md`).
Both reset when a module is installed under the plug-in's id again, including the same module. A live-effect plug-in is an effect with
id `plugin.<id>`: `effect.apply`, `effect.setParams` and `effect.expandAppearance` work as for built-in effects, and
`effect.list` lists it. One whose manifest declares `paintOutput` (at plug-in API level 2; `plugin.list` gives `api`
and `paintOutput: true`) draws the pieces it returns with paints of their own, and `effect.expandAppearance` writes them
+70 -6
View File
@@ -439,6 +439,7 @@ capability model proposed for PhotoCraft plug-ins
| `settings` | all | Keep settings of its own between runs and sessions ([settings and cache](#settings-and-cache)). Needs `api` 2. |
| `cache` | all | Keep a cache of its own, which the user can clear ([settings and cache](#settings-and-cache)). Needs `api` 2. |
| `commands` | filter | Run the commands its `commandAllowlist` lists on the document ([command calls](#command-calls)). Needs `api` 2. |
| `events` | all | Run on its own when the selection, a document or a layer changes, for the `events` it names ([events](#events-api-level-2)). Needs `api` 2. |
- A manifest without `permissions` gets the ones its kind implies, as plug-ins did before the key existed: a filter
`doc.read`, `doc.write` and `state`; an effect `doc.read` and `effect.render`, and also `doc.write` and `state`
@@ -448,9 +449,9 @@ capability model proposed for PhotoCraft plug-ins
- An effect, an exporter, an importer or a generator that lists permissions lists all of its implied ones (`doc.read`
and `effect.render`; `doc.read` and `export.write`; `import.read`; `doc.write`). An effect with commands may add `doc.write` and
`state`, which only its commands use. A filter may list any of its three, and `commands` with a `commandAllowlist`.
Any kind may add `progress`, `settings` and `cache`, which no kind implies. An unknown name, a name listed twice, a
name that doesn't apply to the kind, more than 16 names, `progress`, `settings`, `cache` or `commands` with an `api`
below 2, or one of the names kept for a later plug-in API (`ui.panel`, `ui.tool`) is refused when the module is
Any kind may add `progress`, `settings`, `cache` and `events`, which no kind implies. An unknown name, a name listed
twice, a name that doesn't apply to the kind, more than 16 names, `progress`, `settings`, `cache`, `commands` or
`events` with an `api` below 2, or one of the names kept for a later plug-in API (`ui.panel`, `ui.tool`) is refused when the module is
installed, and the error names it.
- **Installing asks first.** Install Plug-in… and File › Open show the plug-in's name, id, version, the SHA-256 of
the file and each permission in plain words, and install it once the user clicks OK, if the file still has the
@@ -672,6 +673,7 @@ pointers are offsets into the module's memory.
| `vc_manifest` | `() -> i64` | `(len << 32) \| ptr` of the UTF-8 manifest JSON (≤ 64 KiB). Needed only by a module without a `vc_manifest` custom section. |
| `vc_alloc` | `(size) -> ptr` | A block of `size` bytes the host may write, or `0` on failure. Never freed: each run gets a fresh instance. |
| `vc_run` | `(input, input_len, params, params_len) -> i64` | Runs the plug-in on the input JSON with the parameters JSON; returns `(len << 32) \| ptr` of the output JSON, or a negative error code. |
| `vc_event` | `(event, event_len) -> i32` | Only in a module whose manifest lists [`events`](#events-api-level-2): reacts to the event JSON; returns `0` when it handled it, anything else when it failed. |
### Manifest section
@@ -812,7 +814,8 @@ arguments as a JSON object, the params the command takes from any request:
`-3` when the arguments are not a JSON object, `-4` when `commandAllowlist` doesn't list the id, `-5` when no command
has the id, `-6` when a plug-in may not call the command, `-7` when the command can't run now (nothing is selected),
`-8` when the command ran and failed, `-9` when a limit below is passed, and `-11` when nothing can be called (from
the module's start function, in a run that isn't a filter's run on a document, or after a call in the run failed).
the module's start function, in a run that isn't a filter's run on a document or an [event](#events-api-level-2)
handler, or after a call in the run failed).
- Every code also fails the run, whatever the plug-in does next, and the error names the call and why it failed. The
run's calls and its output are one undo step, named after the plug-in or its command. A run that fails, traps, runs
@@ -844,6 +847,62 @@ the module's start function, in a run that isn't a filter's run on a document, o
`commandAllowlist` and `budget: "heavy"` is refused. On the web it runs in a worker, and the page makes each call
([The web build](#the-web-build)).
### Events (API level 2)
A plug-in of any kind whose manifest gives `"api": 2`, lists the `events` permission and names events in `events`
exports `vc_event`, and VectorCraft calls it after each change of those kinds:
```json
{"id": "org.example.watch", "name": "Watch", "kind": "filter", "api": 2,
"permissions": ["doc.read", "events"], "events": ["selection.changed", "document.saved"]}
```
| Event | When | The event JSON |
|---|---|---|
| `selection.changed` | The selection in a document changed: other objects, anchors or segments, or nothing (`count` 0). | `{"type", "document", "count", "ids", "truncated"}`: `ids` lists the selected objects, at most 2,048 of them (`truncated` is then `true`), and is `null` without `doc.read`. |
| `document.opened` | A file opened as a document (File › Open, Open Recent, New from Template). A new blank document is not one. | `{"type", "document"}` |
| `document.saved` | Save or Save As wrote the document's own file. Save a Copy, a template and an export are not. | `{"type", "document"}` |
| `layer.changed` | The current layer changed, or a layer or sublayer was added, deleted, moved or given other options. | `{"type", "document", "layer", "reasons"}`: `layer` is the current layer's id (`null` when there is none), `reasons` lists any of `current`, `added`, `deleted`, `reordered` and `options`. `reordered` means a layer's or sublayer's place among the rows beside it changed, also when an object moved past it. |
`document` is a number that names the open document for the rest of the session. No event carries a path, a file name
or the document's contents.
- VectorCraft calls `vc_event(event, event_len)` in a fresh instance with the UTF-8 event JSON in a block from
`vc_alloc`, after the change has finished: after the command, after Undo or Redo, after the file was written or the
document opened. Nothing happens while a drag is still being previewed, for a failed command, or for a command that
leaves the document as it was (a Layer Options that sets the name it had). Installing a plug-in hands it no past
events, also none that were waiting for the next delivery when it was installed. A change made to a document opened
or created since the last delivery is an event at the next one, after that document's `document.opened`.
- The selection changes of one document between two deliveries are one `selection.changed` with the state they ended
with, and its layer changes are one `layer.changed`; each document's events are separate. The desktop app delivers
in each frame, after the work that finished in the background and again at the end of the frame, after the canvas,
panels, dialogs and window keys have run, so a burst of selection changes in one frame is one `selection.changed` and an idle window does
not hold an event back. Requests through the control channel, and through MCP in remote mode, run in the desktop app
and are delivered by the frame too, and several of them can run in one frame. `vectorcraft-cli` and headless MCP
deliver after each request, also one that fails: a save in a `command.batch` whose later step fails still gives its
`document.saved`. Opens and saves are each their own event, in order, and are delivered even when the
document closed before the delivery. The opens and saves of a running script wait until its run ends, also
through any delivery between its slices. The desktop app does not deliver while a script runs; a frontend that
does can give its own opens and saves made while the run was paused before the script's earlier ones. A run that fails gives its saves and none of its opens. At most 32
events wait; past that the oldest is dropped.
- A handler only reads. VectorCraft applies nothing it returns, and it is outside any undo step. With `commands` and a
`commandAllowlist`, it may [call](#command-calls) these commands, when the allowlist also names them, on the active
document: `dataset.list`, `graphicStyle.list`, `guide.list`, `image.info`, `object.blend.info`, `swatch.list`,
`symbol.list`, `text.getRange`, `transparency.info` and `variable.list`. A call of any other command fails with `-6`
before it runs, the error names the event (`a selection.changed handler only reads: …`), and the handler fails.
Afterwards VectorCraft puts back every document, its selection, current layer and undo history, which document is
active, and the session state a command call can change (paint defaults, the Appearance panel's active row,
preferences); a call that changed a document is refused the same way. An event raised while a handler runs waits
for the next delivery: handlers never run inside one another.
- A handler gets at most 5,000,000 instructions and 200 ms, or its plug-in's own budget when that is smaller, for the
module's start function, `vc_alloc` and `vc_event` together; its settings, cache and log lines work as in a run.
These limits are VectorCraft's own values. A handler that returns anything but `0`, traps or runs out of budget
leaves the change it was told of as it is. Every failure goes to the log, and the first failure in a row also shows
in the status bar; after 3 failures in a row, the plug-in gets no more events until VectorCraft
starts again or a module is installed with its id again, the same module included. A warning or error line a handler writes with `vc_log`
shows in the status bar after the plug-in's name. `plugin.info` gives `eventsOff` and `lastEventError`.
- In Safe Mode no handler runs. When no installed plug-in names an event, VectorCraft does not compare anything.
### Manifest
```json
@@ -929,6 +988,11 @@ the module's start function, in a run that isn't a filter's run on a document, o
it): the ids of the commands the filter may [call](#command-calls), at most 256, each once (`"commandAllowlist":
["select.all", "object.move"]`). An id is 1–128 characters from `A-Z a-z 0-9 . _ -` that starts with a letter, with
no empty part between dots. A malformed list is refused when the module is installed, and the error names the id.
- `events` (any kind at `api` 2, and only with the `events` permission, which needs it): the
[events](#events-api-level-2) the plug-in reacts to, any of `"selection.changed"`, `"document.opened"`,
`"document.saved"` and `"layer.changed"`, each at most once. The module then exports `vc_event`. An unknown or
repeated name, an entry that isn't a string, `api` 1, a list without the permission, the permission without a list,
and a missing or wrongly typed `vc_event` are refused when the module is installed, and the error names the fault.
- `translations`: the plug-in's text in other languages ([Translations](#translations)).
- `params`: in dialog order. Names are `[A-Za-z0-9_]`, not starting with `_`, and not `id`, `ids`, `params` or
`preview`. The host validates the user's values before calling: missing values take the default, numbers are
@@ -1541,8 +1605,8 @@ function run(input, params) {
The manifest has the keys of a module's [manifest](#manifest), with `"runtime": "js"` and `script`, a file name of 1 to
128 bytes ending in `.js`, without a folder or `:`, and not starting with `.`. Left out, `runtime` is WebAssembly, so
existing modules load as before; a module's own manifest may not give `"js"`. A JavaScript plug-in is a filter (`kind`
`"filter"`), and of the host's [permissions](#permissions) it may list `progress` but not `settings`, `cache` or
`commands`, so it has no `commandAllowlist`.
`"filter"`), and of the host's [permissions](#permissions) it may list `progress` but not `settings`, `cache`,
`commands` or `events`, so it has no `commandAllowlist` and no `events`.
`plugin.install {path}` and `plugin.inspect {path}` take the `.vcplugin` file, and File › Open and `plugin.reload`
install it like a `.wasm` file. The host refuses a manifest without `script`, with `source`, or with a `runtime` other
+1
View File
@@ -2844,6 +2844,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Changed plug-in gradients lose spot plates (G17):** a gradient that a filter or importer changes loses each stop's swatch link, tint and process `plates` together, in fills and strokes, and keeps the stop's color, offset, opacity and midpoint; a gradient returned unchanged keeps all three. Regressions: `crates/plugins/src/objects/tests.rs` (`changed_gradient_fill_and_stroke_drop_spot_plates`, `unchanged_gradient_paint_keeps_spot_plates`). Scores and hours unchanged.
- **Plug-in data kept with the document (G17):** a filter writes JSON of at most 1 MiB with `documentData` (one undo step with its objects; `null` removes it) and reads it back in `_context.documentData`, which no other filter is given. It is the document's foreign data (`unknown.pluginData`, by plug-in id), as the perspective grid is, so the native file keeps it with no section of its own; an exporter is given the whole document, so it can read every plug-in's. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_export.rs` (the exporter), `crates/doc/src/plugin_data.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged.
- **Heavy filter plug-ins (G17):** a filter's manifest may ask for `"budget": "heavy"`: 1 G instructions (20 times a light run's) and 300 s a run, for routing, packing or simulation. Install Plug-in… and File › Open ask the user first, `plugin.install` needs `allowHeavy: true` (`plugin.inspect` tells beforehand), the Additional Plug-ins Folder skips such filters, and the plug-in store keeps the answer. Its dialog has no Preview; the app runs it on a thread of its own with a progress window (Cancel, Continue in Background) and applies the result as `plugin.run` with the same parameters, one undo step, unless the document or the plug-in changed meanwhile. Regressions: `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged.
- **Plug-ins react to events (G17, VectorCraft's own API):** a plug-in at API level 2 with the `events` permission names any of `selection.changed`, `document.opened`, `document.saved` and `layer.changed` in its manifest, and its `vc_event` export is given a small JSON event after each change of that kind has finished, outside any undo step: the selection changes of one document between two checks are one event, and so are its layer changes, while each open and each save is its own event and each document's events stay separate. At most 32 events wait for delivery; past that the oldest waiting event is dropped. The desktop app checks after background work and at the end of each UI pass; `vectorcraft-cli` and headless MCP check after each top-level command. Each UI frame runs at most four handlers across background delivery and all UI passes, and requests another frame while runnable handlers remain queued, even without notices. An open drag holds events until it ends. A plug-in loaded during a drag records its baseline after commit or cancel, before the next edit, without recording temporary previews. A handler only reads: it may call only ten listed commands that read, any other call fails with an error naming the event, and what a call changed is put back. It gets 5 M instructions and 200 ms, a handler that fails 3 times in a row gets no more events for the session or until the plug-in is installed again, and an event raised while a handler runs waits for the next delivery. Regressions: `crates/engine/src/tests/plugin_events.rs`, `crates/engine/src/plugin_events.rs`, `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged.
- **Apply Last Filter and Last Filter… for filter plug-ins (G17):** Object › Plug-ins starts with Apply Last Filter (`plugin.applyLastFilter`), which runs the filter plug-in that last ran in the session again with the same parameters on the selection, without its dialog, as one undo step, and Last Filter… (`plugin.lastFilter`), which opens that filter's dialog with those parameters; once a filter has run, both items are named after it. [The help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=357) describes the same pair for filters: one item repeats the last filter with its last settings, the other opens its options. Each filter's own dialog opens with the parameters that filter last ran with. A heavy filter repeats in the background as its menu item runs it. Both items are grayed out with no document open, before a filter ran, and once that filter was removed, installed again or no longer takes the parameters as they are; they don't need a selection (VectorCraft's own rules). Regressions: `crates/ui-egui/src/tests/last_filter.rs`. Scores and hours unchanged.
- **Plug-in instruction budget preference (G17, VectorCraft's own setting):** Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget (`pluginInstructionBudget`) is Normal by default, which keeps the 50 M instructions a light filter run gets, or Large, which gives each object filter run 250 M plus the 4,000 per input byte, with the 60 s time budget, Cancel and the other limits unchanged. A heavy filter keeps its 1 G and 300 s with either choice; live effects, exporters and importers keep their own budgets. A change applies to the next run of an installed filter; `prefs.set` refuses any other value, and a saved file with another value reads as Normal. Regressions: `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. Scores and hours unchanged.
- **Safe Mode for plug-ins (G17):** `vectorcraft --safe-mode` and `vectorcraft-cli --safe-mode <subcommand>` start without plug-ins. When a launch stopped while a plug-in was loading or drawing its first live effect, the next launch names that plug-in, without saying it caused the stop, and offers Disable and Continue, Start Normally or Start in Safe Mode. Help › Safe Mode lists the disabled plug-ins with Enable on Re-launch, which takes effect at the next launch, and the app bar and the window title show Safe Mode. The help page (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf, pages 65 to 69) describes the same choice between diagnosing and starting normally, a Safe Mode with the problem item off and the rest of the app working, and turning the item back on at the next launch. In Safe Mode no plug-in loads or runs, and a live-effect plug-in draws its object's geometry unchanged while the object keeps the effect, which the Appearance panel marks "(Safe Mode)" with the plug-in's id in its tooltip and `effect.list` marks `skipped`; Expand Appearance refuses such an object. The web build keeps no plug-ins between page loads and has no marker. Each desktop launch with preferences keeps a marker in the `Launch` folder next to them; `vectorcraft-cli` and a desktop launch without preferences keep none, so a stop there leads to no choice at the next launch. Disabled plug-ins are listed in `Plug-ins/disabled.json`. `plugin.safeMode` reports Safe Mode and the disabled plug-ins, and `plugin.setEnabled` changes the list. Regressions: `crates/plugins/src/safe_mode.rs`, `crates/plugins/tests/safe_mode.rs`, `crates/engine/tests/plugin_safe_mode.rs`, `crates/ui-egui/tests/safe_mode.rs`. Scores and hours unchanged.