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