Files
vectorcraft/crates/plugins/src/events.rs
T
dotCooCoo 54cd14b3cd Plug-ins: react to selection, layer, open and save events
A plug-in at API level 2 with the new `events` permission can name any of
`selection.changed`, `document.opened`, `document.saved` and
`layer.changed` in its manifest's `events` list. Its `vc_event` export is
then called with a small JSON event after each change of that kind has
finished, outside any undo step. Changes between two deliveries are one
event. The desktop app delivers twice a frame, after the work that
finished in the background and at the end of the frame after the canvas,
panels and dialogs ran; control-channel requests run in the desktop app
and are delivered by the frame. vectorcraft-cli and headless MCP deliver
after each request. A plug-in installed after a change is not given it,
and a change made after an install reaches the new plug-in at the next
delivery.

- A handler only reads. It may call ten commands that read
  (dataset.list, graphicStyle.list, guide.list, image.info,
  object.blend.info, swatch.list, symbol.list, text.getRange,
  transparency.info and variable.list); any other call fails before it
  runs with an error naming the event. After each call every document
  with its selection, current layer and undo history, the active
  document, the paint defaults, the active Appearance row and the
  preferences are put back, and a call that changed a document is
  refused.
- A handler gets 5 M instructions and 200 ms, shared by the module's start
  function, `vc_alloc` and `vc_event`. A handler that fails 3 times in a
  row gets no more events until VectorCraft starts again.
- An event raised while a handler runs waits for the next delivery.
- Events carry the document number and counts; selected ids (at most
  2,048) only with `doc.read`. No paths or file contents.
- A save that finishes after its document closed is still reported.
- A document opened or created since the last delivery is compared with
  its state when the command that added it ended, so the first change
  made to it is an event.
- A waiting event is dropped for a plug-in that was removed, so the same
  module installed again is not given it.
- The desktop app delivers the events of a script in the frame the script
  ends in.

plugin.list and plugin.info report `events`, `eventsOff` and
`lastEventError`. Docs: docs/plugins.md (Events), docs/mcp.md and one
progress line in docs/target-app-parity.md. The new plug-in messages, the
status lines for a failed handler and the permission's words in Install
Plug-in... have rows in every complete catalog.
2026-11-22 13:50:35 -08:00

95 lines
4.0 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 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");
}
}