//! Events plug-ins react to ([`vectorcraft_plugins::events`]): the session notices a changed //! selection, current layer or set of layers by comparing each open document with how it was at the //! last check, and hears of each successful open and save ([`Session::note_plugin_event`]). It then //! calls the `vc_event` handler of each installed plug-in whose manifest names the event, after the //! change has finished and outside any undo step. //! //! - A check runs after each top-level command, or when a frontend that sets //! [`Session::plugin_event_frames`] delivers ([`Session::deliver_plugin_events`]), by the frame. //! Changes between two checks are one event: a burst of selection changes is one //! `selection.changed` with the final selection. No check or delivery runs while an interaction //! is open (a drag being previewed); waiting events wait for it to end. A document opened or //! created since the last check is compared with how it was when it was added //! ([`Session::plugin_events_see_new_documents`]). //! A check after commit or cancel records the settled state for plug-ins installed during the interaction. //! - At most [`MAX_PENDING`] events wait; past that the oldest is dropped. An event raised while a //! handler runs waits for the next delivery: handlers never run inside one another. //! A frontend frame runs at most [`MAX_FRAME_HANDLERS`] handlers across all its deliveries, //! after [`Session::begin_plugin_event_frame`] resets the budget. Runnable recipients still //! waiting request another frame through the delivery's return value. //! - A handler only reads. The host applies nothing it returns, and it may call only the commands //! in [`super::cmd::plugin_call::EVENT_READS`]; any other call is refused with an error that names //! the event, and what a call changes is put back ([`super::cmd::plugin_call::event_call`]). //! - A handler that fails is reported once a streak; after //! [`vectorcraft_plugins::events::MAX_EVENT_FAILURES`] failures in a row the plug-in's events stop //! until the session ends, or until a module is installed under its id again. //! - When no installed plug-in reacts to events, a check returns before comparing anything. use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; use std::hash::Hash; use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::{Document, NodeId, NodeKind, Selection}; use vectorcraft_plugins::events::{Event, MAX_EVENT_FAILURES, MAX_EVENT_IDS}; use vectorcraft_plugins::permissions::Permission; use vectorcraft_plugins::{LogLevel, Plugin, registry}; use crate::Session; /// Most events that wait for delivery. pub const MAX_PENDING: usize = 32; /// Most events kept after the queue dropped them for room, until the next delivery, for a /// rollback to put back. const MAX_EVICTED: usize = 1024; /// Most handlers called across all deliveries in one frontend frame. pub const MAX_FRAME_HANDLERS: usize = 4; /// Most notices kept for the frontend to show; older ones are dropped. pub const MAX_NOTICES: usize = 64; /// The reasons a `layer.changed` event gives, in the order it lists them. pub const LAYER_REASONS: [&str; 5] = ["current", "added", "deleted", "reordered", "options"]; /// A document as the last check saw it. struct Seen { uid: u64, doc: Arc, selection: Selection, layer: Option, } /// A plug-in an event is for: its id, the hash of its module and its installation /// ([`Plugin::serial`]), so a module removed and installed again is another recipient. type Recipient = (String, String, u64); #[cfg(test)] std::thread_local! { pub(crate) static RECIPIENT_IDENTITIES: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// The recipient `p` is. fn recipient(p: &Plugin) -> Recipient { #[cfg(test)] RECIPIENT_IDENTITIES.with(|count| count.set(count.get() + 1)); (p.id().to_string(), p.hash().to_string(), p.serial()) } /// An event waiting for delivery: what changed, in which document, and the plug-ins it is for /// (those installed when it happened), each with the reasons of a `layer.changed` it was given. #[derive(Clone, Debug, PartialEq)] struct Pending { event: Event, document: u64, to: Vec<(Recipient, Vec<&'static str>)>, /// When it was queued ([`PluginEvents::queued`] then). seq: u64, /// The [`Pending::seq`] of the event that pushed this one out of the waiting queue, and whether /// that event was a `document.opened`. pushed_out_by: Option<(u64, bool)>, /// Queued by a command of the running script, whose run has not ended yet /// ([`Session::plugin_events_script_ended`]). by_script: bool, } impl Pending { /// Whether this event is for `r`. #[cfg(test)] fn is_for(&self, r: &Recipient) -> bool { self.to.iter().any(|(x, _)| x == r) } /// The reasons of a `layer.changed` that `r` is given. #[cfg(test)] fn reasons_for(&self, r: &Recipient) -> &[&'static str] { self.to.iter().find(|(x, _)| x == r).map_or(&[], |(_, reasons)| reasons.as_slice()) } } /// One plug-in's failed handlers in a row, for the installation `serial` of the module with `hash`. #[derive(Clone, Debug, Default)] struct Failures { hash: String, serial: u64, count: u32, disabled: bool, last_error: Option, } /// A line a handler wrote with `vc_log`, or a handler's failure, for the frontend to show. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Notice { /// The plug-in's id and name. pub plugin: String, pub name: String, /// The event its handler was given. pub event: &'static str, pub level: LogLevel, /// The text, in English for a failure. pub text: String, /// For a failure, what failed, for the frontend to word in the interface language; `None` for /// a line the handler wrote. pub failure: Option, } /// A failure a [`Notice`] reports. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Failure { /// A handler failed with `error`, the first time in a row. Handler { error: String }, /// The plug-in's events stopped after `count` failed handlers in a row. EventsOff { count: u32 }, } impl Failure { /// The English message with `{event}`, `{error}` and `{n}` placeholders, `one` or `other` by /// the count. pub const HANDLER: &'static str = "its {event} handler failed: {error}"; pub const EVENTS_OFF_ONE: &'static str = "its events are off until it is installed again or VectorCraft starts again, after {n} failed handler in a row"; pub const EVENTS_OFF_OTHER: &'static str = "its events are off until it is installed again or VectorCraft starts again, after {n} failed handlers in a row"; } /// The session's plug-in event state. #[derive(Default)] pub struct PluginEvents { seen: Vec, /// The plug-ins that reacted to events when `seen` was taken. seen_by: Vec, pending: VecDeque, /// 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, /// The [`Pending::seq`] of each `document.opened` the running script's commands queued. script_opens: HashSet, /// How many events have been queued as their own entry. queued: u64, dispatching: bool, frame_handlers: usize, interaction_ended: bool, failures: BTreeMap, notices: VecDeque, /// The installed plug-ins that react to events, as of a registry revision. subscribers: Option<(u64, Vec>)>, #[cfg(test)] pub(crate) test_subscribers: Option>>, } impl PluginEvents { /// The installed plug-ins that react to events (none in Safe Mode). fn subscribers(&mut self) -> Vec> { #[cfg(test)] if let Some(subs) = &self.test_subscribers { return subs.clone(); } if vectorcraft_plugins::safe_mode::active() { return Vec::new(); } let revision = registry::revision(); if let Some((at, subs)) = &self.subscribers && *at == revision { return subs.clone(); } let subs: Vec> = registry::list().into_iter().filter(|p| !p.manifest().events.is_empty()).collect(); self.subscribers = Some((revision, subs.clone())); subs } /// Queues `event` for document `uid`, for the plug-ins `to`, with the reasons of a /// `layer.changed`. A `selection.changed` or `layer.changed` already waiting for that document /// takes it in: each plug-in in `to` is added, or adds the new reasons to the ones it was given, /// so a plug-in is given only the reasons of the changes it was given. Past [`MAX_PENDING`] the /// oldest event is dropped. fn queue(&mut self, event: Event, uid: u64, reasons: Vec<&'static str>, to: Vec) { if matches!(event, Event::SelectionChanged | Event::LayerChanged) && let Some(p) = self.pending.iter_mut().find(|p| p.event == event && p.document == uid) { for r in to { let i = match p.to.iter().position(|(x, _)| *x == r) { Some(i) => i, None => { p.to.push((r, Vec::new())); p.to.len() - 1 } }; let given = &mut p.to[i].1; for reason in &reasons { if !given.contains(reason) { given.push(*reason); } } given.sort_by_key(|r| LAYER_REASONS.iter().position(|x| x == r)); } return; } if self.pending.len() >= MAX_PENDING && let Some(mut dropped) = self.pending.pop_front() { dropped.pushed_out_by = Some((self.queued, event == Event::DocumentOpened)); 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, pushed_out_by: None, by_script: false }); self.queued += 1; self.prune_script_opens(); } /// Drops the `document.opened` events, waiting or pushed out, whose [`Pending::seq`] `undone` /// picks. The events those opens pushed out of the waiting queue return in their original /// order, ahead of the events still waiting, while there is room. fn drop_opens(&mut self, undone: impl Fn(u64) -> bool) { let dropped = |p: &Pending| p.event == Event::DocumentOpened && undone(p.seq); self.pending.retain(|p| !dropped(p)); self.evicted.retain(|p| !dropped(p)); let first = self.evicted.iter().filter(|p| p.pushed_out_by.is_some_and(|(seq, open)| open && undone(seq))).map(|p| p.seq).min(); while self.pending.len() < MAX_PENDING && let Some(at) = self.evicted.iter().rposition(|p| first.is_some_and(|seq| p.seq >= seq)) && let Some(mut p) = self.evicted.remove(at) { p.pushed_out_by = None; self.pending.push_front(p); } self.prune_script_opens(); } /// Forgets the running script's opens that no waiting or pushed-out event refers to. fn prune_script_opens(&mut self) { if self.script_opens.is_empty() { return; } let referenced: HashSet = self.pending.iter().chain(self.evicted.iter()).flat_map(|p| std::iter::once(p.seq).chain(p.pushed_out_by.map(|(seq, _)| seq))).collect(); self.script_opens.retain(|seq| referenced.contains(seq)); } fn notice(&mut self, n: Notice) { if self.notices.len() >= MAX_NOTICES { self.notices.pop_front(); } self.notices.push_back(n); } /// The failures of plug-in `p`, started again when a module was installed under its id since /// they were recorded, the same module again included. fn failures_of(&mut self, p: &Plugin) -> &mut Failures { let f = self.failures.entry(p.id().to_string()).or_default(); if !f.is_of(p) { *f = Failures { hash: p.hash().to_string(), serial: p.serial(), ..Failures::default() }; } f } } impl Failures { /// Whether these are the failures of `p` as it is installed now. fn is_of(&self, p: &Plugin) -> bool { self.hash == p.hash() && self.serial == p.serial() } } /// A layer or sublayer: its id, its parent (`None` at the top), the layer itself without its /// contents (for comparing its options) and the ids of the rows directly in it, in order. type LayerRow = (Id, Option, vectorcraft_doc::Node, Vec); /// Each layer and sublayer of `doc`, in order. fn layer_rows(doc: &Document) -> Vec { let mut out = Vec::new(); let mut stack: Vec<(&Arc, Option)> = doc.layers.iter().rev().map(|l| (l, None)).collect(); while let Some((n, parent)) = stack.pop() { let NodeKind::Layer { children, .. } = &n.kind else { continue }; stack.extend(children.iter().rev().filter(|c| c.is_layer()).map(|c| (c, Some(n.id)))); let rows = children.iter().map(|c| c.id).collect(); let mut bare = (**n).clone(); if let Some(c) = bare.children_mut() { c.clear(); } out.push((n.id, parent, bare, rows)); } out } /// Whether a layer's place among the rows beside it differs between `old` (of `before`) and `new` /// (of `after`), counting only the rows on both sides, so an object added or deleted next to a /// sublayer is not a move. fn layers_moved_among_rows(before: &Document, old: &[LayerRow], after: &Document, new: &[LayerRow]) -> bool { use std::collections::{HashMap, HashSet}; let layers: HashSet = old.iter().map(|r| r.0).collect(); let lists = |doc: &Document, rows: &[LayerRow]| { let mut m: HashMap, Vec> = rows.iter().map(|r| (Some(r.0), r.3.clone())).collect(); m.insert(None, doc.layers.iter().map(|l| l.id).collect()); m }; let (a, b) = (lists(before, old), lists(after, new)); a.iter().any(|(parent, xs)| { let Some(ys) = b.get(parent) else { return false }; let (in_x, in_y): (HashSet, HashSet) = (xs.iter().copied().collect(), ys.iter().copied().collect()); let places = |list: &[NodeId], other: &HashSet| { list.iter().filter(|id| other.contains(id)).enumerate().filter(|(_, id)| layers.contains(id)).map(|(i, id)| (i, *id)).collect::>() }; places(xs, &in_y) != places(ys, &in_x) }) } /// Why the layers of `after` (with current layer `layer_after`) differ from those of `before` /// (with `layer_before`), in [`LAYER_REASONS`] order; empty when they don't. fn layer_reasons(before: &Arc, layer_before: Option, after: &Arc, layer_after: Option) -> Vec<&'static str> { let mut reasons = Vec::new(); if layer_before != layer_after { reasons.push("current"); } if Arc::ptr_eq(before, after) { return reasons; } let (old, new) = (layer_rows(before), layer_rows(after)); reasons.extend(layer_row_reasons(&old, &new, || layers_moved_among_rows(before, &old, after, &new))); reasons } /// Compares layer membership, order and options by id. fn layer_row_reasons(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(|r| !new_by_id.contains_key(&r.0)) { reasons.push("deleted"); } 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_by_id.get(&r.0).is_some_and(|o| o.2 != r.2)) { reasons.push("options"); } reasons } impl Session { /// Hears that `event` (`document.opened` or `document.saved`) happened to document `uid`, which /// the next delivery hands the plug-ins that react to it. Nothing is kept when none does. pub(crate) fn note_plugin_event(&mut self, event: Event, uid: u64) { let to: Vec = self.plugin_events.subscribers().iter().filter(|p| p.manifest().reacts_to(event)).map(|p| recipient(p)).collect(); if to.is_empty() { return; } self.plugin_events.queue(event, uid, Vec::new(), to); // An open or a save is queued as its own entry, the newest. if self.script_in_run && let Some(p) = self.plugin_events.pending.back_mut() { p.by_script = true; if event == Event::DocumentOpened { self.plugin_events.script_opens.insert(p.seq); } } } /// 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. Events those opens pushed out of the waiting queue come back, as after /// [`Session::forget_plugin_opens_since`]. 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; let opens = std::mem::take(&mut events.script_opens); if !kept { events.drop_opens(|seq| opens.contains(&seq)); } for p in events.pending.iter_mut().chain(events.evicted.iter_mut()) { p.by_script = false; } } /// A mark for [`Session::forget_plugin_opens_since`]: the events queued so far. pub(crate) fn plugin_events_mark(&self) -> u64 { self.plugin_events.queued } /// Drops the waiting `document.opened` events queued since `mark`, for opens that a rollback /// undid (a failed `command.batch`, or a failed command of a script or a plug-in call). The /// saves stay, since the files they wrote stay written ([`PluginEvents::drop_opens`]). pub(crate) fn forget_plugin_opens_since(&mut self, mark: u64) { self.plugin_events.drop_opens(|seq| seq >= mark); } /// Compares each open document with how the last check saw it and queues the events its changes /// give the installed plug-ins: `selection.changed` and `layer.changed`. A document neither the /// last check nor [`Session::plugin_events_see_new_documents`] saw gives none, and a plug-in /// installed since the last check is given none: the /// change may have come before it. A waiting event is no longer for a plug-in that is not /// installed now, so a module removed and installed again is not given it. Nothing is compared /// while an interaction is open, nor when no plug-in reacts to events. fn check_plugin_events(&mut self, interaction_ended: bool) { if self.script_in_run { return; } let subs = self.plugin_events.subscribers(); if subs.is_empty() { self.plugin_events.seen.clear(); self.plugin_events.seen_by.clear(); self.plugin_events.pending.clear(); self.plugin_events.evicted.clear(); return; } let installed: Vec = subs.iter().map(|p| recipient(p)).collect(); self.plugin_events.pending.retain_mut(|p| { p.to.retain(|(r, _)| installed.contains(r)); !p.to.is_empty() }); if self.holds_interaction() || (self.in_tool_actions && !interaction_ended) || self.docs.iter().any(|d| d.interaction.is_some()) { return; } let mut events = std::mem::take(&mut self.plugin_events); let before = std::mem::take(&mut events.seen); let before_by = std::mem::take(&mut events.seen_by); let to = |e: Event| -> Vec { subs.iter().filter(|p| p.manifest().reacts_to(e)).map(|p| recipient(p)).filter(|r| before_by.contains(r)).collect() }; let (selection, layers) = (to(Event::SelectionChanged), to(Event::LayerChanged)); let mut seen = Vec::with_capacity(self.docs.len()); for st in &self.docs { if let Some(old) = before.iter().find(|s| s.uid == st.uid) { if !selection.is_empty() && old.selection != st.selection { events.queue(Event::SelectionChanged, st.uid, Vec::new(), selection.clone()); } if !layers.is_empty() { let reasons = layer_reasons(&old.doc, old.layer, &st.doc, st.active_layer); if !reasons.is_empty() { events.queue(Event::LayerChanged, st.uid, reasons, layers.clone()); } } } seen.push(Seen { uid: st.uid, doc: st.doc.clone(), selection: st.selection.clone(), layer: st.active_layer }); } events.seen = seen; events.seen_by = subs.iter().map(|p| recipient(p)).collect(); events.pending.retain(|p| p.event.outlives_document() || self.docs.iter().any(|d| d.uid == p.document)); self.plugin_events = events; } /// Resets the handler budget for a frontend frame. Call once before the frame's deliveries, /// including background work and all UI passes, when [`Session::plugin_event_frames`] is on. pub fn begin_plugin_event_frame(&mut self) { self.plugin_events.frame_handlers = 0; } /// Checks the open documents for changes ([`Session::check_plugin_events`]) and calls the /// handlers of the events waiting, oldest first, one handler at a time. While a handler runs, /// this returns at once: what the handler's calls change waits for the next delivery. While an /// interaction is open, the events wait for the first delivery after it ends. /// A set-aside interaction also holds events. A frontend frame calls at most /// [`MAX_FRAME_HANDLERS`] handlers across all deliveries since [`Session::begin_plugin_event_frame`] /// and keeps the remaining recipients for later frames. Returns whether runnable handlers /// remain queued, so the frontend can request another frame even when no handler wrote a notice. pub fn deliver_plugin_events(&mut self) -> bool { if self.plugin_events.dispatching { return false; } self.check_plugin_events(false); if self.plugin_events.pending.is_empty() || self.holds_interaction() || self.in_tool_actions || self.docs.iter().any(|d| d.interaction.is_some()) { return false; } let subs: HashMap> = self.plugin_events.subscribers().into_iter().map(|p| (recipient(&p), p)).collect(); self.plugin_events.dispatching = true; // Events pushed out by the opens of a running script stay until its run ends, which puts // them back if the run fails. let events = &mut self.plugin_events; let opens = &events.script_opens; let restorable = |p: &Pending| p.pushed_out_by.is_some_and(|(seq, open)| open && opens.contains(&seq)); let first = events.evicted.iter().filter(|p| restorable(p)).map(|p| p.seq).min(); events.evicted.retain(|p| { restorable(p) || (first.is_some_and(|seq| p.seq >= seq) && (!p.by_script || p.event != Event::DocumentOpened || p.to.iter().any(|(r, _)| subs.contains_key(r)))) }); let frontend_barrier = events.evicted.iter().filter(|p| !p.by_script).map(|p| p.seq).min(); events.prune_script_opens(); // A handler's calls are checked as calls from outside, also when the command that ended // played saved steps ([`Session::replay`] puts its flag back only after this delivery). let replaying = self.set_replaying(false); // The commands a handler calls run nested, never journaled; a panic in one leaves the depth // as it was found. let depth = self.depth; self.depth += 1; // An open or a save a running script queued waits for the end of the run // ([`Session::plugin_events_script_ended`]), also when a frontend delivers between its // slices: a run that fails discards the documents it opened. let mut held = VecDeque::new(); let mut budget = if self.plugin_event_frames { MAX_FRAME_HANDLERS.saturating_sub(self.plugin_events.frame_handlers) } else { usize::MAX }; let waiting = self.plugin_events.pending.len(); for _ in 0..waiting { let Some(mut p) = self.plugin_events.pending.pop_front() else { break }; if p.by_script { held.push_back(p); continue; } if !p.event.outlives_document() && !self.docs.iter().any(|d| d.uid == p.document) { continue; } p.to.retain(|(r, _)| subs.get(r).is_some_and(|plugin| plugin.manifest().reacts_to(p.event))); if !p.to.is_empty() && frontend_barrier.is_some_and(|seq| p.seq > seq) { held.push_back(p); continue; } let mut served = 0; for (i, (r, reasons)) in p.to.iter().enumerate() { let Some(plugin) = subs.get(r).filter(|s| s.manifest().reacts_to(p.event)) else { served = i + 1; continue; }; if self.plugin_events.failures_of(plugin).disabled { served = i + 1; continue; } if budget == 0 { break; } self.run_handler(plugin, &p, reasons); served = i + 1; budget -= 1; if self.plugin_event_frames { self.plugin_events.frame_handlers += 1; } } p.to.drain(..served); if !p.to.is_empty() { held.push_back(p); } if budget == 0 { break; } } // The held events are older than any a handler's calls queued meanwhile. while let Some(p) = held.pop_back() { self.plugin_events.pending.push_front(p); } self.depth = depth; self.set_replaying(replaying); self.plugin_events.dispatching = false; self.plugin_events.prune_script_opens(); self.plugin_events.pending.iter().any(|p| { !p.by_script && frontend_barrier.is_none_or(|seq| p.seq < seq) && (p.event.outlives_document() || self.docs.iter().any(|d| d.uid == p.document)) && p.to.iter().any(|(r, _)| subs.get(r).is_some_and(|plugin| !self.plugin_event_status(plugin).0)) }) } /// The JSON event `p` as plug-in `plugin` is given it: the selected object ids of a /// `selection.changed` only with `doc.read`, and `reasons`, the reasons of a `layer.changed` /// it was given. fn event_json(&self, plugin: &Plugin, p: &Pending, reasons: &[&'static str]) -> Value { let mut v = json!({ "type": p.event.name(), "document": p.document }); let Some(st) = self.docs.iter().find(|d| d.uid == p.document) else { return v }; match p.event { Event::SelectionChanged => { let objects = &st.selection.objects; v["count"] = json!(objects.len()); v["truncated"] = json!(false); v["ids"] = Value::Null; if plugin.manifest().permissions().contains(&Permission::DocRead) { v["ids"] = json!(objects.iter().take(MAX_EVENT_IDS).map(|i| i.0).collect::>()); v["truncated"] = json!(objects.len() > MAX_EVENT_IDS); } } Event::LayerChanged => { v["layer"] = json!(st.active_layer.map(|l| l.0)); v["reasons"] = json!(reasons); } Event::DocumentOpened | Event::DocumentSaved => {} } v } /// Calls `plugin`'s handler with event `p`, given `reasons`, and records what it wrote and /// whether it failed. fn run_handler(&mut self, plugin: &Arc, p: &Pending, reasons: &[&'static str]) { let event = p.event.name(); let text = serde_json::to_vec(&self.event_json(plugin, p, reasons)).unwrap_or_default(); let m = plugin.manifest(); let may = m.permissions(); let (r, report) = if may.contains(&Permission::Commands) && !m.command_allowlist.is_empty() { let calls = crate::cmd::plugin_call::Calls::of(self, may.contains(&Permission::DocRead), false); let mut bridge = |id: &str, args: &Value| crate::cmd::plugin_call::event_call(self, &calls, event, id, args); plugin.run_event(&text, Some(&mut bridge)) } else { plugin.run_event(&text, None) }; let (id, name) = (plugin.id().to_string(), m.name.clone()); for line in report.lines { self.plugin_events.notice(Notice { plugin: id.clone(), name: name.clone(), event, level: line.level, text: line.text, failure: None }); } let failures = self.plugin_events.failures_of(plugin); let e = match r { Ok(()) => { failures.count = 0; return; } Err(e) => e.to_string(), }; failures.count += 1; failures.last_error = Some(e.clone()); let (count, first) = (failures.count, failures.count == 1); log::warn!("plug-in {id}: its {event} handler failed: {e}"); if first { let text = Failure::HANDLER.replace("{event}", event).replace("{error}", &e); let failure = Some(Failure::Handler { error: e }); self.plugin_events.notice(Notice { plugin: id.clone(), name: name.clone(), event, level: LogLevel::Error, text, failure }); } if count >= MAX_EVENT_FAILURES { self.plugin_events.failures_of(plugin).disabled = true; let text = if count == 1 { Failure::EVENTS_OFF_ONE } else { Failure::EVENTS_OFF_OTHER }.replace("{n}", &count.to_string()); let failure = Some(Failure::EventsOff { count }); self.plugin_events.notice(Notice { plugin: id, name, event, level: LogLevel::Error, text, failure }); } } /// Takes each open document the last check didn't see, one opened or created since, as it is /// now, so the next check compares it with this state: a change made to it before the next /// delivery gives its event. Called when a document is added and after each top-level command. /// When no check has seen a plug-in that reacts to events, the first check runs now for the /// plug-ins installed. Nothing is kept when none is installed, nor for a document in an /// interaction. pub(crate) fn plugin_events_see_new_documents(&mut self) { if self.plugin_events.seen_by.is_empty() { // No check has run since plug-ins that react to events were installed: one now takes // every open document as it is, for the plug-ins installed now. if !self.plugin_events.subscribers().is_empty() { self.check_plugin_events(false); } return; } for st in &self.docs { if st.interaction.is_none() && !self.plugin_events.seen.iter().any(|s| s.uid == st.uid) { self.plugin_events.seen.push(Seen { uid: st.uid, doc: st.doc.clone(), selection: st.selection.clone(), layer: st.active_layer }); } } } /// Delivers the events of a top-level command that just ended, unless the frontend delivers /// them once a frame ([`Session::plugin_event_frames`]) or a script is running. pub(crate) fn plugin_events_after_command(&mut self) { self.plugin_events_see_new_documents(); if std::mem::take(&mut self.plugin_events.interaction_ended) { self.plugin_events_interaction_ended(); } if !self.plugin_event_frames && !self.script_in_run { self.deliver_plugin_events(); } } /// After a plug-in was installed or removed, compares the open documents with the last check /// ([`Session::check_plugin_events`]): what changed before is given only to the plug-ins that /// were installed then, and what changes from now on to every plug-in installed now, also /// before the next delivery. pub(crate) fn plugins_changed_for_events(&mut self) { if !self.plugin_events.dispatching { self.check_plugin_events(false); } } /// Before a batch's steps run: checks the documents when the batch settled an interaction /// (`settled`), or when the installed plug-ins differ from the last check's, so that a plug-in /// installed since then is given the batch's changes. Otherwise the last check stays the /// baseline. pub(crate) fn plugin_events_batch_settled(&mut self, settled: bool) { if self.plugin_events.dispatching || self.batch_stash.is_some() || self.script_in_run { return; } if !settled { let installed: Vec = self.plugin_events.subscribers().iter().map(|p| recipient(p)).collect(); if installed == self.plugin_events.seen_by { // Events for plug-ins removed, or for documents closed, since then still leave the // queue first. let set: HashSet<&Recipient> = installed.iter().collect(); let docs = &self.docs; self.plugin_events.pending.retain_mut(|p| { p.to.retain(|(r, _)| set.contains(r)); !p.to.is_empty() && (p.event.outlives_document() || docs.iter().any(|d| d.uid == p.document)) }); self.plugin_events.seen.retain(|s| docs.iter().any(|d| d.uid == s.uid)); return; } } self.check_plugin_events(true); } /// Records the settled document state after an interaction ends, including subscribers /// installed during its previews. Tool actions may still be finishing; handlers wait for them. pub(crate) fn plugin_events_interaction_ended(&mut self) { if !self.plugin_events.dispatching { if self.depth == 0 { self.check_plugin_events(true); } else { self.plugin_events.interaction_ended = true; } } } /// The handlers' log lines and failures since the last call, oldest first. pub fn take_plugin_event_notices(&mut self) -> Vec { self.plugin_events.notices.drain(..).collect() } /// Whether this session stopped delivering events to plug-in `p` after its handlers failed, and /// the last failure's error. pub fn plugin_event_status(&self, p: &Plugin) -> (bool, Option) { match self.plugin_events.failures.get(p.id()).filter(|f| f.is_of(p)) { Some(f) => (f.disabled, f.last_error.clone()), None => (false, None), } } } #[cfg(test)] mod tests { use super::*; #[test] fn layer_comparison_indexes_ids_instead_of_scanning_each_snapshot() { use std::cell::Cell; use std::hash::Hasher; #[derive(Clone, Copy)] struct Counted<'a> { value: u64, comparisons: &'a Cell, } 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] fn waiting_selection_and_layer_events_of_a_document_merge() { let (a, b): (Recipient, Recipient) = (("a".into(), "1".into(), 1), ("b".into(), "2".into(), 2)); let mut e = PluginEvents::default(); e.queue(Event::SelectionChanged, 1, vec![], vec![a.clone()]); e.queue(Event::LayerChanged, 1, vec!["options"], vec![a.clone()]); e.queue(Event::SelectionChanged, 1, vec![], vec![a.clone()]); e.queue(Event::LayerChanged, 1, vec!["current", "options"], vec![a.clone()]); e.queue(Event::LayerChanged, 1, vec!["deleted", "current"], vec![a.clone(), b.clone()]); e.queue(Event::SelectionChanged, 2, vec![], vec![a.clone()]); e.queue(Event::DocumentSaved, 1, vec![], vec![a.clone()]); e.queue(Event::DocumentSaved, 1, vec![], vec![a.clone()]); let got: Vec<(Event, u64, Vec<&str>)> = e.pending.iter().map(|p| (p.event, p.document, p.reasons_for(&a).to_vec())).collect(); assert_eq!( got, [ (Event::SelectionChanged, 1, vec![]), (Event::LayerChanged, 1, vec!["current", "deleted", "options"]), (Event::SelectionChanged, 2, vec![]), (Event::DocumentSaved, 1, vec![]), (Event::DocumentSaved, 1, vec![]), ] ); assert_eq!(e.pending[1].reasons_for(&b), ["current", "deleted"], "only the change it was given"); assert!(!e.pending[0].is_for(&b)); } /// While a handler runs, a delivery returns at once; the change waits for the next one, which /// hands it over once. #[test] fn an_event_raised_while_a_handler_runs_waits_for_the_next_delivery() { use serde_json::json; use vectorcraft_plugins::wat as tpl; let id = "test.events.nested"; let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); s.allow_plugin_grants_from_requests(); let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].clone(); s.execute("select.none", &json!({})).unwrap(); let manifest = format!(r#"{{"id":"{id}","name":"Test","kind":"filter","api":2,"permissions":["progress","events"],"events":["selection.changed"]}}"#); let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap(); let grant = json!(["progress", "events"]); s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap(); s.plugin_event_frames = true; let given = |s: &mut Session| s.take_plugin_event_notices().into_iter().filter(|n| n.plugin == id).count(); s.plugin_events.dispatching = true; s.execute("select.set", &json!({"ids": [r]})).unwrap(); s.deliver_plugin_events(); assert_eq!(given(&mut s), 0, "not inside the running handler"); s.plugin_events.dispatching = false; s.deliver_plugin_events(); assert_eq!(given(&mut s), 1); s.deliver_plugin_events(); assert_eq!(given(&mut s), 0, "once"); s.execute("plugin.remove", &json!({"id": id})).unwrap(); } #[test] fn at_most_32_events_wait() { let mut e = PluginEvents::default(); for uid in 0..(MAX_PENDING as u64 + 5) { e.queue(Event::DocumentOpened, uid, vec![], vec![]); } assert_eq!(e.pending.len(), MAX_PENDING); assert_eq!(e.pending.front().map(|p| p.document), Some(5), "the oldest are dropped"); } #[test] fn a_rollback_of_opens_brings_back_the_events_they_pushed_out() { let mut s = Session::new(); let r: Recipient = ("a".into(), "h".into(), 1); for uid in 1..=3 { s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![r.clone()]); } let mark = s.plugin_events_mark(); for uid in 0..(2 * MAX_PENDING) as u64 { s.plugin_events.queue(Event::DocumentOpened, 100 + uid, vec![], vec![r.clone()]); } assert!(s.plugin_events.pending.iter().all(|p| p.event == Event::DocumentOpened), "the save was pushed out"); s.plugin_events.queue(Event::DocumentSaved, 999, vec![], vec![r]); s.forget_plugin_opens_since(mark); let left: Vec<_> = s.plugin_events.pending.iter().map(|p| (p.event.name(), p.document)).collect(); assert_eq!( left, [ (Event::DocumentSaved.name(), 1), (Event::DocumentSaved.name(), 2), (Event::DocumentSaved.name(), 3), (Event::DocumentSaved.name(), 999) ] ); } #[test] fn a_failed_script_run_brings_back_the_events_its_opens_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 before = s.plugin_events.pending.clone(); // Enough opens to fill the store of pushed-out events, which then drops opens first. for uid in 0..(MAX_PENDING + MAX_EVICTED + 8) as u64 { queue_script_open(&mut s, 100 + uid, &r); } assert_eq!(s.plugin_events.evicted.len(), MAX_EVICTED); assert_eq!(s.plugin_events.pending.len(), MAX_PENDING); assert!(s.plugin_events.pending.iter().all(|p| p.event == Event::DocumentOpened), "the saves were pushed out"); s.plugin_events_script_ended(false); assert_eq!(s.plugin_events.pending, before); } #[test] fn a_failed_script_keeps_the_newest_saves_when_its_open_displaced_a_save() { let mut s = Session::new(); let r: Recipient = ("a".into(), "h".into(), 1); for uid in 1..=MAX_PENDING as u64 { s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![r.clone()]); } queue_script_open(&mut s, 100, &r); s.plugin_events.queue(Event::DocumentSaved, MAX_PENDING as u64 + 1, vec![], vec![r]); s.plugin_events.pending.back_mut().unwrap().by_script = true; s.plugin_events_script_ended(false); let saves: Vec<_> = s.plugin_events.pending.iter().map(|p| (p.event, p.document)).collect(); let expected: Vec<_> = (2..=MAX_PENDING as u64 + 1).map(|uid| (Event::DocumentSaved, uid)).collect(); assert_eq!(saves, expected); } #[test] fn a_frontend_save_waits_for_its_restorable_open_between_script_slices() { use vectorcraft_plugins::wat as tpl; let mut s = Session::new(); let manifest = concat!( r#"{"id":"test.events.frontend_order","name":"Test","kind":"filter","api":2,"permissions":["progress","events"],"#, r#""events":["document.opened","document.saved"]}"# ); let wasm = wat::parse_str(tpl::reacting(manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap(); let plugin = Arc::new(Plugin::load(&wasm, vectorcraft_plugins::Limits::default()).unwrap()); let r = recipient(&plugin); s.plugin_events.test_subscribers = Some(vec![plugin]); s.plugin_events.queue(Event::DocumentOpened, 1, vec![], vec![r.clone()]); s.script_in_run = true; for uid in 0..MAX_PENDING as u64 { queue_script_open(&mut s, 100 + uid, &r); } s.plugin_events.queue(Event::DocumentSaved, 1, vec![], vec![r]); assert!(!s.deliver_plugin_events(), "the blocked save must not request another frame"); assert!(s.take_plugin_event_notices().is_empty(), "the save must wait for the earlier frontend open"); s.script_in_run = false; s.plugin_events_script_ended(false); s.deliver_plugin_events(); let given: Vec = s.take_plugin_event_notices().iter().map(|n| serde_json::from_str(&n.text).unwrap()).collect(); let events: Vec<_> = given.iter().map(|event| (event["type"].as_str().unwrap(), event["document"].as_u64().unwrap())).collect(); assert_eq!(events, [("document.opened", 1), ("document.saved", 1)]); } #[test] fn script_open_tracking_is_bounded_after_batch_rollbacks_and_queue_overflow() { let mut s = Session::new(); let r: Recipient = ("a".into(), "h".into(), 1); for uid in 0..2 * MAX_PENDING as u64 { let mark = s.plugin_events_mark(); queue_script_open(&mut s, uid, &r); s.forget_plugin_opens_since(mark); assert!(s.plugin_events.script_opens.is_empty(), "a rolled-back open has no remaining references"); } for uid in 0..2 * (MAX_PENDING + MAX_EVICTED) as u64 { queue_script_open(&mut s, uid, &r); let events = &s.plugin_events; assert!(events.script_opens.len() <= 2 * (events.pending.len() + events.evicted.len())); } s.plugin_events_script_ended(false); assert!(s.plugin_events.pending.is_empty()); assert!(s.plugin_events.evicted.is_empty()); assert!(s.plugin_events.script_opens.is_empty()); } #[test] fn a_delivery_between_script_slices_keeps_the_events_its_opens_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 before = s.plugin_events.pending.clone(); s.script_in_run = true; for uid in 0..MAX_PENDING as u64 { queue_script_open(&mut s, 100 + uid, &r); } // A save a frontend queued while the run is paused pushes out the first open. s.plugin_events.queue(Event::DocumentSaved, 50, vec![], vec![r]); s.deliver_plugin_events(); assert_eq!(s.plugin_events.evicted.len(), 3, "kept while the run goes on"); s.script_in_run = false; s.plugin_events_script_ended(false); assert_eq!(s.plugin_events.pending, before); } /// Queues a `document.opened` as a command of a running script does. fn queue_script_open(s: &mut Session, uid: u64, r: &Recipient) { s.plugin_events.queue(Event::DocumentOpened, uid, vec![], vec![r.clone()]); if let Some(p) = s.plugin_events.pending.back_mut() { p.by_script = true; s.plugin_events.script_opens.insert(p.seq); } } #[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); } }