Skip to main content

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