eov_plugin_api/lib.rs
1//! Shared plugin API for EOV.
2//!
3//! This crate defines the traits, structs, and manifest types that both the
4//! host application and individual plugins depend on. It intentionally avoids
5//! any dependency on Slint or other UI frameworks so that plugin non-UI logic
6//! can be tested independently.
7//!
8//! # Adding a new plugin
9//!
10//! 1. Create a directory under the plugin directory (default `~/.eov/plugins/`).
11//! 2. Add a `plugin.toml` manifest (see [`PluginManifest`]).
12//! 3. Place your `.slint` UI file relative to the plugin root.
13//! 4. Implement the [`Plugin`] trait and register it via the plugin registry.
14//!
15//! # Manifest format (`plugin.toml`)
16//!
17//! ```toml
18//! id = "example_plugin"
19//! name = "Example Plugin"
20//! version = "0.1.0"
21//! entry_ui = "ui/my_panel.slint"
22//! entry_component = "MyPanel"
23//!
24//! [environment]
25//! version = ">=0.4.1"
26//!
27//! [icon]
28//! kind = "svg"
29//! data = "<svg>...</svg>"
30//! ```
31
32pub mod ffi;
33pub mod host;
34pub mod manifest;
35pub mod viewport_filter;
36
37pub use host::{
38 ActiveSidebar, HostLogLevel, HostSnapshot, HostToolMode, ModalDialogRequest, OpenFileInfo,
39 PluginUndoRedoState, SidebarRequest, ViewportOverlayComponentRequest, ViewportSnapshot,
40};
41pub use manifest::ManifestToolbarButton;
42pub use manifest::PluginManifest;
43pub use viewport_filter::ViewportFilter;
44pub use viewport_filter::{DmaBufDescriptor, GpuFilterContext};
45
46use std::path::{Path, PathBuf};
47use thiserror::Error;
48
49// ---------------------------------------------------------------------------
50// Errors
51// ---------------------------------------------------------------------------
52
53#[derive(Debug, Error)]
54pub enum PluginError {
55 #[error("plugin manifest error in '{plugin_id}': {message}")]
56 Manifest { plugin_id: String, message: String },
57 #[error("plugin '{plugin_id}' missing required file: {path}")]
58 MissingFile { plugin_id: String, path: PathBuf },
59 #[error("duplicate plugin id: '{0}'")]
60 DuplicateId(String),
61 #[error("duplicate toolbar button id: '{0}'")]
62 DuplicateButtonId(String),
63 #[error("plugin activation error in '{plugin_id}': {message}")]
64 Activation { plugin_id: String, message: String },
65 #[error("IO error: {0}")]
66 Io(#[from] std::io::Error),
67 #[error("{0}")]
68 Other(String),
69}
70
71pub type PluginResult<T> = Result<T, PluginError>;
72
73// ---------------------------------------------------------------------------
74// Icon descriptor
75// ---------------------------------------------------------------------------
76
77/// Describes how a plugin icon is provided.
78#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
79#[serde(tag = "kind", rename_all = "snake_case")]
80pub enum IconDescriptor {
81 /// Inline SVG string.
82 Svg { data: String },
83 /// Path to an image file, relative to the plugin root.
84 File { path: PathBuf },
85}
86
87// ---------------------------------------------------------------------------
88// Toolbar button registration
89// ---------------------------------------------------------------------------
90
91/// Registration data for a plugin toolbar button.
92///
93/// The host renders the actual button; the plugin only provides metadata and
94/// an action identifier.
95#[derive(Debug, Clone)]
96pub struct ToolbarButtonRegistration {
97 /// Owning plugin id.
98 pub plugin_id: String,
99 /// Unique identifier for this button (scoped to the plugin).
100 pub button_id: String,
101 /// Tooltip / accessible label shown on hover.
102 pub tooltip: String,
103 /// Icon to display.
104 pub icon: IconDescriptor,
105 /// Alternate icon used when a HUD toolbar button is active.
106 pub toggled_icon: Option<IconDescriptor>,
107 /// Opaque action identifier dispatched back to the plugin on click.
108 pub action_id: String,
109 /// Optional host tool mode this button owns and toggles.
110 pub tool_mode: Option<HostToolMode>,
111 /// Optional logical hotkey text that activates this tool button.
112 pub hotkey: Option<String>,
113 /// Whether the host should render this button in its active state.
114 pub active: bool,
115}
116
117/// Registration data for a plugin HUD toolbar button.
118///
119/// The host renders these inside each viewport HUD toolbar. They are icon-only
120/// actions and do not participate in host tool-mode or hotkey ownership.
121#[derive(Debug, Clone)]
122pub struct HudToolbarButtonRegistration {
123 /// Owning plugin id.
124 pub plugin_id: String,
125 /// Unique identifier for this button (scoped to the plugin).
126 pub button_id: String,
127 /// Tooltip / accessible label shown on hover.
128 pub tooltip: String,
129 /// Icon to display.
130 pub icon: IconDescriptor,
131 /// Alternate icon used when the HUD button is active.
132 pub toggled_icon: Option<IconDescriptor>,
133 /// Opaque action identifier dispatched back to the plugin on click.
134 pub action_id: String,
135 /// Whether the host should render this button in its active state.
136 pub active: bool,
137}
138
139// ---------------------------------------------------------------------------
140// Host context — the API surface a plugin can call during activation
141// ---------------------------------------------------------------------------
142
143/// Trait implemented by the host and passed to plugins during activation.
144///
145/// Plugins call methods on the host context to register toolbar buttons and
146/// request windows. The trait is object-safe so it can be used with `dyn`.
147pub trait HostContext {
148 /// Register a toolbar button. The button is appended after all built-in
149 /// toolbar items.
150 fn add_toolbar_button(&mut self, button: ToolbarButtonRegistration) -> PluginResult<()>;
151
152 /// Register an icon button in the viewport HUD toolbar.
153 fn add_hud_toolbar_button(
154 &mut self,
155 _button: HudToolbarButtonRegistration,
156 ) -> PluginResult<()> {
157 Err(PluginError::Other(
158 "host does not support HUD toolbar buttons".to_string(),
159 ))
160 }
161
162 /// Request the host to open a plugin window.
163 ///
164 /// `ui_path` is an absolute path to the `.slint` file.
165 /// `component` is the exported component name within that file.
166 fn open_plugin_window(
167 &mut self,
168 plugin_id: &str,
169 ui_path: &Path,
170 component: &str,
171 ) -> PluginResult<()>;
172
173 /// Show a plugin-owned sidebar inside the main application window.
174 fn show_sidebar(&mut self, plugin_id: &str, _request: SidebarRequest) -> PluginResult<()> {
175 Err(PluginError::Other(format!(
176 "host does not support sidebars for plugin '{plugin_id}'"
177 )))
178 }
179
180 /// Hide the currently active sidebar if it belongs to `plugin_id`.
181 fn hide_sidebar(&mut self, plugin_id: &str) -> PluginResult<()> {
182 Err(PluginError::Other(format!(
183 "host does not support sidebars for plugin '{plugin_id}'"
184 )))
185 }
186
187 /// Update plugin-owned undo/redo visibility and availability state.
188 fn set_undo_redo_state(
189 &mut self,
190 plugin_id: &str,
191 _state: PluginUndoRedoState,
192 ) -> PluginResult<()> {
193 Err(PluginError::Other(format!(
194 "host does not support undo/redo for plugin '{plugin_id}'"
195 )))
196 }
197}
198
199// ---------------------------------------------------------------------------
200// Plugin trait
201// ---------------------------------------------------------------------------
202
203/// The core trait that every plugin must implement.
204pub trait Plugin: Send + Sync {
205 /// Return the parsed manifest for this plugin.
206 fn manifest(&self) -> &PluginManifest;
207
208 /// Called once during startup. The plugin should register toolbar buttons
209 /// and any other contributions via `host`. `plugin_root` is the absolute
210 /// path to the plugin directory on disk.
211 fn activate(&self, host: &mut dyn HostContext, plugin_root: &Path) -> PluginResult<()>;
212
213 /// Called when a toolbar button registered by this plugin is clicked.
214 /// `action_id` corresponds to `ToolbarButtonRegistration::action_id`.
215 /// `plugin_root` is the absolute path to the plugin directory on disk.
216 fn on_action(
217 &self,
218 action_id: &str,
219 host: &mut dyn HostContext,
220 plugin_root: &Path,
221 ) -> PluginResult<()>;
222
223 /// Called when the host dispatches an undo request to this plugin.
224 fn on_undo(&self, _host: &mut dyn HostContext, _plugin_root: &Path) -> PluginResult<()> {
225 Ok(())
226 }
227
228 /// Called when the host dispatches a redo request to this plugin.
229 fn on_redo(&self, _host: &mut dyn HostContext, _plugin_root: &Path) -> PluginResult<()> {
230 Ok(())
231 }
232}
233
234// ---------------------------------------------------------------------------
235// Plugin descriptor — returned by discovery, before the plugin is loaded
236// ---------------------------------------------------------------------------
237
238/// Lightweight descriptor produced by directory scanning before the plugin is
239/// fully loaded.
240#[derive(Debug, Clone)]
241pub struct PluginDescriptor {
242 /// Absolute path to the plugin root directory.
243 pub root: PathBuf,
244 /// Parsed manifest.
245 pub manifest: PluginManifest,
246}
247
248impl PluginDescriptor {
249 /// Resolve the `entry_ui` path against the plugin root.
250 /// Returns `None` if the plugin has no UI entry.
251 pub fn resolve_ui_path(&self) -> Option<PathBuf> {
252 self.manifest.entry_ui.as_ref().map(|ui| self.root.join(ui))
253 }
254}
255
256#[cfg(test)]
257mod tests {
258 use crate::manifest::PluginEnvironment;
259
260 use super::*;
261
262 #[test]
263 fn toolbar_button_fields_preserved() {
264 let reg = ToolbarButtonRegistration {
265 plugin_id: "test".into(),
266 button_id: "btn1".into(),
267 tooltip: "Test Button".into(),
268 icon: IconDescriptor::Svg {
269 data: "<svg/>".into(),
270 },
271 toggled_icon: None,
272 action_id: "do_thing".into(),
273 tool_mode: None,
274 hotkey: None,
275 active: false,
276 };
277 assert_eq!(reg.plugin_id, "test");
278 assert_eq!(reg.button_id, "btn1");
279 assert_eq!(reg.tooltip, "Test Button");
280 assert_eq!(reg.action_id, "do_thing");
281 assert_eq!(reg.tool_mode, None);
282 assert_eq!(reg.hotkey, None);
283 assert!(!reg.active);
284 }
285
286 #[test]
287 fn descriptor_resolves_ui_path() {
288 let desc = PluginDescriptor {
289 root: PathBuf::from("/plugins/my_plugin"),
290 manifest: PluginManifest {
291 id: "my_plugin".into(),
292 name: "My Plugin".into(),
293 version: "0.1.0".into(),
294 entry_ui: Some("ui/panel.slint".into()),
295 entry_component: Some("Panel".into()),
296 icon: None,
297 toolbar_buttons: Vec::new(),
298 environment: PluginEnvironment {
299 version: ">=0.0.0".into(),
300 },
301 },
302 };
303 assert_eq!(
304 desc.resolve_ui_path(),
305 Some(PathBuf::from("/plugins/my_plugin/ui/panel.slint"))
306 );
307 }
308
309 #[test]
310 fn host_snapshot_sidebar_roundtrip_shape() {
311 let snapshot = HostSnapshot {
312 app_name: "eov".into(),
313 app_version: "0.0.0".into(),
314 render_backend: "cpu".into(),
315 filtering_mode: "trilinear".into(),
316 split_enabled: false,
317 focused_pane: 0,
318 open_files: Vec::new(),
319 active_file: None,
320 active_viewport: None,
321 recent_files: Vec::new(),
322 active_sidebar: Some(ActiveSidebar {
323 plugin_id: "annotations".into(),
324 button_id: Some("toggle_annotations".into()),
325 width_px: 250,
326 ui_path: "/plugins/annotations/ui/sidebar.slint".into(),
327 component: "AnnotationsSidebar".into(),
328 }),
329 };
330
331 assert_eq!(
332 snapshot.active_sidebar.as_ref().map(|s| s.width_px),
333 Some(250)
334 );
335 }
336}