From 54cd14b3cd615e5d7096eeee9674351e3f30b101 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 13:50:35 -0800 Subject: [PATCH 01/11] Plug-ins: react to selection, layer, open and save events A plug-in at API level 2 with the new `events` permission can name any of `selection.changed`, `document.opened`, `document.saved` and `layer.changed` in its manifest's `events` list. Its `vc_event` export is then called with a small JSON event after each change of that kind has finished, outside any undo step. Changes between two deliveries are one event. The desktop app delivers twice a frame, after the work that finished in the background and at the end of the frame after the canvas, panels and dialogs ran; control-channel requests run in the desktop app and are delivered by the frame. vectorcraft-cli and headless MCP deliver after each request. A plug-in installed after a change is not given it, and a change made after an install reaches the new plug-in at the next delivery. - A handler only reads. It may call ten commands that read (dataset.list, graphicStyle.list, guide.list, image.info, object.blend.info, swatch.list, symbol.list, text.getRange, transparency.info and variable.list); any other call fails before it runs with an error naming the event. After each call every document with its selection, current layer and undo history, the active document, the paint defaults, the active Appearance row and the preferences are put back, and a call that changed a document is refused. - A handler gets 5 M instructions and 200 ms, shared by the module's start function, `vc_alloc` and `vc_event`. A handler that fails 3 times in a row gets no more events until VectorCraft starts again. - An event raised while a handler runs waits for the next delivery. - Events carry the document number and counts; selected ids (at most 2,048) only with `doc.read`. No paths or file contents. - A save that finishes after its document closed is still reported. - A document opened or created since the last delivery is compared with its state when the command that added it ended, so the first change made to it is an event. - A waiting event is dropped for a plug-in that was removed, so the same module installed again is not given it. - The desktop app delivers the events of a script in the frame the script ends in. plugin.list and plugin.info report `events`, `eventsOff` and `lastEventError`. Docs: docs/plugins.md (Events), docs/mcp.md and one progress line in docs/target-app-parity.md. The new plug-in messages, the status lines for a failed handler and the permission's words in Install Plug-in... have rows in every complete catalog. --- crates/engine/src/cmd/fileio/load.rs | 3 +- crates/engine/src/cmd/fileio/save.rs | 2 + crates/engine/src/cmd/plugin.rs | 16 +- crates/engine/src/cmd/plugin_call.rs | 118 ++++++ crates/engine/src/lib.rs | 7 + crates/engine/src/plugin_events.rs | 515 +++++++++++++++++++++++ crates/engine/src/session/documents.rs | 6 + crates/engine/src/session/execute.rs | 1 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/plugin_events.rs | 459 ++++++++++++++++++++ crates/plugins/src/events.rs | 94 +++++ crates/plugins/src/lib.rs | 5 +- crates/plugins/src/manifest.rs | 101 ++++- crates/plugins/src/permissions.rs | 16 +- crates/plugins/src/runtime.rs | 104 ++++- crates/plugins/src/wat.rs | 12 + crates/plugins/tests/abi.rs | 73 ++++ crates/ui-egui/src/app.rs | 34 ++ crates/ui-egui/src/dialogs/tests.rs | 1 + crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 10 + crates/ui-egui/src/i18n/cs.tsv | 10 + crates/ui-egui/src/i18n/da.tsv | 10 + crates/ui-egui/src/i18n/de.tsv | 10 + crates/ui-egui/src/i18n/el.tsv | 10 + crates/ui-egui/src/i18n/es.tsv | 10 + crates/ui-egui/src/i18n/fi.tsv | 10 + crates/ui-egui/src/i18n/fr.tsv | 10 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 10 + crates/ui-egui/src/i18n/hu.tsv | 10 + crates/ui-egui/src/i18n/id.tsv | 10 + crates/ui-egui/src/i18n/it.tsv | 10 + crates/ui-egui/src/i18n/ja.tsv | 10 + crates/ui-egui/src/i18n/ka.tsv | 10 + crates/ui-egui/src/i18n/ko.tsv | 10 + crates/ui-egui/src/i18n/nl.tsv | 10 + crates/ui-egui/src/i18n/pl.tsv | 10 + crates/ui-egui/src/i18n/pt-br.tsv | 10 + crates/ui-egui/src/i18n/ru.tsv | 10 + crates/ui-egui/src/i18n/sv.tsv | 10 + crates/ui-egui/src/i18n/tests.rs | 27 ++ crates/ui-egui/src/i18n/tr.tsv | 10 + crates/ui-egui/src/i18n/uk.tsv | 10 + crates/ui-egui/src/i18n/vi.tsv | 10 + crates/ui-egui/src/i18n/zh-hans.tsv | 10 + crates/ui-egui/src/i18n/zh-hant.tsv | 10 + crates/ui-egui/src/io/open.rs | 1 + crates/ui-egui/src/tests/plugins.rs | 40 ++ crates/ui-egui/src/tests/script_run.rs | 32 ++ docs/mcp.md | 5 +- docs/plugins.md | 67 ++- docs/target-app-parity.md | 1 + 54 files changed, 1976 insertions(+), 18 deletions(-) create mode 100644 crates/engine/src/plugin_events.rs create mode 100644 crates/engine/src/tests/plugin_events.rs create mode 100644 crates/plugins/src/events.rs diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 1818816842..128d91c4f6 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -1003,7 +1003,8 @@ fn open_loaded( st.import_losses = losses; st.links_from = read_from; let opened = &s.documents()[index]; - let (title, file_info_title) = (opened.title(), opened.doc.info_title().to_string()); + let (title, file_info_title, uid) = (opened.title(), opened.doc.info_title().to_string(), opened.uid); + s.note_plugin_event(vectorcraft_plugins::Event::DocumentOpened, uid); Ok(super::merge( json!({ "index": index, "title": title, "fileInfoTitle": file_info_title, "format": format.id, "warnings": warnings, "restored": restored }), links.to_json(), diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index f03dc6fe0d..830378e28a 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1201,6 +1201,8 @@ impl SaveJob { } if saved { crate::cmd::recovery::forget(s, uid); + // Also when the document closed while its file was being written. + s.note_plugin_event(vectorcraft_plugins::Event::DocumentSaved, uid); } if let Some(path) = written { if native { diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 2a1b8c8b40..5cd4686afb 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -104,6 +104,9 @@ pub fn describe(p: &Plugin) -> Value { if m.paint_output { v["paintOutput"] = json!(true); } + if !m.events.is_empty() { + v["events"] = json!(m.events); + } if !m.command_allowlist.is_empty() { v["commandAllowlist"] = json!(m.command_allowlist); } @@ -886,6 +889,7 @@ fn install(s: &mut Session, p: &Value) -> Result { s.store_disabled_plugins_in(&turn); } drop(turn); + s.plugins_changed_for_events(); let mut v = describe_installed(&installed); if !unknown.is_empty() { v["unknownCommands"] = json!(unknown); @@ -1198,12 +1202,17 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result { Ok(json!({"changed": changed, "saved": saved, "disabled": safe_mode::disabled().iter().map(shown_item).collect::>()})) } -fn info(_: &mut Session, p: &Value) -> Result { +fn info(s: &mut Session, p: &Value) -> Result { let plugin = plugin_by_id("plugin.info", p)?; let mut v = describe_installed(&plugin); v["manifest"] = serde_json::to_value(plugin.manifest()).unwrap_or(Value::Null); v["defaults"] = Value::Object(plugin.manifest().defaults()); v["lastError"] = json!(effect::last_error(plugin.id())); + if !plugin.manifest().events.is_empty() { + let (off, last) = s.plugin_event_status(&plugin); + v["eventsOff"] = json!(off); + v["lastEventError"] = json!(last); + } Ok(v) } @@ -1241,6 +1250,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { if !stored && (!installed || !registry::remove(id)) { return Err(err(vectorcraft_plugins::Error::NotFound(id.into()))); } + s.plugins_changed_for_events(); Ok(json!({"removed": id})) } @@ -1270,7 +1280,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md; events: it reacts to the events it names, see events), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), events?: [\"selection.changed\"|\"document.opened\"|\"document.saved\"|\"layer.changed\"] (the events its vc_event handler is given after each change of that kind, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), @@ -1279,7 +1289,7 @@ pub fn specs() -> Vec { "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)}", + "{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)}", always, info ), diff --git a/crates/engine/src/cmd/plugin_call.rs b/crates/engine/src/cmd/plugin_call.rs index 867c1f2ff0..21d515163f 100644 --- a/crates/engine/src/cmd/plugin_call.rs +++ b/crates/engine/src/cmd/plugin_call.rs @@ -461,6 +461,78 @@ pub(crate) fn call(s: &mut Session, run: &Calls, id: &str, args: &Value) -> std: Ok(value) } +/// The commands a plug-in's event handler may call ([`event_call`]), in order: each one only reads +/// the document and returns what it found. Every other command is refused before it runs. +pub(crate) const EVENT_READS: &[&str] = &[ + "dataset.list", + "graphicStyle.list", + "guide.list", + "image.info", + "object.blend.info", + "swatch.list", + "symbol.list", + "text.getRange", + "transparency.info", + "variable.list", +]; + +/// Makes call `id` with `args` from a plug-in's handler of event `event` ([`crate::plugin_events`]) +/// as [`call`] does, for a command in [`EVENT_READS`]; any other command is refused before it runs, +/// with an error that names the event. The call runs inside [`read_only`]: every document and the +/// session state the commands a plug-in may call change go back to how they were afterwards, and a +/// call that changed a document, its selection, current layer or layer rows, or which document is +/// active, is refused. +pub(crate) fn event_call(s: &mut Session, run: &Calls, event: &str, id: &str, args: &Value) -> std::result::Result { + if super::find_command(id).is_none() { + return Err(CallFailure { code: CALL_UNKNOWN_COMMAND, why: super::params::unknown_command(id).to_string() }); + } + if !EVENT_READS.contains(&id) { + return Err(CallFailure { code: CALL_DENIED_COMMAND, why: format!("a {event} handler only reads: `{id}` is not a command it may call") }); + } + let (r, changed) = read_only(s, |s| call(s, run, id, args)); + if changed { + return Err(CallFailure { code: CALL_DENIED_COMMAND, why: format!("a {event} handler only reads: `{id}` changed the document") }); + } + r +} + +/// Runs `f` and then puts every open document (its art, selection, current layer, rows and +/// history), which document is active and the session state the commands a plug-in may call change +/// ([`Saved`]) back to how they were → `f`'s result, and whether `f` changed a document, its +/// selection, current layer or layer rows, opened or closed one, or changed which one is active. +/// A document `f` changed is given a newer revision, so it redraws. +fn read_only(s: &mut Session, f: impl FnOnce(&mut Session) -> R) -> (R, bool) { + let saved = Saved::of(s); + let pending_paint = s.pending_paint.clone(); + let start = s.docs.clone(); + let active = s.active; + let r = 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 { + let Some(n) = now.iter().find(|d| d.uid == st.uid) else { + changed = true; + continue; + }; + if n.revision != st.revision + || !Arc::ptr_eq(&n.doc, &st.doc) + || n.selection != st.selection + || n.active_layer != st.active_layer + || n.layer_rows != st.layer_rows + { + st.revision = st.revision.max(n.revision).saturating_add(1); + changed = true; + } + } + s.active = active; + saved.restore(s); + s.pending_paint = pending_paint; + if changed { + s.sync_front_profiles(); + } + (r, changed) +} + /// Runs command `id` with `args` in `s` with no file or folder readable or writable: every path the /// command reaches through the checked file access ([`crate::file_access`]) is refused, whatever /// param carries it. @@ -917,4 +989,50 @@ mod tests { assert!(!names_key("{pathData: 1}", "path")); assert!(names_key("path: x", "path")); } + + /// Each command an event handler may call is one a plug-in may call and one the journal does + /// not record, listed once, in order. + #[test] + fn event_reads_are_reviewed_reads() { + for id in EVENT_READS { + let Some(spec) = crate::cmd::find_command(id) else { panic!("no command {id}") }; + assert_eq!(denied(spec), None, "{id} is refused to every plug-in"); + assert!(!spec.journal, "{id} is journaled"); + } + assert!(EVENT_READS.windows(2).all(|w| w[0] < w[1]), "in order, once each"); + } + + /// [`read_only`] puts back what its function changed: the document, its selection, the + /// preferences and the paint defaults, and says that the document changed; a function that + /// changes nothing is no change. + #[test] + fn read_only_puts_everything_back() { + use serde_json::json; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].clone(); + s.execute("select.none", &json!({})).unwrap(); + let st = s.doc().unwrap(); + let (doc, revision, history) = (st.doc.clone(), st.revision, st.history.undo.len()); + let (prefs, paint) = (s.prefs.history_states, s.paint.clone()); + let ((), changed) = read_only(&mut s, |s| { + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap(); + s.prefs.history_states += 1; + s.paint.stroke_width += 3.0; + }); + assert!(changed); + let st = s.doc().unwrap(); + assert!(Arc::ptr_eq(&st.doc, &doc), "the same document"); + assert!(st.selection.objects.is_empty(), "the selection as it was"); + assert_eq!(st.history.undo.len(), history, "no undo step"); + assert!(st.revision > revision, "a newer revision, so it redraws"); + assert_eq!((s.prefs.history_states, &s.paint), (prefs, &paint)); + let revision = st.revision; + let ((), changed) = read_only(&mut s, |s| { + s.execute("variable.list", &json!({})).unwrap(); + }); + assert!(!changed, "a read changes nothing"); + assert_eq!(s.doc().unwrap().revision, revision); + } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 68067dc697..ed85ece069 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -12,6 +12,7 @@ pub mod guard; pub mod inspect; pub mod journal; pub mod link_watch; +pub mod plugin_events; pub mod schemas; pub mod steps; pub mod store; @@ -317,6 +318,12 @@ pub struct Session { /// While the active tool's actions run: their commands aren't "a command from outside the /// tool" ([`Session::after_command`]). pub(crate) in_tool_actions: bool, + /// The events plug-ins react to that wait for delivery, and how the documents were at the last + /// 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. + 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`]). settled_warnings: Option>, diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs new file mode 100644 index 0000000000..9951904991 --- /dev/null +++ b/crates/engine/src/plugin_events.rs @@ -0,0 +1,515 @@ +//! 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 runs while an interaction is open (a +//! drag being previewed). A document opened or created since the last check is compared with how +//! it was when the command that added it ended ([`Session::plugin_events_see_new_documents`]). +//! - 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 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 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::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 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 and the hash of its module. +type Recipient = (String, String); + +/// The recipient `p` is. +fn recipient(p: &Plugin) -> Recipient { + (p.id().to_string(), p.hash().to_string()) +} + +/// An event waiting for delivery: what changed, in which document, for `layer.changed` why, and +/// the plug-ins it is for: those installed when it happened. +#[derive(Clone, Debug, PartialEq)] +struct Pending { + event: Event, + document: u64, + reasons: Vec<&'static str>, + to: Vec, +} + +/// One plug-in's failed handlers in a row, for the module with `hash`. +#[derive(Clone, Debug, Default)] +struct Failures { + hash: String, + 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, +} + +/// 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, + dispatching: bool, + failures: BTreeMap, + notices: VecDeque, + /// The installed plug-ins that react to events, as of a registry revision. + subscribers: Option<(u64, Vec>)>, +} + +impl PluginEvents { + /// The installed plug-ins that react to events (none in Safe Mode). + fn subscribers(&mut self) -> Vec> { + 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`. A `selection.changed` or + /// `layer.changed` already waiting for that document takes it in (a layer event adds the new + /// reasons to its own, and the new plug-ins to its own); 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 reasons { + if !p.reasons.contains(&r) { + p.reasons.push(r); + } + } + p.reasons.sort_by_key(|r| LAYER_REASONS.iter().position(|x| x == r)); + for r in to { + if !p.to.contains(&r) { + p.to.push(r); + } + } + return; + } + if self.pending.len() >= MAX_PENDING + && let Some(dropped) = self.pending.pop_front() + { + log::warn!("plug-in events: dropped a waiting {} event, past {MAX_PENDING} waiting", dropped.event.name()); + } + self.pending.push_back(Pending { event, document: uid, reasons, to }); + } + + 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 another module was installed under its id. + 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() }; + } + f + } +} + +/// 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); + +/// 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)); + if new.iter().any(|(id, ..)| !old.iter().any(|(o, ..)| o == id)) { + reasons.push("added"); + } + if old.iter().any(|(id, ..)| !new.iter().any(|(n, ..)| n == id)) { + 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) { + reasons.push("reordered"); + } + if old.iter().any(|r| new.iter().any(|o| o.0 == r.0 && 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); + } + + /// 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) { + 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(); + 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.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; + } + + /// 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. + pub fn deliver_plugin_events(&mut self) { + if self.plugin_events.dispatching { + return; + } + self.check_plugin_events(); + if self.plugin_events.pending.is_empty() { + return; + } + let subs = self.plugin_events.subscribers(); + self.plugin_events.dispatching = true; + // 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; + while let Some(p) = self.plugin_events.pending.pop_front() { + 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.to.contains(&recipient(s))) { + if self.plugin_events.failures_of(plugin).disabled { + continue; + } + self.run_handler(plugin, &p); + } + } + self.depth = depth; + self.plugin_events.dispatching = false; + } + + /// The JSON event `p` as plug-in `plugin` is given it: the selected object ids of a + /// `selection.changed` only with `doc.read`. + fn event_json(&self, plugin: &Plugin, p: &Pending) -> 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!(p.reasons); + } + Event::DocumentOpened | Event::DocumentSaved => {} + } + v + } + + /// Calls `plugin`'s handler with event `p` and records what it wrote and whether it failed. + fn run_handler(&mut self, plugin: &Arc, p: &Pending) { + let event = p.event.name(); + let text = serde_json::to_vec(&self.event_json(plugin, p)).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 }); + } + 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 = format!("its {event} handler failed: {e}"); + self.plugin_events.notice(Notice { plugin: id.clone(), name: name.clone(), event, level: LogLevel::Error, text }); + } + 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 }); + } + } + + /// 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 + /// document in an interaction. + pub(crate) fn plugin_events_see_new_documents(&mut self) { + if self.plugin_events.seen_by.is_empty() { + 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 !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(); + } + } + + /// 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.hash == p.hash()) { + Some(f) => (f.disabled, f.last_error.clone()), + None => (false, None), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn waiting_selection_and_layer_events_of_a_document_merge() { + let mut e = PluginEvents::default(); + e.queue(Event::SelectionChanged, 1, vec![], vec![]); + e.queue(Event::LayerChanged, 1, vec!["options"], vec![]); + e.queue(Event::SelectionChanged, 1, vec![], vec![]); + e.queue(Event::LayerChanged, 1, vec!["current", "options"], vec![]); + e.queue(Event::SelectionChanged, 2, vec![], vec![]); + e.queue(Event::DocumentSaved, 1, vec![], vec![]); + e.queue(Event::DocumentSaved, 1, vec![], vec![]); + let got: Vec<(Event, u64, Vec<&str>)> = e.pending.iter().map(|p| (p.event, p.document, p.reasons.clone())).collect(); + assert_eq!( + got, + [ + (Event::SelectionChanged, 1, vec![]), + (Event::LayerChanged, 1, vec!["current", "options"]), + (Event::SelectionChanged, 2, vec![]), + (Event::DocumentSaved, 1, vec![]), + (Event::DocumentSaved, 1, vec![]), + ] + ); + } + + /// 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"); + } +} diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 1685adc40f..684b2b881a 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -136,6 +136,8 @@ impl Session { screens_hand_off: None, recovery: Default::default(), in_tool_actions: false, + plugin_events: Default::default(), + plugin_event_frames: false, settled_warnings: None, previewing: false, decoded_images: Default::default(), @@ -365,6 +367,10 @@ 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(); + } i } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 046c480079..19cd41fdb0 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -249,6 +249,7 @@ 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/tests.rs b/crates/engine/src/tests.rs index e524d1c63c..36fb0b0f47 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -145,6 +145,7 @@ mod perspgrid; mod pixelalign; mod place; mod placed_document; +mod plugin_events; mod plugins; mod prefs; mod prefs_file; diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs new file mode 100644 index 0000000000..df8dd04cb4 --- /dev/null +++ b/crates/engine/src/tests/plugin_events.rs @@ -0,0 +1,459 @@ +//! Events plug-ins react to (`events`, `vc_event`): each event reaches the plug-ins that name it, +//! once, after the change; a burst of selection changes in one frame is one event; a handler only +//! reads; and a handler that keeps failing stops being called. + +use serde_json::{Value, json}; +use vectorcraft_plugins::LogLevel; +use vectorcraft_plugins::wat as tpl; + +use crate::*; + +fn run(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +/// A session with a 400 × 200 document that takes `grant` from requests. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); + s.allow_plugin_grants_from_requests(); + s +} + +fn rect(s: &mut Session, x: f64) -> NodeId { + NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 10, "width": 10, "height": 10}))["id"].as_u64().unwrap()) +} + +/// Installs plug-in `id` that reacts to `events` (a JSON list) with the vc_event body `handler`, +/// writes log lines and also has the permissions `more`; `imports` are module fields its handler +/// uses besides the host imports, and `allowlist` the commands it may call. +fn install(s: &mut Session, id: &str, events: &str, more: &[&str], imports: &str, handler: &str, allowlist: &[&str]) { + let mut grant = vec!["progress", "events"]; + grant.extend_from_slice(more); + let allow = if allowlist.is_empty() { String::new() } else { format!(r#","commandAllowlist":{}"#, json!(allowlist)) }; + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":{},"events":{events}{allow}}}"#, json!(grant)); + let wasm = wat::parse_str(tpl::reacting(&manifest, &format!("{} {imports}", tpl::HOST_IMPORTS), handler)).unwrap(); + run(s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})); +} + +/// The events plug-in `id`'s handler was given since the last call, as it logged them. +fn given(s: &mut Session, id: &str) -> Vec { + let notices = s.take_plugin_event_notices(); + notices.iter().filter(|n| n.plugin == id && n.level == LogLevel::Info).map(|n| serde_json::from_str(&n.text).unwrap()).collect() +} + +fn types(events: &[Value]) -> Vec<&str> { + events.iter().map(|e| e["type"].as_str().unwrap()).collect() +} + +/// 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. +#[test] +fn each_event_reaches_the_plugins_that_name_it_once() { + let (all, saves) = ("test.events.all", "test.events.saves"); + let mut s = session(); + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + install(&mut s, all, r#"["selection.changed","document.opened","document.saved","layer.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + install(&mut s, saves, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + assert!(given(&mut s, all).is_empty(), "installing replays nothing"); + let doc = s.doc().unwrap().uid; + + run(&mut s, "select.set", json!({"ids": [r.0]})); + let notices = s.take_plugin_event_notices(); + let got: Vec = notices.iter().filter(|n| n.plugin == all).map(|n| serde_json::from_str(&n.text).unwrap()).collect(); + assert_eq!(got, [json!({"type": "selection.changed", "document": doc, "count": 1, "ids": [r.0], "truncated": false})]); + assert!(notices.iter().all(|n| n.plugin != saves), "not named, not given"); + + run(&mut s, "select.set", json!({"ids": [r.0]})); + assert!(given(&mut s, all).is_empty(), "the same selection again is no change"); + + let layer = run(&mut s, "layer.new", json!({"name": "Notes"}))["id"].as_u64().unwrap(); + let got = given(&mut s, all); + assert_eq!(types(&got), ["layer.changed"]); + assert_eq!(got[0]["layer"], json!(layer)); + assert!(got[0]["reasons"].as_array().unwrap().contains(&json!("added")), "{}", got[0]); + + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("events.vectorcraft").to_string_lossy().into_owned(); + run(&mut s, "document.save", json!({"path": path})); + let notices = s.take_plugin_event_notices(); + for id in [all, saves] { + let got: Vec = notices.iter().filter(|n| n.plugin == id).map(|n| serde_json::from_str(&n.text).unwrap()).collect(); + assert_eq!(got, [json!({"type": "document.saved", "document": doc})], "{id}"); + } + + run(&mut s, "document.open", json!({"path": path})); + let opened = s.doc().unwrap().uid; + assert_ne!(opened, doc); + assert_eq!(given(&mut s, all), [json!({"type": "document.opened", "document": opened})], "a new document's own selection is no change"); + + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": all})); + run(&mut s, "plugin.remove", json!({"id": saves})); +} + +/// A save of a document that closes before the frame's delivery still reaches the plug-in, with +/// the document's number; its selection change does not. So does a save written on another thread +/// that finishes after its document closed. +#[test] +fn a_save_reaches_the_plugin_when_its_document_closes_first() { + let id = "test.events.closed"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + 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, &[]); + s.plugin_event_frames = true; + run(&mut s, "select.set", json!({"ids": [r.0]})); + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-closed-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("closed.vectorcraft").to_string_lossy()})); + run(&mut s, "file.close", json!({})); + assert!(s.docs.iter().all(|d| d.uid != doc), "the document closed"); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})]); + + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let later = s.doc().unwrap().uid; + let p = json!({"path": dir.join("later.vectorcraft").to_string_lossy()}); + let plan = crate::cmd::fileio::save_plan(&s, crate::cmd::fileio::SaveMode::SaveAs, &p).unwrap(); + let job = crate::cmd::fileio::save_job(&mut s, plan).unwrap(); + job.write(|path, bytes| std::fs::write(path, bytes).map_err(|e| EngineError::Other(e.to_string()))).unwrap(); + run(&mut s, "file.close", json!({})); + assert!(s.docs.iter().all(|d| d.uid != later), "the document closed"); + job.complete(&mut s, later); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": later})]); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A plug-in installed after a save or a selection change, before the frame's delivery, is given +/// neither; the plug-in installed before is given both, and the next change reaches both. +#[test] +fn a_plugin_installed_before_the_delivery_gets_no_earlier_events() { + let (early, late) = ("test.events.early", "test.events.late"); + let events = r#"["selection.changed","document.saved"]"#; + let mut s = session(); + let doc = s.doc().unwrap().uid; + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 40.0)); + run(&mut s, "select.none", json!({})); + install(&mut s, early, events, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-late-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("late.vectorcraft").to_string_lossy()})); + run(&mut s, "select.set", json!({"ids": [a.0]})); + install(&mut s, late, events, &[], "", tpl::LOG_EVENT, &[]); + s.deliver_plugin_events(); + let notices = s.take_plugin_event_notices(); + let of = |id: &str| -> Vec { notices.iter().filter(|n| n.plugin == id).map(|n| serde_json::from_str(&n.text).unwrap()).collect() }; + assert_eq!(types(&of(early)), ["document.saved", "selection.changed"]); + assert!(of(late).is_empty(), "{:?}", of(late)); + run(&mut s, "select.set", json!({"ids": [b.0]})); + s.deliver_plugin_events(); + let notices = s.take_plugin_event_notices(); + for id in [early, late] { + let got: Vec = notices.iter().filter(|n| n.plugin == id).map(|n| serde_json::from_str(&n.text).unwrap()).collect(); + assert_eq!(got, [json!({"type": "selection.changed", "document": doc, "count": 1, "ids": null, "truncated": false})], "{id}"); + } + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": early})); + run(&mut s, "plugin.remove", json!({"id": late})); +} + +/// With delivery once a frame, a selection change made after a plug-in was installed, in the same +/// frame, reaches it. +#[test] +fn a_change_after_the_install_in_the_same_frame_reaches_the_plugin() { + let id = "test.events.same_frame"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + s.plugin_event_frames = true; + install(&mut s, id, r#"["selection.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + run(&mut s, "select.set", json!({"ids": [r.0]})); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "selection.changed", "document": doc, "count": 1, "ids": [r.0], "truncated": false})]); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// With delivery once a frame, a change made to a document created or opened since the last +/// delivery gives its event at the next one; an opened document's `document.opened` comes first, +/// once. +#[test] +fn a_change_to_a_document_opened_since_the_last_delivery_gives_its_event() { + let id = "test.events.new_doc"; + let mut s = session(); + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-new-doc-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("new-doc.vectorcraft").to_string_lossy().into_owned(); + run(&mut s, "document.save", json!({"path": path})); + install(&mut s, id, r#"["selection.changed","document.opened","layer.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty()); + + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let created = s.doc().unwrap().uid; + let r = rect(&mut s, 10.0); + run(&mut s, "select.set", json!({"ids": [r.0]})); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "selection.changed", "document": created, "count": 1, "ids": [r.0], "truncated": false})]); + + run(&mut s, "document.open", json!({"path": path})); + let opened = s.doc().unwrap().uid; + let layer = run(&mut s, "layer.new", json!({"name": "Notes"}))["id"].as_u64().unwrap(); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["document.opened", "layer.changed"], "{got:?}"); + assert_eq!((got[0]["document"].clone(), got[1]["document"].clone(), got[1]["layer"].clone()), (json!(opened), json!(opened), json!(layer))); + assert!(got[1]["reasons"].as_array().unwrap().contains(&json!("added")), "{}", got[1]); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "once"); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A save waiting for delivery is not given to the same module removed and installed again before +/// the delivery. +#[test] +fn a_module_installed_again_gets_no_event_from_before_its_removal() { + let id = "test.events.again"; + let mut s = session(); + s.plugin_event_frames = true; + install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-again-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("again.vectorcraft").to_string_lossy()})); + run(&mut s, "plugin.remove", json!({"id": id})); + install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "the save came before this install"); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A `selection.changed` event of a plug-in without `doc.read` gives the count and no ids; one +/// with it lists the selected ids. +#[test] +fn selected_ids_need_doc_read() { + let id = "test.events.noread"; + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 40.0)); + install(&mut s, id, r#"["selection.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + let got = given(&mut s, id); + assert_eq!(got.len(), 1); + assert_eq!((got[0]["count"].clone(), got[0]["ids"].clone()), (json!(2), Value::Null)); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// With delivery once a frame, the selection changes of one frame are one event with the selection +/// the frame ended with, and changes that end where they started are none. +#[test] +fn selection_changes_in_one_frame_are_one_event() { + let id = "test.events.burst"; + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 40.0)); + run(&mut s, "select.none", json!({})); + install(&mut s, id, r#"["selection.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + for ids in [vec![a.0], vec![b.0], vec![], vec![a.0, b.0], vec![b.0]] { + run(&mut s, "select.set", json!({"ids": ids})); + } + assert!(given(&mut s, id).is_empty(), "nothing before the frame"); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["selection.changed"]); + assert_eq!(got[0]["ids"], json!([b.0])); + run(&mut s, "select.set", json!({"ids": [a.0]})); + run(&mut s, "select.set", json!({"ids": [b.0]})); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "back where the frame started"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// `layer.changed` names what changed: a new name is `options`, the same name again is no change, +/// another current layer is `current`, a moved layer `reordered` and a deleted one `deleted`. +#[test] +fn layer_changes_name_their_reasons() { + let id = "test.events.layers"; + let mut s = session(); + let first = s.doc().unwrap().active_layer.unwrap(); + let second = NodeId(run(&mut s, "layer.new", json!({"name": "Two"}))["id"].as_u64().unwrap()); + install(&mut s, id, r#"["layer.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + let reasons = |s: &mut Session, cmd: &str, p: Value| { + run(s, cmd, p); + given(s, id).iter().map(|e| e["reasons"].clone()).collect::>() + }; + assert_eq!(reasons(&mut s, "layer.setProps", json!({"id": second.0, "name": "Notes"})), [json!(["options"])]); + assert!(reasons(&mut s, "layer.setProps", json!({"id": second.0, "name": "Notes"})).is_empty(), "same name, no change"); + assert_eq!(reasons(&mut s, "layer.setCurrent", json!({"id": first.0})), [json!(["current"])]); + assert_eq!(reasons(&mut s, "layer.move", json!({"ids": [first.0], "target": second.0, "place": "above"})), [json!(["reordered"])]); + let deleted = reasons(&mut s, "layer.delete", json!({"ids": [second.0]})); + assert_eq!(deleted.len(), 1); + assert!(deleted[0].as_array().unwrap().contains(&json!("deleted")), "{deleted:?}"); + + // A sublayer moved past an object beside it is reordered; an object drawn beside it is not. + run(&mut s, "layer.setCurrent", json!({"id": first.0})); + given(&mut s, id); + let sub = NodeId(run(&mut s, "layer.newSublayer", json!({"parent": first.0, "name": "Sub"}))["id"].as_u64().unwrap()); + run(&mut s, "layer.setCurrent", json!({"id": first.0})); + given(&mut s, id); + let r = rect(&mut s, 10.0); + assert!(given(&mut s, id).is_empty(), "drawing beside a sublayer moves no layer"); + assert_eq!(reasons(&mut s, "layer.move", json!({"ids": [sub.0], "target": r.0, "place": "above"})), [json!(["reordered"])]); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A handler may call a command listed for handlers, and is given its result; one that calls a +/// command that changes the document or the current layer, or a read not listed for handlers, is +/// refused with an error that names the event, and the selection, the current layer and the undo +/// history stay as the user left them. +#[test] +fn a_handler_only_reads() { + let (reads, edits) = ("test.events.reads", "test.events.edits"); + let (unlisted, layers) = ("test.events.unlisted", "test.events.layer"); + let mut s = session(); + let first = s.doc().unwrap().active_layer.unwrap(); + let other = run(&mut s, "layer.new", json!({"name": "Other"}))["id"].as_u64().unwrap(); + run(&mut s, "layer.setCurrent", json!({"id": first.0})); + let (a, _) = (rect(&mut s, 10.0), rect(&mut s, 40.0)); + run(&mut s, "select.none", json!({})); + let expected = run(&mut s, "variable.list", json!({})); + // The read's result, copied with `vc_call_result`, is written as a log line. + let (imports, call) = calling("variable.list", "{}"); + let imports = format!(r#"{imports} (import "env" "vc_call_result" (func $vc_call_result (param i32 i32) (result i32)))"#); + let handler = format!( + "(drop {call}) (drop (call $vc_log (i32.const 2) (i32.const 0x4000) (call $vc_call_result (i32.const 0x4000) (i32.const 0x4000)))) (i32.const 0)" + ); + install(&mut s, reads, r#"["selection.changed"]"#, &["doc.read", "commands"], &imports, &handler, &["variable.list"]); + assert!(!find_command("addon.cleanup.check").unwrap().journal, "a query the journal does not record"); + let (imports, handler) = calling("addon.cleanup.check", "{}"); + install(&mut s, unlisted, r#"["selection.changed"]"#, &["doc.read", "commands"], &imports, &handler, &["addon.cleanup.check"]); + let (imports, handler) = calling("select.all", "{}"); + install(&mut s, edits, r#"["selection.changed"]"#, &["doc.read", "commands"], &imports, &handler, &["select.all"]); + let (imports, handler) = calling("layer.setCurrent", &format!(r#"{{"id":{other}}}"#)); + install(&mut s, layers, r#"["selection.changed"]"#, &["doc.read", "commands"], &imports, &handler, &["layer.setCurrent"]); + let (undo, rows) = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().layer_rows.clone()); + run(&mut s, "select.set", json!({"ids": [a.0]})); + let notices = s.take_plugin_event_notices(); + let read: Vec = notices.iter().filter(|n| n.plugin == reads).map(|n| serde_json::from_str(&n.text).unwrap()).collect(); + assert_eq!(read, [expected], "the read call succeeds and gives its result: {notices:?}"); + for (id, cmd) in [(unlisted, "addon.cleanup.check"), (edits, "select.all"), (layers, "layer.setCurrent")] { + let failed: Vec<&str> = notices.iter().filter(|n| n.plugin == id && n.level == LogLevel::Error).map(|n| n.text.as_str()).collect(); + assert_eq!(failed.len(), 1, "{failed:?}"); + assert!(failed[0].contains(&format!("a selection.changed handler only reads: `{cmd}` is not a command it may call")), "{}", failed[0]); + } + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects, [a], "the selection the user made"); + assert_eq!((st.active_layer, &st.layer_rows), (Some(first), &rows), "the current layer the user chose"); + assert_eq!(st.history.undo.len(), undo, "no undo step"); + let info = run(&mut s, "plugin.info", json!({"id": edits})); + assert!(info["lastEventError"].as_str().unwrap().contains("only reads"), "{info}"); + assert_eq!(info["eventsOff"], json!(false)); + assert_eq!(info["events"], json!(["selection.changed"])); + run(&mut s, "plugin.remove", json!({"id": reads})); + run(&mut s, "plugin.remove", json!({"id": unlisted})); + run(&mut s, "plugin.remove", json!({"id": edits})); + run(&mut s, "plugin.remove", json!({"id": layers})); +} + +/// A handler that calls a query the journal does not record but that changes the selection (Select +/// All Instances) is refused before the query runs: the document, its revision, selection and undo +/// history, and the session's paint and Appearance state, are as the user left them. +#[test] +fn a_handler_query_that_selects_is_refused_before_it_runs() { + let id = "test.events.selects"; + let (cmd, args) = ("symbol.selectInstances", r#"{"name":"Dot"}"#); + assert!(!find_command(cmd).unwrap().journal, "a query the journal does not record"); + let mut s = session(); + let dot = rect(&mut s, 10.0); + run(&mut s, "symbol.new", json!({"name": "Dot", "ids": [dot.0]})); + let b = rect(&mut s, 40.0); + run(&mut s, "select.none", json!({})); + let (imports, handler) = calling(cmd, args); + install(&mut s, id, r#"["selection.changed"]"#, &["doc.read", "commands"], &imports, &handler, &[cmd]); + s.plugin_event_frames = true; + run(&mut s, "select.set", json!({"ids": [b.0]})); + let st = s.doc().unwrap(); + let (doc, revision, undo) = (st.doc.clone(), st.revision, st.history.undo.len()); + let (paint, appearance, fill_active) = (s.paint.clone(), format!("{:?}", s.active_appearance_item), s.fill_active); + s.deliver_plugin_events(); + let notices = s.take_plugin_event_notices(); + let failed: Vec<&str> = notices.iter().filter(|n| n.plugin == id && n.level == LogLevel::Error).map(|n| n.text.as_str()).collect(); + assert_eq!(failed.len(), 1, "{notices:?}"); + assert!(failed[0].contains(&format!("a selection.changed handler only reads: `{cmd}` is not a command it may call")), "{}", failed[0]); + let st = s.doc().unwrap(); + assert!(std::sync::Arc::ptr_eq(&st.doc, &doc), "the same document"); + assert_eq!((st.revision, st.history.undo.len()), (revision, undo), "the same revision and undo history"); + assert_eq!(st.selection.objects, [b], "the selection the user made"); + assert_eq!((&s.paint, format!("{:?}", s.active_appearance_item), s.fill_active), (&paint, appearance, fill_active)); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A refused handler call leaves the Appearance panel's active row and the Fill or Stroke in +/// front as the user chose them, also when the query it called selected art. +#[test] +fn a_refused_handler_call_keeps_the_active_appearance_row() { + let id = "test.events.appearance"; + let (cmd, args) = ("addon.cleanup.show", r#"{"kind":"duplicateObjects","scope":"document"}"#); + assert!(!find_command(cmd).unwrap().journal, "a query the journal does not record"); + let mut s = session(); + let (a, _) = (rect(&mut s, 10.0), rect(&mut s, 10.0)); + run(&mut s, "select.set", json!({"ids": [a.0]})); + let (imports, handler) = calling(cmd, args); + install(&mut s, id, r#"["layer.changed"]"#, &["doc.read", "commands"], &imports, &handler, &[cmd]); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + let fill_active = s.fill_active; + run(&mut s, "layer.new", json!({"name": "Other"})); + let notices = s.take_plugin_event_notices(); + let failed: Vec<&str> = notices.iter().filter(|n| n.plugin == id && n.level == LogLevel::Error).map(|n| n.text.as_str()).collect(); + assert_eq!(failed.len(), 1, "{notices:?}"); + assert!(failed[0].contains(&format!("a layer.changed handler only reads: `{cmd}` is not a command it may call")), "{}", failed[0]); + assert_eq!(s.doc().unwrap().selection.objects, [a], "the selection the user made"); + assert!(s.active_appearance_item.is_some(), "the active Appearance row"); + assert_eq!(s.fill_active, fill_active); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// Module fields that import `vc_call` and hold `cmd` and `args`, and a `vc_event` body that calls +/// `cmd` with `args` and returns what the call returned. +fn calling(cmd: &str, args: &str) -> (String, String) { + let imports = format!( + r#"(import "env" "vc_call" (func $vc_call (param i32 i32 i32 i32) (result i32))) + (data (i32.const 0x2000) "{}") (data (i32.const 0x2100) "{}")"#, + tpl::string(cmd), + tpl::string(args) + ); + let handler = format!("(call $vc_call (i32.const 0x2000) (i32.const {}) (i32.const 0x2100) (i32.const {}))", cmd.len(), args.len()); + (imports, handler) +} + +/// A handler that fails is reported once; after three failures in a row its events stop for the +/// session, while each selection the user makes stays. +#[test] +fn a_handler_that_keeps_failing_is_turned_off() { + let id = "test.events.failing"; + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 40.0)); + run(&mut s, "select.none", json!({})); + install(&mut s, id, r#"["selection.changed"]"#, &[], "", "unreachable", &[]); + let mut notices = Vec::new(); + for ids in [vec![a.0], vec![b.0], vec![a.0], vec![b.0], vec![a.0]] { + run(&mut s, "select.set", json!({"ids": ids.clone()})); + assert_eq!(s.doc().unwrap().selection.objects.iter().map(|i| i.0).collect::>(), ids, "the user's selection stays"); + notices.extend(s.take_plugin_event_notices().into_iter().filter(|n| n.plugin == id).map(|n| n.text)); + } + assert_eq!(notices.len(), 2, "{notices:?}"); + assert!(notices[0].starts_with("its selection.changed handler failed") && notices[0].contains("trapped"), "{}", notices[0]); + 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)); + run(&mut s, "plugin.remove", json!({"id": id})); +} diff --git a/crates/plugins/src/events.rs b/crates/plugins/src/events.rs new file mode 100644 index 0000000000..53a5ad2a2a --- /dev/null +++ b/crates/plugins/src/events.rs @@ -0,0 +1,94 @@ +//! Events a plug-in may react to, from plug-in API level 2 on: its manifest's `events` names them +//! ([`Event`]) and lists the `events` permission, and the module exports +//! `vc_event(event_ptr: i32, event_len: i32) -> i32`. After a change has finished, the host calls +//! `vc_event` in a fresh instance with a small JSON object that names the event and the document +//! ([`crate::Plugin::run_event`]). A handler only reads: the host applies nothing it returns, and +//! a command call that would change a document is refused ([`crate::host`]). +//! +//! The limits are VectorCraft's own values: [`EVENT_FUEL`] instructions and +//! [`EVENT_WALL_TIME_MS`] for one handler, an event of at most [`MAX_EVENT_BYTES`], and +//! [`MAX_EVENT_IDS`] selected ids in a `selection.changed` event. + +/// The plug-in API level that adds `events`, the `events` permission and `vc_event`. +pub const EVENTS_API: u32 = 2; + +/// Instructions one handler may use, or the plug-in's own budget when that is smaller. +pub const EVENT_FUEL: u64 = 5_000_000; + +/// Wall-clock budget of one handler, in milliseconds, or the plug-in's own when that is shorter. +pub const EVENT_WALL_TIME_MS: u64 = 200; + +/// Largest event JSON the host hands a handler, in bytes. +pub const MAX_EVENT_BYTES: usize = 64 * 1024; + +/// Most selected object ids a `selection.changed` event lists; a larger selection sends the first +/// ones with `truncated: true` and its whole `count`. That many ids of the largest value still fit +/// in [`MAX_EVENT_BYTES`]. +pub const MAX_EVENT_IDS: usize = 2048; + +/// Failed handlers in a row after which the host stops calling a plug-in's handler until the app +/// starts again. +pub const MAX_EVENT_FAILURES: u32 = 3; + +/// One thing a plug-in may react to. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Event { + /// The selection in a document changed: other objects, anchors or segments, or nothing. + SelectionChanged, + /// A file opened as a document (File › Open, a recent file, New from Template). + DocumentOpened, + /// A document was saved to its own file (Save, Save As). + DocumentSaved, + /// The current layer changed, or a layer was added, deleted, moved or given other options. + LayerChanged, +} + +impl Event { + /// Every event, in the order the docs list them. + pub const ALL: [Event; 4] = [Event::SelectionChanged, Event::DocumentOpened, Event::DocumentSaved, Event::LayerChanged]; + + /// Its name in a manifest's `events`, which is also the event's `type`. + pub fn name(self) -> &'static str { + match self { + Event::SelectionChanged => "selection.changed", + Event::DocumentOpened => "document.opened", + Event::DocumentSaved => "document.saved", + Event::LayerChanged => "layer.changed", + } + } + + /// The event named `name`. + pub fn parse(name: &str) -> Option { + Event::ALL.into_iter().find(|e| e.name() == name) + } + + /// Whether the event is still delivered when its document has closed before the delivery: + /// an open or a save is, a selection or layer change is not. + pub fn outlives_document(self) -> bool { + matches!(self, Event::DocumentOpened | Event::DocumentSaved) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_round_trip() { + for e in Event::ALL { + assert_eq!(Event::parse(e.name()), Some(e)); + } + assert_eq!(Event::parse("selection.change"), None); + assert_eq!(Event::parse(""), None); + } + + /// A `selection.changed` event that lists the most ids, each of the largest value, fits in the + /// largest event a handler is given. + #[test] + fn the_largest_selection_event_fits() { + let ids = vec![u64::MAX; MAX_EVENT_IDS]; + let event = serde_json::json!({"type": "selection.changed", "document": u64::MAX, "count": u64::MAX, "ids": ids, "truncated": true}); + let len = serde_json::to_vec(&event).unwrap().len(); + assert!(len <= MAX_EVENT_BYTES, "{len} bytes"); + } +} diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index 019dd0d858..a77f243efb 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -31,12 +31,14 @@ //! them well: labels, units, groups, help and conditions ([`dialog`]). What a plug-in may do is //! the set of [`permissions`] its manifest lists, which the user approves when it is installed. A //! filter or a live effect may also add menu commands of its own ([`Command`]), which the host -//! runs through `vc_run` with the command's id in `_context`. +//! runs through `vc_run` with the command's id in `_context`. Any kind may also react to the +//! [`events`] its manifest names, through `vc_event`, without changing the document. #![forbid(unsafe_code)] pub mod deferred; pub mod dialog; pub mod effect; +pub mod events; pub mod export; pub mod host; pub mod import; @@ -51,6 +53,7 @@ pub mod storage; pub mod wat; pub use dialog::ParamUi; +pub use events::Event; pub use host::{LogLevel, LogLine, Report}; pub use manifest::{Budget, Command, InputKind, Kind, Manifest, Param, ParamSpec}; pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms}; diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index b6e17e3ad0..493e0a3b63 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{Map, Value, json}; use crate::dialog::ParamUi; +use crate::events::{EVENTS_API, Event}; use crate::permissions::{self, API_LEVEL, INPUTS_API, PROGRESS_API, Permission}; use crate::{Error, Result}; @@ -348,6 +349,11 @@ pub struct Manifest { /// lists any ([`Manifest::validate`]). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub command_allowlist: Vec, + /// The events it reacts to, by [`Event::name`]: only a module at `api` 2 or later whose + /// `permissions` list `events` lists any, and it exports `vc_event` ([`crate::events`]). Left + /// out or empty, it reacts to none. + #[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "event_names")] + pub events: Vec, } impl Manifest { @@ -383,6 +389,7 @@ impl Manifest { paint_output: false, commands: Vec::new(), command_allowlist: Vec::new(), + events: Vec::new(), } } @@ -440,7 +447,42 @@ impl Manifest { } self.validate_params()?; self.validate_commands()?; - self.validate_allowlist() + self.validate_allowlist()?; + self.validate_events() + } + + /// `events` names each [`Event`] at most once, and a list needs `api` 2 or later and the + /// permission `events`, which needs a list. + fn validate_events(&self) -> Result<()> { + for (i, name) in self.events.iter().enumerate() { + let shown = permissions::display_text(name, permissions::MAX_SHOWN_FIELD); + if Event::parse(name).is_none() { + return Err(Error::Manifest(format!( + "`events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed" + ))); + } + if self.events.get(..i).is_some_and(|before| before.contains(name)) { + return Err(Error::Manifest(format!("`events` lists `{shown}` twice"))); + } + } + let listed = self.permissions.as_ref().is_some_and(|p| p.iter().any(|n| n == Permission::Events.name())); + if self.events.is_empty() == listed { + return Err(Error::Manifest("`events` needs the permission `events`, and `events` needs a list of `events`".into())); + } + if listed && self.api < EVENTS_API { + return Err(Error::Manifest(format!("`events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API}"))); + } + Ok(()) + } + + /// The events it reacts to (`events`). + pub fn event_kinds(&self) -> Vec { + self.events.iter().filter_map(|n| Event::parse(n)).collect() + } + + /// Does it react to `event`? + pub fn reacts_to(&self, event: Event) -> bool { + self.events.iter().any(|n| n == event.name()) } /// `commandAllowlist` lists at most [`MAX_ALLOWED_COMMANDS`] distinct command ids @@ -733,6 +775,17 @@ fn input_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result>(d: D) -> std::result::Result, D::Error> { + let wrong = || serde::de::Error::custom("`events` must be a list of event names, such as selection.changed"); + match Value::deserialize(d)? { + Value::Null => Ok(Vec::new()), + Value::Array(names) => names.into_iter().map(|n| if let Value::String(s) = n { Ok(s) } else { Err(wrong()) }).collect(), + _ => Err(wrong()), + } +} + /// Reads the `commands` list one entry at a time from the manifest itself, so each command's /// `params` keep their declaration order and a repeated parameter is refused. A malformed entry /// is an error that names it (its id when the id comes before the fault, otherwise its place in @@ -1394,6 +1447,52 @@ mod tests { assert!(Manifest::parse(manifest(MAX_PARAMS + 1, MAX_PARAMS).as_bytes()).is_err(), "too many in all"); } + /// Any kind at `api` 2 that lists the permission `events` names the events it reacts to; an + /// unknown or repeated name, a list without the permission or the permission without a list, + /// and a list at `api` 1 are refused, and the error names the fault. + #[test] + fn events_are_listed_with_their_permission_at_api_2() { + let m = Manifest::parse( + br#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":["layer.changed","selection.changed"]}"#, + ) + .unwrap(); + assert_eq!(m.event_kinds(), [Event::LayerChanged, Event::SelectionChanged]); + assert!(m.reacts_to(Event::SelectionChanged) && !m.reacts_to(Event::DocumentSaved)); + assert_eq!(m.permissions(), [Permission::Events]); + assert_eq!(serde_json::to_value(&m).unwrap()["events"], json!(["layer.changed", "selection.changed"])); + let effect = + br#"{"id":"a","name":"x","kind":"effect","api":2,"permissions":["doc.read","effect.render","events"],"events":["document.saved"]}"#; + assert_eq!(Manifest::parse(effect).unwrap().event_kinds(), [Event::DocumentSaved]); + let importer = + br#"{"id":"a","name":"x","kind":"importer","api":2,"extensions":["q"],"permissions":["import.read","events"],"events":["document.opened"]}"#; + assert!(Manifest::parse(importer).is_ok()); + let plain = Manifest::parse(br#"{"id":"a","name":"x","kind":"filter","events":null}"#).unwrap(); + assert!(plain.events.is_empty() && serde_json::to_value(&plain).unwrap().get("events").is_none()); + for (bad, says) in [ + ( + r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":["selection.change"]}"#, + "unknown event `selection.change`", + ), + ( + r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":["layer.changed","layer.changed"]}"#, + "lists `layer.changed` twice", + ), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"events":["layer.changed"]}"#, "needs the permission `events`"), + ( + r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"events":["layer.changed"]}"#, + "needs the permission `events`", + ), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"]}"#, "needs the permission `events`"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":[]}"#, "needs the permission `events`"), + (r#"{"id":"a","name":"x","kind":"filter","permissions":["events"],"events":["layer.changed"]}"#, "needs plug-in API level 2"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":"layer.changed"}"#, "must be a list"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":[1]}"#, "must be a list"), + ] { + let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + } + #[test] fn rejects_bad_manifests() { for bad in [ diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index b8c8672693..01a0d00b3a 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -7,7 +7,8 @@ //! `permissions` gets the ones its kind implies ([`Permission::implied`]): what every plug-in of //! that kind could do before manifests listed them. `progress`, `settings`, `cache` and `commands`, //! which let a plug-in use the host imports of API level 2 ([`crate::host`]), are never implied: a -//! manifest lists them. +//! manifest lists them. Nor is `events`, which lets a plug-in of any kind react to the events its +//! manifest names ([`crate::events`]). use serde::{Deserialize, Serialize}; @@ -74,10 +75,14 @@ pub enum Permission { /// ([`crate::host::IMPORTS`]): a filter only. #[serde(rename = "commands")] Commands, + /// Run on its own after the changes its manifest's `events` names ([`crate::events`]), with + /// `vc_event`: any kind. + #[serde(rename = "events")] + Events, } /// Every permission this host grants, in the order prompts list them. -pub const ALL: [Permission; 10] = [ +pub const ALL: [Permission; 11] = [ Permission::DocRead, Permission::DocWrite, Permission::State, @@ -88,6 +93,7 @@ pub const ALL: [Permission; 10] = [ Permission::Settings, Permission::Cache, Permission::Commands, + Permission::Events, ]; /// The permissions of the host imports, which any kind may list and none implies; each needs plug-in @@ -109,6 +115,7 @@ impl Permission { Permission::Settings => "settings", Permission::Cache => "cache", Permission::Commands => "commands", + Permission::Events => "events", } } @@ -130,13 +137,14 @@ impl Permission { Permission::Settings => "Keep settings of its own", Permission::Cache => "Keep a cache of its own, which you can clear", Permission::Commands => "Run these commands", + Permission::Events => "Run on its own when the selection, a document or a layer changes", } } /// May a plug-in of `kind` that declares `commands` or not list it: one [`Permission::allowed`] - /// gives it, or one of the host imports' ([`HOST`]), which any kind may list. + /// gives it, one of the host imports' ([`HOST`]) or `events`, which any kind may list. pub fn applies(self, kind: Kind, commands: bool) -> bool { - HOST.contains(&self) || Permission::allowed(kind, commands).contains(&self) + self == Permission::Events || HOST.contains(&self) || Permission::allowed(kind, commands).contains(&self) } /// The permissions a manifest of `kind` without `permissions` gets. A manifest may also list diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 7c4262dd4e..699fe15161 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -219,6 +219,9 @@ fn wasm_err(e: wasmi::Error) -> Error { /// `vc_run(input_ptr, input_len, params_ptr, params_len) -> len << 32 | ptr` (negative: error). type RunArgs = (i32, i32, i32, i32); +/// `vc_event(event_ptr, event_len) -> 0` (anything else: the handler failed). +type EventArgs = (i32, i32); + impl Plugin { /// Validates and loads a module: checks the ABI version, the exports and reads the manifest, and /// checks that each host import it asks for is one the host offers ([`crate::host::IMPORTS`]) @@ -269,6 +272,9 @@ impl Plugin { // The other exports must exist with the right types. live.func::("vc_alloc")?; live.func::("vc_run")?; + if !p.manifest.events.is_empty() { + live.func::("vc_event")?; + } Ok(p) } @@ -315,13 +321,19 @@ impl Plugin { /// A new instance for `run`, with the host imports of the permissions `granted` linked. When the /// module's start function fails, what it reported through the host imports goes to `report`. fn instantiate(&self, run: Run, granted: &[Permission], report: &mut Report) -> Result { + self.instantiate_with(run, granted, report, self.limits.fuel_base) + } + + /// [`Plugin::instantiate`] with the start function given at most `start_fuel` instructions; + /// the instance's store holds what it left. + fn instantiate_with(&self, run: Run, granted: &[Permission], report: &mut Report, start_fuel: u64) -> Result { let limits = StoreLimitsBuilder::new().memory_size(self.limits.max_memory_bytes).memories(1).tables(4).table_elements(100_000).instances(1).build(); let mut store = Store::new(&self.engine, Host { limits, run }); store.limiter(|h| &mut h.limits); // The start function (if any) runs on one slice of fuel: it runs before `call` can check // the deadline or a cancel between slices, so a heavy budget would let it run for minutes. - store.set_fuel(self.limits.fuel_base.min(FUEL_SLICE)).map_err(wasm_err)?; + store.set_fuel(start_fuel.min(FUEL_SLICE)).map_err(wasm_err)?; let linker = host::linker(&self.engine, granted); let instance = match linker.instantiate_and_start(&mut store, &self.module) { Ok(instance) => instance, @@ -360,16 +372,34 @@ impl Plugin { params: P, fuel: u64, deadline: &Deadline, + bridge: Option<&mut Bridge<'_>>, + ) -> Result { + let mut budget = fuel; + self.call_budget(live, f, params, &mut budget, deadline, bridge) + } + + /// [`Plugin::call_with`] on at most `budget` instructions, which holds what the call left + /// unused when it returns `Ok`, for the next call to share. + fn call_budget( + &self, + live: &mut Live, + f: &TypedFunc, + params: P, + budget: &mut u64, + deadline: &Deadline, mut bridge: Option<&mut Bridge<'_>>, ) -> Result { - let mut left = fuel; + let mut left = *budget; let give = left.min(FUEL_SLICE); left -= give; live.store.set_fuel(give).map_err(wasm_err)?; let mut call = slice(live, &mut left, |store| f.call_resumable(store, params))?; loop { match call { - TypedResumableCall::Finished(r) => return Ok(r), + TypedResumableCall::Finished(r) => { + *budget = left.saturating_add(live.store.get_fuel().map_err(wasm_err)?); + return Ok(r); + } TypedResumableCall::HostTrap(inv) => { if inv.host_error().downcast_ref::().is_some() { return Err(stop_reason(&mut live.store)); @@ -505,4 +535,72 @@ impl Plugin { } live.read_packed(packed, "the output", limits.max_output_bytes) } + + /// Its limits for one event handler: at most [`crate::events::EVENT_FUEL`] instructions and + /// [`crate::events::EVENT_WALL_TIME_MS`], or its own budgets when they are smaller, and every + /// other limit as it is. + pub fn event_limits(&self) -> Limits { + Limits { + fuel_base: self.limits.fuel_base.min(crate::events::EVENT_FUEL), + wall_time_ms: self.limits.wall_time_ms.min(crate::events::EVENT_WALL_TIME_MS), + ..self.limits.clone() + } + } + + /// Calls `vc_event` with `event` (the event JSON) in a fresh instance under + /// [`Plugin::event_limits`] → `Ok` when it returned 0, and what it reported through the host + /// imports. With `bridge`, each `vc_call` of a command its `commandAllowlist` names is made with + /// it; a failed call fails the handler. A module that doesn't react to events, an event past + /// [`crate::events::MAX_EVENT_BYTES`] and Safe Mode run nothing. + pub fn run_event(&self, event: &[u8], bridge: Option<&mut Bridge<'_>>) -> (Result<()>, Report) { + let mut report = Report::default(); + if let Err(e) = crate::safe_mode::check() { + return (Err(e), report); + } + if self.manifest.events.is_empty() { + return (Err(Error::Abi("the module reacts to no events".into())), report); + } + if event.len() > crate::events::MAX_EVENT_BYTES { + let (len, max) = (event.len(), crate::events::MAX_EVENT_BYTES); + return (Err(Error::Limit(format!("event size ({len} bytes, limit {max})"))), report); + } + let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.event_inner(event, &mut report, bridge))); + (run.map_err(|_| Error::Trap("the runtime panicked".into())).and_then(|r| r), report) + } + + fn event_inner(&self, event: &[u8], report: &mut Report, bridge: Option<&mut Bridge<'_>>) -> Result<()> { + let limits = self.event_limits(); + let deadline = Deadline::new(limits.wall_time_ms); + let m = &self.manifest; + let run = Run::new(&m.id, false, true, deadline).with_storage(crate::registry::storage(&m.id)); + let mut live = self.instantiate_with(run, &m.permissions(), report, limits.fuel_base)?; + // The start function, `vc_alloc` and `vc_event` share the one budget. + let mut budget = live.store.get_fuel().map_err(wasm_err)?; + if bridge.is_some() { + live.store.data_mut().run.allow_calls(m.command_allowlist.clone()); + } + let out = (|| { + let alloc: TypedFunc = live.func("vc_alloc")?; + let handler: TypedFunc = live.func("vc_event")?; + let ptr = self.call_budget(&mut live, &alloc, event.len().max(1) as i32, &mut budget, &deadline, None)? as u32 as usize; + if ptr == 0 { + return Err(Error::Failed("vc_alloc returned 0 (out of memory)".into())); + } + let outside = || Error::Abi("vc_alloc returned a block outside memory".into()); + let end = ptr.checked_add(event.len()).ok_or_else(outside)?; + live.memory.data_mut(&mut live.store).get_mut(ptr..end).ok_or_else(outside)?.copy_from_slice(event); + let code = self.call_budget(&mut live, &handler, (ptr as i32, event.len() as i32), &mut budget, &deadline, bridge)?; + deadline.check()?; + if code != 0 { + return Err(Error::Failed(format!("vc_event returned {code}"))); + } + Ok(()) + })(); + let state = &mut live.store.data_mut().run; + *report = std::mem::take(&mut state.report); + match (state.call_failure.take(), out) { + (Some(e), _) => Err(e), + (None, out) => out, + } + } } diff --git a/crates/plugins/src/wat.rs b/crates/plugins/src/wat.rs index 936d5d9e53..a1348242d7 100644 --- a/crates/plugins/src/wat.rs +++ b/crates/plugins/src/wat.rs @@ -34,6 +34,18 @@ pub fn module(manifest: &str, run: &str, extra: &str, pages: u32) -> String { /// A `vc_run` body returning the input unchanged. pub const ECHO: &str = "(i64.or (i64.shl (i64.extend_i32_u (local.get $il)) (i64.const 32)) (i64.extend_i32_u (local.get $in)))"; +/// A plug-in that reacts to events ([`crate::events`]): `manifest` (JSON that lists `events`), the +/// module fields `imports` before the others, a `vc_event` whose body is `handler` (parameters +/// `$ep $el`, result i32) and a `vc_run` that returns its input. +pub fn reacting(manifest: &str, imports: &str, handler: &str) -> String { + let extra = format!(r#"{imports} (func (export "vc_event") (param $ep i32) (param $el i32) (result i32) {handler})"#); + module(manifest, ECHO, &extra, 1) +} + +/// A `vc_event` body that writes the event it is given as an information log line (with +/// [`HOST_IMPORTS`]) and returns 0. +pub const LOG_EVENT: &str = "(drop (call $vc_log (i32.const 2) (local.get $ep) (local.get $el))) (i32.const 0)"; + /// A plug-in that always returns `output` (whatever it is given). pub fn returning(manifest: &str, output: &str) -> String { then_returning(manifest, "", output) diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index f4cb2e103b..bb28afd450 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -1025,6 +1025,79 @@ fn a_plugin_reaches_only_its_own_storage() { registry::set_storage("test.storage.theirs", None); } +/// The manifest of an event plug-in `id` that writes log lines and reacts to `events` (JSON list). +fn reacting_manifest(id: &str, events: &str) -> String { + format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":["progress","events"],"events":{events}}}"#) +} + +/// A module that lists `events` needs a `vc_event` export of the right type; one that lists none +/// may leave it out. +#[test] +fn an_event_plugin_exports_vc_event() { + let manifest = reacting_manifest("test.events.export", r#"["selection.changed"]"#); + let e = Plugin::load(&build(&tpl::reporting(&manifest, "", INPUT)), Limits::default()).unwrap_err(); + assert!(e.to_string().contains("vc_event"), "{e}"); + let wrong = format!(r#"{} (func (export "vc_event") (param i32) (result i32) (i32.const 0))"#, tpl::HOST_IMPORTS); + let e = Plugin::load(&build(&tpl::module(&manifest, tpl::ECHO, &wrong, 1)), Limits::default()).unwrap_err(); + assert!(e.to_string().contains("vc_event"), "{e}"); + assert!(Plugin::load(&build(&tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)), Limits::default()).is_ok()); + assert!(Plugin::load(&ok_module(tpl::ECHO), Limits::default()).is_ok(), "no events, no vc_event"); +} + +/// `vc_event` is given the event JSON in its own memory and returns 0; anything else, a trap and a +/// handler past its instruction budget fail it. A module without events runs no handler. +#[test] +fn vc_event_is_given_the_event_and_its_code_is_checked() { + let manifest = reacting_manifest("test.events.run", r#"["layer.changed"]"#); + let p = Plugin::load(&build(&tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)), Limits::default()).unwrap(); + let event = br#"{"type":"layer.changed","document":7}"#; + let (r, report) = p.run_event(event, None); + r.unwrap(); + assert_eq!(report.lines.iter().map(|l| l.text.as_str()).collect::>(), [std::str::from_utf8(event).unwrap()]); + for (handler, says) in [ + ("(i32.const 3)", "vc_event returned 3"), + ("unreachable", "trapped"), + // The instruction budget, or the time budget on a loaded machine. + ("(loop $l (br $l)) (i32.const 0)", "budget"), + ] { + let p = Plugin::load(&build(&tpl::reacting(&manifest, tpl::HOST_IMPORTS, handler)), Limits::default()).unwrap(); + let e = p.run_event(event, None).0.unwrap_err().to_string(); + assert!(e.contains(says), "{handler}: {e}"); + } + let e = p.run_event(&vec![b' '; vectorcraft_plugins::events::MAX_EVENT_BYTES + 1], None).0.unwrap_err(); + assert!(e.to_string().contains("event size"), "{e}"); + let plain = Plugin::load(&ok_module(tpl::ECHO), Limits::default()).unwrap(); + assert!(plain.run_event(event, None).0.is_err()); + let limits = p.event_limits(); + assert_eq!((limits.fuel_base, limits.wall_time_ms), (vectorcraft_plugins::events::EVENT_FUEL, vectorcraft_plugins::events::EVENT_WALL_TIME_MS)); +} + +/// The start function, `vc_alloc` and `vc_event` share one event budget: work that fits it in the +/// handler alone fits it no longer when the start function has done as much first. +#[test] +fn a_handler_and_its_start_function_share_the_event_budget() { + let manifest = reacting_manifest("test.events.shared", r#"["layer.changed"]"#); + let burn = r#"(func $burn (param $k i32) (block $b (loop $l + (br_if $b (i32.eqz (local.get $k))) + (local.set $k (i32.sub (local.get $k) (i32.const 1))) + (br $l))))"#; + let plugin = |start: u32, handler: u32| { + let imports = format!("{} {burn} (func $s (call $burn (i32.const {start}))) (start $s)", tpl::HOST_IMPORTS); + let body = format!("(call $burn (i32.const {handler})) (i32.const 0)"); + Plugin::load(&build(&tpl::reacting(&manifest, &imports, &body)), Limits::default()).unwrap() + }; + let event = br#"{"type":"layer.changed","document":1}"#; + // The most loop turns, doubling, that fit the budget in the handler alone: twice as many don't. + let mut k = 1u32 << 16; + while plugin(0, k * 2).run_event(event, None).0.is_ok() { + k *= 2; + assert!(k < 1 << 30, "a handler that never runs out of its budget"); + } + assert!(plugin(0, k).run_event(event, None).0.is_ok()); + let e = plugin(k, k).run_event(event, None).0.unwrap_err().to_string(); + assert!(e.contains("budget"), "{e}"); +} + /// A heavy filter installs once the user agrees, which loading a folder doesn't ask: it is skipped /// and reported. #[test] diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba6a5d83d..79296d8b40 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -55,6 +55,9 @@ impl VectorcraftApp { session.place_cursor_requests = true; // A script runs a slice per frame, so the window keeps drawing and Stop can be pressed. session.script_frames = true; + // Plug-in events are delivered by the frame: after the work that finished in the + // background, and at the end of the UI pass ([`VectorcraftApp::deliver_plugin_events`]). + session.plugin_event_frames = true; let views = session.documents().iter().map(View::of).collect(); let view_uids = session.documents().iter().map(|d| d.uid).collect(); let known = session.documents().iter().map(|d| d.uid).collect(); @@ -270,6 +273,25 @@ impl VectorcraftApp { plugin_runs::poll(self); trace_runs::poll(self); placing::poll(self); + let _ = 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. + fn deliver_plugin_events(&mut self) -> bool { + 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 name = vectorcraft_plugins::permissions::display_text(&n.name, vectorcraft_plugins::permissions::MAX_SHOWN_NAME); + self.status(format!("{name}: {}", n.text)); + true } /// The language the UI is drawn in: the Preferences dialog's choice while it is open (so a @@ -362,8 +384,14 @@ impl VectorcraftApp { // them, even if the worker below finishes them during this same tick. ctx.data_mut(|d| d.insert_temp(egui::Id::unique("clipboard.pending-at-tick"), self.clipboard_publishing.is_pending())); screen_color::poll(self, ctx); + let script_was_running = self.session.script_running(); self.poll_finished_work(); 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(); + } // A panel's, a dialog's or the text input's commit journaled in the frame before. crate::panels::actions::after_journaled_edit(self); crate::scripts_menu::poll(self, ctx); @@ -670,6 +698,12 @@ impl VectorcraftApp { // A command run by a menu, panel or dialog in this pass may have queued its text copy // after the UI phase's input flush. Publish it now for the same reason as there. self.flush_clipboard_out(&ctx); + // What the canvas, a panel or a dialog changed in this pass reaches the plug-ins that react + // to it now, since an idle app draws no further frame; a line a handler wrote shows in the + // next one. + if !self.session.script_running() && self.deliver_plugin_events() { + ctx.request_repaint(); + } if opening::long_operation_busy(self) { ctx.set_cursor_icon(egui::CursorIcon::Progress); } diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 4561f3dc73..0f4fb39940 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -720,6 +720,7 @@ impl PluginIntField { paint_output: false, commands: Vec::new(), command_allowlist: Vec::new(), + events: Vec::new(), }; let mut f = PluginIntField { ctx, d: Dialog::new(plugin::KIND, json!({ "seed": start })), m, pos: egui::Pos2::ZERO }; fn number_rect(shape: &egui::Shape, text: &str) -> Option { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..4014b51fc8 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6690,6 +6690,7 @@ axis Y Axis Y ос Show its progress, see Cancel and write log lines Показване на напредъка, разпознаване на отказ и записване на редове в дневника Keep settings of its own Съхраняване на собствени настройки Keep a cache of its own, which you can clear Съхраняване на собствен кеш, който можете да изчистите + Run on its own when the selection, a document or a layer changes Изпълняване самостоятелно, когато се промени селекцията, документ или слой Run these commands on the document: {ids} Изпълняване на тези команди върху документа: {ids} Clear Plug-in Cache Изчистване на кеша на добавката # Actions panel: action sets (#3712). diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..84fecd5884 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6718,6 +6718,7 @@ axis Y Axis Y osa Show its progress, see Cancel and write log lines Prikazati napredak, prepoznati otkazivanje i zapisivati redove dnevnika Keep settings of its own Čuvati vlastite postavke Keep a cache of its own, which you can clear Čuvati vlastitu predmemoriju koju možete očistiti + Run on its own when the selection, a document or a layer changes Pokretati se samostalno kada se promijeni odabir, dokument ili sloj Run these commands on the document: {ids} Izvršavati ove naredbe na dokumentu: {ids} Clear Plug-in Cache Očisti predmemoriju dodatka @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} dozvola `{permission}` zahtijeva nivo API-ja dodataka {PROGRESS_API}: navedite `api` {PROGRESS_API} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..f2a186f792 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7842,6 +7842,7 @@ variable-list-end {0}, {1} {0} i {1} Show its progress, see Cancel and write log lines Mostrar el progrés, detectar la cancel·lació i escriure línies de registre Keep settings of its own Desar una configuració pròpia Keep a cache of its own, which you can clear Desar una memòria cau pròpia, que podeu buidar + Run on its own when the selection, a document or a layer changes Executar-se per si sol quan canvia la selecció, un document o una capa Run these commands on the document: {ids} Executar aquestes ordres al document: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call «{name}» inclou `{id}` a `commandAllowlist`, que un complement no pot cridar @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7873,6 +7874,15 @@ variable-list-end {0}, {1} {0} i {1} @msg only a filter declares `inputs` només un filtre declara `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` anomena un tipus d’objecte desconegut `{shown}`: feu servir type, image o symbolInstance @msg `inputs` lists `{shown}` twice `inputs` inclou `{shown}` dues vegades +@msg `events` lists `{shown}` twice `events` inclou `{shown}` dues vegades +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` anomena un esdeveniment desconegut `{shown}`: feu servir selection.changed, document.opened, document.saved o layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` necessita el nivell d’API de complements {EVENTS_API}: indiqueu `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` necessita el permís `events`, i `events` necessita una llista d’`events` +@msg event size ({len} bytes, limit {max}) mida de l’esdeveniment ({len} bytes, límit {max}) +@msg the module reacts to no events el mòdul no reacciona a cap esdeveniment +@msg vc_event returned {code} vc_event ha retornat {code} +@msg {name}: its {event} handler failed: {e} {name}: el seu gestor de {event} ha fallat: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: els seus esdeveniments estan desactivats fins que VectorCraft torni a iniciar-se, després de {count} gestors fallits seguits @msg `inputs` needs `api` 2 or later `inputs` requereix `api` 2 o posterior @msg `inputs` needs the permission `doc.read` `inputs` requereix el permís `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) pressupost de memòria (l’objecte {_1} necessita {size} bytes d’entrada, en queden {left}) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..394d8b42a7 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7452,6 +7452,7 @@ axis Y Axis osa Y Show its progress, see Cancel and write log lines Zobrazit průběh, rozpoznat zrušení a zapisovat řádky protokolu Keep settings of its own Uchovávat vlastní nastavení Keep a cache of its own, which you can clear Uchovávat vlastní mezipaměť, kterou můžete vymazat + Run on its own when the selection, a document or a layer changes Spouštět se samostatně, když se změní výběr, dokument nebo vrstva Run these commands on the document: {ids} Spouštět v dokumentu tyto příkazy: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ uvádí v `commandAllowlist` příkaz `{id}`, který zásuvný modul nesmí volat @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7483,6 +7484,15 @@ axis Y Axis osa Y @msg only a filter declares `inputs` `inputs` deklaruje pouze filtr @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` uvádí neznámý druh objektu `{shown}`: použijte type, image nebo symbolInstance @msg `inputs` lists `{shown}` twice `inputs` uvádí `{shown}` dvakrát +@msg `events` lists `{shown}` twice `events` uvádí `{shown}` dvakrát +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` uvádí neznámou událost `{shown}`: použijte selection.changed, document.opened, document.saved nebo layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` vyžaduje úroveň API zásuvných modulů {EVENTS_API}: uveďte `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` potřebuje oprávnění `events` a `events` potřebuje seznam `events` +@msg event size ({len} bytes, limit {max}) velikost události ({len} bajtů, limit {max}) +@msg the module reacts to no events modul nereaguje na žádné události +@msg vc_event returned {code} vc_event vrátila {code} +@msg {name}: its {event} handler failed: {e} {name}: jeho obslužná rutina {event} selhala: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: jeho události jsou vypnuté, dokud se VectorCraft znovu nespustí, po {count} neúspěšných obslužných rutinách za sebou @msg `inputs` needs `api` 2 or later `inputs` vyžaduje `api` 2 nebo vyšší @msg `inputs` needs the permission `doc.read` `inputs` vyžaduje oprávnění `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) rozpočet paměti (objekt {_1} potřebuje {size} bajtů vstupu, zbývá {left}) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..b8415a4299 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -695,6 +695,15 @@ liquify-list-end {0}, {1} {0} og {1} @msg only a filter declares `inputs` kun et filter angiver `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` angiver en ukendt objekttype `{shown}`: brug type, image eller symbolInstance @msg `inputs` lists `{shown}` twice `inputs` angiver `{shown}` to gange +@msg `events` lists `{shown}` twice `events` angiver `{shown}` to gange +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` angiver en ukendt hændelse `{shown}`: brug selection.changed, document.opened, document.saved eller layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` kræver plug-in-API-niveau {EVENTS_API}: angiv `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` kræver tilladelsen `events`, og `events` kræver en liste `events` +@msg event size ({len} bytes, limit {max}) hændelsesstørrelse ({len} byte, grænse {max}) +@msg the module reacts to no events modulet reagerer ikke på nogen hændelser +@msg vc_event returned {code} vc_event returnerede {code} +@msg {name}: its {event} handler failed: {e} {name}: dens {event}-handler mislykkedes: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: dens hændelser er slået fra, indtil VectorCraft starter igen, efter {count} mislykkede handlere i træk @msg `inputs` needs `api` 2 or later `inputs` kræver `api` 2 eller nyere @msg `inputs` needs the permission `doc.read` `inputs` kræver tilladelsen `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) hukommelsesbudget (objekt {_1} kræver {size} byte input, {left} tilbage) @@ -9609,6 +9618,7 @@ axis Y Axis Y-akse Show its progress, see Cancel and write log lines Vise sin fremdrift, se en annullering og skrive logrækker Keep settings of its own Gemme sine egne indstillinger Keep a cache of its own, which you can clear Gemme sin egen cache, som du kan rydde + Run on its own when the selection, a document or a layer changes Køre af sig selv, når markeringen, et dokument eller et lag ændres Run these commands on the document: {ids} Køre disse kommandoer på dokumentet: {ids} Clear Plug-in Cache Ryd plug-in-cache # Actions panel: action sets (#3712). diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..99a8424807 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -7035,6 +7035,7 @@ axis Y Axis Y-Achse Show its progress, see Cancel and write log lines Den Fortschritt anzeigen, ein Abbrechen erkennen und Protokollzeilen schreiben Keep settings of its own Eigene Einstellungen speichern Keep a cache of its own, which you can clear Einen eigenen Cache anlegen, den Sie leeren können + Run on its own when the selection, a document or a layer changes Von selbst ausgeführt werden, wenn sich die Auswahl, ein Dokument oder eine Ebene ändert Run these commands on the document: {ids} Diese Befehle im Dokument ausführen: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ führt `{id}` in `commandAllowlist` auf, den ein Plug-in nicht aufrufen darf @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7066,6 +7067,15 @@ axis Y Axis Y-Achse @msg only a filter declares `inputs` nur ein Filter deklariert `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` nennt eine unbekannte Objektart `{shown}`: verwenden Sie type, image oder symbolInstance @msg `inputs` lists `{shown}` twice `inputs` führt `{shown}` doppelt auf +@msg `events` lists `{shown}` twice `events` führt `{shown}` doppelt auf +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` nennt ein unbekanntes Ereignis `{shown}`: verwenden Sie selection.changed, document.opened, document.saved oder layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` braucht die Plug-in-API-Stufe {EVENTS_API}: Geben Sie `api` {EVENTS_API} an +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` braucht die Berechtigung `events`, und `events` braucht eine Liste `events` +@msg event size ({len} bytes, limit {max}) Ereignisgröße ({len} Byte, Grenze {max}) +@msg the module reacts to no events das Modul reagiert auf keine Ereignisse +@msg vc_event returned {code} vc_event hat {code} zurückgegeben +@msg {name}: its {event} handler failed: {e} {name}: sein Handler für {event} ist fehlgeschlagen: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: seine Ereignisse sind aus, bis VectorCraft neu startet, nach {count} fehlgeschlagenen Handlern in Folge @msg `inputs` needs `api` 2 or later `inputs` erfordert `api` 2 oder höher @msg `inputs` needs the permission `doc.read` `inputs` erfordert die Berechtigung `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) Speicherbudget (Objekt {_1} benötigt {size} Byte Eingabe, {left} verbleiben) diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..34be251bb2 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7442,6 +7442,7 @@ axis Y Axis Άξονας Y Show its progress, see Cancel and write log lines Εμφάνιση της προόδου, αναγνώριση της ακύρωσης και εγγραφή γραμμών καταγραφής Keep settings of its own Διατήρηση δικών του ρυθμίσεων Keep a cache of its own, which you can clear Διατήρηση δικής του κρυφής μνήμης, την οποία μπορείτε να εκκαθαρίσετε + Run on its own when the selection, a document or a layer changes Εκτέλεση από μόνο του όταν αλλάζει η επιλογή, ένα έγγραφο ή ένα επίπεδο Run these commands on the document: {ids} Εκτέλεση αυτών των εντολών στο έγγραφο: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call το «{name}» αναφέρει το `{id}` στο `commandAllowlist`, το οποίο ένα πρόσθετο δεν επιτρέπεται να καλέσει @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7473,6 +7474,15 @@ axis Y Axis Άξονας Y @msg only a filter declares `inputs` μόνο ένα φίλτρο δηλώνει `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance το `inputs` αναφέρει άγνωστο είδος αντικειμένου `{shown}`: χρησιμοποιήστε type, image ή symbolInstance @msg `inputs` lists `{shown}` twice το `inputs` αναφέρει το `{shown}` δύο φορές +@msg `events` lists `{shown}` twice το `events` αναφέρει το `{shown}` δύο φορές +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed το `events` αναφέρει άγνωστο συμβάν `{shown}`: χρησιμοποιήστε selection.changed, document.opened, document.saved ή layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} το `events` χρειάζεται το επίπεδο API προσθέτων {EVENTS_API}: δώστε `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` το `events` χρειάζεται το δικαίωμα `events`, και το `events` χρειάζεται μια λίστα `events` +@msg event size ({len} bytes, limit {max}) μέγεθος συμβάντος ({len} byte, όριο {max}) +@msg the module reacts to no events η λειτουργική μονάδα δεν αντιδρά σε κανένα συμβάν +@msg vc_event returned {code} η vc_event επέστρεψε {code} +@msg {name}: its {event} handler failed: {e} {name}: ο χειριστής {event} του απέτυχε: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: τα συμβάντα του είναι απενεργοποιημένα μέχρι να ξεκινήσει ξανά το VectorCraft, μετά από {count} αποτυχημένους χειριστές στη σειρά @msg `inputs` needs `api` 2 or later το `inputs` απαιτεί `api` 2 ή νεότερο @msg `inputs` needs the permission `doc.read` το `inputs` απαιτεί το δικαίωμα `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) προϋπολογισμός μνήμης (το αντικείμενο {_1} χρειάζεται {size} byte εισόδου, απομένουν {left}) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..3e8a481554 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7428,6 +7428,7 @@ axis Y Axis Eje Y Show its progress, see Cancel and write log lines Mostrar su progreso, detectar la cancelación y escribir líneas de registro Keep settings of its own Guardar una configuración propia Keep a cache of its own, which you can clear Guardar una caché propia, que usted puede vaciar + Run on its own when the selection, a document or a layer changes Ejecutarse por sí solo cuando cambia la selección, un documento o una capa Run these commands on the document: {ids} Ejecutar estos comandos en el documento: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” incluye `{id}` en `commandAllowlist`, que un plugin no puede llamar @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7459,6 +7460,15 @@ axis Y Axis Eje Y @msg only a filter declares `inputs` solo un filtro declara `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` nombra un tipo de objeto desconocido `{shown}`: use type, image o symbolInstance @msg `inputs` lists `{shown}` twice `inputs` incluye `{shown}` dos veces +@msg `events` lists `{shown}` twice `events` incluye `{shown}` dos veces +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` nombra un evento desconocido `{shown}`: use selection.changed, document.opened, document.saved o layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` necesita el nivel de API de plugins {EVENTS_API}: indique `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` necesita el permiso `events`, y `events` necesita una lista de `events` +@msg event size ({len} bytes, limit {max}) tamaño del evento ({len} bytes, límite {max}) +@msg the module reacts to no events el módulo no reacciona a ningún evento +@msg vc_event returned {code} vc_event devolvió {code} +@msg {name}: its {event} handler failed: {e} {name}: su controlador de {event} falló: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: sus eventos están desactivados hasta que VectorCraft se inicie de nuevo, tras {count} controladores fallidos seguidos @msg `inputs` needs `api` 2 or later `inputs` requiere `api` 2 o posterior @msg `inputs` needs the permission `doc.read` `inputs` requiere el permiso `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) presupuesto de memoria (el objeto {_1} necesita {size} bytes de entrada, quedan {left}) diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..8324910fae 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7519,6 +7519,7 @@ axis Y Axis Y-akseli Show its progress, see Cancel and write log lines Näyttää edistymisensä, havaita peruutuksen ja kirjoittaa lokirivejä Keep settings of its own Säilyttää omat asetuksensa Keep a cache of its own, which you can clear Säilyttää oman välimuistin, jonka voit tyhjentää + Run on its own when the selection, a document or a layer changes Käynnistyä itsestään, kun valinta, asiakirja tai taso muuttuu Run these commands on the document: {ids} Suorittaa nämä komennot asiakirjassa: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call ”{name}” luettelee `commandAllowlist`-luettelossa komennon `{id}`, jota laajennus ei saa kutsua @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7550,6 +7551,15 @@ axis Y Axis Y-akseli @msg only a filter declares `inputs` vain suodatin voi määrittää `inputs`-avaimen @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` nimeää tuntemattoman objektilajin `{shown}`: käytä arvoa type, image tai symbolInstance @msg `inputs` lists `{shown}` twice `inputs` luettelee kohteen `{shown}` kahdesti +@msg `events` lists `{shown}` twice `events` luettelee kohteen `{shown}` kahdesti +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` nimeää tuntemattoman tapahtuman `{shown}`: käytä arvoa selection.changed, document.opened, document.saved tai layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` vaatii laajennus-API:n tason {EVENTS_API}: anna `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` tarvitsee käyttöoikeuden `events`, ja `events` tarvitsee `events`-luettelon +@msg event size ({len} bytes, limit {max}) tapahtuman koko ({len} tavua, raja {max}) +@msg the module reacts to no events moduuli ei reagoi mihinkään tapahtumaan +@msg vc_event returned {code} vc_event palautti {code} +@msg {name}: its {event} handler failed: {e} {name}: sen {event}-käsittelijä epäonnistui: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: sen tapahtumat ovat pois päältä, kunnes VectorCraft käynnistyy uudelleen, {count} peräkkäin epäonnistuneen käsittelijän jälkeen @msg `inputs` needs `api` 2 or later `inputs` edellyttää `api`-tasoa 2 tai uudempaa @msg `inputs` needs the permission `doc.read` `inputs` edellyttää käyttöoikeutta `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) muistibudjetti (objekti {_1} tarvitsee {size} tavua syötettä, jäljellä {left}) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..84b857b264 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7448,6 +7448,7 @@ axis Y Axis Axe Y Show its progress, see Cancel and write log lines Afficher sa progression, détecter l’annulation et écrire des lignes de journal Keep settings of its own Conserver ses propres réglages Keep a cache of its own, which you can clear Conserver son propre cache, que vous pouvez vider + Run on its own when the selection, a document or a layer changes S’exécuter de lui-même quand la sélection, un document ou un calque change Run these commands on the document: {ids} Exécuter ces commandes sur le document : {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call « {name} » indique `{id}` dans `commandAllowlist`, qu’un module externe ne peut pas appeler @msg vc_call `{shown}`: {why} vc_call `{shown}` : {why} @@ -7480,6 +7481,15 @@ axis Y Axis Axe Y @msg only a filter declares `inputs` seul un filtre déclare `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` désigne un type d’objet inconnu `{shown}` : utilisez type, image ou symbolInstance @msg `inputs` lists `{shown}` twice `inputs` mentionne `{shown}` deux fois +@msg `events` lists `{shown}` twice `events` mentionne `{shown}` deux fois +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` désigne un événement inconnu `{shown}`, utilisez selection.changed, document.opened, document.saved ou layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` nécessite le niveau d’API de module externe {EVENTS_API}, indiquez `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` a besoin de l’autorisation `events`, et `events` a besoin d’une liste `events` +@msg event size ({len} bytes, limit {max}) taille de l’événement ({len} octets, limite {max}) +@msg the module reacts to no events le module ne réagit à aucun événement +@msg vc_event returned {code} vc_event a renvoyé {code} +@msg {name}: its {event} handler failed: {e} {name} : son gestionnaire {event} a échoué : {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name} : ses événements sont désactivés jusqu’au prochain démarrage de VectorCraft, après {count} gestionnaires en échec d’affilée @msg `inputs` needs `api` 2 or later `inputs` nécessite `api` 2 ou plus @msg `inputs` needs the permission `doc.read` `inputs` nécessite l’autorisation `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) budget mémoire (l’objet {_1} nécessite {size} octets d’entrée, il en reste {left}) diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..69e14c4fd3 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2023,6 +2023,7 @@ Keep Shared Points Together વહેંચાયેલા પોઇન્ટ સાથે રાખો Keep Tools Beside the Canvas ટૂલ્સ કેનવાસની બાજુમાં રાખો Keep a cache of its own, which you can clear તેનું પોતાનું કેશ રાખો, જે તમે સાફ કરી શકો છો + Run on its own when the selection, a document or a layer changes પસંદગી, દસ્તાવેજ અથવા લેયર બદલાય ત્યારે આપમેળે ચાલો Keep a link to an image file instead of only embedding it ઇમેજ ફાઇલને ફક્ત એમ્બેડ કરવાને બદલે તેની લિંક રાખો Keep both sides the same width બંને બાજુ સમાન પહોળાઈ રાખો Keep data of its own with the document દસ્તાવેજ સાથે પોતાનો ડેટા રાખો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..e068bda2aa 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6636,6 +6636,7 @@ arrowhead Feather पंख Show its progress, see Cancel and write log lines अपनी प्रगति दिखाना, रद्द करने का अनुरोध देखना और लॉग पंक्तियाँ लिखना Keep settings of its own अपनी सेटिंग्स रखना Keep a cache of its own, which you can clear अपना कैश रखना, जिसे आप साफ़ कर सकते हैं + Run on its own when the selection, a document or a layer changes सिलेक्शन, कोई डॉक्यूमेंट या कोई लेयर बदलने पर अपने आप चलना Run these commands on the document: {ids} दस्तावेज़ पर ये कमांड चलाना: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” `commandAllowlist` में `{id}` सूचीबद्ध करता है, जिसे कोई प्लग-इन कॉल नहीं कर सकता @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -6667,6 +6668,15 @@ arrowhead Feather पंख @msg only a filter declares `inputs` केवल फ़िल्टर `inputs` घोषित करता है @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` में अज्ञात ऑब्जेक्ट प्रकार `{shown}` है: type, image या symbolInstance का उपयोग करें @msg `inputs` lists `{shown}` twice `inputs` में `{shown}` दो बार सूचीबद्ध है +@msg `events` lists `{shown}` twice `events` में `{shown}` दो बार सूचीबद्ध है +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` में अज्ञात इवेंट `{shown}` है: selection.changed, document.opened, document.saved या layer.changed का उपयोग करें +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` के लिए प्लग-इन API स्तर {EVENTS_API} चाहिए: `api` {EVENTS_API} दें +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` को `events` अनुमति चाहिए, और `events` को `events` की सूची चाहिए +@msg event size ({len} bytes, limit {max}) इवेंट का आकार ({len} बाइट्स, सीमा {max}) +@msg the module reacts to no events मॉड्यूल किसी भी इवेंट पर प्रतिक्रिया नहीं करता +@msg vc_event returned {code} vc_event ने {code} लौटाया +@msg {name}: its {event} handler failed: {e} {name}: इसका {event} हैंडलर विफल हुआ: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: लगातार {count} हैंडलर विफल होने के बाद, VectorCraft के फिर से शुरू होने तक इसके इवेंट बंद हैं @msg `inputs` needs `api` 2 or later `inputs` के लिए `api` 2 या बाद का स्तर आवश्यक है @msg `inputs` needs the permission `doc.read` `inputs` के लिए अनुमति `doc.read` आवश्यक है @msg memory budget (object {_1} needs {size} bytes of input, {left} left) मेमोरी बजट (ऑब्जेक्ट {_1} को इनपुट के {size} बाइट चाहिए, {left} शेष हैं) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..d2eaaf10b8 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7437,6 +7437,7 @@ axis Y Axis Y tengely Show its progress, see Cancel and write log lines Megjelenítheti az előrehaladását, észlelheti a megszakítást és naplósorokat írhat Keep settings of its own Saját beállításokat tárolhat Keep a cache of its own, which you can clear Saját gyorsítótárat tárolhat, amelyet Ön kiüríthet + Run on its own when the selection, a document or a layer changes Magától futhat, amikor a kijelölés, egy dokumentum vagy egy réteg megváltozik Run these commands on the document: {ids} Ezeket a parancsokat futtathatja a dokumentumon: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call a(z) „{name}” a(z) `{id}` parancsot sorolja fel a `commandAllowlist` listában, amelyet bővítmény nem hívhat meg @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7468,6 +7469,15 @@ axis Y Axis Y tengely @msg only a filter declares `inputs` `inputs` kulcsot csak szűrő adhat meg @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance az `inputs` ismeretlen objektumfajtát nevez meg: `{shown}`; használja a type, image vagy symbolInstance értéket @msg `inputs` lists `{shown}` twice az `inputs` kétszer sorolja fel ezt: `{shown}` +@msg `events` lists `{shown}` twice az `events` kétszer sorolja fel ezt: `{shown}` +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed az `events` ismeretlen eseményt nevez meg: `{shown}`; használja a selection.changed, document.opened, document.saved vagy layer.changed értéket +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} az `events` listához {EVENTS_API}. szintű bővítmény-API kell: adja meg az `api` {EVENTS_API} értéket +@msg `events` needs the permission `events`, and `events` needs a list of `events` az `events` listához az `events` engedély szükséges, az `events` engedélyhez pedig `events` lista +@msg event size ({len} bytes, limit {max}) esemény mérete ({len} bájt, korlát {max}) +@msg the module reacts to no events a modul egyetlen eseményre sem reagál +@msg vc_event returned {code} a vc_event {code} értéket adott vissza +@msg {name}: its {event} handler failed: {e} {name}: a(z) {event} kezelője sikertelen volt: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: az eseményei ki vannak kapcsolva a VectorCraft következő indításáig, {count} egymást követő sikertelen kezelő után @msg `inputs` needs `api` 2 or later az `inputs` használatához `api` 2 vagy újabb szükséges @msg `inputs` needs the permission `doc.read` az `inputs` használatához a(z) `doc.read` engedély szükséges @msg memory budget (object {_1} needs {size} bytes of input, {left} left) memóriakeret (a(z) {_1} objektumnak {size} bájt bemenet kell, {left} maradt) diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..936f46e0ad 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -577,6 +577,15 @@ @msg only a filter declares `inputs` hanya filter yang mendeklarasikan `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` menyebut jenis objek yang tidak dikenal `{shown}`: gunakan type, image atau symbolInstance @msg `inputs` lists `{shown}` twice `inputs` mencantumkan `{shown}` dua kali +@msg `events` lists `{shown}` twice `events` mencantumkan `{shown}` dua kali +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` menyebut peristiwa yang tidak dikenal `{shown}`: gunakan selection.changed, document.opened, document.saved atau layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` memerlukan API plug-in tingkat {EVENTS_API}: berikan `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` memerlukan izin `events`, dan `events` memerlukan daftar `events` +@msg event size ({len} bytes, limit {max}) ukuran peristiwa ({len} byte, batas {max}) +@msg the module reacts to no events modul tidak bereaksi terhadap peristiwa apa pun +@msg vc_event returned {code} vc_event mengembalikan {code} +@msg {name}: its {event} handler failed: {e} {name}: handler {event}-nya gagal: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: event-nya dimatikan hingga VectorCraft dimulai lagi, setelah {count} handler gagal berturut-turut @msg `inputs` needs `api` 2 or later `inputs` memerlukan `api` 2 atau lebih baru @msg `inputs` needs the permission `doc.read` `inputs` memerlukan izin `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) anggaran memori (objek {_1} memerlukan {size} byte masukan, tersisa {left}) @@ -7394,6 +7403,7 @@ axis Y Axis Sumbu Y Show its progress, see Cancel and write log lines Menampilkan kemajuannya, mengenali pembatalan, dan menulis baris log Keep settings of its own Menyimpan pengaturannya sendiri Keep a cache of its own, which you can clear Menyimpan cache-nya sendiri, yang dapat Anda kosongkan + Run on its own when the selection, a document or a layer changes Berjalan sendiri saat seleksi, dokumen, atau lapisan berubah Run these commands on the document: {ids} Menjalankan perintah ini pada dokumen: {ids} Clear Plug-in Cache Kosongkan cache plug-in # Actions panel: action sets (#3712). diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..c3fbb39ac9 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -7074,6 +7074,7 @@ axis Y Axis Asse Y Show its progress, see Cancel and write log lines Mostrare il proprio avanzamento, rilevare l’annullamento e scrivere righe di registro Keep settings of its own Conservare impostazioni proprie Keep a cache of its own, which you can clear Conservare una cache propria, che è possibile svuotare + Run on its own when the selection, a document or a layer changes Eseguirsi da solo quando cambia la selezione, un documento o un livello Run these commands on the document: {ids} Eseguire questi comandi sul documento: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” elenca `{id}` in `commandAllowlist`, che un plug-in non può chiamare @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7105,6 +7106,15 @@ axis Y Axis Asse Y @msg only a filter declares `inputs` solo un filtro dichiara `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` indica un tipo di oggetto sconosciuto `{shown}`: usa type, image o symbolInstance @msg `inputs` lists `{shown}` twice `inputs` elenca `{shown}` due volte +@msg `events` lists `{shown}` twice `events` elenca `{shown}` due volte +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` indica un evento sconosciuto `{shown}`: usa selection.changed, document.opened, document.saved o layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` richiede il livello API dei plug-in {EVENTS_API}: indicare `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` richiede l’autorizzazione `events`, e `events` richiede un elenco `events` +@msg event size ({len} bytes, limit {max}) dimensione dell’evento ({len} byte, limite {max}) +@msg the module reacts to no events il modulo non reagisce ad alcun evento +@msg vc_event returned {code} vc_event ha restituito {code} +@msg {name}: its {event} handler failed: {e} {name}: il suo gestore di {event} non è riuscito: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: i suoi eventi sono disattivati finché VectorCraft non si riavvia, dopo {count} gestori non riusciti di fila @msg `inputs` needs `api` 2 or later `inputs` richiede `api` 2 o successivo @msg `inputs` needs the permission `doc.read` `inputs` richiede l’autorizzazione `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) budget di memoria (l’oggetto {_1} richiede {size} byte di input, ne restano {left}) diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..f505fe6e6a 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7149,6 +7149,7 @@ axis Y Axis Y 軸 Show its progress, see Cancel and write log lines 進行状況の表示、キャンセルの検知、ログ行の書き込み Keep settings of its own 独自の設定の保持 Keep a cache of its own, which you can clear 消去できる独自のキャッシュの保持 + Run on its own when the selection, a document or a layer changes 選択、ドキュメント、またはレイヤーが変わったときの自動実行 Run these commands on the document: {ids} ドキュメントでのこれらのコマンドの実行: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call 「{name}」は `commandAllowlist` にプラグインが呼び出せない `{id}` を挙げています @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7180,6 +7181,15 @@ axis Y Axis Y 軸 @msg only a filter declares `inputs` `inputs` を宣言できるのはフィルターだけです @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` に不明なオブジェクトの種類 `{shown}` があります。type、image、symbolInstance のいずれかを使ってください @msg `inputs` lists `{shown}` twice `inputs` に `{shown}` が 2 回指定されています +@msg `events` lists `{shown}` twice `events` に `{shown}` が 2 回指定されています +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` に不明なイベント `{shown}` があります。selection.changed、document.opened、document.saved、layer.changed のいずれかを使ってください +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` にはプラグイン API レベル {EVENTS_API} が必要です。`api` {EVENTS_API} を指定してください +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` には権限 `events` が必要で、`events` には `events` のリストが必要です +@msg event size ({len} bytes, limit {max}) イベントサイズ ({len} バイト、上限 {max}) +@msg the module reacts to no events このモジュールはどのイベントにも反応しません +@msg vc_event returned {code} vc_event が {code} を返しました +@msg {name}: its {event} handler failed: {e} {name}: {event} のハンドラーが失敗しました: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: ハンドラーが {count} 回続けて失敗したため、VectorCraft を再起動するまでイベントはオフです @msg `inputs` needs `api` 2 or later `inputs` には `api` 2 以上が必要です @msg `inputs` needs the permission `doc.read` `inputs` には権限 `doc.read` が必要です @msg memory budget (object {_1} needs {size} bytes of input, {left} left) メモリ予算 (オブジェクト {_1} には {size} バイトの入力が必要ですが、残りは {left} です) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..4f8df8bba8 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9555,6 +9555,7 @@ axis Y Axis Y ღერძი Show its progress, see Cancel and write log lines პროგრესის ჩვენება, გაუქმების შემჩნევა და ჟურნალის სტრიქონების ჩაწერა Keep settings of its own საკუთარი პარამეტრების შენახვა Keep a cache of its own, which you can clear საკუთარი ქეშის შენახვა, რომლის გასუფთავებაც შეგიძლიათ + Run on its own when the selection, a document or a layer changes თავისით გაშვება, როცა იცვლება მონიშნული, დოკუმენტი ან შრე Run these commands on the document: {ids} ამ ბრძანებების გაშვება დოკუმენტზე: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ `commandAllowlist`-ში ასახელებს `{id}`-ს, რომლის გამოძახებაც პლაგინს არ შეუძლია @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -9586,6 +9587,15 @@ axis Y Axis Y ღერძი @msg only a filter declares `inputs` `inputs`-ის გამოცხადება მხოლოდ ფილტრს შეუძლია @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` უცნობ ობიექტის სახეობას ასახელებს `{shown}`: გამოიყენეთ type, image ან symbolInstance @msg `inputs` lists `{shown}` twice `inputs`-ში `{shown}` ორჯერაა ჩამოთვლილი +@msg `events` lists `{shown}` twice `events`-ში `{shown}` ორჯერაა ჩამოთვლილი +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` უცნობ მოვლენას ასახელებს `{shown}`: გამოიყენეთ selection.changed, document.opened, document.saved ან layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events`-ს სჭირდება პლაგინის API-ის დონე {EVENTS_API}: მიუთითეთ `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events`-ს სჭირდება ნებართვა `events`, ხოლო `events`-ს სჭირდება `events`-ის სია +@msg event size ({len} bytes, limit {max}) მოვლენის ზომა ({len} ბაიტი, ლიმიტი {max}) +@msg the module reacts to no events მოდული არცერთ მოვლენაზე არ რეაგირებს +@msg vc_event returned {code} vc_event-მა დააბრუნა {code} +@msg {name}: its {event} handler failed: {e} {name}: მისი {event} დამმუშავებელი ვერ შესრულდა: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: მისი მოვლენები გამორთულია VectorCraft-ის ხელახლა გაშვებამდე, ზედიზედ {count} წარუმატებელი დამმუშავებლის შემდეგ @msg `inputs` needs `api` 2 or later `inputs`-ს სჭირდება `api` 2 ან უფრო ახალი @msg `inputs` needs the permission `doc.read` `inputs`-ს სჭირდება ნებართვა `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) მეხსიერების ბიუჯეტი (ობიექტს {_1} სჭირდება შეყვანის {size} ბაიტი, დარჩენილია {left}) diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..684c27a922 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7046,6 +7046,7 @@ axis Y Axis Y축 Show its progress, see Cancel and write log lines 진행률 표시, 취소 감지 및 로그 줄 쓰기 Keep settings of its own 자체 설정 보관 Keep a cache of its own, which you can clear 지울 수 있는 자체 캐시 보관 + Run on its own when the selection, a document or a layer changes 선택 영역, 문서 또는 레이어가 바뀔 때 자동 실행 Run these commands on the document: {ids} 문서에서 다음 명령 실행: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}”의 `commandAllowlist`에 플러그인이 호출할 수 없는 `{id}`가 있습니다 @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7077,6 +7078,15 @@ axis Y Axis Y축 @msg only a filter declares `inputs` 필터만 `inputs`를 선언할 수 있습니다 @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs`에 알 수 없는 개체 종류 `{shown}`이(가) 있습니다. type, image 또는 symbolInstance를 사용하세요 @msg `inputs` lists `{shown}` twice `inputs`에 `{shown}`이(가) 두 번 나열되어 있습니다 +@msg `events` lists `{shown}` twice `events`에 `{shown}`이(가) 두 번 나열되어 있습니다 +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events`에 알 수 없는 이벤트 `{shown}`이(가) 있습니다. selection.changed, document.opened, document.saved 또는 layer.changed를 사용하세요 +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events`에는 플러그인 API 수준 {EVENTS_API}이(가) 필요합니다. `api` {EVENTS_API}을(를) 지정하십시오 +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events`에는 `events` 권한이 필요하고, `events`에는 `events` 목록이 필요합니다 +@msg event size ({len} bytes, limit {max}) 이벤트 크기({len}바이트, 제한 {max}) +@msg the module reacts to no events 이 모듈은 어떤 이벤트에도 반응하지 않습니다 +@msg vc_event returned {code} vc_event가 {code}을(를) 반환했습니다 +@msg {name}: its {event} handler failed: {e} {name}: {event} 처리기가 실패했습니다: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: 처리기가 {count}번 연속 실패하여 VectorCraft를 다시 시작할 때까지 이벤트가 꺼집니다 @msg `inputs` needs `api` 2 or later `inputs`에는 `api` 2 이상이 필요합니다 @msg `inputs` needs the permission `doc.read` `inputs`에는 `doc.read` 권한이 필요합니다 @msg memory budget (object {_1} needs {size} bytes of input, {left} left) 메모리 예산(개체 {_1}에 입력 {size}바이트가 필요하지만 {left}바이트 남음) diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..685d671ff7 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -541,6 +541,15 @@ liquify-list-end {0}, {1} {0} en {1} @msg only a filter declares `inputs` alleen een filter declareert `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` noemt een onbekend objectsoort `{shown}`: gebruik type, image of symbolInstance @msg `inputs` lists `{shown}` twice `inputs` noemt `{shown}` twee keer +@msg `events` lists `{shown}` twice `events` noemt `{shown}` twee keer +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` noemt een onbekende gebeurtenis `{shown}`: gebruik selection.changed, document.opened, document.saved of layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` vereist plug-in-API-niveau {EVENTS_API}: geef `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` vereist de machtiging `events`, en `events` vereist een lijst `events` +@msg event size ({len} bytes, limit {max}) gebeurtenisgrootte ({len} bytes, limiet {max}) +@msg the module reacts to no events de module reageert op geen enkele gebeurtenis +@msg vc_event returned {code} vc_event gaf {code} terug +@msg {name}: its {event} handler failed: {e} {name}: de handler voor {event} is mislukt: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: de gebeurtenissen staan uit tot VectorCraft opnieuw start, na {count} mislukte handlers op rij @msg `inputs` needs `api` 2 or later `inputs` vereist `api` 2 of hoger @msg `inputs` needs the permission `doc.read` `inputs` vereist de machtiging `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) geheugenbudget (object {_1} heeft {size} bytes invoer nodig, {left} over) @@ -9447,6 +9456,7 @@ axis Y Axis Y-as Show its progress, see Cancel and write log lines De voortgang tonen, een annulering zien en logregels schrijven Keep settings of its own Eigen instellingen bewaren Keep a cache of its own, which you can clear Een eigen cache bewaren, die u kunt legen + Run on its own when the selection, a document or a layer changes Vanzelf worden uitgevoerd wanneer de selectie, een document of een laag verandert Run these commands on the document: {ids} Deze opdrachten op het document uitvoeren: {ids} Clear Plug-in Cache Plug-incache legen # Actions panel: action sets (#3712). diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..f38ee32d93 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7307,6 +7307,7 @@ axis Y Axis Oś Y Show its progress, see Cancel and write log lines Pokazywać swój postęp, wykrywać anulowanie i zapisywać wiersze dziennika Keep settings of its own Przechowywać własne ustawienia Keep a cache of its own, which you can clear Przechowywać własną pamięć podręczną, którą możesz wyczyścić + Run on its own when the selection, a document or a layer changes Uruchamiać się samodzielnie, gdy zmieni się zaznaczenie, dokument lub warstwa Run these commands on the document: {ids} Uruchamiać w dokumencie te polecenia: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}” wymienia w `commandAllowlist` polecenie `{id}`, którego wtyczka nie może wywołać @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7338,6 +7339,15 @@ axis Y Axis Oś Y @msg only a filter declares `inputs` tylko filtr deklaruje `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` wymienia nieznany rodzaj obiektu `{shown}`: użyj type, image lub symbolInstance @msg `inputs` lists `{shown}` twice `inputs` wymienia `{shown}` dwa razy +@msg `events` lists `{shown}` twice `events` wymienia `{shown}` dwa razy +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` wymienia nieznane zdarzenie `{shown}`: użyj selection.changed, document.opened, document.saved lub layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` wymaga poziomu API wtyczek {EVENTS_API}: podaj `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` potrzebuje uprawnienia `events`, a `events` potrzebuje listy `events` +@msg event size ({len} bytes, limit {max}) rozmiar zdarzenia ({len} bajtów, limit {max}) +@msg the module reacts to no events moduł nie reaguje na żadne zdarzenia +@msg vc_event returned {code} vc_event zwróciła {code} +@msg {name}: its {event} handler failed: {e} {name}: jego procedura obsługi {event} nie powiodła się: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: jego zdarzenia są wyłączone do ponownego uruchomienia VectorCraft, po {count} nieudanych procedurach obsługi z rzędu @msg `inputs` needs `api` 2 or later `inputs` wymaga `api` 2 lub nowszego @msg `inputs` needs the permission `doc.read` `inputs` wymaga uprawnienia `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) budżet pamięci (obiekt {_1} wymaga {size} bajtów danych wejściowych, pozostało {left}) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..71dc272146 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7351,6 +7351,7 @@ axis Y Axis Eixo Y Show its progress, see Cancel and write log lines Mostrar seu progresso, detectar o cancelamento e gravar linhas de log Keep settings of its own Guardar configurações próprias Keep a cache of its own, which you can clear Guardar um cache próprio, que você pode limpar + Run on its own when the selection, a document or a layer changes Executar-se sozinho quando a seleção, um documento ou uma camada muda Run these commands on the document: {ids} Executar estes comandos no documento: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” lista `{id}` em `commandAllowlist`, que um plug-in não pode chamar @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7382,6 +7383,15 @@ axis Y Axis Eixo Y @msg only a filter declares `inputs` somente um filtro declara `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` cita um tipo de objeto desconhecido `{shown}`: use type, image ou symbolInstance @msg `inputs` lists `{shown}` twice `inputs` lista `{shown}` duas vezes +@msg `events` lists `{shown}` twice `events` lista `{shown}` duas vezes +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` cita um evento desconhecido `{shown}`: use selection.changed, document.opened, document.saved ou layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` exige o nível de API de plug-in {EVENTS_API}: informe `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` precisa da permissão `events`, e `events` precisa de uma lista de `events` +@msg event size ({len} bytes, limit {max}) tamanho do evento ({len} bytes, limite {max}) +@msg the module reacts to no events o módulo não reage a nenhum evento +@msg vc_event returned {code} vc_event retornou {code} +@msg {name}: its {event} handler failed: {e} {name}: seu manipulador de {event} falhou: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: seus eventos estão desativados até o VectorCraft iniciar de novo, após {count} manipuladores com falha seguidos @msg `inputs` needs `api` 2 or later `inputs` exige `api` 2 ou posterior @msg `inputs` needs the permission `doc.read` `inputs` exige a permissão `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) orçamento de memória (o objeto {_1} precisa de {size} bytes de entrada, restam {left}) diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..da28f599bf 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7074,6 +7074,7 @@ axis Y Axis Ось Y Show its progress, see Cancel and write log lines Показывать свой ход выполнения, замечать отмену и записывать строки журнала Keep settings of its own Хранить собственные настройки Keep a cache of its own, which you can clear Хранить собственный кэш, который можно очистить + Run on its own when the selection, a document or a layer changes Запускаться самостоятельно, когда меняется выделение, документ или слой Run these commands on the document: {ids} Выполнять в документе эти команды: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call «{name}» указывает в `commandAllowlist` команду `{id}`, которую модуль вызывать не может @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7105,6 +7106,15 @@ axis Y Axis Ось Y @msg only a filter declares `inputs` `inputs` может объявлять только фильтр @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance в `inputs` указан неизвестный вид объекта `{shown}`: используйте type, image или symbolInstance @msg `inputs` lists `{shown}` twice в `inputs` `{shown}` указано дважды +@msg `events` lists `{shown}` twice в `events` `{shown}` указано дважды +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed в `events` указано неизвестное событие `{shown}`: используйте selection.changed, document.opened, document.saved или layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} для `events` нужен уровень API модулей {EVENTS_API}: укажите `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` для `events` нужно разрешение `events`, а для `events` нужен список `events` +@msg event size ({len} bytes, limit {max}) размер события ({len} байт, предел {max}) +@msg the module reacts to no events модуль не реагирует ни на какие события +@msg vc_event returned {code} vc_event вернула {code} +@msg {name}: its {event} handler failed: {e} {name}: его обработчик {event} завершился ошибкой: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: его события отключены до следующего запуска VectorCraft после {count} неудачных обработчиков подряд @msg `inputs` needs `api` 2 or later для `inputs` нужен `api` 2 или выше @msg `inputs` needs the permission `doc.read` для `inputs` нужно разрешение `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) бюджет памяти (объекту {_1} нужно {size} байт входных данных, осталось {left}) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..c83e6ef5f1 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7464,6 +7464,7 @@ axis Y Axis Y-axel Show its progress, see Cancel and write log lines Visa sitt förlopp, se när det avbryts och skriva loggrader Keep settings of its own Spara egna inställningar Keep a cache of its own, which you can clear Spara en egen cache, som du kan tömma + Run on its own when the selection, a document or a layer changes Köras av sig själv när markeringen, ett dokument eller ett lager ändras Run these commands on the document: {ids} Köra dessa kommandon på dokumentet: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call ”{name}” anger `{id}` i `commandAllowlist`, som ett plugin inte får anropa @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7495,6 +7496,15 @@ axis Y Axis Y-axel @msg only a filter declares `inputs` bara ett filter anger `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` anger en okänd objekttyp `{shown}`: använd type, image eller symbolInstance @msg `inputs` lists `{shown}` twice `inputs` anger `{shown}` två gånger +@msg `events` lists `{shown}` twice `events` anger `{shown}` två gånger +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` anger en okänd händelse `{shown}`: använd selection.changed, document.opened, document.saved eller layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` kräver plugin-API-nivå {EVENTS_API}: ange `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` behöver behörigheten `events`, och `events` behöver en lista `events` +@msg event size ({len} bytes, limit {max}) händelsestorlek ({len} byte, gräns {max}) +@msg the module reacts to no events modulen reagerar inte på några händelser +@msg vc_event returned {code} vc_event returnerade {code} +@msg {name}: its {event} handler failed: {e} {name}: dess {event}-hanterare misslyckades: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: dess händelser är avstängda tills VectorCraft startas igen, efter {count} misslyckade hanterare i rad @msg `inputs` needs `api` 2 or later `inputs` kräver `api` 2 eller senare @msg `inputs` needs the permission `doc.read` `inputs` kräver behörigheten `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) minnesbudget (objekt {_1} behöver {size} byte indata, {left} återstår) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..679e207708 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -949,6 +949,33 @@ fn artboard_add_button_tooltips_are_in_complete_catalogs() { } } +/// Install Plug-in… lists what each permission lets a plug-in do, so each complete catalog has a +/// row for the `events` permission's words. +#[test] +fn plugin_events_permission_words_are_in_complete_catalogs() { + let label = "Run on its own when the selection, a document or a layer changes"; + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus || COMPLETE_MESSAGES.contains(&lang.code)) { + assert!(lang.catalog().plain(label).is_some_and(|t| !t.is_empty() && t != label), "{} is missing {label}", lang.code); + } +} + +/// The status bar's lines for a plug-in whose event handler failed, which the engine writes after +/// the plug-in's name, are translated in each language of [`COMPLETE_MESSAGES`]. +#[test] +fn plugin_event_handler_failures_are_translated() { + let failed = "Run Events: its selection.changed handler failed: vc_event returned 3"; + let off = "Run Events: its events are off until VectorCraft starts again, after 3 failed handlers in a row"; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for s in [failed, off] { + let shown = message(lang, s); + assert!(shown != s && shown.starts_with("Run Events") && shown.contains('3'), "{code}: {shown}"); + } + } + assert_eq!(message(de(), failed), "Run Events: sein Handler für selection.changed ist fehlgeschlagen: vc_event hat 3 zurückgegeben"); + assert_eq!(message(de(), off), "Run Events: seine Ereignisse sind aus, bis VectorCraft neu startet, nach 3 fehlgeschlagenen Handlern in Folge"); +} + /// Preferences › Performance › Use Monitor Profile for Canvas and the note under it. #[test] fn monitor_profile_labels_are_in_complete_catalogs() { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..5beaea8907 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7524,6 +7524,7 @@ axis Y Axis Y ekseni Show its progress, see Cancel and write log lines İlerlemesini gösterme, iptali algılama ve günlük satırları yazma Keep settings of its own Kendi ayarlarını saklama Keep a cache of its own, which you can clear Temizleyebileceğiniz kendi önbelleğini saklama + Run on its own when the selection, a document or a layer changes Seçim, bir belge veya bir katman değiştiğinde kendiliğinden çalışma Run these commands on the document: {ids} Belgede şu komutları çalıştırma: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}”, `commandAllowlist` içinde bir eklentinin çağıramayacağı `{id}` komutunu listeliyor @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7555,6 +7556,15 @@ axis Y Axis Y ekseni @msg only a filter declares `inputs` `inputs` yalnızca bir filtrede bildirilebilir @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` bilinmeyen bir nesne türü belirtiyor: `{shown}`; type, image veya symbolInstance kullanın @msg `inputs` lists `{shown}` twice `inputs` `{shown}` değerini iki kez listeliyor +@msg `events` lists `{shown}` twice `events` `{shown}` değerini iki kez listeliyor +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` bilinmeyen bir olay belirtiyor: `{shown}`; selection.changed, document.opened, document.saved veya layer.changed kullanın +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` için eklenti API düzeyi {EVENTS_API} gerekir: `api` {EVENTS_API} verin +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` için `events` izni, `events` izni için de bir `events` listesi gerekir +@msg event size ({len} bytes, limit {max}) olay boyutu ({len} bayt, sınır {max}) +@msg the module reacts to no events modül hiçbir olaya tepki vermiyor +@msg vc_event returned {code} vc_event {code} döndürdü +@msg {name}: its {event} handler failed: {e} {name}: {event} işleyicisi başarısız oldu: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: art arda {count} işleyici başarısız olduğundan, VectorCraft yeniden başlayana kadar olayları kapalı @msg `inputs` needs `api` 2 or later `inputs` için `api` 2 veya üstü gerekir @msg `inputs` needs the permission `doc.read` `inputs` için `doc.read` izni gerekir @msg memory budget (object {_1} needs {size} bytes of input, {left} left) bellek bütçesi (nesne {_1} için {size} bayt girdi gerekiyor, {left} kaldı) diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..d3db0a5137 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -7056,6 +7056,7 @@ axis Y Axis Вісь Y Show its progress, see Cancel and write log lines Показувати свій поступ, помічати скасування і записувати рядки журналу Keep settings of its own Зберігати власні налаштування Keep a cache of its own, which you can clear Зберігати власний кеш, який можна очистити + Run on its own when the selection, a document or a layer changes Запускатися самостійно, коли змінюється виділення, документ або шар Run these commands on the document: {ids} Виконувати в документі ці команди: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call «{name}» вказує в `commandAllowlist` команду `{id}`, яку модуль викликати не може @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7087,6 +7088,15 @@ axis Y Axis Вісь Y @msg only a filter declares `inputs` `inputs` може оголошувати лише фільтр @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance в `inputs` указано невідомий вид об’єкта `{shown}`: використовуйте type, image або symbolInstance @msg `inputs` lists `{shown}` twice в `inputs` `{shown}` указано двічі +@msg `events` lists `{shown}` twice в `events` `{shown}` указано двічі +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed в `events` указано невідому подію `{shown}`: використовуйте selection.changed, document.opened, document.saved або layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} для `events` потрібен рівень API модулів {EVENTS_API}: укажіть `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` для `events` потрібен дозвіл `events`, а для `events` потрібен список `events` +@msg event size ({len} bytes, limit {max}) розмір події ({len} байтів, межа {max}) +@msg the module reacts to no events модуль не реагує на жодні події +@msg vc_event returned {code} vc_event повернула {code} +@msg {name}: its {event} handler failed: {e} {name}: його обробник {event} завершився помилкою: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: його події вимкнено до наступного запуску VectorCraft після {count} невдалих обробників поспіль @msg `inputs` needs `api` 2 or later для `inputs` потрібен `api` 2 або новіший @msg `inputs` needs the permission `doc.read` для `inputs` потрібен дозвіл `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) бюджет пам’яті (об’єкту {_1} потрібно {size} байтів вхідних даних, залишилося {left}) diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..806f7f509b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7103,6 +7103,7 @@ axis Y Axis Trục Y Show its progress, see Cancel and write log lines Hiển thị tiến độ, nhận biết yêu cầu hủy và ghi các dòng nhật ký Keep settings of its own Lưu cài đặt riêng Keep a cache of its own, which you can clear Lưu bộ nhớ đệm riêng mà bạn có thể xóa + Run on its own when the selection, a document or a layer changes Tự chạy khi vùng chọn, một tài liệu hoặc một lớp thay đổi Run these commands on the document: {ids} Chạy các lệnh này trên tài liệu: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” liệt kê `{id}` trong `commandAllowlist`, lệnh mà plug-in không được gọi @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7134,6 +7135,15 @@ axis Y Axis Trục Y @msg only a filter declares `inputs` chỉ bộ lọc mới khai báo `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` nêu một loại đối tượng không xác định `{shown}`: dùng type, image hoặc symbolInstance @msg `inputs` lists `{shown}` twice `inputs` liệt kê `{shown}` hai lần +@msg `events` lists `{shown}` twice `events` liệt kê `{shown}` hai lần +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` nêu một sự kiện không xác định `{shown}`: dùng selection.changed, document.opened, document.saved hoặc layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` cần API plug-in cấp {EVENTS_API}: hãy đặt `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` cần quyền `events`, và `events` cần một danh sách `events` +@msg event size ({len} bytes, limit {max}) kích thước sự kiện ({len} byte, giới hạn {max}) +@msg the module reacts to no events mô-đun không phản ứng với sự kiện nào +@msg vc_event returned {code} vc_event trả về {code} +@msg {name}: its {event} handler failed: {e} {name}: trình xử lý {event} của nó đã thất bại: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: các sự kiện của nó bị tắt cho đến khi VectorCraft khởi động lại, sau {count} trình xử lý thất bại liên tiếp @msg `inputs` needs `api` 2 or later `inputs` cần `api` 2 trở lên @msg `inputs` needs the permission `doc.read` `inputs` cần quyền `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) ngân sách bộ nhớ (đối tượng {_1} cần {size} byte đầu vào, còn lại {left}) diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..f752620e19 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7284,6 +7284,7 @@ axis Y Axis Y 轴 Show its progress, see Cancel and write log lines 显示进度、检测取消请求并写入日志行 Keep settings of its own 保存自己的设置 Keep a cache of its own, which you can clear 保存自己的缓存,您可以清除它 + Run on its own when the selection, a document or a layer changes 在所选对象、文档或图层发生变化时自动运行 Run these commands on the document: {ids} 在文档上运行这些命令:{ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}”在 `commandAllowlist` 中列出了增效工具不能调用的 `{id}` @msg vc_call `{shown}`: {why} vc_call `{shown}`:{why} @@ -7315,6 +7316,15 @@ axis Y Axis Y 轴 @msg only a filter declares `inputs` 只有滤镜才能声明 `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` 列出了未知的对象类型 `{shown}`:请使用 type、image 或 symbolInstance @msg `inputs` lists `{shown}` twice `inputs` 列出了两次 `{shown}` +@msg `events` lists `{shown}` twice `events` 列出了两次 `{shown}` +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` 列出了未知的事件 `{shown}`:请使用 selection.changed、document.opened、document.saved 或 layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` 需要增效工具 API 级别 {EVENTS_API}:请设置 `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` 需要权限 `events`,而 `events` 需要 `events` 列表 +@msg event size ({len} bytes, limit {max}) 事件大小({len} 字节,上限 {max}) +@msg the module reacts to no events 该模块不响应任何事件 +@msg vc_event returned {code} vc_event 返回了 {code} +@msg {name}: its {event} handler failed: {e} {name}:其 {event} 处理程序失败:{e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}:处理程序连续 {count} 次失败,其事件已关闭,直到 VectorCraft 再次启动 @msg `inputs` needs `api` 2 or later `inputs` 需要 `api` 2 或更高 @msg `inputs` needs the permission `doc.read` `inputs` 需要权限 `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) 内存预算(对象 {_1} 需要 {size} 字节的输入,剩余 {left}) diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..d941e2cae4 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7105,6 +7105,7 @@ axis Y Axis Y 軸 Show its progress, see Cancel and write log lines 顯示進度、偵測取消要求並寫入記錄行 Keep settings of its own 保存自己的設定 Keep a cache of its own, which you can clear 保存自己的快取,您可以清除它 + Run on its own when the selection, a document or a layer changes 在選取範圍、文件或圖層變更時自動執行 Run these commands on the document: {ids} 在文件上執行這些指令:{ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call 「{name}」在 `commandAllowlist` 中列出了增效模組不能呼叫的 `{id}` @msg vc_call `{shown}`: {why} vc_call `{shown}`:{why} @@ -7136,6 +7137,15 @@ axis Y Axis Y 軸 @msg only a filter declares `inputs` 只有濾鏡才能宣告 `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` 列出了未知的物件類型 `{shown}`:請使用 type、image 或 symbolInstance @msg `inputs` lists `{shown}` twice `inputs` 列出了兩次 `{shown}` +@msg `events` lists `{shown}` twice `events` 列出了兩次 `{shown}` +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` 列出了未知的事件 `{shown}`:請使用 selection.changed、document.opened、document.saved 或 layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` 需要增效模組 API 層級 {EVENTS_API}:請設定 `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` 需要權限 `events`,而 `events` 需要 `events` 清單 +@msg event size ({len} bytes, limit {max}) 事件大小({len} 位元組,上限 {max}) +@msg the module reacts to no events 此模組不回應任何事件 +@msg vc_event returned {code} vc_event 傳回了 {code} +@msg {name}: its {event} handler failed: {e} {name}:其 {event} 處理常式失敗:{e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}:處理常式連續 {count} 次失敗,其事件已關閉,直到 VectorCraft 再次啟動 @msg `inputs` needs `api` 2 or later `inputs` 需要 `api` 2 或更高 @msg `inputs` needs the permission `doc.read` `inputs` 需要權限 `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) 記憶體預算(物件 {_1} 需要 {size} 位元組的輸入,剩餘 {left}) diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 180c459453..2d20911711 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -239,6 +239,7 @@ fn permission_words(name: &str, commands: &[String]) -> String { Some(permissions::Permission::Progress) => tl!("Show its progress, see Cancel and write log lines"), Some(permissions::Permission::Settings) => tl!("Keep settings of its own"), Some(permissions::Permission::Cache) => tl!("Keep a cache of its own, which you can clear"), + Some(permissions::Permission::Events) => tl!("Run on its own when the selection, a document or a layer changes"), None => return permissions::display_text(name, permissions::MAX_SHOWN_FIELD), }; words.to_string() diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 0a80254db0..ed18dd4015 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -720,3 +720,43 @@ fn installing_a_plugin_that_reports_progress_says_so() { assert_eq!(vectorcraft_plugins::registry::granted(id).map(|g| g.permissions.len()), Some(2)); app.run("plugin.remove", json!({"id": id})).unwrap(); } + +/// A selection made in the UI pass, after the frame's background work (as a click on the canvas or +/// a panel makes it), reaches a plug-in that reacts to `selection.changed` before that pass ends: +/// nothing is left for a later delivery. +#[test] +fn a_change_made_in_a_ui_pass_is_delivered_in_that_pass() { + let mut app = app(); + app.session.allow_plugin_grants_from_requests(); + let id = "test.UI.ui_pass_events"; + let grant = json!(["progress", "events"]); + let manifest = format!(r#"{{"id":"{id}","name":"Pass Events","kind":"filter","api":2,"permissions":{grant},"events":["selection.changed"]}}"#); + // 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. + let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap(); + let r = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("select.none", json!({})).unwrap(); + let ctx = egui::Context::default(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)); + let pass = |app: &mut VectorcraftApp, select: bool| { + app.begin_host_iteration(); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + app.tick(ui.ctx()); + if select { + app.session.execute("select.set", &json!({"ids": [r]})).unwrap(); + } + app.ui(ui); + }); + out.textures_delta.clear(); + }; + // Fonts install on the first pass and are ready on the second. + pass(&mut app, false); + pass(&mut app, false); + pass(&mut app, true); + app.session.deliver_plugin_events(); + let left: Vec = 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:?}"); + assert_eq!(app.session.doc().unwrap().selection.objects.len(), 1, "the selection was made"); + app.run("plugin.remove", json!({"id": id})).unwrap(); +} diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index fee27caa13..addee8c79a 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -244,6 +244,38 @@ fn finished_background_work_waits_for_the_run_to_end() { assert!(app.opening.activate.is_empty()); } +/// The selection a script changes reaches a plug-in that reacts to `selection.changed` in the +/// frame the script ends in: once it has ended, nothing asks for another frame. +#[test] +fn a_finished_run_delivers_its_plugin_events_in_the_frame_it_ends() { + use vectorcraft_plugins::wat as tpl; + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + app.session.allow_plugin_grants_from_requests(); + let id = "test.UI.script_run_events"; + 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(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap(); + app.poll_finished_work(); + 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(); + for _ in 0..10_000 { + if !app.session.script_running() { + break; + } + app.begin_host_iteration(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx())); + 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); +} + #[test] fn quitting_asks_to_stop_and_stop_undoes_the_run() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..ed02d61332 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13262,7 +13262,10 @@ while it runs, through `vc_call`: the calls and its output are one undo step, an fails leaves the documents, selections and history as they were. Without `doc.read` every call fails. A command that reads or writes files, uses the clipboard, changes preferences or the view, runs a script, an action or a plug-in, switches documents or undoes is never called; `plugin.install` refuses a manifest that lists one, and `plugin.inspect` lists such ids as -`refusedCommands` and ids no command has as `unknownCommands` (`plugin.install` lists those too). A live-effect plug-in is an effect with +`refusedCommands` and ids no command has as `unknownCommands` (`plugin.install` lists those too). A plug-in at API level 2 +whose manifest lists the `events` permission and `events` (in its `plugin.list` entry) is given `selection.changed`, +`document.opened`, `document.saved` and `layer.changed` events 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 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/plugins.md b/docs/plugins.md index ab294db1ff..8aba315c74 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -210,6 +210,7 @@ capability model proposed for PhotoCraft plug-ins | `settings` | all | Keep settings of its own between runs and sessions ([settings and cache](#settings-and-cache)). Needs `api` 2. | | `cache` | all | Keep a cache of its own, which the user can clear ([settings and cache](#settings-and-cache)). Needs `api` 2. | | `commands` | filter | Run the commands its `commandAllowlist` lists on the document ([command calls](#command-calls)). Needs `api` 2. | +| `events` | all | Run on its own when the selection, a document or a layer changes, for the `events` it names ([events](#events-api-level-2)). Needs `api` 2. | - A manifest without `permissions` gets the ones its kind implies, as plug-ins did before the key existed: a filter `doc.read`, `doc.write` and `state`; an effect `doc.read` and `effect.render`, and also `doc.write` and `state` @@ -219,9 +220,9 @@ capability model proposed for PhotoCraft plug-ins - An effect, an exporter or an importer that lists permissions lists all of its implied ones (`doc.read` and `effect.render`; `doc.read` and `export.write`; `import.read`). An effect with commands may add `doc.write` and `state`, which only its commands use. A filter may list any of its three, and `commands` with a `commandAllowlist`. - Any kind may add `progress`, `settings` and `cache`, which no kind implies. An unknown name, a name listed twice, a - name that doesn't apply to the kind, more than 16 names, `progress`, `settings`, `cache` or `commands` with an `api` - below 2, or one of the names kept for a later plug-in API (`ui.panel`, `ui.tool`) is refused when the module is + Any kind may add `progress`, `settings`, `cache` and `events`, which no kind implies. An unknown name, a name listed + twice, a name that doesn't apply to the kind, more than 16 names, `progress`, `settings`, `cache`, `commands` or + `events` with an `api` below 2, or one of the names kept for a later plug-in API (`ui.panel`, `ui.tool`) is refused when the module is installed, and the error names it. - **Installing asks first.** Install Plug-in… and File › Open show the plug-in's name, id, version, the SHA-256 of the file and each permission in plain words, and install it once the user clicks OK, if the file still has the @@ -371,6 +372,7 @@ pointers are offsets into the module's memory. | `vc_manifest` | `() -> i64` | `(len << 32) \| ptr` of the UTF-8 manifest JSON (≤ 64 KiB). | | `vc_alloc` | `(size) -> ptr` | A block of `size` bytes the host may write, or `0` on failure. Never freed: each run gets a fresh instance. | | `vc_run` | `(input, input_len, params, params_len) -> i64` | Runs the plug-in on the input JSON with the parameters JSON; returns `(len << 32) \| ptr` of the output JSON, or a negative error code. | +| `vc_event` | `(event, event_len) -> i32` | Only in a module whose manifest lists [`events`](#events-api-level-2): reacts to the event JSON; returns `0` when it handled it, anything else when it failed. | ### Host imports (API level 2) @@ -491,7 +493,8 @@ arguments as a JSON object, the params the command takes from any request: `-3` when the arguments are not a JSON object, `-4` when `commandAllowlist` doesn't list the id, `-5` when no command has the id, `-6` when a plug-in may not call the command, `-7` when the command can't run now (nothing is selected), `-8` when the command ran and failed, `-9` when a limit below is passed, and `-11` when nothing can be called (from -the module's start function, in a run that isn't a filter's run on a document, or after a call in the run failed). +the module's start function, in a run that isn't a filter's run on a document or an [event](#events-api-level-2) +handler, or after a call in the run failed). - Every code also fails the run, whatever the plug-in does next, and the error names the call and why it failed. The run's calls and its output are one undo step, named after the plug-in or its command. A run that fails, traps, runs @@ -522,6 +525,57 @@ the module's start function, in a run that isn't a filter's run on a document, o - A filter that calls commands runs on the app's main thread, so it can't ask for a heavy budget: a manifest with `commandAllowlist` and `budget: "heavy"` is refused. +### Events (API level 2) + +A plug-in of any kind whose manifest gives `"api": 2`, lists the `events` permission and names events in `events` +exports `vc_event`, and VectorCraft calls it after each change of those kinds: + +```json +{"id": "org.example.watch", "name": "Watch", "kind": "filter", "api": 2, + "permissions": ["doc.read", "events"], "events": ["selection.changed", "document.saved"]} +``` + +| Event | When | The event JSON | +|---|---|---| +| `selection.changed` | The selection in a document changed: other objects, anchors or segments, or nothing (`count` 0). | `{"type", "document", "count", "ids", "truncated"}`: `ids` lists the selected objects, at most 2,048 of them (`truncated` is then `true`), and is `null` without `doc.read`. | +| `document.opened` | A file opened as a document (File › Open, Open Recent, New from Template). A new blank document is not one. | `{"type", "document"}` | +| `document.saved` | Save or Save As wrote the document's own file. Save a Copy, a template and an export are not. | `{"type", "document"}` | +| `layer.changed` | The current layer changed, or a layer or sublayer was added, deleted, moved or given other options. | `{"type", "document", "layer", "reasons"}`: `layer` is the current layer's id (`null` when there is none), `reasons` lists any of `current`, `added`, `deleted`, `reordered` and `options`. `reordered` means a layer's or sublayer's place among the rows beside it changed, also when an object moved past it. | + +`document` is a number that names the open document for the rest of the session. No event carries a path, a file name +or the document's contents. + +- VectorCraft calls `vc_event(event, event_len)` in a fresh instance with the UTF-8 event JSON in a block from + `vc_alloc`, after the change has finished: after the command, after Undo or Redo, after the file was written or the + document opened. Nothing happens while a drag is still being previewed, for a failed command, or for a command that + leaves the document as it was (a Layer Options that sets the name it had). Installing a plug-in hands it no past + events, also none that were waiting for the next delivery when it was installed. A change made to a document opened + or created since the last delivery is an event at the next one, after that document's `document.opened`. +- Changes between two deliveries are one event with the state they ended with. The desktop app delivers in each + frame, after the work that finished in the background and again at the end of the frame, after the canvas, panels + and dialogs have run, so a burst of selection changes in one frame is one `selection.changed` and an idle window does + not hold an event back. Requests through the control channel, and through MCP in remote mode, run in the desktop app + and are delivered by the frame too, and several of them can run in one frame. `vectorcraft-cli` and headless MCP + deliver after each request. Opens and saves are each their own event, in order, and are delivered even when the + document closed before the delivery. At most 32 events wait; past that the oldest is dropped. +- A handler only reads. VectorCraft applies nothing it returns, and it is outside any undo step. With `commands` and a + `commandAllowlist`, it may [call](#command-calls) these commands, when the allowlist also names them, on the active + document: `dataset.list`, `graphicStyle.list`, `guide.list`, `image.info`, `object.blend.info`, `swatch.list`, + `symbol.list`, `text.getRange`, `transparency.info` and `variable.list`. A call of any other command fails with `-6` + before it runs, the error names the event (`a selection.changed handler only reads: …`), and the handler fails. + Afterwards VectorCraft puts back every document, its selection, current layer and undo history, which document is + active, and the session state a command call can change (paint defaults, the Appearance panel's active row, + preferences); a call that changed a document is refused the same way. An event raised while a handler runs waits + for the next delivery: handlers never run inside one another. +- A handler gets at most 5,000,000 instructions and 200 ms, or its plug-in's own budget when that is smaller, for the + module's start function, `vc_alloc` and `vc_event` together; its settings, cache and log lines work as in a run. + 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` + 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. + ### Manifest ```json @@ -574,6 +628,11 @@ the module's start function, in a run that isn't a filter's run on a document, o it): the ids of the commands the filter may [call](#command-calls), at most 256, each once (`"commandAllowlist": ["select.all", "object.move"]`). An id is 1–128 characters from `A-Z a-z 0-9 . _ -` that starts with a letter, with no empty part between dots. A malformed list is refused when the module is installed, and the error names the id. +- `events` (any kind at `api` 2, and only with the `events` permission, which needs it): the + [events](#events-api-level-2) the plug-in reacts to, any of `"selection.changed"`, `"document.opened"`, + `"document.saved"` and `"layer.changed"`, each at most once. The module then exports `vc_event`. An unknown or + repeated name, an entry that isn't a string, `api` 1, a list without the permission, the permission without a list, + and a missing or wrongly typed `vc_event` are refused when the module is installed, and the error names the fault. - `params`: in dialog order. Names are `[A-Za-z0-9_]`, not starting with `_`, and not `id`, `ids`, `params` or `preview`. The host validates the user's values before calling: missing values take the default, numbers are clamped to `min..max` (ints rounded), a wrong type or an unknown choice is an error. Numeric defaults are also clamped diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..540f5e8b1c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2654,6 +2654,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Changed plug-in gradients lose spot plates (G17):** a gradient that a filter or importer changes loses each stop's swatch link, tint and process `plates` together, in fills and strokes, and keeps the stop's color, offset, opacity and midpoint; a gradient returned unchanged keeps all three. Regressions: `crates/plugins/src/objects/tests.rs` (`changed_gradient_fill_and_stroke_drop_spot_plates`, `unchanged_gradient_paint_keeps_spot_plates`). Scores and hours unchanged. - **Plug-in data kept with the document (G17):** a filter writes JSON of at most 1 MiB with `documentData` (one undo step with its objects; `null` removes it) and reads it back in `_context.documentData`, which no other filter is given. It is the document's foreign data (`unknown.pluginData`, by plug-in id), as the perspective grid is, so the native file keeps it with no section of its own; an exporter is given the whole document, so it can read every plug-in's. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_export.rs` (the exporter), `crates/doc/src/plugin_data.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged. - **Heavy filter plug-ins (G17):** a filter's manifest may ask for `"budget": "heavy"`: 1 G instructions (20 times a light run's) and 300 s a run, for routing, packing or simulation. Install Plug-in… and File › Open ask the user first, `plugin.install` needs `allowHeavy: true` (`plugin.inspect` tells beforehand), the Additional Plug-ins Folder skips such filters, and the plug-in store keeps the answer. Its dialog has no Preview; the app runs it on a thread of its own with a progress window (Cancel, Continue in Background) and applies the result as `plugin.run` with the same parameters, one undo step, unless the document or the plug-in changed meanwhile. Regressions: `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. +- **Plug-ins react to events (G17, VectorCraft's own API):** a plug-in at API level 2 with the `events` permission names any of `selection.changed`, `document.opened`, `document.saved` and `layer.changed` in its manifest, and its `vc_event` export is given a small JSON event after each change of that kind has finished, outside any undo step: changes between two deliveries (a frame in the desktop app, a request in `vectorcraft-cli` or headless MCP) are one event. A handler only reads: it may call only ten listed commands that read, any other call fails with an error naming the event, and what a call changed is put back. It gets 5 M instructions and 200 ms, a handler that fails 3 times in a row gets no more events for the session, and an event raised while a handler runs waits for the next delivery. Regressions: `crates/engine/src/tests/plugin_events.rs`, `crates/engine/src/plugin_events.rs`, `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. - **Plug-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. - **Hang report and Copy Troubleshooting Info:** when the desktop app's interface thread stays in one part of a frame for 3 s (VectorCraft's own value), a watching thread writes a hang report to the log and to `logs/hang-report-.txt`, and removes the file when the interface answers again. A later launch that finds a report no process holds writes it to the log, keeps it as `logs/hang-report.1.txt` and, unless another start-up message is showing, says so in the status bar. Help › Copy Troubleshooting Info (`help.copyTroubleshootingInfo`) copies the platform facts, the recent commands and frame times, and the reports of this session and the last one. Regressions: `apps/vectorcraft/src/hang_watch/tests.rs`, `crates/ui-egui/src/hang_beacon.rs`, `crates/ui-egui/src/troubleshooting.rs`. Scores and hours unchanged. From 50dcc11e4dd7da5fd6410c91e7a228a4f4ca9b8e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 16:19:15 -0800 Subject: [PATCH 02/11] Plug-ins: keep waiting events to the changes each plug-in was given - A waiting event names each recipient by its installation serial too, so a module that another session removed and installed again is not given an event from before. - A merged layer.changed keeps the reasons per plug-in: one installed between two changes is given only the later change's reasons. - Delivery waits while an interaction is open; the events go out at the first delivery after it ends. - A failed top-level request still delivers what finished before the failure, such as a save in a command.batch whose later step fails. A document.opened for a document that the rollback closes again (a batch, or a failed command of a script or a plug-in call) is dropped. - An event's handler checks the deadline before vc_alloc and before vc_event. - The shared-budget test uses a small instruction budget and checks for an instruction-budget error, and the UI test removes its plug-in when it ends. --- crates/engine/src/cmd/fileio/batch.rs | 3 + crates/engine/src/plugin_events.rs | 118 ++++++++++++++++------- crates/engine/src/script/mod.rs | 5 + crates/engine/src/session/execute.rs | 3 + crates/engine/src/tests/plugin_events.rs | 90 +++++++++++++++++ crates/plugins/src/runtime.rs | 3 + crates/plugins/tests/abi.rs | 23 +++-- crates/ui-egui/src/tests/script_run.rs | 11 +++ docs/plugins.md | 3 +- 9 files changed, 213 insertions(+), 46 deletions(-) diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 93670cefd9..316fae8573 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -25,6 +25,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // file, format and saved state share their data with the open ones until a step changes them. let start = s.docs.clone(); let active = s.active; + let opens = s.plugin_events_mark(); s.batch_stash = Some(vec![]); let mut grouped = Vec::with_capacity(cmds.len()); // The Type tool keeps what the steps' Undo and Redo change in it, to put back on a rollback. @@ -39,6 +40,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { } Err(e) => { roll_back(s, start, &stash); + // The documents the steps opened are closed again: plug-ins are not told of them. + s.forget_plugin_opens_since(opens); s.notify_text_tool("batch.rollBack"); s.active = active; s.sync_front_profiles(); diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index 9951904991..552d93bd21 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -7,9 +7,10 @@ //! - 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 runs while an interaction is open (a -//! drag being previewed). A document opened or created since the last check is compared with how -//! it was when the command that added it ended ([`Session::plugin_events_see_new_documents`]). +//! `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 +//! ([`Session::plugin_events_see_new_documents`]). //! - 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 handler only reads. The host applies nothing it returns, and it may call only the commands @@ -48,22 +49,36 @@ struct Seen { layer: Option, } -/// A plug-in an event is for: its id and the hash of its module. -type Recipient = (String, String); +/// 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); /// The recipient `p` is. fn recipient(p: &Plugin) -> Recipient { - (p.id().to_string(), p.hash().to_string()) + (p.id().to_string(), p.hash().to_string(), p.serial()) } -/// An event waiting for delivery: what changed, in which document, for `layer.changed` why, and -/// the plug-ins it is for: those installed when it happened. +/// 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, - reasons: Vec<&'static str>, - to: Vec, + to: Vec<(Recipient, Vec<&'static str>)>, + /// When it was queued ([`PluginEvents::queued`] then). + seq: u64, +} + +impl Pending { + /// Whether this event is for `r`. + fn is_for(&self, r: &Recipient) -> bool { + self.to.iter().any(|(x, _)| x == r) + } + + /// The reasons of a `layer.changed` that `r` is given. + 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 module with `hash`. @@ -95,6 +110,8 @@ pub struct PluginEvents { /// The plug-ins that reacted to events when `seen` was taken. seen_by: Vec, pending: VecDeque, + /// How many events have been queued as their own entry. + queued: u64, dispatching: bool, failures: BTreeMap, notices: VecDeque, @@ -119,24 +136,30 @@ impl PluginEvents { subs } - /// Queues `event` for document `uid`, for the plug-ins `to`. A `selection.changed` or - /// `layer.changed` already waiting for that document takes it in (a layer event adds the new - /// reasons to its own, and the new plug-ins to its own); past [`MAX_PENDING`] the oldest event is - /// dropped. + /// 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 reasons { - if !p.reasons.contains(&r) { - p.reasons.push(r); - } - } - p.reasons.sort_by_key(|r| LAYER_REASONS.iter().position(|x| x == r)); for r in to { - if !p.to.contains(&r) { - p.to.push(r); + 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; } @@ -145,7 +168,9 @@ impl PluginEvents { { log::warn!("plug-in events: dropped a waiting {} event, past {MAX_PENDING} waiting", dropped.event.name()); } - self.pending.push_back(Pending { event, document: uid, reasons, to }); + let to = to.into_iter().map(|r| (r, reasons.clone())).collect(); + self.pending.push_back(Pending { event, document: uid, to, seq: self.queued }); + self.queued += 1; } fn notice(&mut self, n: Notice) { @@ -247,6 +272,18 @@ impl Session { self.plugin_events.queue(event, uid, Vec::new(), to); } + /// 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. + pub(crate) fn forget_plugin_opens_since(&mut self, mark: u64) { + self.plugin_events.pending.retain(|p| p.event != Event::DocumentOpened || p.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 @@ -264,7 +301,7 @@ impl Session { } 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.retain(|(r, _)| installed.contains(r)); !p.to.is_empty() }); if self.docs.iter().any(|d| d.interaction.is_some()) { @@ -300,13 +337,14 @@ impl Session { /// 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. + /// 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) { if self.plugin_events.dispatching { return; } self.check_plugin_events(); - if self.plugin_events.pending.is_empty() { + if self.plugin_events.pending.is_empty() || self.docs.iter().any(|d| d.interaction.is_some()) { return; } let subs = self.plugin_events.subscribers(); @@ -319,7 +357,7 @@ 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.to.contains(&recipient(s))) { + 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 { continue; } @@ -348,7 +386,7 @@ impl Session { } Event::LayerChanged => { v["layer"] = json!(st.active_layer.map(|l| l.0)); - v["reasons"] = json!(p.reasons); + v["reasons"] = json!(p.reasons_for(&recipient(plugin))); } Event::DocumentOpened | Event::DocumentSaved => {} } @@ -449,27 +487,33 @@ impl Session { mod tests { use super::*; + /// 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![]); - e.queue(Event::LayerChanged, 1, vec!["options"], vec![]); - e.queue(Event::SelectionChanged, 1, vec![], vec![]); - e.queue(Event::LayerChanged, 1, vec!["current", "options"], vec![]); - e.queue(Event::SelectionChanged, 2, vec![], vec![]); - e.queue(Event::DocumentSaved, 1, vec![], vec![]); - e.queue(Event::DocumentSaved, 1, vec![], vec![]); - let got: Vec<(Event, u64, Vec<&str>)> = e.pending.iter().map(|p| (p.event, p.document, p.reasons.clone())).collect(); + 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", "options"]), + (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 diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0e702c0076..2d15652731 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -642,6 +642,8 @@ pub(crate) struct Savepoint { pending_paint: Option, choices: Choices, journal: usize, + /// The plug-in events queued before the command ([`Session::plugin_events_mark`]). + plugin_events: u64, } impl Savepoint { @@ -676,6 +678,7 @@ impl Savepoint { pending_paint: s.pending_paint.clone(), choices: Choices::of(s), journal: s.journal.len(), + plugin_events: s.plugin_events_mark(), } } @@ -728,6 +731,8 @@ impl Savepoint { s.pending_paint = self.pending_paint; self.choices.put(s); s.journal.truncate(self.journal); + // The documents the command opened are closed again: plug-ins are not told of them. + s.forget_plugin_opens_since(self.plugin_events); s.sync_front_profiles(); exact } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 19cd41fdb0..9f4591423f 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -206,6 +206,9 @@ 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 { diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs index df8dd04cb4..6ee0e8342b 100644 --- a/crates/engine/src/tests/plugin_events.rs +++ b/crates/engine/src/tests/plugin_events.rs @@ -238,6 +238,96 @@ fn a_module_installed_again_gets_no_event_from_before_its_removal() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// A save waiting in one session is not given to the same module that another session removed and +/// installed again before this session's delivery. +#[test] +fn a_module_installed_again_by_another_session_gets_no_earlier_event() { + let id = "test.events.again_elsewhere"; + let mut s = session(); + s.plugin_event_frames = true; + install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-elsewhere-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("elsewhere.vectorcraft").to_string_lossy()})); + let mut other = session(); + run(&mut other, "plugin.remove", json!({"id": id})); + install(&mut other, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "the save came before this install"); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A plug-in installed between two layer changes waiting for the same delivery is given only the +/// reason of the change after its install; the plug-in installed before is given both. +#[test] +fn a_plugin_installed_between_layer_changes_gets_only_the_later_reason() { + let (early, late) = ("test.events.reasons_early", "test.events.reasons_late"); + let mut s = session(); + let first = s.doc().unwrap().active_layer.unwrap(); + let second = NodeId(run(&mut s, "layer.new", json!({"name": "Two"}))["id"].as_u64().unwrap()); + install(&mut s, early, r#"["layer.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + run(&mut s, "layer.setProps", json!({"id": second.0, "name": "Notes"})); + install(&mut s, late, r#"["layer.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + run(&mut s, "layer.setCurrent", json!({"id": first.0})); + s.deliver_plugin_events(); + let notices = s.take_plugin_event_notices(); + let reasons = |id: &str| -> Vec { + notices.iter().filter(|n| n.plugin == id).map(|n| serde_json::from_str::(&n.text).unwrap()["reasons"].clone()).collect() + }; + assert_eq!(reasons(early), [json!(["current", "options"])]); + assert_eq!(reasons(late), [json!(["current"])], "the rename came before this install"); + run(&mut s, "plugin.remove", json!({"id": early})); + run(&mut s, "plugin.remove", json!({"id": late})); +} + +/// A save waiting for delivery is held while an interaction is open, and given at the first +/// delivery after it ends. +#[test] +fn waiting_events_are_held_while_an_interaction_is_open() { + let id = "test.events.interaction"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-interaction-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("interaction.vectorcraft").to_string_lossy()})); + s.begin_interaction("Move").unwrap(); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "not while the interaction is open"); + s.cancel_interaction().unwrap(); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})]); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A save in a batch whose later step fails is still given to the plug-in when the request ends; +/// an open in that batch, which the rollback closes again, is not. +#[test] +fn a_save_before_a_failed_batch_step_is_delivered() { + let id = "test.events.failed_batch"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + install(&mut s, id, r#"["document.saved","document.opened"]"#, &[], "", tpl::LOG_EVENT, &[]); + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-failed-batch-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("failed-batch.vectorcraft").to_string_lossy().into_owned(); + let steps = json!([ + {"command": "document.save", "params": {"path": path}}, + {"command": "document.open", "params": {"path": path}}, + {"command": "no.such.command", "params": {}} + ]); + assert!(s.execute("command.batch", &json!({"commands": steps})).is_err()); + assert!(std::path::Path::new(&path).exists(), "the save was written"); + assert_eq!(s.documents().len(), 1, "the opened document was closed again"); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})]); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + /// A `selection.changed` event of a plug-in without `doc.read` gives the count and no ids; one /// with it lists the selected ids. #[test] diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 699fe15161..54e315b2cf 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -582,6 +582,8 @@ impl Plugin { let out = (|| { let alloc: TypedFunc = live.func("vc_alloc")?; let handler: TypedFunc = live.func("vc_event")?; + // The start function may have used the time: neither call runs past it. + deadline.check()?; let ptr = self.call_budget(&mut live, &alloc, event.len().max(1) as i32, &mut budget, &deadline, None)? as u32 as usize; if ptr == 0 { return Err(Error::Failed("vc_alloc returned 0 (out of memory)".into())); @@ -589,6 +591,7 @@ impl Plugin { let outside = || Error::Abi("vc_alloc returned a block outside memory".into()); let end = ptr.checked_add(event.len()).ok_or_else(outside)?; live.memory.data_mut(&mut live.store).get_mut(ptr..end).ok_or_else(outside)?.copy_from_slice(event); + deadline.check()?; let code = self.call_budget(&mut live, &handler, (ptr as i32, event.len() as i32), &mut budget, &deadline, bridge)?; deadline.check()?; if code != 0 { diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index bb28afd450..146118162e 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -1073,7 +1073,9 @@ fn vc_event_is_given_the_event_and_its_code_is_checked() { } /// The start function, `vc_alloc` and `vc_event` share one event budget: work that fits it in the -/// handler alone fits it no longer when the start function has done as much first. +/// handler alone fits it no longer when the start function has done as much first. The budget is +/// 200,000 instructions, which run in far less than the 200 ms an event is given, so the run that +/// fails is stopped by its instruction budget. #[test] fn a_handler_and_its_start_function_share_the_event_budget() { let manifest = reacting_manifest("test.events.shared", r#"["layer.changed"]"#); @@ -1084,18 +1086,23 @@ fn a_handler_and_its_start_function_share_the_event_budget() { let plugin = |start: u32, handler: u32| { let imports = format!("{} {burn} (func $s (call $burn (i32.const {start}))) (start $s)", tpl::HOST_IMPORTS); let body = format!("(call $burn (i32.const {handler})) (i32.const 0)"); - Plugin::load(&build(&tpl::reacting(&manifest, &imports, &body)), Limits::default()).unwrap() + Plugin::load(&build(&tpl::reacting(&manifest, &imports, &body)), Limits { fuel_base: 200_000, ..Limits::default() }).unwrap() }; let event = br#"{"type":"layer.changed","document":1}"#; - // The most loop turns, doubling, that fit the budget in the handler alone: twice as many don't. - let mut k = 1u32 << 16; - while plugin(0, k * 2).run_event(event, None).0.is_ok() { - k *= 2; + // The most loop turns, doubling, that fit the budget in the handler alone: twice as many run out + // of instructions. + let mut k = 1u32 << 8; + let e = loop { + match plugin(0, k * 2).run_event(event, None).0 { + Ok(()) => k *= 2, + Err(e) => break e.to_string(), + } assert!(k < 1 << 30, "a handler that never runs out of its budget"); - } + }; + assert!(e.contains("instruction budget"), "{e}"); assert!(plugin(0, k).run_event(event, None).0.is_ok()); let e = plugin(k, k).run_event(event, None).0.unwrap_err().to_string(); - assert!(e.contains("budget"), "{e}"); + assert!(e.contains("instruction budget"), "{e}"); } /// A heavy filter installs once the user agrees, which loading a folder doesn't ask: it is skipped diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index addee8c79a..03917c635f 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -249,10 +249,21 @@ fn finished_background_work_waits_for_the_run_to_end() { #[test] fn a_finished_run_delivers_its_plugin_events_in_the_frame_it_ends() { use vectorcraft_plugins::wat as tpl; + + /// Removes the plug-in when the test ends, failed or not: the registry serves every session in + /// the process. + struct Remove(&'static str); + impl Drop for Remove { + fn drop(&mut self) { + vectorcraft_plugins::registry::remove(self.0); + } + } + let mut app = app(); app.session.prefs.show_external_script_warning = false; app.session.allow_plugin_grants_from_requests(); let id = "test.UI.script_run_events"; + 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. diff --git a/docs/plugins.md b/docs/plugins.md index 8aba315c74..e50e2455e1 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -556,7 +556,8 @@ or the document's contents. and dialogs have run, so a burst of selection changes in one frame is one `selection.changed` and an idle window does not hold an event back. Requests through the control channel, and through MCP in remote mode, run in the desktop app and are delivered by the frame too, and several of them can run in one frame. `vectorcraft-cli` and headless MCP - deliver after each request. Opens and saves are each their own event, in order, and are delivered even when the + deliver after each request, also one that fails: a save in a `command.batch` whose later step fails still gives its + `document.saved`. Opens and saves are each their own event, in order, and are delivered even when the document closed before the delivery. At most 32 events wait; past that the oldest is dropped. - A handler only reads. VectorCraft applies nothing it returns, and it is outside any undo step. With `commands` and a `commandAllowlist`, it may [call](#command-calls) these commands, when the allowlist also names them, on the active From 01ec822509dfd2adde186cf25f543aed4c29ad9b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 09:41:53 -0800 Subject: [PATCH 03/11] Plug-ins: drop the open events of a script run that fails A script that opens a document and then throws, runs out of budget or is abandoned loses that document with its working copy, so its waiting document.opened event is now dropped when the run ends. The saves it made before failing are still delivered, and so is a document the frontend opened while the run was paused. --- crates/engine/src/plugin_events.rs | 24 ++++++++++++- crates/engine/src/script/mod.rs | 4 +++ crates/engine/src/tests/plugin_events.rs | 43 ++++++++++++++++++++++++ 3 files changed, 70 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index 552d93bd21..555f2ac308 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -67,6 +67,9 @@ struct Pending { to: Vec<(Recipient, Vec<&'static str>)>, /// When it was queued ([`PluginEvents::queued`] then). seq: u64, + /// Queued by a command of the running script, whose run has not ended yet + /// ([`Session::plugin_events_script_ended`]). + by_script: bool, } impl Pending { @@ -169,7 +172,7 @@ impl PluginEvents { log::warn!("plug-in events: dropped a waiting {} event, past {MAX_PENDING} waiting", dropped.event.name()); } let to = to.into_iter().map(|r| (r, reasons.clone())).collect(); - self.pending.push_back(Pending { event, document: uid, to, seq: self.queued }); + self.pending.push_back(Pending { event, document: uid, to, seq: self.queued, by_script: false }); self.queued += 1; } @@ -270,6 +273,25 @@ impl Session { 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; + } + } + + /// At the end of a script's run. When the run failed (`kept` false), drops the waiting + /// `document.opened` events its commands queued, since the documents they opened were discarded + /// with its working copy. Its saves stay, since the files they wrote stay written, and so do the + /// events of documents a frontend opened while the run was paused. + pub(crate) fn plugin_events_script_ended(&mut self, kept: bool) { + if !kept { + self.plugin_events.pending.retain(|p| !(p.by_script && p.event == Event::DocumentOpened)); + } + for p in &mut self.plugin_events.pending { + p.by_script = false; + } } /// A mark for [`Session::forget_plugin_opens_since`]: the events queued so far. diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 2d15652731..83f6b588d3 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1910,6 +1910,8 @@ impl Session { lost }); drop(lost); + // The job's working copy went with it, with the documents the run opened. + self.plugin_events_script_ended(false); raise_ids(self); self.script_stop.clear(); self.reset_tool(); @@ -2182,6 +2184,7 @@ impl Session { let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left)); close_run(self, &job.host, &mut report, ending(&e.kind)); self.end_job(job, e.kind == RunErrorKind::Internal); + self.plugin_events_script_ended(false); raise_ids(self); self.script_stop.clear(); self.reset_tool(); @@ -2271,6 +2274,7 @@ impl Session { host.more_written(&mut report); close_run(self, host, &mut report, console::Ending::Finished); self.end_job(job, false); + self.plugin_events_script_ended(true); self.script_report = Some(report.clone()); Ok(report) } diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs index 6ee0e8342b..9f757b020e 100644 --- a/crates/engine/src/tests/plugin_events.rs +++ b/crates/engine/src/tests/plugin_events.rs @@ -328,6 +328,49 @@ fn a_save_before_a_failed_batch_step_is_delivered() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// A document a script opened before it failed is discarded with the run's working copy, so the +/// plug-in is not told of it. The save the script made before failing is still given, and so is a +/// document the frontend opened while the run was paused. +#[test] +fn a_failed_script_gives_its_save_but_not_its_open() { + let id = "test.events.failed_script"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + install(&mut s, id, r#"["document.saved","document.opened"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-failed-script-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("failed-script.vectorcraft").to_string_lossy()})); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})]); + let data = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + + s.script_frames = true; + let source = format!( + "vc.run('document.save', {{}}); vc.run('document.open', {{name: 'b.vectorcraft', dataBase64: '{data}'}}); \ + for (var i = 0; i < 3000000; i++) {{}} throw new Error('stop');" + ); + assert_eq!(run(&mut s, "script.run", json!({"source": source, "name": "t.js"}))["running"], true); + assert!(s.script_pump().is_none(), "paused after its first slice"); + let bytes = vectorcraft_format::base64_decode(&data).unwrap(); + let index = crate::cmd::fileio::open_bytes(&mut s, "front.vectorcraft", &bytes, None).unwrap()["index"].as_u64().unwrap(); + let front = s.documents()[index as usize].uid; + let mut slices = 0; + let r = loop { + slices += 1; + assert!(slices < 100_000, "the script ends"); + if let Some(r) = s.script_pump() { + break r; + } + }; + assert!(r.is_err(), "the script threw"); + assert!(s.docs.iter().all(|d| d.uid == doc || d.uid == front), "the script's document was discarded"); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc}), json!({"type": "document.opened", "document": front})]); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + /// A `selection.changed` event of a plug-in without `doc.read` gives the count and no ids; one /// with it lists the selected ids. #[test] From ab75ac0c13e25eaa61848dd518edabfa19b252e0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:19:22 -0800 Subject: [PATCH 04/11] Plug-ins: a module with a manifest section that lists events must export vc_event Changes on main needed the events code and its tests to follow them. - A module that carries its manifest in the `vc_manifest` custom section is loaded without being instantiated, and its exports are checked by `check_exports`. That check now also requires `vc_event` with the type (param i32 i32) (result i32) when the manifest lists `events`, as the instantiated path already did. The `an_event_plugin_exports_vc_event` test covers a sectioned module without `vc_event`, with the wrong type and with the right one. - JavaScript plug-ins have no `vc_event`, so their manifest may not list the permission `events`, next to `settings`, `cache` and `commands`. The JavaScript bundle test and docs/plugins.md say so. - The craft UI framework port removed `VectorcraftApp::begin_host_iteration`, so the two UI-pass event tests no longer call it. - On the framework, the whole window draws only on a context with the framework's runtime installed. `a_change_made_in_a_ui_pass_is_delivered_in_that_pass` drew it on a plain `egui::Context`, where the runtime panics ("the runtime plugin's hooks did not run for the previous pass") and the test did not finish. It now draws its passes with `testing::ui_context` and `testing::part_frame`, as the window tests on main do. --- crates/plugins/src/js.rs | 2 ++ crates/plugins/src/manifest.rs | 4 ++-- crates/plugins/src/runtime.rs | 10 +++++++--- crates/plugins/tests/abi.rs | 10 ++++++++++ crates/ui-egui/src/tests/plugins.rs | 8 +++----- crates/ui-egui/src/tests/script_run.rs | 1 - docs/plugins.md | 4 ++-- 7 files changed, 26 insertions(+), 13 deletions(-) diff --git a/crates/plugins/src/js.rs b/crates/plugins/src/js.rs index a8fa158c41..b10506011f 100644 --- a/crates/plugins/src/js.rs +++ b/crates/plugins/src/js.rs @@ -460,6 +460,8 @@ mod tests { assert!(matches!(&e, Error::Manifest(why) if why.contains("`runtime` \"js\" is for an object filter")), "{e:?}"); let e = refused(bundle("test.js.settings", ok, json!({"api": 2, "permissions": ["settings"]}))); assert!(matches!(&e, Error::Manifest(why) if why.contains("`settings`")), "{e:?}"); + let e = refused(bundle("test.js.events", ok, json!({"api": 2, "permissions": ["events"], "events": ["selection.changed"]}))); + assert!(matches!(&e, Error::Manifest(why) if why.contains("can't list the permission `events`")), "{e:?}"); let e = refused(bundle("test.js.name", ok, json!({"script": "../x.js"}))); assert!(matches!(&e, Error::Manifest(why) if why.starts_with("`script`")), "{e:?}"); let e = refused(bundle("test.js.py", ok, json!({"runtime": "py"}))); diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index 5b06ed24c5..611d51ebbf 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -704,7 +704,7 @@ impl Manifest { } /// A JavaScript plug-in (`"runtime": "js"`) is an object filter, and of the host's permissions - /// it lists only `progress`: its realm has no settings, cache or command calls. + /// it lists only `progress`: its realm has no settings, cache, command calls or `vc_event`. fn validate_runtime(&self) -> Result<()> { if self.runtime == Runtime::Wasm { return Ok(()); @@ -714,7 +714,7 @@ impl Manifest { return Err(Error::Manifest(format!("`runtime` \"js\" is for an object filter (`kind` \"filter\"), not `kind` \"{kind}\""))); } let listed = self.permissions.as_deref().unwrap_or_default(); - for p in [Permission::Settings, Permission::Cache, Permission::Commands] { + for p in [Permission::Settings, Permission::Cache, Permission::Commands, Permission::Events] { if listed.iter().any(|n| n == p.name()) { let name = p.name(); return Err(Error::Manifest(format!( diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 9dd6d574e7..ce8ca5e32c 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -322,8 +322,9 @@ fn check_tables(bytes: &[u8]) -> Result<()> { } /// Checks the exports a run needs without instantiating `module`: its memory as `memory`, whose -/// initial size fits in `max_memory_bytes`, and `vc_alloc` and `vc_run` with the ABI's types. -fn check_exports(module: &Module, max_memory_bytes: usize) -> Result<()> { +/// initial size fits in `max_memory_bytes`, and `vc_alloc` and `vc_run` with the ABI's types, and +/// `vc_event` with its type when `events` is set (the manifest lists events). +fn check_exports(module: &Module, max_memory_bytes: usize, events: bool) -> Result<()> { use ValType::{I32, I64}; let export = |name: &str| module.exports().find(|e| e.name() == name).map(|e| e.ty().clone()); let Some(ExternType::Memory(memory)) = export("memory") else { @@ -341,6 +342,9 @@ fn check_exports(module: &Module, max_memory_bytes: usize) -> Result<()> { return Err(Error::Abi(format!("the module must export `{name}` with the type {signature}"))); } } + if events && !matches!(export("vc_event"), Some(ExternType::Func(f)) if f.params() == [I32, I32] && f.results() == [I32]) { + return Err(Error::Abi("the module lists `events`, so it must export `vc_event` with the type (param i32 i32) (result i32)".into())); + } Ok(()) } @@ -428,7 +432,7 @@ impl Plugin { } } None => { - check_exports(&module, p.limits.max_memory_bytes)?; + check_exports(&module, p.limits.max_memory_bytes, !p.manifest.events.is_empty())?; check_tables(bytes)?; } } diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index 634762ef4e..206faa721e 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -1264,6 +1264,16 @@ fn an_event_plugin_exports_vc_event() { assert!(e.to_string().contains("vc_event"), "{e}"); assert!(Plugin::load(&build(&tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)), Limits::default()).is_ok()); assert!(Plugin::load(&ok_module(tpl::ECHO), Limits::default()).is_ok(), "no events, no vc_event"); + // A module whose manifest is in its custom section is checked without being instantiated. + let section = + r#"{"id":"test.events.section","name":"T","kind":"filter","api":2,"permissions":["events"],"events":["selection.changed"],"abi":1}"#; + let e = Plugin::load(&build(&tpl::sectioned(section, tpl::ECHO, "", 1)), Limits::default()).unwrap_err(); + assert!(e.to_string().contains("vc_event"), "{e}"); + let one_param = r#"(func (export "vc_event") (param i32) (result i32) (i32.const 0))"#; + let e = Plugin::load(&build(&tpl::sectioned(section, tpl::ECHO, one_param, 1)), Limits::default()).unwrap_err(); + assert!(e.to_string().contains("vc_event"), "{e}"); + let handler = r#"(func (export "vc_event") (param i32 i32) (result i32) (i32.const 0))"#; + assert!(Plugin::load(&build(&tpl::sectioned(section, tpl::ECHO, handler, 1)), Limits::default()).is_ok()); } /// `vc_event` is given the event JSON in its own memory and returns 0; anything else, a trap and a diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 1eb8f2081a..53e4f89f33 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -838,20 +838,18 @@ fn a_change_made_in_a_ui_pass_is_delivered_in_that_pass() { app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap(); let r = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); app.run("select.none", json!({})).unwrap(); - let ctx = egui::Context::default(); + let ctx = crate::testing::ui_context(); let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)); let pass = |app: &mut VectorcraftApp, select: bool| { - app.begin_host_iteration(); - let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + crate::testing::part_frame(app, &ctx, egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |app, ui| { app.tick(ui.ctx()); if select { app.session.execute("select.set", &json!({"ids": [r]})).unwrap(); } app.ui(ui); }); - out.textures_delta.clear(); }; - // Fonts install on the first pass and are ready on the second. + // The window lays itself out in the first two passes. pass(&mut app, false); pass(&mut app, false); pass(&mut app, true); diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index a5bd95e881..91803e6b70 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -343,7 +343,6 @@ fn a_finished_run_delivers_its_plugin_events_in_the_frame_it_ends() { if !app.session.script_running() { break; } - app.begin_host_iteration(); let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx())); out.textures_delta.clear(); } diff --git a/docs/plugins.md b/docs/plugins.md index 385925d30f..1646097587 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -1308,8 +1308,8 @@ function run(input, params) { The manifest has the keys of a module's [manifest](#manifest), with `"runtime": "js"` and `script`, a file name of 1 to 128 bytes ending in `.js`, without a folder or `:`, and not starting with `.`. Left out, `runtime` is WebAssembly, so existing modules load as before; a module's own manifest may not give `"js"`. A JavaScript plug-in is a filter (`kind` -`"filter"`), and of the host's [permissions](#permissions) it may list `progress` but not `settings`, `cache` or -`commands`, so it has no `commandAllowlist`. +`"filter"`), and of the host's [permissions](#permissions) it may list `progress` but not `settings`, `cache`, +`commands` or `events`, so it has no `commandAllowlist` and no `events`. `plugin.install {path}` and `plugin.inspect {path}` take the `.vcplugin` file, and File › Open and `plugin.reload` install it like a `.wasm` file. The host refuses a manifest without `script`, with `source`, or with a `runtime` other From c04c53ca6cb612a92a61ffe611afa439e206cc1a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 00:24:17 -0800 Subject: [PATCH 05/11] Plug-ins: hold a running script's events and deliver window-key changes in their pass A delivery between a script's slices no longer gives the opens and saves the script queued; they wait until the run ends, so a run that fails never gives the opens of documents it discarded. The desktop app now delivers after the window keys run, so a selection Escape changes when it leaves isolation mode reaches plug-ins in that pass, and the handlers' time counts toward the frame time. The docs state the per-document grouping and the script rule. --- crates/engine/src/plugin_events.rs | 22 +++++++++--- crates/engine/src/tests/plugin_events.rs | 44 ++++++++++++++++++++++++ crates/ui-egui/src/app.rs | 17 +++++---- crates/ui-egui/src/tests/plugins.rs | 33 ++++++++++++++++++ docs/plugins.md | 12 ++++--- docs/target-app-parity.md | 2 +- 6 files changed, 115 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index 555f2ac308..f853198ebb 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -281,10 +281,12 @@ impl Session { } } - /// At the end of a script's run. When the run failed (`kept` false), drops the waiting - /// `document.opened` events its commands queued, since the documents they opened were discarded - /// with its working copy. Its saves stay, since the files they wrote stay written, and so do the - /// events of documents a frontend opened while the run was paused. + /// At the end of a script's run. The opens and saves its commands queued wait until then, also + /// through deliveries between its slices ([`Session::deliver_plugin_events`]). When the run + /// failed (`kept` false), drops the waiting `document.opened` events its commands queued, since + /// the documents they opened were discarded with its working copy. Its saves stay, since the + /// files they wrote stay written, and so do the events of documents a frontend opened while the + /// run was paused. The next delivery gives what is left in the order it was queued. pub(crate) fn plugin_events_script_ended(&mut self, kept: bool) { if !kept { self.plugin_events.pending.retain(|p| !(p.by_script && p.event == Event::DocumentOpened)); @@ -375,7 +377,15 @@ impl Session { // as it was found. let depth = self.depth; self.depth += 1; + // An open or a save a running script queued waits for the end of the run + // ([`Session::plugin_events_script_ended`]), also when a frontend delivers between its + // slices: a run that fails discards the documents it opened. + let mut held = VecDeque::new(); while let Some(p) = self.plugin_events.pending.pop_front() { + if p.by_script { + held.push_back(p); + continue; + } if !p.event.outlives_document() && !self.docs.iter().any(|d| d.uid == p.document) { continue; } @@ -386,6 +396,10 @@ impl Session { self.run_handler(plugin, &p); } } + // The held events are older than any a handler's calls queued meanwhile. + while let Some(p) = held.pop_back() { + self.plugin_events.pending.push_front(p); + } self.depth = depth; self.plugin_events.dispatching = false; } diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs index 9f757b020e..66b8804a58 100644 --- a/crates/engine/src/tests/plugin_events.rs +++ b/crates/engine/src/tests/plugin_events.rs @@ -371,6 +371,50 @@ fn a_failed_script_gives_its_save_but_not_its_open() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// A delivery between a script's slices, as a frontend makes one for a command it runs while the +/// script is paused, gives the frontend's open but holds the open and the save the script queued +/// until the run ends: the run fails, so its open is never given, and its save is given after it. +#[test] +fn a_delivery_between_script_slices_holds_the_script_events() { + let id = "test.events.between_slices"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + install(&mut s, id, r#"["document.saved","document.opened"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-between-slices-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("between-slices.vectorcraft").to_string_lossy()})); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})]); + let data = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + + s.script_frames = true; + let source = format!( + "vc.run('document.save', {{}}); vc.run('document.open', {{name: 'b.vectorcraft', dataBase64: '{data}'}}); \ + for (var i = 0; i < 3000000; i++) {{}} throw new Error('stop');" + ); + assert_eq!(run(&mut s, "script.run", json!({"source": source, "name": "t.js"}))["running"], true); + assert!(s.script_pump().is_none(), "paused after its first slice"); + let bytes = vectorcraft_format::base64_decode(&data).unwrap(); + let index = crate::cmd::fileio::open_bytes(&mut s, "front.vectorcraft", &bytes, None).unwrap()["index"].as_u64().unwrap(); + let front = s.documents()[index as usize].uid; + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.opened", "document": front})], "only the frontend's open, while the run is paused"); + let mut slices = 0; + let r = loop { + slices += 1; + assert!(slices < 100_000, "the script ends"); + if let Some(r) = s.script_pump() { + break r; + } + }; + assert!(r.is_err(), "the script threw"); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})], "the script's save, and not its open"); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + /// A `selection.changed` event of a plug-in without `doc.read` gives the count and no ids; one /// with it lists the selected ids. #[test] diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index d75c545869..d1998ecd1e 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -673,6 +673,17 @@ impl VectorcraftApp { self.handle_input(&ctx); self.ui_frame(ui); self.window_keys(&ctx); + // What the canvas, a panel, a dialog or a window key changed in this pass reaches + // the plug-ins that react to it now, since an idle app draws no further frame; a + // line a handler wrote shows in the next one. The handlers' time counts toward the + // frame-time sample of a pass egui presents. + let t0 = monotonic_ms(); + if !self.session.script_running() && self.deliver_plugin_events() { + ctx.request_repaint(); + } + if !ctx.will_discard() { + self.perf.frame_ms += monotonic_ms() - t0; + } }) }) { self.session.set_replaying(false); @@ -757,12 +768,6 @@ impl VectorcraftApp { // A command run by a menu, panel or dialog in this pass may have queued its text copy // after the input. Publish it now: an idle web host may have no further frame to run it in. self.flush_clipboard_out(); - // What the canvas, a panel or a dialog changed in this pass reaches the plug-ins that react - // to it now, since an idle app draws no further frame; a line a handler wrote shows in the - // next one. - if !self.session.script_running() && self.deliver_plugin_events() { - ctx.request_repaint(); - } crate::cursors::request_busy(self, &ctx); // A pass egui will discard and rerun is not a presented frame: it must not become the // frame-time sample, and it must not issue a capture of what it drew. diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 27508fb744..455493afaf 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -1065,6 +1065,39 @@ fn a_change_made_in_a_ui_pass_is_delivered_in_that_pass() { app.run("plugin.remove", json!({"id": id})).unwrap(); } +/// Escape leaving isolation mode restores the selection from before entry after the window's +/// panels and dialogs are drawn; the plug-in that reacts to `selection.changed` is still given the +/// change in that pass. +#[test] +fn a_selection_a_window_key_changes_is_delivered_in_that_pass() { + let mut app = app(); + app.session.allow_plugin_grants_from_requests(); + let id = "test.UI.window_key_events"; + let grant = json!(["progress", "events"]); + let manifest = format!(r#"{{"id":"{id}","name":"Key Events","kind":"filter","api":2,"permissions":{grant},"events":["selection.changed"]}}"#); + let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap(); + let a = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + let b = app.run("shape.rectangle", json!({"x": 40, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let g = app.run("object.group", json!({})).unwrap()["id"].clone(); + app.run("object.isolate", json!({"id": g})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let ctx = crate::testing::ui_context(); + super::synthetic::key_frame(&mut app, &ctx, vec![]); + super::synthetic::key_frame(&mut app, &ctx, vec![]); + app.session.deliver_plugin_events(); + let _ = app.session.take_plugin_event_notices(); + let before = app.session.doc().unwrap().selection.objects.clone(); + let esc = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + super::synthetic::key_frame(&mut app, &ctx, vec![esc]); + assert_ne!(app.session.doc().unwrap().selection.objects, before, "Escape left isolation and restored the selection"); + app.session.deliver_plugin_events(); + let left: Vec = app.session.take_plugin_event_notices().into_iter().filter(|n| n.plugin == id).map(|n| n.text).collect(); + assert!(left.is_empty(), "delivered in the pass of the key, not later: {left:?}"); + app.run("plugin.remove", json!({"id": id})).unwrap(); +} + /// The approval names a plug-in whose manifest translates its name in the UI language and also /// gives the manifest's own name, both escaped; a language without a translation shows the /// manifest's name alone. What OK installs stays bound to the id and hash shown. diff --git a/docs/plugins.md b/docs/plugins.md index be672b22b5..cbcdc68d8c 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -873,14 +873,18 @@ or the document's contents. leaves the document as it was (a Layer Options that sets the name it had). Installing a plug-in hands it no past events, also none that were waiting for the next delivery when it was installed. A change made to a document opened or created since the last delivery is an event at the next one, after that document's `document.opened`. -- Changes between two deliveries are one event with the state they ended with. The desktop app delivers in each - frame, after the work that finished in the background and again at the end of the frame, after the canvas, panels - and dialogs have run, so a burst of selection changes in one frame is one `selection.changed` and an idle window does +- The selection changes of one document between two deliveries are one `selection.changed` with the state they ended + with, and its layer changes are one `layer.changed`; each document's events are separate. The desktop app delivers + in each frame, after the work that finished in the background and again at the end of the frame, after the canvas, + panels, dialogs and window keys have run, so a burst of selection changes in one frame is one `selection.changed` and an idle window does not hold an event back. Requests through the control channel, and through MCP in remote mode, run in the desktop app and are delivered by the frame too, and several of them can run in one frame. `vectorcraft-cli` and headless MCP deliver after each request, also one that fails: a save in a `command.batch` whose later step fails still gives its `document.saved`. Opens and saves are each their own event, in order, and are delivered even when the - document closed before the delivery. At most 32 events wait; past that the oldest is dropped. + document closed before the delivery. The opens and saves of a running script wait until its run ends, also + through any delivery between its slices. The desktop app does not deliver while a script runs; a frontend that + does can give its own opens and saves made while the run was paused before the script's earlier ones. A run that fails gives its saves and none of its opens. At most 32 + events wait; past that the oldest is dropped. - A handler only reads. VectorCraft applies nothing it returns, and it is outside any undo step. With `commands` and a `commandAllowlist`, it may [call](#command-calls) these commands, when the allowlist also names them, on the active document: `dataset.list`, `graphicStyle.list`, `guide.list`, `image.info`, `object.blend.info`, `swatch.list`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ff2a01dc47..96e6748b6a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2836,7 +2836,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Changed plug-in gradients lose spot plates (G17):** a gradient that a filter or importer changes loses each stop's swatch link, tint and process `plates` together, in fills and strokes, and keeps the stop's color, offset, opacity and midpoint; a gradient returned unchanged keeps all three. Regressions: `crates/plugins/src/objects/tests.rs` (`changed_gradient_fill_and_stroke_drop_spot_plates`, `unchanged_gradient_paint_keeps_spot_plates`). Scores and hours unchanged. - **Plug-in data kept with the document (G17):** a filter writes JSON of at most 1 MiB with `documentData` (one undo step with its objects; `null` removes it) and reads it back in `_context.documentData`, which no other filter is given. It is the document's foreign data (`unknown.pluginData`, by plug-in id), as the perspective grid is, so the native file keeps it with no section of its own; an exporter is given the whole document, so it can read every plug-in's. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_export.rs` (the exporter), `crates/doc/src/plugin_data.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged. - **Heavy filter plug-ins (G17):** a filter's manifest may ask for `"budget": "heavy"`: 1 G instructions (20 times a light run's) and 300 s a run, for routing, packing or simulation. Install Plug-in… and File › Open ask the user first, `plugin.install` needs `allowHeavy: true` (`plugin.inspect` tells beforehand), the Additional Plug-ins Folder skips such filters, and the plug-in store keeps the answer. Its dialog has no Preview; the app runs it on a thread of its own with a progress window (Cancel, Continue in Background) and applies the result as `plugin.run` with the same parameters, one undo step, unless the document or the plug-in changed meanwhile. Regressions: `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. -- **Plug-ins react to events (G17, VectorCraft's own API):** a plug-in at API level 2 with the `events` permission names any of `selection.changed`, `document.opened`, `document.saved` and `layer.changed` in its manifest, and its `vc_event` export is given a small JSON event after each change of that kind has finished, outside any undo step: changes between two deliveries (a frame in the desktop app, a request in `vectorcraft-cli` or headless MCP) are one event. A handler only reads: it may call only ten listed commands that read, any other call fails with an error naming the event, and what a call changed is put back. It gets 5 M instructions and 200 ms, a handler that fails 3 times in a row gets no more events for the session, and an event raised while a handler runs waits for the next delivery. Regressions: `crates/engine/src/tests/plugin_events.rs`, `crates/engine/src/plugin_events.rs`, `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. +- **Plug-ins react to events (G17, VectorCraft's own API):** a plug-in at API level 2 with the `events` permission names any of `selection.changed`, `document.opened`, `document.saved` and `layer.changed` in its manifest, and its `vc_event` export is given a small JSON event after each change of that kind has finished, outside any undo step: the selection changes of one document between two deliveries (a frame in the desktop app, a request in `vectorcraft-cli` or headless MCP) are one event, and so are its layer changes, while each open and each save is its own event and each document's events stay separate. A handler only reads: it may call only ten listed commands that read, any other call fails with an error naming the event, and what a call changed is put back. It gets 5 M instructions and 200 ms, a handler that fails 3 times in a row gets no more events for the session, and an event raised while a handler runs waits for the next delivery. Regressions: `crates/engine/src/tests/plugin_events.rs`, `crates/engine/src/plugin_events.rs`, `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. - **Apply Last Filter and Last Filter… for filter plug-ins (G17):** Object › Plug-ins starts with Apply Last Filter (`plugin.applyLastFilter`), which runs the filter plug-in that last ran in the session again with the same parameters on the selection, without its dialog, as one undo step, and Last Filter… (`plugin.lastFilter`), which opens that filter's dialog with those parameters; once a filter has run, both items are named after it. [The help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=357) describes the same pair for filters: one item repeats the last filter with its last settings, the other opens its options. Each filter's own dialog opens with the parameters that filter last ran with. A heavy filter repeats in the background as its menu item runs it. Both items are grayed out with no document open, before a filter ran, and once that filter was removed, installed again or no longer takes the parameters as they are; they don't need a selection (VectorCraft's own rules). Regressions: `crates/ui-egui/src/tests/last_filter.rs`. Scores and hours unchanged. - **Plug-in instruction budget preference (G17, VectorCraft's own setting):** Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget (`pluginInstructionBudget`) is Normal by default, which keeps the 50 M instructions a light filter run gets, or Large, which gives each object filter run 250 M plus the 4,000 per input byte, with the 60 s time budget, Cancel and the other limits unchanged. A heavy filter keeps its 1 G and 300 s with either choice; live effects, exporters and importers keep their own budgets. A change applies to the next run of an installed filter; `prefs.set` refuses any other value, and a saved file with another value reads as Normal. Regressions: `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. Scores and hours unchanged. - **Safe Mode for plug-ins (G17):** `vectorcraft --safe-mode` and `vectorcraft-cli --safe-mode ` 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. From 975c43a680432dc408f0b449ca1bdcc571e8eb96 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 09:51:27 -0800 Subject: [PATCH 06/11] Plug-ins: correct the plugin.install fields and event delivery in docs/mcp.md docs/mcp.md now says that plugin.install lists only unknownCommands, and that a plug-in receives only the event kinds its manifest's events list names. The translated catalog rows for the event strings are removed; feature pull requests add English only. --- crates/ui-egui/src/i18n/bg.tsv | 1 - crates/ui-egui/src/i18n/bs.tsv | 1 - crates/ui-egui/src/i18n/ca.tsv | 10 ---------- crates/ui-egui/src/i18n/cs.tsv | 10 ---------- crates/ui-egui/src/i18n/da.tsv | 10 ---------- crates/ui-egui/src/i18n/de.tsv | 10 ---------- crates/ui-egui/src/i18n/el.tsv | 10 ---------- crates/ui-egui/src/i18n/es.tsv | 10 ---------- crates/ui-egui/src/i18n/fi.tsv | 10 ---------- crates/ui-egui/src/i18n/fr.tsv | 10 ---------- crates/ui-egui/src/i18n/gu.tsv | 1 - crates/ui-egui/src/i18n/hi.tsv | 10 ---------- crates/ui-egui/src/i18n/hu.tsv | 10 ---------- crates/ui-egui/src/i18n/id.tsv | 10 ---------- crates/ui-egui/src/i18n/it.tsv | 10 ---------- crates/ui-egui/src/i18n/ja.tsv | 10 ---------- crates/ui-egui/src/i18n/ka.tsv | 10 ---------- crates/ui-egui/src/i18n/ko.tsv | 10 ---------- crates/ui-egui/src/i18n/nl.tsv | 10 ---------- crates/ui-egui/src/i18n/pl.tsv | 10 ---------- crates/ui-egui/src/i18n/pt-br.tsv | 10 ---------- crates/ui-egui/src/i18n/ru.tsv | 10 ---------- crates/ui-egui/src/i18n/sv.tsv | 10 ---------- crates/ui-egui/src/i18n/tr.tsv | 10 ---------- crates/ui-egui/src/i18n/uk.tsv | 10 ---------- crates/ui-egui/src/i18n/vi.tsv | 10 ---------- crates/ui-egui/src/i18n/zh-hans.tsv | 10 ---------- crates/ui-egui/src/i18n/zh-hant.tsv | 10 ---------- docs/mcp.md | 7 ++++--- 29 files changed, 4 insertions(+), 256 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 7ad579423d..b7ad3eb99b 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7405,7 +7405,6 @@ axis Y Axis Y ос Show its progress, see Cancel and write log lines Показване на напредъка, разпознаване на отказ и записване на редове в дневника Keep settings of its own Съхраняване на собствени настройки Keep a cache of its own, which you can clear Съхраняване на собствен кеш, който можете да изчистите - Run on its own when the selection, a document or a layer changes Изпълняване самостоятелно, когато се промени селекцията, документ или слой Run these commands on the document: {ids} Изпълняване на тези команди върху документа: {ids} Clear Plug-in Cache Изчистване на кеша на добавката # Actions panel: action sets (#3712). diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index b42abae79d..b125e378f5 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6762,7 +6762,6 @@ axis Y Axis Y osa Show its progress, see Cancel and write log lines Prikazati napredak, prepoznati otkazivanje i zapisivati redove dnevnika Keep settings of its own Čuvati vlastite postavke Keep a cache of its own, which you can clear Čuvati vlastitu predmemoriju koju možete očistiti - Run on its own when the selection, a document or a layer changes Pokretati se samostalno kada se promijeni odabir, dokument ili sloj Run these commands on the document: {ids} Izvršavati ove naredbe na dokumentu: {ids} Clear Plug-in Cache Očisti predmemoriju dodatka @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} dozvola `{permission}` zahtijeva nivo API-ja dodataka {PROGRESS_API}: navedite `api` {PROGRESS_API} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a1f357f9e9..555080655a 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7922,7 +7922,6 @@ variable-list-end {0}, {1} {0} i {1} Show its progress, see Cancel and write log lines Mostrar el progrés, detectar la cancel·lació i escriure línies de registre Keep settings of its own Desar una configuració pròpia Keep a cache of its own, which you can clear Desar una memòria cau pròpia, que podeu buidar - Run on its own when the selection, a document or a layer changes Executar-se per si sol quan canvia la selecció, un document o una capa Run these commands on the document: {ids} Executar aquestes ordres al document: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call «{name}» inclou `{id}` a `commandAllowlist`, que un complement no pot cridar @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7956,15 +7955,6 @@ variable-list-end {0}, {1} {0} i {1} @msg only a filter declares `inputs` només un filtre declara `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` anomena un tipus d’objecte desconegut `{shown}`: feu servir type, image o symbolInstance @msg `inputs` lists `{shown}` twice `inputs` inclou `{shown}` dues vegades -@msg `events` lists `{shown}` twice `events` inclou `{shown}` dues vegades -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` anomena un esdeveniment desconegut `{shown}`: feu servir selection.changed, document.opened, document.saved o layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` necessita el nivell d’API de complements {EVENTS_API}: indiqueu `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` necessita el permís `events`, i `events` necessita una llista d’`events` -@msg event size ({len} bytes, limit {max}) mida de l’esdeveniment ({len} bytes, límit {max}) -@msg the module reacts to no events el mòdul no reacciona a cap esdeveniment -@msg vc_event returned {code} vc_event ha retornat {code} -@msg {name}: its {event} handler failed: {e} {name}: el seu gestor de {event} ha fallat: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: els seus esdeveniments estan desactivats fins que VectorCraft torni a iniciar-se, després de {count} gestors fallits seguits @msg `inputs` needs `api` 2 or later `inputs` requereix `api` 2 o posterior @msg `inputs` needs the permission `doc.read` `inputs` requereix el permís `doc.read` @msg only a filter declares `writes` només un filtre declara `writes` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 3bf50bbad7..8d11266cdd 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7533,7 +7533,6 @@ axis Y Axis osa Y Show its progress, see Cancel and write log lines Zobrazit průběh, rozpoznat zrušení a zapisovat řádky protokolu Keep settings of its own Uchovávat vlastní nastavení Keep a cache of its own, which you can clear Uchovávat vlastní mezipaměť, kterou můžete vymazat - Run on its own when the selection, a document or a layer changes Spouštět se samostatně, když se změní výběr, dokument nebo vrstva Run these commands on the document: {ids} Spouštět v dokumentu tyto příkazy: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ uvádí v `commandAllowlist` příkaz `{id}`, který zásuvný modul nesmí volat @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7567,15 +7566,6 @@ axis Y Axis osa Y @msg only a filter declares `inputs` `inputs` deklaruje pouze filtr @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` uvádí neznámý druh objektu `{shown}`: použijte type, image nebo symbolInstance @msg `inputs` lists `{shown}` twice `inputs` uvádí `{shown}` dvakrát -@msg `events` lists `{shown}` twice `events` uvádí `{shown}` dvakrát -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` uvádí neznámou událost `{shown}`: použijte selection.changed, document.opened, document.saved nebo layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` vyžaduje úroveň API zásuvných modulů {EVENTS_API}: uveďte `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` potřebuje oprávnění `events` a `events` potřebuje seznam `events` -@msg event size ({len} bytes, limit {max}) velikost události ({len} bajtů, limit {max}) -@msg the module reacts to no events modul nereaguje na žádné události -@msg vc_event returned {code} vc_event vrátila {code} -@msg {name}: its {event} handler failed: {e} {name}: jeho obslužná rutina {event} selhala: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: jeho události jsou vypnuté, dokud se VectorCraft znovu nespustí, po {count} neúspěšných obslužných rutinách za sebou @msg `inputs` needs `api` 2 or later `inputs` vyžaduje `api` 2 nebo vyšší @msg `inputs` needs the permission `doc.read` `inputs` vyžaduje oprávnění `doc.read` @msg only a filter declares `writes` `writes` deklaruje pouze filtr diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 86e3898446..9820804ff0 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -732,15 +732,6 @@ liquify-list-end {0}, {1} {0} og {1} @msg only a filter declares `inputs` kun et filter angiver `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` angiver en ukendt objekttype `{shown}`: brug type, image eller symbolInstance @msg `inputs` lists `{shown}` twice `inputs` angiver `{shown}` to gange -@msg `events` lists `{shown}` twice `events` angiver `{shown}` to gange -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` angiver en ukendt hændelse `{shown}`: brug selection.changed, document.opened, document.saved eller layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` kræver plug-in-API-niveau {EVENTS_API}: angiv `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` kræver tilladelsen `events`, og `events` kræver en liste `events` -@msg event size ({len} bytes, limit {max}) hændelsesstørrelse ({len} byte, grænse {max}) -@msg the module reacts to no events modulet reagerer ikke på nogen hændelser -@msg vc_event returned {code} vc_event returnerede {code} -@msg {name}: its {event} handler failed: {e} {name}: dens {event}-handler mislykkedes: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: dens hændelser er slået fra, indtil VectorCraft starter igen, efter {count} mislykkede handlere i træk @msg `inputs` needs `api` 2 or later `inputs` kræver `api` 2 eller nyere @msg `inputs` needs the permission `doc.read` `inputs` kræver tilladelsen `doc.read` @msg only a filter declares `writes` kun et filter angiver `writes` @@ -9773,7 +9764,6 @@ axis Y Axis Y-akse Show its progress, see Cancel and write log lines Vise sin fremdrift, se en annullering og skrive logrækker Keep settings of its own Gemme sine egne indstillinger Keep a cache of its own, which you can clear Gemme sin egen cache, som du kan rydde - Run on its own when the selection, a document or a layer changes Køre af sig selv, når markeringen, et dokument eller et lag ændres Run these commands on the document: {ids} Køre disse kommandoer på dokumentet: {ids} Clear Plug-in Cache Ryd plug-in-cache # Actions panel: action sets (#3712). diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 93a3791445..d29f3c46c0 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -7114,7 +7114,6 @@ axis Y Axis Y-Achse Show its progress, see Cancel and write log lines Den Fortschritt anzeigen, ein Abbrechen erkennen und Protokollzeilen schreiben Keep settings of its own Eigene Einstellungen speichern Keep a cache of its own, which you can clear Einen eigenen Cache anlegen, den Sie leeren können - Run on its own when the selection, a document or a layer changes Von selbst ausgeführt werden, wenn sich die Auswahl, ein Dokument oder eine Ebene ändert Run these commands on the document: {ids} Diese Befehle im Dokument ausführen: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ führt `{id}` in `commandAllowlist` auf, den ein Plug-in nicht aufrufen darf @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7148,15 +7147,6 @@ axis Y Axis Y-Achse @msg only a filter declares `inputs` nur ein Filter deklariert `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` nennt eine unbekannte Objektart `{shown}`: verwenden Sie type, image oder symbolInstance @msg `inputs` lists `{shown}` twice `inputs` führt `{shown}` doppelt auf -@msg `events` lists `{shown}` twice `events` führt `{shown}` doppelt auf -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` nennt ein unbekanntes Ereignis `{shown}`: verwenden Sie selection.changed, document.opened, document.saved oder layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` braucht die Plug-in-API-Stufe {EVENTS_API}: Geben Sie `api` {EVENTS_API} an -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` braucht die Berechtigung `events`, und `events` braucht eine Liste `events` -@msg event size ({len} bytes, limit {max}) Ereignisgröße ({len} Byte, Grenze {max}) -@msg the module reacts to no events das Modul reagiert auf keine Ereignisse -@msg vc_event returned {code} vc_event hat {code} zurückgegeben -@msg {name}: its {event} handler failed: {e} {name}: sein Handler für {event} ist fehlgeschlagen: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: seine Ereignisse sind aus, bis VectorCraft neu startet, nach {count} fehlgeschlagenen Handlern in Folge @msg `inputs` needs `api` 2 or later `inputs` erfordert `api` 2 oder höher @msg `inputs` needs the permission `doc.read` `inputs` erfordert die Berechtigung `doc.read` @msg only a filter declares `writes` nur ein Filter deklariert `writes` diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 5793976fc4..e4a651342a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7525,7 +7525,6 @@ axis Y Axis Άξονας Y Show its progress, see Cancel and write log lines Εμφάνιση της προόδου, αναγνώριση της ακύρωσης και εγγραφή γραμμών καταγραφής Keep settings of its own Διατήρηση δικών του ρυθμίσεων Keep a cache of its own, which you can clear Διατήρηση δικής του κρυφής μνήμης, την οποία μπορείτε να εκκαθαρίσετε - Run on its own when the selection, a document or a layer changes Εκτέλεση από μόνο του όταν αλλάζει η επιλογή, ένα έγγραφο ή ένα επίπεδο Run these commands on the document: {ids} Εκτέλεση αυτών των εντολών στο έγγραφο: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call το «{name}» αναφέρει το `{id}` στο `commandAllowlist`, το οποίο ένα πρόσθετο δεν επιτρέπεται να καλέσει @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7559,15 +7558,6 @@ axis Y Axis Άξονας Y @msg only a filter declares `inputs` μόνο ένα φίλτρο δηλώνει `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance το `inputs` αναφέρει άγνωστο είδος αντικειμένου `{shown}`: χρησιμοποιήστε type, image ή symbolInstance @msg `inputs` lists `{shown}` twice το `inputs` αναφέρει το `{shown}` δύο φορές -@msg `events` lists `{shown}` twice το `events` αναφέρει το `{shown}` δύο φορές -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed το `events` αναφέρει άγνωστο συμβάν `{shown}`: χρησιμοποιήστε selection.changed, document.opened, document.saved ή layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} το `events` χρειάζεται το επίπεδο API προσθέτων {EVENTS_API}: δώστε `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` το `events` χρειάζεται το δικαίωμα `events`, και το `events` χρειάζεται μια λίστα `events` -@msg event size ({len} bytes, limit {max}) μέγεθος συμβάντος ({len} byte, όριο {max}) -@msg the module reacts to no events η λειτουργική μονάδα δεν αντιδρά σε κανένα συμβάν -@msg vc_event returned {code} η vc_event επέστρεψε {code} -@msg {name}: its {event} handler failed: {e} {name}: ο χειριστής {event} του απέτυχε: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: τα συμβάντα του είναι απενεργοποιημένα μέχρι να ξεκινήσει ξανά το VectorCraft, μετά από {count} αποτυχημένους χειριστές στη σειρά @msg `inputs` needs `api` 2 or later το `inputs` απαιτεί `api` 2 ή νεότερο @msg `inputs` needs the permission `doc.read` το `inputs` απαιτεί το δικαίωμα `doc.read` @msg only a filter declares `writes` μόνο ένα φίλτρο δηλώνει `writes` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c28838db0b..008a0b6483 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7511,7 +7511,6 @@ axis Y Axis Eje Y Show its progress, see Cancel and write log lines Mostrar su progreso, detectar la cancelación y escribir líneas de registro Keep settings of its own Guardar una configuración propia Keep a cache of its own, which you can clear Guardar una caché propia, que usted puede vaciar - Run on its own when the selection, a document or a layer changes Ejecutarse por sí solo cuando cambia la selección, un documento o una capa Run these commands on the document: {ids} Ejecutar estos comandos en el documento: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” incluye `{id}` en `commandAllowlist`, que un plugin no puede llamar @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7545,15 +7544,6 @@ axis Y Axis Eje Y @msg only a filter declares `inputs` solo un filtro declara `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` nombra un tipo de objeto desconocido `{shown}`: use type, image o symbolInstance @msg `inputs` lists `{shown}` twice `inputs` incluye `{shown}` dos veces -@msg `events` lists `{shown}` twice `events` incluye `{shown}` dos veces -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` nombra un evento desconocido `{shown}`: use selection.changed, document.opened, document.saved o layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` necesita el nivel de API de plugins {EVENTS_API}: indique `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` necesita el permiso `events`, y `events` necesita una lista de `events` -@msg event size ({len} bytes, limit {max}) tamaño del evento ({len} bytes, límite {max}) -@msg the module reacts to no events el módulo no reacciona a ningún evento -@msg vc_event returned {code} vc_event devolvió {code} -@msg {name}: its {event} handler failed: {e} {name}: su controlador de {event} falló: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: sus eventos están desactivados hasta que VectorCraft se inicie de nuevo, tras {count} controladores fallidos seguidos @msg `inputs` needs `api` 2 or later `inputs` requiere `api` 2 o posterior @msg `inputs` needs the permission `doc.read` `inputs` requiere el permiso `doc.read` @msg only a filter declares `writes` solo un filtro declara `writes` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 52c17b0d07..ffbeb6f49b 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7602,7 +7602,6 @@ axis Y Axis Y-akseli Show its progress, see Cancel and write log lines Näyttää edistymisensä, havaita peruutuksen ja kirjoittaa lokirivejä Keep settings of its own Säilyttää omat asetuksensa Keep a cache of its own, which you can clear Säilyttää oman välimuistin, jonka voit tyhjentää - Run on its own when the selection, a document or a layer changes Käynnistyä itsestään, kun valinta, asiakirja tai taso muuttuu Run these commands on the document: {ids} Suorittaa nämä komennot asiakirjassa: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call ”{name}” luettelee `commandAllowlist`-luettelossa komennon `{id}`, jota laajennus ei saa kutsua @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7636,15 +7635,6 @@ axis Y Axis Y-akseli @msg only a filter declares `inputs` vain suodatin voi määrittää `inputs`-avaimen @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` nimeää tuntemattoman objektilajin `{shown}`: käytä arvoa type, image tai symbolInstance @msg `inputs` lists `{shown}` twice `inputs` luettelee kohteen `{shown}` kahdesti -@msg `events` lists `{shown}` twice `events` luettelee kohteen `{shown}` kahdesti -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` nimeää tuntemattoman tapahtuman `{shown}`: käytä arvoa selection.changed, document.opened, document.saved tai layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` vaatii laajennus-API:n tason {EVENTS_API}: anna `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` tarvitsee käyttöoikeuden `events`, ja `events` tarvitsee `events`-luettelon -@msg event size ({len} bytes, limit {max}) tapahtuman koko ({len} tavua, raja {max}) -@msg the module reacts to no events moduuli ei reagoi mihinkään tapahtumaan -@msg vc_event returned {code} vc_event palautti {code} -@msg {name}: its {event} handler failed: {e} {name}: sen {event}-käsittelijä epäonnistui: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: sen tapahtumat ovat pois päältä, kunnes VectorCraft käynnistyy uudelleen, {count} peräkkäin epäonnistuneen käsittelijän jälkeen @msg `inputs` needs `api` 2 or later `inputs` edellyttää `api`-tasoa 2 tai uudempaa @msg `inputs` needs the permission `doc.read` `inputs` edellyttää käyttöoikeutta `doc.read` @msg only a filter declares `writes` vain suodatin voi määrittää `writes`-avaimen diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index dc7c27f2c1..7e03e3b7c4 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7529,7 +7529,6 @@ axis Y Axis Axe Y Show its progress, see Cancel and write log lines Afficher sa progression, détecter l’annulation et écrire des lignes de journal Keep settings of its own Conserver ses propres réglages Keep a cache of its own, which you can clear Conserver son propre cache, que vous pouvez vider - Run on its own when the selection, a document or a layer changes S’exécuter de lui-même quand la sélection, un document ou un calque change Run these commands on the document: {ids} Exécuter ces commandes sur le document : {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call « {name} » indique `{id}` dans `commandAllowlist`, qu’un module externe ne peut pas appeler @msg vc_call `{shown}`: {why} vc_call `{shown}` : {why} @@ -7564,15 +7563,6 @@ axis Y Axis Axe Y @msg only a filter declares `inputs` seul un filtre déclare `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` désigne un type d’objet inconnu `{shown}` : utilisez type, image ou symbolInstance @msg `inputs` lists `{shown}` twice `inputs` mentionne `{shown}` deux fois -@msg `events` lists `{shown}` twice `events` mentionne `{shown}` deux fois -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` désigne un événement inconnu `{shown}`, utilisez selection.changed, document.opened, document.saved ou layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` nécessite le niveau d’API de module externe {EVENTS_API}, indiquez `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` a besoin de l’autorisation `events`, et `events` a besoin d’une liste `events` -@msg event size ({len} bytes, limit {max}) taille de l’événement ({len} octets, limite {max}) -@msg the module reacts to no events le module ne réagit à aucun événement -@msg vc_event returned {code} vc_event a renvoyé {code} -@msg {name}: its {event} handler failed: {e} {name} : son gestionnaire {event} a échoué : {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name} : ses événements sont désactivés jusqu’au prochain démarrage de VectorCraft, après {count} gestionnaires en échec d’affilée @msg `inputs` needs `api` 2 or later `inputs` nécessite `api` 2 ou plus @msg `inputs` needs the permission `doc.read` `inputs` nécessite l’autorisation `doc.read` @msg only a filter declares `writes` seul un filtre déclare `writes` diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 1c14d54ee4..497ef4d6d8 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2039,7 +2039,6 @@ Keep Shared Points Together વહેંચાયેલા પોઇન્ટ સાથે રાખો Keep Tools Beside the Canvas ટૂલ્સ કેનવાસની બાજુમાં રાખો Keep a cache of its own, which you can clear તેનું પોતાનું કેશ રાખો, જે તમે સાફ કરી શકો છો - Run on its own when the selection, a document or a layer changes પસંદગી, દસ્તાવેજ અથવા લેયર બદલાય ત્યારે આપમેળે ચાલો Keep a link to an image file instead of only embedding it ઇમેજ ફાઇલને ફક્ત એમ્બેડ કરવાને બદલે તેની લિંક રાખો Keep both sides the same width બંને બાજુ સમાન પહોળાઈ રાખો Keep data of its own with the document દસ્તાવેજ સાથે પોતાનો ડેટા રાખો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 5acd19bcd8..8ad28968c5 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6686,7 +6686,6 @@ arrowhead Feather पंख Show its progress, see Cancel and write log lines अपनी प्रगति दिखाना, रद्द करने का अनुरोध देखना और लॉग पंक्तियाँ लिखना Keep settings of its own अपनी सेटिंग्स रखना Keep a cache of its own, which you can clear अपना कैश रखना, जिसे आप साफ़ कर सकते हैं - Run on its own when the selection, a document or a layer changes सिलेक्शन, कोई डॉक्यूमेंट या कोई लेयर बदलने पर अपने आप चलना Run these commands on the document: {ids} दस्तावेज़ पर ये कमांड चलाना: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” `commandAllowlist` में `{id}` सूचीबद्ध करता है, जिसे कोई प्लग-इन कॉल नहीं कर सकता @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -6720,15 +6719,6 @@ arrowhead Feather पंख @msg only a filter declares `inputs` केवल फ़िल्टर `inputs` घोषित करता है @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` में अज्ञात ऑब्जेक्ट प्रकार `{shown}` है: type, image या symbolInstance का उपयोग करें @msg `inputs` lists `{shown}` twice `inputs` में `{shown}` दो बार सूचीबद्ध है -@msg `events` lists `{shown}` twice `events` में `{shown}` दो बार सूचीबद्ध है -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` में अज्ञात इवेंट `{shown}` है: selection.changed, document.opened, document.saved या layer.changed का उपयोग करें -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` के लिए प्लग-इन API स्तर {EVENTS_API} चाहिए: `api` {EVENTS_API} दें -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` को `events` अनुमति चाहिए, और `events` को `events` की सूची चाहिए -@msg event size ({len} bytes, limit {max}) इवेंट का आकार ({len} बाइट्स, सीमा {max}) -@msg the module reacts to no events मॉड्यूल किसी भी इवेंट पर प्रतिक्रिया नहीं करता -@msg vc_event returned {code} vc_event ने {code} लौटाया -@msg {name}: its {event} handler failed: {e} {name}: इसका {event} हैंडलर विफल हुआ: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: लगातार {count} हैंडलर विफल होने के बाद, VectorCraft के फिर से शुरू होने तक इसके इवेंट बंद हैं @msg `inputs` needs `api` 2 or later `inputs` के लिए `api` 2 या बाद का स्तर आवश्यक है @msg `inputs` needs the permission `doc.read` `inputs` के लिए अनुमति `doc.read` आवश्यक है @msg only a filter declares `writes` केवल फ़िल्टर `writes` घोषित करता है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index da7fda0f8d..3116815efa 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7518,7 +7518,6 @@ axis Y Axis Y tengely Show its progress, see Cancel and write log lines Megjelenítheti az előrehaladását, észlelheti a megszakítást és naplósorokat írhat Keep settings of its own Saját beállításokat tárolhat Keep a cache of its own, which you can clear Saját gyorsítótárat tárolhat, amelyet Ön kiüríthet - Run on its own when the selection, a document or a layer changes Magától futhat, amikor a kijelölés, egy dokumentum vagy egy réteg megváltozik Run these commands on the document: {ids} Ezeket a parancsokat futtathatja a dokumentumon: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call a(z) „{name}” a(z) `{id}` parancsot sorolja fel a `commandAllowlist` listában, amelyet bővítmény nem hívhat meg @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7552,15 +7551,6 @@ axis Y Axis Y tengely @msg only a filter declares `inputs` `inputs` kulcsot csak szűrő adhat meg @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance az `inputs` ismeretlen objektumfajtát nevez meg: `{shown}`; használja a type, image vagy symbolInstance értéket @msg `inputs` lists `{shown}` twice az `inputs` kétszer sorolja fel ezt: `{shown}` -@msg `events` lists `{shown}` twice az `events` kétszer sorolja fel ezt: `{shown}` -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed az `events` ismeretlen eseményt nevez meg: `{shown}`; használja a selection.changed, document.opened, document.saved vagy layer.changed értéket -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} az `events` listához {EVENTS_API}. szintű bővítmény-API kell: adja meg az `api` {EVENTS_API} értéket -@msg `events` needs the permission `events`, and `events` needs a list of `events` az `events` listához az `events` engedély szükséges, az `events` engedélyhez pedig `events` lista -@msg event size ({len} bytes, limit {max}) esemény mérete ({len} bájt, korlát {max}) -@msg the module reacts to no events a modul egyetlen eseményre sem reagál -@msg vc_event returned {code} a vc_event {code} értéket adott vissza -@msg {name}: its {event} handler failed: {e} {name}: a(z) {event} kezelője sikertelen volt: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: az eseményei ki vannak kapcsolva a VectorCraft következő indításáig, {count} egymást követő sikertelen kezelő után @msg `inputs` needs `api` 2 or later az `inputs` használatához `api` 2 vagy újabb szükséges @msg `inputs` needs the permission `doc.read` az `inputs` használatához a(z) `doc.read` engedély szükséges @msg only a filter declares `writes` `writes` kulcsot csak szűrő adhat meg diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 7a7852a3e2..b159d2bfb7 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -613,15 +613,6 @@ @msg only a filter declares `inputs` hanya filter yang mendeklarasikan `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` menyebut jenis objek yang tidak dikenal `{shown}`: gunakan type, image atau symbolInstance @msg `inputs` lists `{shown}` twice `inputs` mencantumkan `{shown}` dua kali -@msg `events` lists `{shown}` twice `events` mencantumkan `{shown}` dua kali -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` menyebut peristiwa yang tidak dikenal `{shown}`: gunakan selection.changed, document.opened, document.saved atau layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` memerlukan API plug-in tingkat {EVENTS_API}: berikan `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` memerlukan izin `events`, dan `events` memerlukan daftar `events` -@msg event size ({len} bytes, limit {max}) ukuran peristiwa ({len} byte, batas {max}) -@msg the module reacts to no events modul tidak bereaksi terhadap peristiwa apa pun -@msg vc_event returned {code} vc_event mengembalikan {code} -@msg {name}: its {event} handler failed: {e} {name}: handler {event}-nya gagal: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: event-nya dimatikan hingga VectorCraft dimulai lagi, setelah {count} handler gagal berturut-turut @msg `inputs` needs `api` 2 or later `inputs` memerlukan `api` 2 atau lebih baru @msg `inputs` needs the permission `doc.read` `inputs` memerlukan izin `doc.read` @msg only a filter declares `writes` hanya filter yang mendeklarasikan `writes` @@ -7555,7 +7546,6 @@ axis Y Axis Sumbu Y Show its progress, see Cancel and write log lines Menampilkan kemajuannya, mengenali pembatalan, dan menulis baris log Keep settings of its own Menyimpan pengaturannya sendiri Keep a cache of its own, which you can clear Menyimpan cache-nya sendiri, yang dapat Anda kosongkan - Run on its own when the selection, a document or a layer changes Berjalan sendiri saat seleksi, dokumen, atau lapisan berubah Run these commands on the document: {ids} Menjalankan perintah ini pada dokumen: {ids} Clear Plug-in Cache Kosongkan cache plug-in # Actions panel: action sets (#3712). diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5333bdc0b3..d6b341a367 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -7153,7 +7153,6 @@ axis Y Axis Asse Y Show its progress, see Cancel and write log lines Mostrare il proprio avanzamento, rilevare l’annullamento e scrivere righe di registro Keep settings of its own Conservare impostazioni proprie Keep a cache of its own, which you can clear Conservare una cache propria, che è possibile svuotare - Run on its own when the selection, a document or a layer changes Eseguirsi da solo quando cambia la selezione, un documento o un livello Run these commands on the document: {ids} Eseguire questi comandi sul documento: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” elenca `{id}` in `commandAllowlist`, che un plug-in non può chiamare @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7187,15 +7186,6 @@ axis Y Axis Asse Y @msg only a filter declares `inputs` solo un filtro dichiara `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` indica un tipo di oggetto sconosciuto `{shown}`: usa type, image o symbolInstance @msg `inputs` lists `{shown}` twice `inputs` elenca `{shown}` due volte -@msg `events` lists `{shown}` twice `events` elenca `{shown}` due volte -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` indica un evento sconosciuto `{shown}`: usa selection.changed, document.opened, document.saved o layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` richiede il livello API dei plug-in {EVENTS_API}: indicare `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` richiede l’autorizzazione `events`, e `events` richiede un elenco `events` -@msg event size ({len} bytes, limit {max}) dimensione dell’evento ({len} byte, limite {max}) -@msg the module reacts to no events il modulo non reagisce ad alcun evento -@msg vc_event returned {code} vc_event ha restituito {code} -@msg {name}: its {event} handler failed: {e} {name}: il suo gestore di {event} non è riuscito: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: i suoi eventi sono disattivati finché VectorCraft non si riavvia, dopo {count} gestori non riusciti di fila @msg `inputs` needs `api` 2 or later `inputs` richiede `api` 2 o successivo @msg `inputs` needs the permission `doc.read` `inputs` richiede l’autorizzazione `doc.read` @msg only a filter declares `writes` solo un filtro dichiara `writes` diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index b9f738160e..48f6dd36cf 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7228,7 +7228,6 @@ axis Y Axis Y 軸 Show its progress, see Cancel and write log lines 進行状況の表示、キャンセルの検知、ログ行の書き込み Keep settings of its own 独自の設定の保持 Keep a cache of its own, which you can clear 消去できる独自のキャッシュの保持 - Run on its own when the selection, a document or a layer changes 選択、ドキュメント、またはレイヤーが変わったときの自動実行 Run these commands on the document: {ids} ドキュメントでのこれらのコマンドの実行: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call 「{name}」は `commandAllowlist` にプラグインが呼び出せない `{id}` を挙げています @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7262,15 +7261,6 @@ axis Y Axis Y 軸 @msg only a filter declares `inputs` `inputs` を宣言できるのはフィルターだけです @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` に不明なオブジェクトの種類 `{shown}` があります。type、image、symbolInstance のいずれかを使ってください @msg `inputs` lists `{shown}` twice `inputs` に `{shown}` が 2 回指定されています -@msg `events` lists `{shown}` twice `events` に `{shown}` が 2 回指定されています -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` に不明なイベント `{shown}` があります。selection.changed、document.opened、document.saved、layer.changed のいずれかを使ってください -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` にはプラグイン API レベル {EVENTS_API} が必要です。`api` {EVENTS_API} を指定してください -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` には権限 `events` が必要で、`events` には `events` のリストが必要です -@msg event size ({len} bytes, limit {max}) イベントサイズ ({len} バイト、上限 {max}) -@msg the module reacts to no events このモジュールはどのイベントにも反応しません -@msg vc_event returned {code} vc_event が {code} を返しました -@msg {name}: its {event} handler failed: {e} {name}: {event} のハンドラーが失敗しました: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: ハンドラーが {count} 回続けて失敗したため、VectorCraft を再起動するまでイベントはオフです @msg `inputs` needs `api` 2 or later `inputs` には `api` 2 以上が必要です @msg `inputs` needs the permission `doc.read` `inputs` には権限 `doc.read` が必要です @msg only a filter declares `writes` `writes` を宣言できるのはフィルターだけです diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 5af6b8a652..cbb58ee5ab 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9640,7 +9640,6 @@ axis Y Axis Y ღერძი Show its progress, see Cancel and write log lines პროგრესის ჩვენება, გაუქმების შემჩნევა და ჟურნალის სტრიქონების ჩაწერა Keep settings of its own საკუთარი პარამეტრების შენახვა Keep a cache of its own, which you can clear საკუთარი ქეშის შენახვა, რომლის გასუფთავებაც შეგიძლიათ - Run on its own when the selection, a document or a layer changes თავისით გაშვება, როცა იცვლება მონიშნული, დოკუმენტი ან შრე Run these commands on the document: {ids} ამ ბრძანებების გაშვება დოკუმენტზე: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ `commandAllowlist`-ში ასახელებს `{id}`-ს, რომლის გამოძახებაც პლაგინს არ შეუძლია @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -9674,15 +9673,6 @@ axis Y Axis Y ღერძი @msg only a filter declares `inputs` `inputs`-ის გამოცხადება მხოლოდ ფილტრს შეუძლია @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` უცნობ ობიექტის სახეობას ასახელებს `{shown}`: გამოიყენეთ type, image ან symbolInstance @msg `inputs` lists `{shown}` twice `inputs`-ში `{shown}` ორჯერაა ჩამოთვლილი -@msg `events` lists `{shown}` twice `events`-ში `{shown}` ორჯერაა ჩამოთვლილი -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` უცნობ მოვლენას ასახელებს `{shown}`: გამოიყენეთ selection.changed, document.opened, document.saved ან layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events`-ს სჭირდება პლაგინის API-ის დონე {EVENTS_API}: მიუთითეთ `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events`-ს სჭირდება ნებართვა `events`, ხოლო `events`-ს სჭირდება `events`-ის სია -@msg event size ({len} bytes, limit {max}) მოვლენის ზომა ({len} ბაიტი, ლიმიტი {max}) -@msg the module reacts to no events მოდული არცერთ მოვლენაზე არ რეაგირებს -@msg vc_event returned {code} vc_event-მა დააბრუნა {code} -@msg {name}: its {event} handler failed: {e} {name}: მისი {event} დამმუშავებელი ვერ შესრულდა: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: მისი მოვლენები გამორთულია VectorCraft-ის ხელახლა გაშვებამდე, ზედიზედ {count} წარუმატებელი დამმუშავებლის შემდეგ @msg `inputs` needs `api` 2 or later `inputs`-ს სჭირდება `api` 2 ან უფრო ახალი @msg `inputs` needs the permission `doc.read` `inputs`-ს სჭირდება ნებართვა `doc.read` @msg only a filter declares `writes` `writes`-ის გამოცხადება მხოლოდ ფილტრს შეუძლია diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index f5e2ff281b..bd430d2fc1 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7125,7 +7125,6 @@ axis Y Axis Y축 Show its progress, see Cancel and write log lines 진행률 표시, 취소 감지 및 로그 줄 쓰기 Keep settings of its own 자체 설정 보관 Keep a cache of its own, which you can clear 지울 수 있는 자체 캐시 보관 - Run on its own when the selection, a document or a layer changes 선택 영역, 문서 또는 레이어가 바뀔 때 자동 실행 Run these commands on the document: {ids} 문서에서 다음 명령 실행: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}”의 `commandAllowlist`에 플러그인이 호출할 수 없는 `{id}`가 있습니다 @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7159,15 +7158,6 @@ axis Y Axis Y축 @msg only a filter declares `inputs` 필터만 `inputs`를 선언할 수 있습니다 @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs`에 알 수 없는 개체 종류 `{shown}`이(가) 있습니다. type, image 또는 symbolInstance를 사용하세요 @msg `inputs` lists `{shown}` twice `inputs`에 `{shown}`이(가) 두 번 나열되어 있습니다 -@msg `events` lists `{shown}` twice `events`에 `{shown}`이(가) 두 번 나열되어 있습니다 -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events`에 알 수 없는 이벤트 `{shown}`이(가) 있습니다. selection.changed, document.opened, document.saved 또는 layer.changed를 사용하세요 -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events`에는 플러그인 API 수준 {EVENTS_API}이(가) 필요합니다. `api` {EVENTS_API}을(를) 지정하십시오 -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events`에는 `events` 권한이 필요하고, `events`에는 `events` 목록이 필요합니다 -@msg event size ({len} bytes, limit {max}) 이벤트 크기({len}바이트, 제한 {max}) -@msg the module reacts to no events 이 모듈은 어떤 이벤트에도 반응하지 않습니다 -@msg vc_event returned {code} vc_event가 {code}을(를) 반환했습니다 -@msg {name}: its {event} handler failed: {e} {name}: {event} 처리기가 실패했습니다: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: 처리기가 {count}번 연속 실패하여 VectorCraft를 다시 시작할 때까지 이벤트가 꺼집니다 @msg `inputs` needs `api` 2 or later `inputs`에는 `api` 2 이상이 필요합니다 @msg `inputs` needs the permission `doc.read` `inputs`에는 `doc.read` 권한이 필요합니다 @msg only a filter declares `writes` 필터만 `writes`를 선언할 수 있습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 2c32ec717a..20365f1488 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -575,15 +575,6 @@ liquify-list-end {0}, {1} {0} en {1} @msg only a filter declares `inputs` alleen een filter declareert `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` noemt een onbekend objectsoort `{shown}`: gebruik type, image of symbolInstance @msg `inputs` lists `{shown}` twice `inputs` noemt `{shown}` twee keer -@msg `events` lists `{shown}` twice `events` noemt `{shown}` twee keer -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` noemt een onbekende gebeurtenis `{shown}`: gebruik selection.changed, document.opened, document.saved of layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` vereist plug-in-API-niveau {EVENTS_API}: geef `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` vereist de machtiging `events`, en `events` vereist een lijst `events` -@msg event size ({len} bytes, limit {max}) gebeurtenisgrootte ({len} bytes, limiet {max}) -@msg the module reacts to no events de module reageert op geen enkele gebeurtenis -@msg vc_event returned {code} vc_event gaf {code} terug -@msg {name}: its {event} handler failed: {e} {name}: de handler voor {event} is mislukt: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: de gebeurtenissen staan uit tot VectorCraft opnieuw start, na {count} mislukte handlers op rij @msg `inputs` needs `api` 2 or later `inputs` vereist `api` 2 of hoger @msg `inputs` needs the permission `doc.read` `inputs` vereist de machtiging `doc.read` @msg only a filter declares `writes` alleen een filter declareert `writes` @@ -9617,7 +9608,6 @@ axis Y Axis Y-as Show its progress, see Cancel and write log lines De voortgang tonen, een annulering zien en logregels schrijven Keep settings of its own Eigen instellingen bewaren Keep a cache of its own, which you can clear Een eigen cache bewaren, die u kunt legen - Run on its own when the selection, a document or a layer changes Vanzelf worden uitgevoerd wanneer de selectie, een document of een laag verandert Run these commands on the document: {ids} Deze opdrachten op het document uitvoeren: {ids} Clear Plug-in Cache Plug-incache legen # Actions panel: action sets (#3712). diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index be3c2a0666..4a22a1dd93 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7386,7 +7386,6 @@ axis Y Axis Oś Y Show its progress, see Cancel and write log lines Pokazywać swój postęp, wykrywać anulowanie i zapisywać wiersze dziennika Keep settings of its own Przechowywać własne ustawienia Keep a cache of its own, which you can clear Przechowywać własną pamięć podręczną, którą możesz wyczyścić - Run on its own when the selection, a document or a layer changes Uruchamiać się samodzielnie, gdy zmieni się zaznaczenie, dokument lub warstwa Run these commands on the document: {ids} Uruchamiać w dokumencie te polecenia: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}” wymienia w `commandAllowlist` polecenie `{id}`, którego wtyczka nie może wywołać @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7420,15 +7419,6 @@ axis Y Axis Oś Y @msg only a filter declares `inputs` tylko filtr deklaruje `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` wymienia nieznany rodzaj obiektu `{shown}`: użyj type, image lub symbolInstance @msg `inputs` lists `{shown}` twice `inputs` wymienia `{shown}` dwa razy -@msg `events` lists `{shown}` twice `events` wymienia `{shown}` dwa razy -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` wymienia nieznane zdarzenie `{shown}`: użyj selection.changed, document.opened, document.saved lub layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` wymaga poziomu API wtyczek {EVENTS_API}: podaj `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` potrzebuje uprawnienia `events`, a `events` potrzebuje listy `events` -@msg event size ({len} bytes, limit {max}) rozmiar zdarzenia ({len} bajtów, limit {max}) -@msg the module reacts to no events moduł nie reaguje na żadne zdarzenia -@msg vc_event returned {code} vc_event zwróciła {code} -@msg {name}: its {event} handler failed: {e} {name}: jego procedura obsługi {event} nie powiodła się: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: jego zdarzenia są wyłączone do ponownego uruchomienia VectorCraft, po {count} nieudanych procedurach obsługi z rzędu @msg `inputs` needs `api` 2 or later `inputs` wymaga `api` 2 lub nowszego @msg `inputs` needs the permission `doc.read` `inputs` wymaga uprawnienia `doc.read` @msg only a filter declares `writes` tylko filtr deklaruje `writes` diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 4a7e033cc5..6d910ce85f 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7432,7 +7432,6 @@ axis Y Axis Eixo Y Show its progress, see Cancel and write log lines Mostrar seu progresso, detectar o cancelamento e gravar linhas de log Keep settings of its own Guardar configurações próprias Keep a cache of its own, which you can clear Guardar um cache próprio, que você pode limpar - Run on its own when the selection, a document or a layer changes Executar-se sozinho quando a seleção, um documento ou uma camada muda Run these commands on the document: {ids} Executar estes comandos no documento: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” lista `{id}` em `commandAllowlist`, que um plug-in não pode chamar @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7466,15 +7465,6 @@ axis Y Axis Eixo Y @msg only a filter declares `inputs` somente um filtro declara `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` cita um tipo de objeto desconhecido `{shown}`: use type, image ou symbolInstance @msg `inputs` lists `{shown}` twice `inputs` lista `{shown}` duas vezes -@msg `events` lists `{shown}` twice `events` lista `{shown}` duas vezes -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` cita um evento desconhecido `{shown}`: use selection.changed, document.opened, document.saved ou layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` exige o nível de API de plug-in {EVENTS_API}: informe `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` precisa da permissão `events`, e `events` precisa de uma lista de `events` -@msg event size ({len} bytes, limit {max}) tamanho do evento ({len} bytes, limite {max}) -@msg the module reacts to no events o módulo não reage a nenhum evento -@msg vc_event returned {code} vc_event retornou {code} -@msg {name}: its {event} handler failed: {e} {name}: seu manipulador de {event} falhou: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: seus eventos estão desativados até o VectorCraft iniciar de novo, após {count} manipuladores com falha seguidos @msg `inputs` needs `api` 2 or later `inputs` exige `api` 2 ou posterior @msg `inputs` needs the permission `doc.read` `inputs` exige a permissão `doc.read` @msg only a filter declares `writes` somente um filtro declara `writes` diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 151d5d5256..60906af64a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7155,7 +7155,6 @@ axis Y Axis Ось Y Show its progress, see Cancel and write log lines Показывать свой ход выполнения, замечать отмену и записывать строки журнала Keep settings of its own Хранить собственные настройки Keep a cache of its own, which you can clear Хранить собственный кэш, который можно очистить - Run on its own when the selection, a document or a layer changes Запускаться самостоятельно, когда меняется выделение, документ или слой Run these commands on the document: {ids} Выполнять в документе эти команды: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call «{name}» указывает в `commandAllowlist` команду `{id}`, которую модуль вызывать не может @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7189,15 +7188,6 @@ axis Y Axis Ось Y @msg only a filter declares `inputs` `inputs` может объявлять только фильтр @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance в `inputs` указан неизвестный вид объекта `{shown}`: используйте type, image или symbolInstance @msg `inputs` lists `{shown}` twice в `inputs` `{shown}` указано дважды -@msg `events` lists `{shown}` twice в `events` `{shown}` указано дважды -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed в `events` указано неизвестное событие `{shown}`: используйте selection.changed, document.opened, document.saved или layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} для `events` нужен уровень API модулей {EVENTS_API}: укажите `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` для `events` нужно разрешение `events`, а для `events` нужен список `events` -@msg event size ({len} bytes, limit {max}) размер события ({len} байт, предел {max}) -@msg the module reacts to no events модуль не реагирует ни на какие события -@msg vc_event returned {code} vc_event вернула {code} -@msg {name}: its {event} handler failed: {e} {name}: его обработчик {event} завершился ошибкой: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: его события отключены до следующего запуска VectorCraft после {count} неудачных обработчиков подряд @msg `inputs` needs `api` 2 or later для `inputs` нужен `api` 2 или выше @msg `inputs` needs the permission `doc.read` для `inputs` нужно разрешение `doc.read` @msg only a filter declares `writes` `writes` может объявлять только фильтр diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 21f2954bb4..bf7420d255 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7535,7 +7535,6 @@ axis Y Axis Y-axel Show its progress, see Cancel and write log lines Visa sitt förlopp, se när det avbryts och skriva loggrader Keep settings of its own Spara egna inställningar Keep a cache of its own, which you can clear Spara en egen cache, som du kan tömma - Run on its own when the selection, a document or a layer changes Köras av sig själv när markeringen, ett dokument eller ett lager ändras Run these commands on the document: {ids} Köra dessa kommandon på dokumentet: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call ”{name}” anger `{id}` i `commandAllowlist`, som ett plugin inte får anropa @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7569,15 +7568,6 @@ axis Y Axis Y-axel @msg only a filter declares `inputs` bara ett filter anger `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` anger en okänd objekttyp `{shown}`: använd type, image eller symbolInstance @msg `inputs` lists `{shown}` twice `inputs` anger `{shown}` två gånger -@msg `events` lists `{shown}` twice `events` anger `{shown}` två gånger -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` anger en okänd händelse `{shown}`: använd selection.changed, document.opened, document.saved eller layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` kräver plugin-API-nivå {EVENTS_API}: ange `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` behöver behörigheten `events`, och `events` behöver en lista `events` -@msg event size ({len} bytes, limit {max}) händelsestorlek ({len} byte, gräns {max}) -@msg the module reacts to no events modulen reagerar inte på några händelser -@msg vc_event returned {code} vc_event returnerade {code} -@msg {name}: its {event} handler failed: {e} {name}: dess {event}-hanterare misslyckades: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: dess händelser är avstängda tills VectorCraft startas igen, efter {count} misslyckade hanterare i rad @msg `inputs` needs `api` 2 or later `inputs` kräver `api` 2 eller senare @msg `inputs` needs the permission `doc.read` `inputs` kräver behörigheten `doc.read` @msg only a filter declares `writes` bara ett filter anger `writes` diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 3584b85291..830b60e56b 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7605,7 +7605,6 @@ axis Y Axis Y ekseni Show its progress, see Cancel and write log lines İlerlemesini gösterme, iptali algılama ve günlük satırları yazma Keep settings of its own Kendi ayarlarını saklama Keep a cache of its own, which you can clear Temizleyebileceğiniz kendi önbelleğini saklama - Run on its own when the selection, a document or a layer changes Seçim, bir belge veya bir katman değiştiğinde kendiliğinden çalışma Run these commands on the document: {ids} Belgede şu komutları çalıştırma: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}”, `commandAllowlist` içinde bir eklentinin çağıramayacağı `{id}` komutunu listeliyor @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7639,15 +7638,6 @@ axis Y Axis Y ekseni @msg only a filter declares `inputs` `inputs` yalnızca bir filtrede bildirilebilir @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` bilinmeyen bir nesne türü belirtiyor: `{shown}`; type, image veya symbolInstance kullanın @msg `inputs` lists `{shown}` twice `inputs` `{shown}` değerini iki kez listeliyor -@msg `events` lists `{shown}` twice `events` `{shown}` değerini iki kez listeliyor -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` bilinmeyen bir olay belirtiyor: `{shown}`; selection.changed, document.opened, document.saved veya layer.changed kullanın -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` için eklenti API düzeyi {EVENTS_API} gerekir: `api` {EVENTS_API} verin -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` için `events` izni, `events` izni için de bir `events` listesi gerekir -@msg event size ({len} bytes, limit {max}) olay boyutu ({len} bayt, sınır {max}) -@msg the module reacts to no events modül hiçbir olaya tepki vermiyor -@msg vc_event returned {code} vc_event {code} döndürdü -@msg {name}: its {event} handler failed: {e} {name}: {event} işleyicisi başarısız oldu: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: art arda {count} işleyici başarısız olduğundan, VectorCraft yeniden başlayana kadar olayları kapalı @msg `inputs` needs `api` 2 or later `inputs` için `api` 2 veya üstü gerekir @msg `inputs` needs the permission `doc.read` `inputs` için `doc.read` izni gerekir @msg only a filter declares `writes` `writes` yalnızca bir filtrede bildirilebilir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 233929fc1b..09a9e4bf6d 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -7135,7 +7135,6 @@ axis Y Axis Вісь Y Show its progress, see Cancel and write log lines Показувати свій поступ, помічати скасування і записувати рядки журналу Keep settings of its own Зберігати власні налаштування Keep a cache of its own, which you can clear Зберігати власний кеш, який можна очистити - Run on its own when the selection, a document or a layer changes Запускатися самостійно, коли змінюється виділення, документ або шар Run these commands on the document: {ids} Виконувати в документі ці команди: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call «{name}» вказує в `commandAllowlist` команду `{id}`, яку модуль викликати не може @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7169,15 +7168,6 @@ axis Y Axis Вісь Y @msg only a filter declares `inputs` `inputs` може оголошувати лише фільтр @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance в `inputs` указано невідомий вид об’єкта `{shown}`: використовуйте type, image або symbolInstance @msg `inputs` lists `{shown}` twice в `inputs` `{shown}` указано двічі -@msg `events` lists `{shown}` twice в `events` `{shown}` указано двічі -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed в `events` указано невідому подію `{shown}`: використовуйте selection.changed, document.opened, document.saved або layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} для `events` потрібен рівень API модулів {EVENTS_API}: укажіть `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` для `events` потрібен дозвіл `events`, а для `events` потрібен список `events` -@msg event size ({len} bytes, limit {max}) розмір події ({len} байтів, межа {max}) -@msg the module reacts to no events модуль не реагує на жодні події -@msg vc_event returned {code} vc_event повернула {code} -@msg {name}: its {event} handler failed: {e} {name}: його обробник {event} завершився помилкою: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: його події вимкнено до наступного запуску VectorCraft після {count} невдалих обробників поспіль @msg `inputs` needs `api` 2 or later для `inputs` потрібен `api` 2 або новіший @msg `inputs` needs the permission `doc.read` для `inputs` потрібен дозвіл `doc.read` @msg only a filter declares `writes` `writes` може оголошувати лише фільтр diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 3251b61524..bc63725d0f 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7184,7 +7184,6 @@ axis Y Axis Trục Y Show its progress, see Cancel and write log lines Hiển thị tiến độ, nhận biết yêu cầu hủy và ghi các dòng nhật ký Keep settings of its own Lưu cài đặt riêng Keep a cache of its own, which you can clear Lưu bộ nhớ đệm riêng mà bạn có thể xóa - Run on its own when the selection, a document or a layer changes Tự chạy khi vùng chọn, một tài liệu hoặc một lớp thay đổi Run these commands on the document: {ids} Chạy các lệnh này trên tài liệu: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” liệt kê `{id}` trong `commandAllowlist`, lệnh mà plug-in không được gọi @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7218,15 +7217,6 @@ axis Y Axis Trục Y @msg only a filter declares `inputs` chỉ bộ lọc mới khai báo `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` nêu một loại đối tượng không xác định `{shown}`: dùng type, image hoặc symbolInstance @msg `inputs` lists `{shown}` twice `inputs` liệt kê `{shown}` hai lần -@msg `events` lists `{shown}` twice `events` liệt kê `{shown}` hai lần -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` nêu một sự kiện không xác định `{shown}`: dùng selection.changed, document.opened, document.saved hoặc layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` cần API plug-in cấp {EVENTS_API}: hãy đặt `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` cần quyền `events`, và `events` cần một danh sách `events` -@msg event size ({len} bytes, limit {max}) kích thước sự kiện ({len} byte, giới hạn {max}) -@msg the module reacts to no events mô-đun không phản ứng với sự kiện nào -@msg vc_event returned {code} vc_event trả về {code} -@msg {name}: its {event} handler failed: {e} {name}: trình xử lý {event} của nó đã thất bại: {e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: các sự kiện của nó bị tắt cho đến khi VectorCraft khởi động lại, sau {count} trình xử lý thất bại liên tiếp @msg `inputs` needs `api` 2 or later `inputs` cần `api` 2 trở lên @msg `inputs` needs the permission `doc.read` `inputs` cần quyền `doc.read` @msg only a filter declares `writes` chỉ bộ lọc mới khai báo `writes` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index e4d122520a..9b7e1c7bbc 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7365,7 +7365,6 @@ axis Y Axis Y 轴 Show its progress, see Cancel and write log lines 显示进度、检测取消请求并写入日志行 Keep settings of its own 保存自己的设置 Keep a cache of its own, which you can clear 保存自己的缓存,您可以清除它 - Run on its own when the selection, a document or a layer changes 在所选对象、文档或图层发生变化时自动运行 Run these commands on the document: {ids} 在文档上运行这些命令:{ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}”在 `commandAllowlist` 中列出了增效工具不能调用的 `{id}` @msg vc_call `{shown}`: {why} vc_call `{shown}`:{why} @@ -7399,15 +7398,6 @@ axis Y Axis Y 轴 @msg only a filter declares `inputs` 只有滤镜才能声明 `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` 列出了未知的对象类型 `{shown}`:请使用 type、image 或 symbolInstance @msg `inputs` lists `{shown}` twice `inputs` 列出了两次 `{shown}` -@msg `events` lists `{shown}` twice `events` 列出了两次 `{shown}` -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` 列出了未知的事件 `{shown}`:请使用 selection.changed、document.opened、document.saved 或 layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` 需要增效工具 API 级别 {EVENTS_API}:请设置 `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` 需要权限 `events`,而 `events` 需要 `events` 列表 -@msg event size ({len} bytes, limit {max}) 事件大小({len} 字节,上限 {max}) -@msg the module reacts to no events 该模块不响应任何事件 -@msg vc_event returned {code} vc_event 返回了 {code} -@msg {name}: its {event} handler failed: {e} {name}:其 {event} 处理程序失败:{e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}:处理程序连续 {count} 次失败,其事件已关闭,直到 VectorCraft 再次启动 @msg `inputs` needs `api` 2 or later `inputs` 需要 `api` 2 或更高 @msg `inputs` needs the permission `doc.read` `inputs` 需要权限 `doc.read` @msg only a filter declares `writes` 只有滤镜才能声明 `writes` diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9fdb9c2d32..2e3bae2d60 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7184,7 +7184,6 @@ axis Y Axis Y 軸 Show its progress, see Cancel and write log lines 顯示進度、偵測取消要求並寫入記錄行 Keep settings of its own 保存自己的設定 Keep a cache of its own, which you can clear 保存自己的快取,您可以清除它 - Run on its own when the selection, a document or a layer changes 在選取範圍、文件或圖層變更時自動執行 Run these commands on the document: {ids} 在文件上執行這些指令:{ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call 「{name}」在 `commandAllowlist` 中列出了增效模組不能呼叫的 `{id}` @msg vc_call `{shown}`: {why} vc_call `{shown}`:{why} @@ -7218,15 +7217,6 @@ axis Y Axis Y 軸 @msg only a filter declares `inputs` 只有濾鏡才能宣告 `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` 列出了未知的物件類型 `{shown}`:請使用 type、image 或 symbolInstance @msg `inputs` lists `{shown}` twice `inputs` 列出了兩次 `{shown}` -@msg `events` lists `{shown}` twice `events` 列出了兩次 `{shown}` -@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` 列出了未知的事件 `{shown}`:請使用 selection.changed、document.opened、document.saved 或 layer.changed -@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` 需要增效模組 API 層級 {EVENTS_API}:請設定 `api` {EVENTS_API} -@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` 需要權限 `events`,而 `events` 需要 `events` 清單 -@msg event size ({len} bytes, limit {max}) 事件大小({len} 位元組,上限 {max}) -@msg the module reacts to no events 此模組不回應任何事件 -@msg vc_event returned {code} vc_event 傳回了 {code} -@msg {name}: its {event} handler failed: {e} {name}:其 {event} 處理常式失敗:{e} -@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}:處理常式連續 {count} 次失敗,其事件已關閉,直到 VectorCraft 再次啟動 @msg `inputs` needs `api` 2 or later `inputs` 需要 `api` 2 或更高 @msg `inputs` needs the permission `doc.read` `inputs` 需要權限 `doc.read` @msg only a filter declares `writes` 只有濾鏡才能宣告 `writes` diff --git a/docs/mcp.md b/docs/mcp.md index 37378a385f..1c39001b62 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -15201,9 +15201,10 @@ while it runs, through `vc_call`: the calls and its output are one undo step, an fails leaves the documents, selections and history as they were. Without `doc.read` every call fails. A command that reads or writes files, uses the clipboard, changes preferences or the view, runs a script, an action or a plug-in, switches documents or undoes is never called; `plugin.install` refuses a manifest that lists one, and `plugin.inspect` lists such ids as -`refusedCommands` and ids no command has as `unknownCommands` (`plugin.install` lists those too). A plug-in at API level 2 -whose manifest lists the `events` permission and `events` (in its `plugin.list` entry) is given `selection.changed`, -`document.opened`, `document.saved` and `layer.changed` events through `vc_event` once the change has finished; +`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 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` From 330aa4dffbc538222a9c7f52232c58d2f674a059 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:27:06 -0800 Subject: [PATCH 07/11] 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. From ebd59b794db04227ac3eb0dd35884ab8c754be99 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 15:15:57 -0800 Subject: [PATCH 08/11] Plug-ins: drop layer events of a rolled-back batch and serve waiting recipients first A layer change seen when a command.batch step settled its interaction was queued before the batch finished, so a failed batch still reported it. The check now waits until the outermost command ends. Delivery under the frame budget now serves recipients in the order they were added to the event, so recipients re-added by a coalesced change no longer take the budget ahead of ones still waiting. The frame-budget tests use a session-local subscriber list instead of the shared plug-in registry. --- crates/engine/src/plugin_events.rs | 24 +++++-- crates/engine/src/tests/plugin_events.rs | 86 +++++++++++++++++++++--- 2 files changed, 95 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index e2e60f445f..93375f4924 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -125,15 +125,22 @@ pub struct PluginEvents { 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(); } @@ -425,11 +432,9 @@ 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)) { - let r = recipient(plugin); - if !p.is_for(&r) { - continue; - } + let recipients = p.to.clone(); + for (r, _) in recipients { + let Some(plugin) = subs.iter().find(|s| recipient(s) == r && s.manifest().reacts_to(p.event)) else { continue }; if self.plugin_events.failures_of(plugin).disabled { p.to.retain(|(to, _)| *to != r); continue; @@ -549,6 +554,9 @@ impl Session { /// 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(); } @@ -568,7 +576,11 @@ impl Session { /// 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); + if self.depth == 0 { + self.check_plugin_events(true); + } else { + self.plugin_events.interaction_ended = true; + } } } diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs index 0ab0becd00..5f471b7925 100644 --- a/crates/engine/src/tests/plugin_events.rs +++ b/crates/engine/src/tests/plugin_events.rs @@ -36,6 +36,21 @@ fn install(s: &mut Session, id: &str, events: &str, more: &[&str], imports: &str run(s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})); } +fn local_session() -> Session { + let mut s = Session::new(); + s.plugin_events.test_subscribers = Some(Vec::new()); + run(&mut s, "file.new", json!({"width": 400, "height": 200})); + s +} + +fn subscribe(s: &mut Session, id: &str, events: &str, handler: &str) { + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":["progress","events"],"events":{events}}}"#); + let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, handler)).unwrap(); + let plugin = vectorcraft_plugins::Plugin::load(&wasm, vectorcraft_plugins::Limits::default()).unwrap(); + s.plugin_events.test_subscribers.as_mut().unwrap().push(std::sync::Arc::new(plugin)); + s.plugins_changed_for_events(); +} + /// The events plug-in `id`'s handler was given since the last call, as it logged them. fn given(s: &mut Session, id: &str) -> Vec { let notices = s.take_plugin_event_notices(); @@ -197,8 +212,8 @@ fn background_installs_during_a_drag_record_the_settled_baseline() { 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)", &[]); + let mut s = local_session(); + subscribe(&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 { @@ -210,15 +225,14 @@ fn silent_handlers_report_when_another_frame_is_needed() { 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, &[]); + let mut s = local_session(); + subscribe(&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) { @@ -232,17 +246,16 @@ fn deliveries_in_one_frame_share_the_handler_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(); + let mut s = local_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, &[]); + subscribe(&mut s, id, r#"["document.saved"]"#, tpl::LOG_EVENT); } let doc = s.doc().unwrap().uid; s.note_plugin_event(Event::DocumentSaved, doc); @@ -258,7 +271,62 @@ fn frame_delivery_bounds_handlers_and_resumes_remaining_recipients() { 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})); + } +} + +#[test] +fn coalesced_changes_serve_waiting_recipients_before_readded_recipients() { + let mut s = local_session(); + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + let ids: Vec = (0..9).map(|i| format!("test.events.fair_selection_{i}")).collect(); + for id in &ids { + subscribe(&mut s, id, r#"["selection.changed"]"#, tpl::LOG_EVENT); + } + s.plugin_event_frames = true; + let mut delivered = Vec::new(); + for frame in 0..3 { + s.begin_plugin_event_frame(); + let selection = if frame % 2 == 0 { vec![r.0] } else { Vec::new() }; + run(&mut s, "select.set", json!({"ids": selection})); + assert!(s.deliver_plugin_events()); + let notices = s.take_plugin_event_notices(); + assert_eq!(notices.len(), crate::plugin_events::MAX_FRAME_HANDLERS); + delivered.extend(notices.into_iter().map(|n| n.plugin)); + } + for id in &ids { + assert!(delivered.contains(id), "{id} was not served while selection kept changing"); + } +} + +#[test] +fn a_failed_batch_drops_layer_changes_from_a_settled_interaction() { + let id = "test.events.rolled_back_layer"; + for frames in [false, true] { + let mut s = local_session(); + subscribe(&mut s, id, r#"["layer.changed","document.opened"]"#, tpl::LOG_EVENT); + s.plugin_event_frames = frames; + let before = s.doc().unwrap().doc.clone(); + let error = s + .execute( + "command.batch", + &json!({"commands": [ + {"command": "layer.new", "params": {"name": "Notes"}}, + {"command": "edit.newDocumentFromState", "params": {}}, + {"command": "no.such.command", "params": {}} + ]}), + ) + .unwrap_err(); + assert!(error.to_string().contains("batch step 2"), "{error}"); + assert_eq!(s.documents().len(), 1); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc)); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "the batch's layer was rolled back"); + run(&mut s, "layer.new", json!({"name": "Committed"})); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["layer.changed"]); + assert!(got[0]["reasons"].as_array().unwrap().contains(&json!("added"))); } } From 95f08201f637298a6a78f4b6a9691f9559883ce3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:25:22 -0800 Subject: [PATCH 09/11] Plug-ins: keep a failed script's layer changes out of events and index recipients Event checks no longer compare documents while a script runs, so a script that throws after a command.batch gives no event for its discarded working copy. A batch that settles an open drag records the plug-in baselines before its own steps edit, so a plug-in loaded during the drag gets the batch's changes. Delivery looks recipients up in a map built once per delivery and drains served recipients once per event. --- crates/engine/src/cmd/fileio/batch.rs | 1 + crates/engine/src/plugin_events.rs | 35 +++++++++--- crates/engine/src/tests/plugin_events.rs | 73 ++++++++++++++++++++++++ 3 files changed, 102 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 316fae8573..51ed9b6cd4 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -19,6 +19,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // would otherwise run inside it and take its baseline as theirs (#1697). if s.active().is_some() && !s.previewing { super::super::edit::settle_interaction(s)?; + s.plugin_events_batch_settled(); } let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone()); // The documents as they are now, whole: what a failed step brings back. Their art, history, diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index 93375f4924..16ea428c56 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -61,8 +61,15 @@ struct Seen { /// ([`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()) } @@ -82,6 +89,7 @@ struct Pending { impl Pending { /// Whether this event is for `r`. + #[cfg(test)] fn is_for(&self, r: &Recipient) -> bool { self.to.iter().any(|(x, _)| x == r) } @@ -342,6 +350,9 @@ impl Session { /// 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(); @@ -411,7 +422,7 @@ impl Session { { return false; } - let subs = self.plugin_events.subscribers(); + let subs: HashMap> = self.plugin_events.subscribers().into_iter().map(|p| (recipient(&p), p)).collect(); self.plugin_events.dispatching = true; // The commands a handler calls run nested, never journaled; a panic in one leaves the depth // as it was found. @@ -432,23 +443,27 @@ impl Session { if !p.event.outlives_document() && !self.docs.iter().any(|d| d.uid == p.document) { continue; } - let recipients = p.to.clone(); - for (r, _) in recipients { - let Some(plugin) = subs.iter().find(|s| recipient(s) == r && s.manifest().reacts_to(p.event)) else { continue }; + let mut served = 0; + for (i, (r, _)) 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 { - p.to.retain(|(to, _)| *to != r); + served = i + 1; continue; } if budget == 0 { break; } self.run_handler(plugin, &p); - p.to.retain(|(to, _)| *to != r); + 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); } @@ -465,7 +480,7 @@ impl Session { 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) + && p.to.iter().any(|(r, _)| subs.get(r).is_some_and(|plugin| !self.plugin_event_status(plugin).0)) }) } @@ -572,6 +587,12 @@ impl Session { } } + pub(crate) fn plugin_events_batch_settled(&mut self) { + if !self.plugin_events.dispatching && self.batch_stash.is_none() { + 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) { diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs index 5f471b7925..3bdca8154c 100644 --- a/crates/engine/src/tests/plugin_events.rs +++ b/crates/engine/src/tests/plugin_events.rs @@ -299,6 +299,79 @@ fn coalesced_changes_serve_waiting_recipients_before_readded_recipients() { } } +#[test] +fn delivery_indexes_subscribers_and_preserves_pending_recipient_order() { + use vectorcraft_plugins::events::Event; + let mut s = local_session(); + let ids: Vec = (0..32).map(|i| format!("test.events.indexed_{i}")).collect(); + for id in &ids { + subscribe(&mut s, id, r#"["document.saved"]"#, tpl::LOG_EVENT); + } + let doc = s.doc().unwrap().uid; + s.note_plugin_event(Event::DocumentSaved, doc); + s.plugin_events.test_subscribers.as_mut().unwrap().reverse(); + crate::plugin_events::RECIPIENT_IDENTITIES.with(|count| count.set(0)); + assert!(!s.deliver_plugin_events()); + let identities = crate::plugin_events::RECIPIENT_IDENTITIES.with(|count| count.get()); + let delivered: Vec<_> = s.take_plugin_event_notices().into_iter().map(|n| n.plugin).collect(); + assert_eq!(delivered, ids); + assert!(identities <= ids.len() * 8, "{identities} recipient identities for {} subscribers", ids.len()); +} + +#[test] +fn a_subscriber_loaded_during_a_drag_receives_the_batch_changes() { + let id = "test.events.batch_drag_baseline"; + for frames in [false, true] { + let mut s = local_session(); + s.plugin_event_frames = frames; + s.begin_interaction("Add layer").unwrap(); + s.preview("layer.new", &json!({"name": "Drag preview"})).unwrap(); + subscribe(&mut s, id, r#"["layer.changed"]"#, tpl::LOG_EVENT); + assert!(!s.deliver_plugin_events()); + assert!(given(&mut s, id).is_empty()); + run(&mut s, "command.batch", json!({"commands": [{"command": "layer.new", "params": {"name": "Batch layer"}}]})); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["layer.changed"]); + assert!(got[0]["reasons"].as_array().unwrap().contains(&json!("added"))); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty()); + } +} + +#[test] +fn script_batches_compare_layers_only_after_the_script_commits() { + let id = "test.events.script_batch_layers"; + for frames in [false, true] { + for kept in [false, true] { + let mut s = local_session(); + subscribe(&mut s, id, r#"["layer.changed"]"#, tpl::LOG_EVENT); + s.plugin_event_frames = frames; + let before = s.doc().unwrap().doc.layers.len(); + let ending = if kept { "" } else { "throw new Error('stop');" }; + let source = format!("vc.run('command.batch', {{commands: [{{command: 'layer.new', params: {{name: 'Script layer'}}}}]}}); {ending}"); + let result = s.execute("script.run", &json!({"source": source, "name": "batch.js"})); + assert_eq!(result.is_ok(), kept, "{result:?}"); + if !kept { + assert_eq!(s.doc().unwrap().doc.layers.len(), before, "the failed script's layer was rolled back"); + } + s.deliver_plugin_events(); + let got = given(&mut s, id); + if kept { + assert_eq!(types(&got), ["layer.changed"]); + assert!(got[0]["reasons"].as_array().unwrap().contains(&json!("added"))); + } else { + assert!(got.is_empty(), "the script's layer was rolled back: {got:?}"); + } + run(&mut s, "layer.new", json!({"name": "Committed"})); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["layer.changed"]); + assert!(got[0]["reasons"].as_array().unwrap().contains(&json!("added"))); + } + } +} + #[test] fn a_failed_batch_drops_layer_changes_from_a_settled_interaction() { let id = "test.events.rolled_back_layer"; From b558bf31441057abdbe36c624351b347d2536266 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 18:11:03 -0800 Subject: [PATCH 10/11] Plug-ins: keep the event baseline when a batch settles no interaction A command.batch checked the documents for plug-in events before its steps even when no drag or typing was open, so a selection that the batch put back as it was reached plug-ins as selection.changed. The check now runs only when the batch settles an interaction, or when the installed plug-ins differ from the last check's. Otherwise the batch only drops queued events for removed plug-ins and closed documents, and the snapshots of closed documents. Each handler is given its layer.changed reasons directly instead of looking them up among the event's recipients. --- crates/engine/src/cmd/fileio/batch.rs | 3 +- crates/engine/src/plugin_events.rs | 47 ++++++++++++++++++------ crates/engine/src/tests/plugin_events.rs | 40 ++++++++++++++++++++ 3 files changed, 77 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 51ed9b6cd4..263cbf57e1 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -18,8 +18,9 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // A drag or typing still in progress is a step of its own, as before Undo: the batch's steps // would otherwise run inside it and take its baseline as theirs (#1697). if s.active().is_some() && !s.previewing { + let open = s.holds_interaction() || s.docs.iter().any(|d| d.interaction.is_some()); super::super::edit::settle_interaction(s)?; - s.plugin_events_batch_settled(); + s.plugin_events_batch_settled(open); } let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone()); // The documents as they are now, whole: what a failed step brings back. Their art, history, diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index 16ea428c56..89a23ae390 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -25,7 +25,7 @@ //! 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, HashMap, VecDeque}; +use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; use std::hash::Hash; use std::sync::Arc; @@ -95,6 +95,7 @@ impl Pending { } /// 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()) } @@ -444,7 +445,7 @@ impl Session { continue; } let mut served = 0; - for (i, (r, _)) in p.to.iter().enumerate() { + 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; @@ -456,7 +457,7 @@ impl Session { if budget == 0 { break; } - self.run_handler(plugin, &p); + self.run_handler(plugin, &p, reasons); served = i + 1; budget -= 1; if self.plugin_event_frames { @@ -485,8 +486,9 @@ impl Session { } /// The JSON event `p` as plug-in `plugin` is given it: the selected object ids of a - /// `selection.changed` only with `doc.read`. - fn event_json(&self, plugin: &Plugin, p: &Pending) -> Value { + /// `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 { @@ -502,17 +504,18 @@ impl Session { } Event::LayerChanged => { v["layer"] = json!(st.active_layer.map(|l| l.0)); - v["reasons"] = json!(p.reasons_for(&recipient(plugin))); + v["reasons"] = json!(reasons); } Event::DocumentOpened | Event::DocumentSaved => {} } v } - /// Calls `plugin`'s handler with event `p` and records what it wrote and whether it failed. - fn run_handler(&mut self, plugin: &Arc, p: &Pending) { + /// 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)).unwrap_or_default(); + 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() { @@ -587,10 +590,30 @@ impl Session { } } - pub(crate) fn plugin_events_batch_settled(&mut self) { - if !self.plugin_events.dispatching && self.batch_stash.is_none() { - self.check_plugin_events(true); + /// 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 diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs index 3bdca8154c..7c83109c01 100644 --- a/crates/engine/src/tests/plugin_events.rs +++ b/crates/engine/src/tests/plugin_events.rs @@ -339,6 +339,46 @@ fn a_subscriber_loaded_during_a_drag_receives_the_batch_changes() { } } +/// A batch with no interaction to settle keeps the last check's state: a selection it puts back +/// as it was is not a change. +#[test] +fn a_batch_without_an_interaction_keeps_the_event_baseline() { + let id = "test.events.batch_no_interaction"; + let mut s = local_session(); + s.plugin_event_frames = true; + 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(); + given(&mut s, id); + run(&mut s, "select.all", json!({})); + run(&mut s, "command.batch", json!({"commands": [{"command": "select.none", "params": {}}]})); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "the selection is as it was at the last delivery"); +} + +/// A plug-in installed since the last check, without this session hearing of it, is given the +/// changes of a batch that settles no interaction. +#[test] +fn a_batch_gives_its_changes_to_a_plugin_installed_since_the_last_check() { + let id = "test.events.batch_new_subscriber"; + let mut s = local_session(); + s.plugin_event_frames = true; + subscribe(&mut s, "test.events.batch_earlier", r#"["selection.changed"]"#, tpl::LOG_EVENT); + s.deliver_plugin_events(); + s.take_plugin_event_notices(); + let manifest = + format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":["progress","events"],"events":["layer.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.as_mut().unwrap().push(std::sync::Arc::new(plugin)); + run(&mut s, "command.batch", json!({"commands": [{"command": "layer.new", "params": {"name": "Batch layer"}}]})); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["layer.changed"]); + assert!(got[0]["reasons"].as_array().unwrap().contains(&json!("added"))); +} + #[test] fn script_batches_compare_layers_only_after_the_script_commits() { let id = "test.events.script_batch_layers"; From b852316921dad971b935ed9b3f9cbb221e2eba50 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 22:12:19 -0800 Subject: [PATCH 11/11] 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. --- crates/engine/src/cmd/plugin.rs | 2 +- crates/engine/src/cmd/plugin_call.rs | 8 +- crates/engine/src/plugin_events.rs | 153 ++++++++++++++++++++--- crates/engine/src/session/edit.rs | 9 +- crates/engine/src/tests/plugin_events.rs | 47 +++++++ crates/ui-egui/src/app.rs | 53 ++++++-- crates/ui-egui/src/caches.rs | 2 + crates/ui-egui/src/chrome/status_bar.rs | 14 +++ crates/ui-egui/src/chrome/tests.rs | 2 +- crates/ui-egui/src/state.rs | 4 + crates/ui-egui/src/tests/plugins.rs | 6 + crates/ui-egui/src/tests/script_run.rs | 13 +- docs/mcp.md | 3 +- docs/plugins.md | 2 +- docs/target-app-parity.md | 2 +- 15 files changed, 279 insertions(+), 41 deletions(-) diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 340e4d4efc..e2ffb44d0c 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -2437,7 +2437,7 @@ pub fn specs() -> Vec { "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 ), diff --git a/crates/engine/src/cmd/plugin_call.rs b/crates/engine/src/cmd/plugin_call.rs index 97a66d3897..71669042f6 100644 --- a/crates/engine/src/cmd/plugin_call.rs +++ b/crates/engine/src/cmd/plugin_call.rs @@ -508,7 +508,8 @@ fn read_only(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(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 diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index 89a23ae390..7a60028afc 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -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, /// 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, @@ -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, +} + +/// 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, 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, /// 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, Option, vectorcraft_doc::Node, Vec); @@ -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 = subs.iter().map(|p| recipient(p)).collect(); @@ -425,6 +489,10 @@ impl Session { } let subs: HashMap> = 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) { - 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); + } } diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 5a7a1ee08d..891f77b789 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -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(()) } diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs index 7c83109c01..f7ac63e770 100644 --- a/crates/engine/src/tests/plugin_events.rs +++ b/crates/engine/src/tests/plugin_events.rs @@ -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"]); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 729a87db09..0b03a8c955 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -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> = 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 { + 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) { diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 06c564f4c8..58b2e6c803 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -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, } diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index b7446defb4..e4a9e91d82 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -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 ¬ice.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) diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 67cc29b63f..440f0f412a 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -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)) }; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index eeef403f06..990d245bc3 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -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, diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index d6d9a48508..2b977059e8 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -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 = 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 = 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:?}"); diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 997d1c5456..8352dc26e4 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -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 = 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] diff --git a/docs/mcp.md b/docs/mcp.md index 93fdc02aad..8fc3bff795 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -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.`: `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/plugins.md b/docs/plugins.md index cbcdc68d8c..81f877afe0 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -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. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ad1689b555..1122b7ed94 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -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 ` 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.