Plug-ins: hold a running script's events and deliver window-key changes in their pass

A delivery between a script's slices no longer gives the opens and saves the
script queued; they wait until the run ends, so a run that fails never gives
the opens of documents it discarded. The desktop app now delivers after the
window keys run, so a selection Escape changes when it leaves isolation mode
reaches plug-ins in that pass, and the handlers' time counts toward the frame
time. The docs state the per-document grouping and the script rule.
This commit is contained in:
dotCooCoo committed 2026-11-29 00:24:17 -08:00
1 parent 6227297ae4
commit c04c53ca6c
6 files changed
+115 -15

No files matched your search

+18 -4
View File
@@ -281,10 +281,12 @@ impl Session {
}
}
/// At the end of a script's run. 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.
/// 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) {
if !kept {
self.plugin_events.pending.retain(|p| !(p.by_script && p.event == Event::DocumentOpened));
@@ -375,7 +377,15 @@ impl Session {
// 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();
while let Some(p) = self.plugin_events.pending.pop_front() {
if p.by_script {
held.push_back(p);
continue;
}
if !p.event.outlives_document() && !self.docs.iter().any(|d| d.uid == p.document) {
continue;
}
@@ -386,6 +396,10 @@ impl Session {
self.run_handler(plugin, &p);
}
}
// 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.plugin_events.dispatching = false;
}
+44
View File
@@ -371,6 +371,50 @@ fn a_failed_script_gives_its_save_but_not_its_open() {
run(&mut s, "plugin.remove", json!({"id": id}));
}
/// A delivery between a script's slices, as a frontend makes one for a command it runs while the
/// script is paused, gives the frontend's open but holds the open and the save the script queued
/// until the run ends: the run fails, so its open is never given, and its save is given after it.
#[test]
fn a_delivery_between_script_slices_holds_the_script_events() {
let id = "test.events.between_slices";
let mut s = session();
let doc = s.doc().unwrap().uid;
install(&mut s, id, r#"["document.saved","document.opened"]"#, &[], "", tpl::LOG_EVENT, &[]);
s.plugin_event_frames = true;
let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-between-slices-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
run(&mut s, "document.save", json!({"path": dir.join("between-slices.vectorcraft").to_string_lossy()}));
s.deliver_plugin_events();
assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})]);
let data = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
s.script_frames = true;
let source = format!(
"vc.run('document.save', {{}}); vc.run('document.open', {{name: 'b.vectorcraft', dataBase64: '{data}'}}); \
for (var i = 0; i < 3000000; i++) {{}} throw new Error('stop');"
);
assert_eq!(run(&mut s, "script.run", json!({"source": source, "name": "t.js"}))["running"], true);
assert!(s.script_pump().is_none(), "paused after its first slice");
let bytes = vectorcraft_format::base64_decode(&data).unwrap();
let index = crate::cmd::fileio::open_bytes(&mut s, "front.vectorcraft", &bytes, None).unwrap()["index"].as_u64().unwrap();
let front = s.documents()[index as usize].uid;
s.deliver_plugin_events();
assert_eq!(given(&mut s, id), [json!({"type": "document.opened", "document": front})], "only the frontend's open, while the run is paused");
let mut slices = 0;
let r = loop {
slices += 1;
assert!(slices < 100_000, "the script ends");
if let Some(r) = s.script_pump() {
break r;
}
};
assert!(r.is_err(), "the script threw");
s.deliver_plugin_events();
assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})], "the script's save, and not its open");
std::fs::remove_dir_all(&dir).ok();
run(&mut s, "plugin.remove", json!({"id": id}));
}
/// A `selection.changed` event of a plug-in without `doc.read` gives the count and no ids; one
/// with it lists the selected ids.
#[test]
+11 -6
View File
@@ -673,6 +673,17 @@ 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;
}
})
}) {
self.session.set_replaying(false);
@@ -757,12 +768,6 @@ impl VectorcraftApp {
// A command run by a menu, panel or dialog in this pass may have queued its text copy
// after the input. Publish it now: an idle web host may have no further frame to run it in.
self.flush_clipboard_out();
// What the canvas, a panel or a dialog 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.
if !self.session.script_running() && self.deliver_plugin_events() {
ctx.request_repaint();
}
crate::cursors::request_busy(self, &ctx);
// 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.
+33
View File
@@ -1065,6 +1065,39 @@ fn a_change_made_in_a_ui_pass_is_delivered_in_that_pass() {
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 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");
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.
+8 -4
View File
@@ -873,14 +873,18 @@ or the document's contents.
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`.
- Changes between two deliveries are one event with the state they ended with. 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
and dialogs have run, so a burst of selection changes in one frame is one `selection.changed` and an idle window does
- 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. At most 32 events wait; past that the oldest is dropped.
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`,
+1 -1
View File
@@ -2836,7 +2836,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: changes between two deliveries (a frame in the desktop app, a request in `vectorcraft-cli` or headless MCP) are one event. 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, 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.
- **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 deliveries (a frame in the desktop app, a request in `vectorcraft-cli` or headless MCP) 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. 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, 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.