Plug-ins: fix event delivery edge cases from review

- A commit or cancel with no drag open no longer ends an interaction for
  plug-in events.
- A host query that panics during a handler still puts the session back.
- Handler calls after a replayed command are checked as calls from outside.
- A rolled-back batch puts back the events its opens pushed out of the
  32-event queue.
- Installing a plug-in again, the same module included, turns its events
  back on; plugin.info's eventsOff follows the same rule.
- A document added before the first check records its baseline.
- Handler failures show in the status bar from their English templates,
  translated when shown, and event handler time counts toward the frame
  time.
- Tests check that the handler ran in the tested pass, and the script-run
  test no longer writes to other sessions' status bar.
This commit is contained in:
dotCooCoo committed 2026-11-30 22:12:19 -08:00
1 parent 8afd855040
commit b852316921
15 files changed
+279 -41

No files matched your search

+1 -1
View File
@@ -2437,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), eventsOff? (with events: true once 3 handlers in a row failed, until the app starts again or another module is installed with its id), lastEventError? (with events: its handler's last failure, null)}",
"{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
),
+6 -2
View File
@@ -508,7 +508,8 @@ fn read_only<R>(s: &mut Session, f: impl FnOnce(&mut Session) -> R) -> (R, bool)
let pending_paint = s.pending_paint.clone();
let start = s.docs.clone();
let active = s.active;
let r = f(s);
// 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 {
@@ -532,7 +533,10 @@ fn read_only<R>(s: &mut Session, f: impl FnOnce(&mut Session) -> R) -> (R, bool)
if changed {
s.sync_front_profiles();
}
(r, changed)
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
+136 -17
View File
@@ -22,7 +22,7 @@
//! 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 another module is installed under its id.
//! 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};
@@ -40,6 +40,10 @@ 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;
@@ -82,6 +86,8 @@ struct Pending {
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,
@@ -101,10 +107,11 @@ impl Pending {
}
}
/// One plug-in's failed handlers in a row, for the module with `hash`.
/// 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>,
@@ -121,6 +128,28 @@ pub struct Notice {
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.
@@ -130,6 +159,9 @@ pub struct PluginEvents {
/// 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,
@@ -191,13 +223,22 @@ impl PluginEvents {
}
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, by_script: false });
self.pending.push_back(Pending { event, document: uid, to, seq: self.queued, displaced, by_script: false });
self.queued += 1;
}
@@ -208,16 +249,24 @@ impl PluginEvents {
self.notices.push_back(n);
}
/// The failures of plug-in `p`, started again when another module was installed under its id.
/// 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.hash != p.hash() {
*f = Failures { hash: p.hash().to_string(), ..Failures::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>);
@@ -323,10 +372,12 @@ impl Session {
/// 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 {
self.plugin_events.pending.retain(|p| !(p.by_script && p.event == Event::DocumentOpened));
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 &mut self.plugin_events.pending {
for p in events.pending.iter_mut().chain(events.evicted.iter_mut()) {
p.by_script = false;
}
}
@@ -339,8 +390,20 @@ impl Session {
/// 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) {
self.plugin_events.pending.retain(|p| p.event != Event::DocumentOpened || p.seq < mark);
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
@@ -359,6 +422,7 @@ impl Session {
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();
@@ -425,6 +489,10 @@ impl Session {
}
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;
@@ -477,6 +545,7 @@ impl Session {
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
@@ -527,7 +596,7 @@ impl Session {
};
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 });
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 {
@@ -542,23 +611,31 @@ impl Session {
let (count, first) = (failures.count, failures.count == 1);
log::warn!("plug-in {id}: its {event} handler failed: {e}");
if first {
let text = format!("its {event} handler failed: {e}");
self.plugin_events.notice(Notice { plugin: id.clone(), name: name.clone(), event, level: LogLevel::Error, text });
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 = format!("its events are off until VectorCraft starts again, after {count} failed handlers in a row");
self.plugin_events.notice(Notice { plugin: id, name, event, level: LogLevel::Error, text });
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.
/// Nothing is kept when no plug-in reacted to events at the last check, nor for a
/// document in an interaction.
/// 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 {
@@ -636,7 +713,7 @@ impl Session {
/// 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.hash == p.hash()) {
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),
}
@@ -750,4 +827,46 @@ mod tests {
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);
}
}
+7 -2
View File
@@ -659,11 +659,13 @@ 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() {
if r.is_ok() && open {
self.plugin_events_interaction_ended();
}
r
@@ -762,6 +764,7 @@ impl Session {
}
pub fn cancel_interaction(&mut self) -> Result<()> {
let open = self.in_interaction() || self.holds_interaction();
self.put_back_interaction();
self.clear_deferred_overlay_cache();
self.decoded_images.empty();
@@ -798,7 +801,9 @@ impl Session {
if !used_defaults_only {
self.inherit_new_art();
}
self.plugin_events_interaction_ended();
if open {
self.plugin_events_interaction_ended();
}
Ok(())
}
+47
View File
@@ -1029,5 +1029,52 @@ fn a_handler_that_keeps_failing_is_turned_off() {
assert!(notices[1].contains("after 3 failed handlers in a row"), "{}", notices[1]);
let info = run(&mut s, "plugin.info", json!({"id": id}));
assert_eq!(info["eventsOff"], json!(true));
// Installing the same module again turns its events back on.
install(&mut s, id, r#"["selection.changed"]"#, &[], "", "unreachable", &[]);
let info = run(&mut s, "plugin.info", json!({"id": id}));
assert_eq!(info["eventsOff"], json!(false), "a new installation starts with no failures");
run(&mut s, "plugin.remove", json!({"id": id}));
}
/// A commit or cancel with no interaction open ends nothing: it records no baseline, so a change
/// made and undone before the next delivery gives no event.
#[test]
fn a_commit_or_cancel_without_an_interaction_records_no_baseline() {
let id = "test.events.no_interaction";
for commit in [true, false] {
let mut s = local_session();
s.plugin_event_frames = true;
let a = rect(&mut s, 10.0);
run(&mut s, "select.none", json!({}));
subscribe(&mut s, id, r#"["selection.changed"]"#, tpl::LOG_EVENT);
s.deliver_plugin_events();
let _ = given(&mut s, id);
run(&mut s, "select.set", json!({"ids": [a.0]}));
if commit {
s.commit_interaction().unwrap();
} else {
s.cancel_interaction().unwrap();
}
run(&mut s, "select.none", json!({}));
s.deliver_plugin_events();
assert!(given(&mut s, id).is_empty(), "commit: {commit}");
}
}
/// A document added before any check of a plug-in that reacts to events is compared with how it
/// was when it was added, so its first selection change gives an event.
#[test]
fn a_document_added_before_the_first_check_gives_its_first_change() {
let id = "test.events.first_document";
let mut s = Session::new();
s.plugin_event_frames = true;
let manifest =
format!(r#"{{"id":"{id}","name":"Test {id}","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 plugin = vectorcraft_plugins::Plugin::load(&wasm, vectorcraft_plugins::Limits::default()).unwrap();
s.plugin_events.test_subscribers = Some(vec![std::sync::Arc::new(plugin)]);
run(&mut s, "file.new", json!({"width": 400, "height": 200}));
rect(&mut s, 10.0);
s.deliver_plugin_events();
assert_eq!(types(&given(&mut s, id)), ["selection.changed"]);
}
+43 -10
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
@@ -376,7 +382,19 @@ impl VectorcraftApp {
trace_runs::poll(self);
placing::poll(self);
retype_runs::poll(self);
self.deliver_plugin_events()
// 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
@@ -385,15 +403,24 @@ impl VectorcraftApp {
/// 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 shown = self
.session
.take_plugin_event_notices()
.into_iter()
.rev()
.find(|n| matches!(n.level, vectorcraft_plugins::LogLevel::Error | vectorcraft_plugins::LogLevel::Warn));
let Some(n) = shown else { return pending };
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);
self.status(format!("{name}: {}", n.text));
// 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
}
@@ -490,6 +517,7 @@ impl VectorcraftApp {
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();
@@ -681,6 +709,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(), || {
@@ -698,6 +729,8 @@ impl VectorcraftApp {
}
if !ctx.will_discard() {
self.perf.frame_ms += monotonic_ms() - t0;
} else {
self.perf.early_events_ms += monotonic_ms() - t0;
}
})
}) {
@@ -793,7 +826,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
@@ -597,7 +597,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))
};
+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,
+6
View File
@@ -1083,7 +1083,10 @@ fn a_change_made_in_a_ui_pass_is_delivered_in_that_pass() {
// 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:?}");
@@ -1114,10 +1117,13 @@ fn a_selection_a_window_key_changes_is_delivered_in_that_pass() {
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:?}");
+8 -5
View File
@@ -343,11 +343,13 @@ fn a_finished_run_delivers_its_plugin_events_in_the_frame_it_ends() {
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 it is given as a warning, which the status bar shows.
let warn = "(drop (call $vc_log (i32.const 1) (local.get $ep) (local.get $el))) (i32.const 0)";
let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, warn)).unwrap();
// 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();
@@ -359,8 +361,9 @@ fn a_finished_run_delivers_its_plugin_events_in_the_frame_it_ends() {
out.textures_delta.clear();
}
assert!(!app.session.script_running(), "the script did not end");
assert!(app.ui.status.starts_with("Run Events: "), "{}", app.ui.status);
assert!(app.ui.status.contains("selection.changed"), "{}", app.ui.status);
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]
+2 -1
View File
@@ -15258,7 +15258,8 @@ An open drag, including one temporarily set aside by a command, holds events unt
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`). A live-effect plug-in is an effect with
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
+1 -1
View File
@@ -899,7 +899,7 @@ or the document's contents.
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 another module is installed with its id. A warning or error line a handler writes with `vc_log`
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.
+1 -1
View File
@@ -2843,7 +2843,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. 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, 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 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.