From 330aa4dffbc538222a9c7f52232c58d2f674a059 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:27:06 -0800 Subject: [PATCH] Plug-ins: deliver events after headless gestures and bound handlers per frame - Headless tool gestures deliver plug-in events once their actions finish, and a drag set aside by a command holds events until it ends. - Documents added in a batch are compared with their state when added. - Background plug-in loads record the event baseline when they install, or after commit or cancel when a drag is open. - Layer snapshots are compared by id through a map. - Each desktop frame runs at most four handlers across background delivery and every UI pass, and asks for another frame while handlers remain queued. --- crates/engine/src/lib.rs | 3 +- crates/engine/src/plugin_events.rs | 146 ++++++++++++--- crates/engine/src/session/documents.rs | 5 +- crates/engine/src/session/edit.rs | 4 + crates/engine/src/session/execute.rs | 7 +- crates/engine/src/store.rs | 2 + crates/engine/src/tests/plugin_events.rs | 216 +++++++++++++++++++++++ crates/engine/src/tooling.rs | 2 + crates/ui-egui/src/app.rs | 29 +-- docs/mcp.md | 8 +- docs/target-app-parity.md | 2 +- 11 files changed, 377 insertions(+), 47 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 773f547802..0d185dcb5f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -393,7 +393,8 @@ pub struct Session { /// 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. + /// 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`]). diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index f853198ebb..e2e60f445f 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -9,10 +9,14 @@ //! 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 the command that added it ended +//! 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`]). @@ -21,7 +25,8 @@ //! until the session ends, or until another module is installed under its id. //! - When no installed plug-in reacts to events, a check returns before comparing anything. -use std::collections::{BTreeMap, VecDeque}; +use std::collections::{BTreeMap, HashMap, VecDeque}; +use std::hash::Hash; use std::sync::Arc; use serde_json::{Value, json}; @@ -35,6 +40,9 @@ use crate::Session; /// Most events that wait for delivery. pub const MAX_PENDING: usize = 32; +/// 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; @@ -116,6 +124,7 @@ pub struct PluginEvents { /// How many events have been queued as their own entry. queued: u64, dispatching: bool, + frame_handlers: usize, failures: BTreeMap, notices: VecDeque, /// The installed plug-ins that react to events, as of a registry revision. @@ -195,7 +204,7 @@ impl PluginEvents { /// 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 = (NodeId, Option, vectorcraft_doc::Node, Vec); +type LayerRow = (Id, Option, vectorcraft_doc::Node, Vec); /// Each layer and sublayer of `doc`, in order. fn layer_rows(doc: &Document) -> Vec { @@ -247,18 +256,28 @@ fn layer_reasons(before: &Arc, layer_before: Option, after: &A return reasons; } let (old, new) = (layer_rows(before), layer_rows(after)); - if new.iter().any(|(id, ..)| !old.iter().any(|(o, ..)| o == id)) { + 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(old: &[LayerRow], new: &[LayerRow], moved: impl FnOnce() -> bool) -> Vec<&'static str> { + let mut reasons = Vec::new(); + let old_by_id: HashMap> = old.iter().map(|r| (r.0, r)).collect(); + let new_by_id: HashMap> = 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(|(id, ..)| !new.iter().any(|(n, ..)| n == id)) { + if old.iter().any(|r| !new_by_id.contains_key(&r.0)) { reasons.push("deleted"); } - let kept = - |rows: &[LayerRow], other: &[LayerRow]| rows.iter().filter(|r| other.iter().any(|o| o.0 == r.0)).map(|r| (r.0, r.1)).collect::>(); - if kept(&old, &new) != kept(&new, &old) || layers_moved_among_rows(before, &old, after, &new) { + let kept = |rows: &[LayerRow], other: &HashMap>| { + rows.iter().filter(|r| other.contains_key(&r.0)).map(|r| (r.0, r.1)).collect::>() + }; + if kept(old, &new_by_id) != kept(new, &old_by_id) || moved() { reasons.push("reordered"); } - if old.iter().any(|r| new.iter().any(|o| o.0 == r.0 && o.2 != r.2)) { + if old.iter().any(|r| new_by_id.get(&r.0).is_some_and(|o| o.2 != r.2)) { reasons.push("options"); } reasons @@ -315,7 +334,7 @@ impl Session { /// 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) { + fn check_plugin_events(&mut self, interaction_ended: bool) { let subs = self.plugin_events.subscribers(); if subs.is_empty() { self.plugin_events.seen.clear(); @@ -328,7 +347,7 @@ impl Session { p.to.retain(|(r, _)| installed.contains(r)); !p.to.is_empty() }); - if self.docs.iter().any(|d| d.interaction.is_some()) { + 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); @@ -359,17 +378,31 @@ impl Session { 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. - pub fn deliver_plugin_events(&mut self) { + /// 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; + return false; } - self.check_plugin_events(); - if self.plugin_events.pending.is_empty() || self.docs.iter().any(|d| d.interaction.is_some()) { - return; + 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 = self.plugin_events.subscribers(); self.plugin_events.dispatching = true; @@ -381,7 +414,10 @@ impl Session { // ([`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() { + 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; @@ -389,11 +425,30 @@ impl Session { if !p.event.outlives_document() && !self.docs.iter().any(|d| d.uid == p.document) { continue; } - for plugin in subs.iter().filter(|s| s.manifest().reacts_to(p.event) && p.is_for(&recipient(s))) { - if self.plugin_events.failures_of(plugin).disabled { + for plugin in subs.iter().filter(|s| s.manifest().reacts_to(p.event)) { + let r = recipient(plugin); + if !p.is_for(&r) { continue; } + if self.plugin_events.failures_of(plugin).disabled { + p.to.retain(|(to, _)| *to != r); + continue; + } + if budget == 0 { + break; + } self.run_handler(plugin, &p); + p.to.retain(|(to, _)| *to != r); + budget -= 1; + if self.plugin_event_frames { + self.plugin_events.frame_handlers += 1; + } + } + 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. @@ -402,6 +457,11 @@ impl Session { } self.depth = depth; 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)) + && subs.iter().any(|plugin| p.is_for(&recipient(plugin)) && !self.plugin_event_status(plugin).0) + }) } /// The JSON event `p` as plug-in `plugin` is given it: the selected object ids of a @@ -471,8 +531,8 @@ impl Session { /// 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 after each top-level command and when a document is added - /// outside one. Nothing is kept when no plug-in reacted to events at the last check, nor for a + /// 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. pub(crate) fn plugin_events_see_new_documents(&mut self) { if self.plugin_events.seen_by.is_empty() { @@ -500,7 +560,15 @@ impl Session { /// before the next delivery. pub(crate) fn plugins_changed_for_events(&mut self) { if !self.plugin_events.dispatching { - self.check_plugin_events(); + self.check_plugin_events(false); + } + } + + /// 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 { + self.check_plugin_events(true); } } @@ -523,6 +591,40 @@ impl Session { 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, + } + 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(&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>> = + (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] diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 464c980811..7812055955 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -420,10 +420,7 @@ impl Session { { self.begin_named_undo_group(label); } - if self.depth == 0 { - // Inside a command, this happens once the command has finished. - self.plugin_events_see_new_documents(); - } + self.plugin_events_see_new_documents(); i } diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index d5d62e607c..653ff993fd 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -662,6 +662,9 @@ impl Session { if let Some(before) = before { self.reveal_since(&before); } + if r.is_ok() { + self.plugin_events_interaction_ended(); + } r } @@ -794,6 +797,7 @@ impl Session { if !used_defaults_only { self.inherit_new_art(); } + self.plugin_events_interaction_ended(); Ok(()) } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 6ea516023b..cee09379c9 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -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 } @@ -255,9 +258,6 @@ impl Session { // A failed or panicked command's documents are put back: type is drawn in their // composite fonts again, not in those the command set. cmd::compositefonts::sync(self); - // Plug-ins still hear of what finished before the failure, such as a save in a batch - // whose later step failed. - self.plugin_events_after_command(); } let r = r?; if self.depth == 0 { @@ -301,7 +301,6 @@ impl Session { self.journal_in_undo_groups(doc, &grouped, journal); self.trim_histories(); self.after_command(Some(id)); - self.plugin_events_after_command(); } else if matches!(id, "edit.undo" | "edit.redo") { // A step of `command.batch`: the tool hears of it as it does of the command alone. self.notify_text_tool(id); diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 1437e9c56c..17a88c7c65 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -1223,11 +1223,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. diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs index 66b8804a58..0ab0becd00 100644 --- a/crates/engine/src/tests/plugin_events.rs +++ b/crates/engine/src/tests/plugin_events.rs @@ -46,6 +46,222 @@ fn types(events: &[Value]) -> Vec<&str> { events.iter().map(|e| e["type"].as_str().unwrap()).collect() } +#[test] +fn a_headless_gesture_delivers_events_when_its_actions_finish() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let id = "test.events.headless_gesture"; + for real_time in [true, false] { + let mut s = session(); + s.prefs.real_time_drawing = real_time; + install(&mut s, id, r#"["selection.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("rectangle", view).unwrap(); + for (kind, x, y) in [(PointerKind::Down, 50.0, 50.0), (PointerKind::Drag, 100.0, 100.0)] { + s.pointer(&PointerEvent::new(kind, x, y), view).unwrap(); + } + assert!(given(&mut s, id).is_empty(), "the drag is still open"); + s.pointer(&PointerEvent::new(PointerKind::Up, 100.0, 100.0), view).unwrap(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["selection.changed"]); + assert_eq!(got[0]["ids"], json!(s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect::>())); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "the event is delivered once"); + run(&mut s, "plugin.remove", json!({"id": id})); + } +} + +#[test] +fn a_set_aside_drag_holds_events_and_their_baseline() { + use vectorcraft_plugins::events::Event; + let id = "test.events.held_drag"; + let mut s = session(); + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + install(&mut s, id, r#"["selection.changed","document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + let doc = s.doc().unwrap().uid; + s.note_plugin_event(Event::DocumentSaved, doc); + s.begin_interaction("Move").unwrap(); + s.active_mut().unwrap().interaction.as_mut().unwrap().tool = true; + s.outside_interaction("select.set", &json!({"ids": [r.0]}), |s| { + assert!(s.holds_interaction()); + assert!(s.docs.iter().all(|d| d.interaction.is_none())); + s.active_mut().unwrap().selection.objects = vec![r]; + s.deliver_plugin_events(); + assert!(given(s, id).is_empty(), "the drag is set aside"); + Ok(Value::Null) + }) + .unwrap(); + s.cancel_interaction().unwrap(); + s.deliver_plugin_events(); + assert_eq!(types(&given(&mut s, id)), ["document.saved"], "the temporary selection did not advance the baseline"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +#[test] +fn batch_steps_compare_new_documents_with_their_initial_state() { + let id = "test.events.batch_new"; + let mut s = session(); + install(&mut s, id, r#"["selection.changed","document.opened","layer.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + let data = run(&mut s, "document.serialize", json!({}))["dataBase64"].clone(); + for first in [ + json!({"command": "file.new", "params": {}}), + json!({"command": "document.open", "params": {"name": "batch.vectorcraft", "dataBase64": data}}), + ] { + let opened = first["command"] == "document.open"; + run( + &mut s, + "command.batch", + json!({"commands": [first, {"command": "layer.new", "params": {"name": "Notes"}}, + {"command": "shape.rectangle", "params": {"x": 10, "y": 10, "width": 10, "height": 10}}]}), + ); + let got = given(&mut s, id); + let expected = + if opened { vec!["document.opened", "selection.changed", "layer.changed"] } else { vec!["selection.changed", "layer.changed"] }; + assert_eq!(types(&got), expected); + assert!(got.iter().all(|e| e["document"] == s.doc().unwrap().uid)); + assert!(got.last().unwrap()["reasons"].as_array().unwrap().contains(&json!("added"))); + } + run(&mut s, "plugin.remove", json!({"id": id})); +} + +#[test] +fn background_installs_record_the_baseline_before_the_next_edit() { + let id = "test.events.background_baseline"; + let folder = crate::tests_links::Folder::new("event-background-baseline"); + let mut writer = session(); + writer.attach_plugin_store(folder.0.clone()); + install(&mut writer, id, r#"["selection.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + assert!(vectorcraft_plugins::registry::remove(id)); + let mut s = session(); + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + s.plugin_event_frames = true; + s.load_plugins_in_background(true); + s.attach_plugin_store(folder.0.clone()); + s.finish_plugin_loads(); + assert!(vectorcraft_plugins::registry::get(id).is_some()); + assert!(given(&mut s, id).is_empty(), "changes before loading are not replayed"); + run(&mut s, "select.set", json!({"ids": [r.0]})); + s.deliver_plugin_events(); + assert_eq!(types(&given(&mut s, id)), ["selection.changed"]); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +#[test] +fn background_installs_during_a_drag_record_the_settled_baseline() { + let id = "test.events.background_drag_baseline"; + let folder = crate::tests_links::Folder::new("event-background-drag-baseline"); + let mut writer = session(); + writer.attach_plugin_store(folder.0.clone()); + install(&mut writer, id, r#"["selection.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + assert!(vectorcraft_plugins::registry::remove(id)); + for commit in [false, true] { + for tool_actions in [false, true] { + for edit_before_delivery in [true, false] { + let mut s = session(); + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + s.plugin_event_frames = true; + s.begin_interaction("Select").unwrap(); + s.preview("select.set", &json!({"ids": [r.0]})).unwrap(); + s.load_plugins_in_background(true); + s.attach_plugin_store(folder.0.clone()); + s.finish_plugin_loads(); + assert!(vectorcraft_plugins::registry::get(id).is_some()); + assert!(!s.deliver_plugin_events(), "the preview holds delivery"); + assert!(given(&mut s, id).is_empty()); + s.in_tool_actions = tool_actions; + if commit { + s.commit_interaction().unwrap(); + } else { + s.cancel_interaction().unwrap(); + } + s.in_tool_actions = false; + if !edit_before_delivery { + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "neither the preview nor its rollback is replayed"); + } + let ids = if commit { vec![] } else { vec![r.0] }; + run(&mut s, "select.set", json!({"ids": ids})); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["selection.changed"], "commit={commit}, tool_actions={tool_actions}"); + assert_eq!(got[0]["ids"], json!(ids)); + assert!(vectorcraft_plugins::registry::remove(id)); + } + } + } +} + +#[test] +fn silent_handlers_report_when_another_frame_is_needed() { + use vectorcraft_plugins::events::Event; + let id = "test.events.silent_pending"; + let mut s = session(); + install(&mut s, id, r#"["document.saved"]"#, &[], "", "(i32.const 0)", &[]); + s.plugin_event_frames = true; + let doc = s.doc().unwrap().uid; + for _ in 0..=crate::plugin_events::MAX_FRAME_HANDLERS { + s.note_plugin_event(Event::DocumentSaved, doc); + } + s.begin_plugin_event_frame(); + assert!(s.deliver_plugin_events(), "silent handlers still need another frame"); + assert!(s.take_plugin_event_notices().is_empty()); + s.begin_plugin_event_frame(); + assert!(!s.deliver_plugin_events(), "the next frame drains the remaining handler"); + assert!(s.take_plugin_event_notices().is_empty()); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +#[test] +fn deliveries_in_one_frame_share_the_handler_budget() { + use vectorcraft_plugins::events::Event; + let id = "test.events.shared_frame_budget"; + let mut s = session(); + install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + let doc = s.doc().unwrap().uid; + for _ in 0..(crate::plugin_events::MAX_FRAME_HANDLERS * 2) { + s.note_plugin_event(Event::DocumentSaved, doc); + } + s.begin_plugin_event_frame(); + assert!(s.deliver_plugin_events()); + assert_eq!(given(&mut s, id).len(), crate::plugin_events::MAX_FRAME_HANDLERS); + assert!(s.deliver_plugin_events(), "the UI pass still has queued handlers"); + assert!(given(&mut s, id).is_empty(), "background delivery already used this frame's budget"); + s.begin_plugin_event_frame(); + assert!(!s.deliver_plugin_events()); + assert_eq!(given(&mut s, id).len(), crate::plugin_events::MAX_FRAME_HANDLERS); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +#[test] +fn frame_delivery_bounds_handlers_and_resumes_remaining_recipients() { + use vectorcraft_plugins::events::Event; + let mut s = session(); + s.plugin_event_frames = true; + let ids: Vec = (0..=crate::plugin_events::MAX_FRAME_HANDLERS).map(|i| format!("test.events.frame_budget_{i}")).collect(); + for id in &ids { + install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + } + let doc = s.doc().unwrap().uid; + s.note_plugin_event(Event::DocumentSaved, doc); + s.note_plugin_event(Event::DocumentSaved, doc); + let mut delivered = Vec::new(); + for _ in 0..(ids.len() * 2) { + s.begin_plugin_event_frame(); + s.deliver_plugin_events(); + let notices: Vec<_> = s.take_plugin_event_notices().into_iter().filter(|n| ids.contains(&n.plugin)).collect(); + assert!(notices.len() <= crate::plugin_events::MAX_FRAME_HANDLERS); + delivered.extend(notices.into_iter().map(|n| n.plugin)); + } + assert_eq!(delivered.len(), ids.len() * 2); + for id in &ids { + assert_eq!(delivered.iter().filter(|got| *got == id).count(), 2, "{id}"); + run(&mut s, "plugin.remove", json!({"id": id})); + } +} + /// A selection change, a new layer, a save and an open each reach the plug-in that names them once, /// after the change, with the document they happened in; a plug-in that names only `document.saved` /// is given only the save. diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index c5d2905963..65673881e5 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1819,6 +1819,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) -> Result> { // The tool acts on its own interaction, which a command from outside it may have set aside. if !acts.is_empty() { @@ -1847,6 +1848,7 @@ impl Session { self.back_to_painter = outer_painter; if !outer && self.depth == 0 { self.trim_histories(); + self.plugin_events_after_command(); } r } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index d88121d42d..0f313192dd 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -361,10 +361,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); @@ -372,22 +373,22 @@ impl VectorcraftApp { trace_runs::poll(self); placing::poll(self); retype_runs::poll(self); - let _ = self.deliver_plugin_events(); + self.deliver_plugin_events() } /// 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. → Whether - /// the status bar shows one. + /// 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 { - self.session.deliver_plugin_events(); + 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 false }; + let Some(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)); true @@ -480,6 +481,9 @@ 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.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. @@ -531,14 +535,13 @@ impl VectorcraftApp { 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); - if script_was_running && !self.session.script_running() { - // The work that waited for the script, and the plug-in events its changes give, are - // taken in the frame it ended in: no repaint is asked for once it has ended. - self.poll_finished_work(); + // 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); diff --git a/docs/mcp.md b/docs/mcp.md index 1c39001b62..487a70a68f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -15204,8 +15204,12 @@ switches documents or undoes is never called; `plugin.install` refuses a manifes `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; -its handler only reads, and `plugin.info` gives `eventsOff` and `lastEventError` (see `docs/plugins.md`). A live-effect plug-in is an effect with +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`). A live-effect plug-in is an effect with id `plugin.`: `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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 50b9678301..df93e7c2c3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2838,7 +2838,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 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. +- **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. - **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 ` 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.