Skip to main content

eov_plugin_api/
sdk.rs

1//! The safe Rust SDK for writing eov plugins.
2//!
3//! Implement [`Plugin`] and export it with [`crate::export_plugin!`]:
4//!
5//! ```no_run
6//! use eov_plugin_api::prelude::*;
7//!
8//! struct Hello {
9//!     host: Host,
10//! }
11//!
12//! impl Plugin for Hello {
13//!     fn create(host: Host, _init: PluginInit) -> Result<Self, String> {
14//!         host.add_toolbar_button(ToolbarButtonSpec {
15//!             button_id: "hello".into(),
16//!             tooltip: "Say hello".into(),
17//!             icon_svg: "<svg xmlns='http://www.w3.org/2000/svg'/>".into(),
18//!             ..Default::default()
19//!         })
20//!         .map_err(|e| e.to_string())?;
21//!         Ok(Self { host })
22//!     }
23//!
24//!     fn on_event(&self, event: HostEvent) -> Result<(), String> {
25//!         if let HostEvent::ToolbarButtonClicked { .. } = event {
26//!             self.host.notify(NotifyLevel::Info, "Hello from a plugin");
27//!         }
28//!         Ok(())
29//!     }
30//! }
31//!
32//! eov_plugin_api::export_plugin!(Hello);
33//! ```
34//!
35//! Every call into the plugin is wrapped in `catch_unwind`: a panic becomes an
36//! error the host reports (and the host disables the plugin) instead of
37//! aborting eov.
38//!
39//! # Slide formats
40//!
41//! A plugin that reads slides eov cannot read itself declares the formats
42//! in its manifest (`[[slide_formats]]`), implements
43//! [`Plugin::open_slide`] and returns a [`SlideReader`] per slide;
44//! [`crate::export_plugin!`] exports the rest:
45//!
46//! ```no_run
47//! use eov_plugin_api::prelude::*;
48//!
49//! struct Flat;
50//!
51//! impl SlideReader for Flat {
52//!     fn info(&self) -> SlideInfo {
53//!         SlideInfo {
54//!             levels: vec![SlideLevel { width: 1024, height: 1024, ..Default::default() }],
55//!             ..Default::default()
56//!         }
57//!     }
58//!
59//!     fn read_region(&self, _region: &SlideRegion, out: &mut [u8]) -> Result<(), String> {
60//!         for px in out.chunks_exact_mut(4) {
61//!             px.copy_from_slice(&[230, 200, 220, 255]);
62//!         }
63//!         Ok(())
64//!     }
65//! }
66//!
67//! struct FlatFormat;
68//!
69//! impl Plugin for FlatFormat {
70//!     fn create(_host: Host, _init: PluginInit) -> Result<Self, String> {
71//!         Ok(Self)
72//!     }
73//!
74//!     fn open_slide(&self, request: &SlideOpenRequest) -> Result<Box<dyn SlideReader>, String> {
75//!         std::fs::metadata(&request.location).map_err(|e| e.to_string())?;
76//!         Ok(Box::new(Flat))
77//!     }
78//! }
79//!
80//! eov_plugin_api::export_plugin!(FlatFormat);
81//! ```
82
83use crate::abi::{
84    self, FfiError, FfiErrorKind, FfiResult, FilterFrame, FilterView, HostBox, Pixels, PluginBox,
85    PluginFfi, PluginFfi_TO, PluginModule, PluginModuleRef, RasterUpload, RegionRequest, SlideBox,
86    SlideFfi, SlideFfi_TO, SlideRegion, SlideSourceBox, SlideSourceFfi, SlideSourceFfi_TO,
87};
88use crate::protocol::{methods, *};
89use abi_stable::{
90    prefix_type::PrefixTypeTrait,
91    sabi_trait::{TD_CanDowncast, TD_Opaque},
92    std_types::{RErr, ROk, RSliceMut, RStr, RString},
93};
94use serde::{Serialize, de::DeserializeOwned};
95use serde_json::{Map, Value};
96use std::any::Any;
97use std::panic::{AssertUnwindSafe, catch_unwind};
98use std::sync::Arc;
99
100/// Name of the static `abi_stable` looks up in a plugin library. Spelled out
101/// so that [`crate::export_plugin!`] needs no `abi_stable` dependency in the
102/// plugin crate; a unit test keeps it in sync.
103pub const ROOT_MODULE_LOADER_SYMBOL: &str = "_1as_0lib_1header_0root_bmodule_bloader";
104
105// ---------------------------------------------------------------------------
106// The plugin trait
107// ---------------------------------------------------------------------------
108
109/// An eov plugin.
110///
111/// The host calls [`on_event`](Self::on_event), [`context_menu`](Self::context_menu)
112/// and [`ui_callback`](Self::ui_callback) on its UI thread, one at a time, with
113/// no host locks held; keep them short and move slow work to your own threads
114/// (every [`Host`] method may be called from any thread).
115/// [`apply_filter`](Self::apply_filter) runs on render worker threads,
116/// possibly concurrently for different panes.
117pub trait Plugin: Send + Sync + Sized + 'static {
118    /// Creates the plugin. Keep `host` to call back into eov later.
119    fn create(host: Host, init: PluginInit) -> Result<Self, String>;
120
121    /// Handles an event. Returned errors are logged and shown to the user.
122    fn on_event(&self, event: HostEvent) -> Result<(), String> {
123        let _ = event;
124        Ok(())
125    }
126
127    /// Contributes items to a viewport context menu.
128    fn context_menu(&self, context: &MenuContext) -> Vec<MenuItem> {
129        let _ = context;
130        Vec::new()
131    }
132
133    /// Handles a callback declared in one of the plugin's `.slint` surfaces.
134    /// The returned value becomes the callback's return value (use `null` for
135    /// callbacks without one).
136    fn ui_callback(&self, surface_id: &str, name: &str, args: &[Value]) -> Result<Value, String> {
137        let _ = (surface_id, name, args);
138        Ok(Value::Null)
139    }
140
141    /// Applies the CPU filter `filter_id` (registered with
142    /// [`Host::register_filter`]) to a rendered frame in place.
143    fn apply_filter(&self, filter_id: &str, frame: &mut Frame<'_>) -> Result<(), String> {
144        let _ = (filter_id, frame);
145        Ok(())
146    }
147
148    /// Opens a slide of one of the formats the manifest declares
149    /// (`[[slide_formats]]`): a file whose extension, or a
150    /// URI whose scheme, matched the format `request.format_id`.
151    ///
152    /// Called on worker threads, possibly several at once, with no host
153    /// locks held; it may take a while (a network round trip), but it must
154    /// return. An error is shown to the user as the reason the slide did
155    /// not open; a panic stops the plugin.
156    fn open_slide(&self, request: &SlideOpenRequest) -> Result<Box<dyn SlideReader>, String> {
157        Err(format!(
158            "this plugin reads no slide formats (asked for '{}')",
159            request.format_id
160        ))
161    }
162
163    /// Called once before the plugin is unloaded. Stop your threads here.
164    /// Slides the plugin opened may still be read (and dropped) afterwards,
165    /// until eov has let go of them.
166    fn shutdown(&self) {}
167}
168
169/// One slide opened by [`Plugin::open_slide`].
170///
171/// eov reads regions from its render workers, several threads at once on
172/// the same reader, so it is `Send + Sync`: guard non-thread-safe decoders
173/// with a lock of your own. Every call runs inside `catch_unwind`; a panic
174/// fails the call and stops the plugin, an `Err` fails only that read (the
175/// tile shows as missing and is tried again later).
176pub trait SlideReader: Send + Sync + 'static {
177    /// The slide's metadata, asked for once right after opening. eov checks
178    /// it ([`SlideInfo::validate`]) and refuses slides it cannot use.
179    fn info(&self) -> SlideInfo;
180
181    /// Fills `out` with the pixels of `region`, which lies inside its level
182    /// (in pixels of that level, see [`SlideRegion`]): `width·height·4`
183    /// bytes of RGBA with straight alpha, rows top to bottom. `out` arrives
184    /// transparent; leave pixels without image data as they are.
185    fn read_region(&self, region: &SlideRegion, out: &mut [u8]) -> Result<(), String>;
186
187    /// Decodes an associated image listed in [`SlideInfo::associated_images`]
188    /// at the size listed there, as RGBA with straight alpha.
189    fn read_associated_image(&self, name: &str) -> Result<Image, String> {
190        Err(format!("no associated image '{name}'"))
191    }
192}
193
194// ---------------------------------------------------------------------------
195// Errors
196// ---------------------------------------------------------------------------
197
198/// An error returned by a host call.
199#[derive(Debug, Clone, PartialEq, Eq)]
200pub struct HostError {
201    pub kind: FfiErrorKind,
202    pub message: String,
203}
204
205impl HostError {
206    fn new(kind: FfiErrorKind, message: impl Into<String>) -> Self {
207        Self {
208            kind,
209            message: message.into(),
210        }
211    }
212
213    /// The host does not know this method (it is older than the plugin).
214    pub fn is_unsupported(&self) -> bool {
215        self.kind == FfiErrorKind::Unsupported
216    }
217}
218
219impl std::fmt::Display for HostError {
220    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
221        f.write_str(&self.message)
222    }
223}
224
225impl std::error::Error for HostError {}
226
227impl From<FfiError> for HostError {
228    fn from(error: FfiError) -> Self {
229        Self::new(error.kind(), error.message.into_string())
230    }
231}
232
233impl From<HostError> for String {
234    fn from(error: HostError) -> Self {
235        error.message
236    }
237}
238
239pub type HostResult<T> = Result<T, HostError>;
240
241fn from_ffi<T>(result: FfiResult<T>) -> HostResult<T> {
242    result.into_result().map_err(HostError::from)
243}
244
245// ---------------------------------------------------------------------------
246// Images and frames
247// ---------------------------------------------------------------------------
248
249/// An RGBA8 image with straight alpha, row-major, without padding.
250#[derive(Debug, Clone, PartialEq, Eq, Default)]
251pub struct Image {
252    pub width: u32,
253    pub height: u32,
254    pub data: Vec<u8>,
255}
256
257impl Image {
258    /// The RGBA value at `(x, y)`.
259    pub fn pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> {
260        if x >= self.width || y >= self.height {
261            return None;
262        }
263        let i = (y as usize * self.width as usize + x as usize) * 4;
264        self.data.get(i..i + 4).map(|p| [p[0], p[1], p[2], p[3]])
265    }
266
267    fn into_pixels(self) -> abi::Pixels {
268        abi::Pixels {
269            width: self.width,
270            height: self.height,
271            data: self.data.into(),
272        }
273    }
274}
275
276impl From<abi::Pixels> for Image {
277    fn from(pixels: abi::Pixels) -> Self {
278        Self {
279            width: pixels.width,
280            height: pixels.height,
281            data: pixels.data.into_vec(),
282        }
283    }
284}
285
286/// A rendered frame handed to [`Plugin::apply_filter`].
287pub struct Frame<'a> {
288    pixels: &'a mut [u8],
289    width: u32,
290    height: u32,
291    stride: usize,
292    view: FilterView,
293}
294
295impl<'a> Frame<'a> {
296    /// Wraps a pixel buffer. `stride` is in bytes and at least `width·4`.
297    /// Returns `None` when the buffer is too small for the dimensions.
298    pub fn new(
299        pixels: &'a mut [u8],
300        width: u32,
301        height: u32,
302        stride: usize,
303        view: FilterView,
304    ) -> Option<Self> {
305        let row = (width as usize).checked_mul(4)?;
306        if stride < row {
307            return None;
308        }
309        let needed = if height == 0 {
310            0
311        } else {
312            stride.checked_mul(height as usize - 1)?.checked_add(row)?
313        };
314        (pixels.len() >= needed).then_some(Self {
315            pixels,
316            width,
317            height,
318            stride,
319            view,
320        })
321    }
322
323    pub fn width(&self) -> u32 {
324        self.width
325    }
326
327    pub fn height(&self) -> u32 {
328        self.height
329    }
330
331    /// Bytes between the starts of consecutive rows.
332    pub fn stride(&self) -> usize {
333        self.stride
334    }
335
336    /// The pane being rendered.
337    pub fn view(&self) -> &FilterView {
338        &self.view
339    }
340
341    /// Row `y` as `width·4` RGBA bytes.
342    pub fn row_mut(&mut self, y: u32) -> &mut [u8] {
343        assert!(y < self.height, "row {y} out of range");
344        let start = y as usize * self.stride;
345        &mut self.pixels[start..start + self.width as usize * 4]
346    }
347
348    /// Every row, top to bottom, each `width·4` RGBA bytes.
349    pub fn rows_mut(&mut self) -> impl Iterator<Item = &mut [u8]> + '_ {
350        let row = self.width as usize * 4;
351        let height = self.height as usize;
352        self.pixels
353            .chunks_mut(self.stride.max(1))
354            .take(height)
355            .map(move |chunk| &mut chunk[..row])
356    }
357
358    /// Calls `f` for every pixel with its coordinates.
359    pub fn for_each_pixel(&mut self, mut f: impl FnMut(u32, u32, &mut [u8])) {
360        let width = self.width;
361        for (y, row) in self.rows_mut().enumerate() {
362            let (pixels, _) = row.as_chunks_mut::<4>();
363            for (x, px) in pixels.iter_mut().enumerate().take(width as usize) {
364                f(x as u32, y as u32, px);
365            }
366        }
367    }
368}
369
370// ---------------------------------------------------------------------------
371// Host handle
372// ---------------------------------------------------------------------------
373
374/// A cheap, cloneable, thread-safe handle to the host.
375#[derive(Clone)]
376pub struct Host {
377    ffi: Arc<HostBox>,
378}
379
380impl Host {
381    /// Wraps the host object passed to the plugin. Used by
382    /// [`crate::export_plugin!`] and [`crate::testing`].
383    pub fn from_ffi(ffi: HostBox) -> Self {
384        Self { ffi: Arc::new(ffi) }
385    }
386
387    /// Invokes a host method with pre-encoded JSON.
388    pub fn call_raw(&self, method: &str, args_json: &str) -> HostResult<String> {
389        from_ffi(
390            self.ffi
391                .call(RStr::from_str(method), RStr::from_str(args_json)),
392        )
393        .map(RString::into_string)
394    }
395
396    /// Invokes a host method with typed arguments and result.
397    pub fn call<A, R>(&self, method: &str, args: &A) -> HostResult<R>
398    where
399        A: Serialize + ?Sized,
400        R: DeserializeOwned,
401    {
402        let args = serde_json::to_string(args)
403            .map_err(|e| HostError::new(FfiErrorKind::InvalidArguments, e.to_string()))?;
404        let reply = self.call_raw(method, &args)?;
405        serde_json::from_str(&reply).map_err(|e| {
406            HostError::new(
407                FfiErrorKind::Failed,
408                format!("unexpected reply to '{method}': {e}"),
409            )
410        })
411    }
412
413    fn command<A: Serialize + ?Sized>(&self, method: &str, args: &A) -> HostResult<()> {
414        self.call::<A, Value>(method, args).map(|_| ())
415    }
416
417    // -- feedback ----------------------------------------------------------
418
419    /// Writes to the eov log. Warnings and errors also reach the user's
420    /// notification list.
421    pub fn log(&self, level: LogLevel, message: impl Into<String>) {
422        let _ = self.command(
423            methods::LOG,
424            &LogArgs {
425                level,
426                message: message.into(),
427            },
428        );
429    }
430
431    pub fn debug(&self, message: impl Into<String>) {
432        self.log(LogLevel::Debug, message);
433    }
434
435    pub fn info(&self, message: impl Into<String>) {
436        self.log(LogLevel::Info, message);
437    }
438
439    pub fn warn(&self, message: impl Into<String>) {
440        self.log(LogLevel::Warn, message);
441    }
442
443    pub fn error(&self, message: impl Into<String>) {
444        self.log(LogLevel::Error, message);
445    }
446
447    /// Shows a toast notification.
448    pub fn notify(&self, level: NotifyLevel, message: impl Into<String>) {
449        let _ = self.command(
450            methods::NOTIFY,
451            &NotifyArgs {
452                level,
453                message: message.into(),
454                detail: None,
455            },
456        );
457    }
458
459    /// Shows an error toast with an expandable detail text.
460    pub fn notify_error(&self, message: impl Into<String>, detail: impl Into<String>) {
461        let _ = self.command(
462            methods::NOTIFY,
463            &NotifyArgs {
464                level: NotifyLevel::Error,
465                message: message.into(),
466                detail: Some(detail.into()),
467            },
468        );
469    }
470
471    /// Sets (or with `None` clears) the plugin's status-bar text.
472    pub fn set_status(&self, text: Option<&str>) {
473        let _ = self.command(
474            methods::STATUS,
475            &StatusArgs {
476                text: text.map(str::to_string),
477            },
478        );
479    }
480
481    // -- state ---------------------------------------------------------------
482
483    /// A recent, consistent copy of the host state.
484    pub fn snapshot(&self) -> HostResult<HostSnapshot> {
485        self.call(methods::SNAPSHOT, &Map::new())
486    }
487
488    pub fn file_info(&self, file_id: FileId) -> HostResult<FileInfo> {
489        self.call(methods::FILE_INFO, &FileArgs { file_id })
490    }
491
492    /// Every vendor property of a slide (OpenSlide property map).
493    pub fn file_properties(&self, file_id: FileId) -> HostResult<PropertyMap> {
494        self.call(methods::FILE_PROPERTIES, &FileArgs { file_id })
495    }
496
497    /// Opens a slide in a new tab.
498    pub fn open_file(&self, path: impl Into<String>) -> HostResult<()> {
499        self.command(methods::FILE_OPEN, &OpenFileArgs { path: path.into() })
500    }
501
502    /// Reads slide pixels on the calling thread. For RGB slides they are
503    /// the slide's own colours, as scanned: eov's colour adjustments and
504    /// its colour management (ICC profile to sRGB, see
505    /// [`DisplayAdjustments::color_managed`]) apply to the display only.
506    ///
507    /// Multichannel slides (see [`FileInfo::channel_names`]) come back as
508    /// RGBA too: their visible channels composited with the user's current
509    /// channel display, as the viewer shows them.
510    pub fn read_region(&self, request: RegionRequest) -> HostResult<Image> {
511        from_ffi(self.ffi.read_region(request)).map(Image::from)
512    }
513
514    /// Reads an associated image (`"label"`, `"macro"`, `"thumbnail"`, …).
515    pub fn read_associated_image(&self, file_id: FileId, name: &str) -> HostResult<Image> {
516        from_ffi(
517            self.ffi
518                .read_associated_image(file_id, RStr::from_str(name)),
519        )
520        .map(Image::from)
521    }
522
523    /// The host region of interest of a slide.
524    pub fn roi(&self, file_id: FileId) -> HostResult<Option<Rect>> {
525        self.call(methods::ROI_GET, &FileArgs { file_id })
526    }
527
528    /// The host measurements of a slide.
529    pub fn measurements(&self, file_id: FileId) -> HostResult<Vec<MeasurementInfo>> {
530        self.call(methods::MEASUREMENTS_LIST, &FileArgs { file_id })
531    }
532
533    // -- toolbar, HUD and tools ----------------------------------------------
534
535    pub fn add_toolbar_button(&self, spec: ToolbarButtonSpec) -> HostResult<()> {
536        self.command(methods::TOOLBAR_ADD, &spec)
537    }
538
539    pub fn update_toolbar_button(&self, update: ButtonUpdate) -> HostResult<()> {
540        self.command(methods::TOOLBAR_UPDATE, &update)
541    }
542
543    /// Shorthand for toggling a toolbar button's pressed state.
544    pub fn set_toolbar_button_active(&self, button_id: &str, active: bool) -> HostResult<()> {
545        self.update_toolbar_button(ButtonUpdate {
546            button_id: button_id.to_string(),
547            active: Some(active),
548            ..Default::default()
549        })
550    }
551
552    pub fn remove_toolbar_button(&self, button_id: &str) -> HostResult<()> {
553        self.command(
554            methods::TOOLBAR_REMOVE,
555            &IdArgs {
556                id: button_id.into(),
557            },
558        )
559    }
560
561    pub fn add_hud_button(&self, spec: HudButtonSpec) -> HostResult<()> {
562        self.command(methods::HUD_ADD, &spec)
563    }
564
565    pub fn update_hud_button(&self, update: ButtonUpdate) -> HostResult<()> {
566        self.command(methods::HUD_UPDATE, &update)
567    }
568
569    pub fn remove_hud_button(&self, button_id: &str) -> HostResult<()> {
570        self.command(
571            methods::HUD_REMOVE,
572            &IdArgs {
573                id: button_id.into(),
574            },
575        )
576    }
577
578    /// Shows a short notice fixed to the corner of the panes showing
579    /// `file_id` (every pane with a slide for `None`); it does not move with
580    /// the view. `text: None` removes it.
581    pub fn set_badge(
582        &self,
583        badge_id: &str,
584        file_id: Option<FileId>,
585        text: Option<&str>,
586    ) -> HostResult<()> {
587        self.command(
588            methods::BADGE_SET,
589            &BadgeArgs {
590                badge_id: badge_id.to_string(),
591                file_id,
592                text: text.map(str::to_string),
593            },
594        )
595    }
596
597    /// Offers a command for headless batch runs (`eov batch run
598    /// <plugin>:<command> SLIDES --out DIR`); slides then arrive as
599    /// [`HostEvent::BatchRun`]. Call it in [`Plugin::create`].
600    pub fn register_batch_command(&self, spec: BatchCommandSpec) -> HostResult<()> {
601        self.command(methods::BATCH_REGISTER, &spec)
602    }
603
604    /// Reports how far the slide of batch run `run_id` is.
605    pub fn batch_progress(
606        &self,
607        run_id: &str,
608        fraction: Option<f32>,
609        message: Option<&str>,
610    ) -> HostResult<()> {
611        self.command(
612            methods::BATCH_PROGRESS,
613            &BatchProgressArgs {
614                run_id: run_id.to_string(),
615                fraction,
616                message: message.map(str::to_string),
617            },
618        )
619    }
620
621    /// Ends the slide of a batch run: the next slide comes once this is
622    /// sent.
623    pub fn finish_batch(&self, result: BatchFinishArgs) -> HostResult<()> {
624        self.command(methods::BATCH_FINISH, &result)
625    }
626
627    /// Binds a key of its own (not tied to a button or tool); presses
628    /// arrive as [`HostEvent::HotkeyPressed`]. A key eov uses (its shortcut
629    /// table, which users can change, and Escape, Enter, Delete, Backspace,
630    /// Tab and plain arrows) or another plugin's key is refused with
631    /// [`HostEvent::RegistrationRefused`]; tool and button hotkeys are
632    /// checked the same way.
633    pub fn register_hotkey(&self, spec: HotkeySpec) -> HostResult<()> {
634        self.command(methods::HOTKEY_REGISTER, &spec)
635    }
636
637    pub fn unregister_hotkey(&self, hotkey_id: &str) -> HostResult<()> {
638        self.command(
639            methods::HOTKEY_UNREGISTER,
640            &IdArgs {
641                id: hotkey_id.to_string(),
642            },
643        )
644    }
645
646    pub fn register_tool(&self, spec: ToolSpec) -> HostResult<()> {
647        self.command(methods::TOOL_REGISTER, &spec)
648    }
649
650    pub fn unregister_tool(&self, tool_id: &str) -> HostResult<()> {
651        self.command(methods::TOOL_UNREGISTER, &IdArgs { id: tool_id.into() })
652    }
653
654    pub fn activate_tool(&self, tool_id: &str) -> HostResult<()> {
655        self.command(methods::TOOL_ACTIVATE, &IdArgs { id: tool_id.into() })
656    }
657
658    /// Returns to the Navigate tool if one of this plugin's tools is active.
659    pub fn deactivate_tools(&self) -> HostResult<()> {
660        self.command(methods::TOOL_DEACTIVATE, &Map::new())
661    }
662
663    // -- overlays --------------------------------------------------------------
664
665    /// Creates (or replaces) an overlay layer.
666    pub fn create_layer(&self, spec: LayerSpec) -> HostResult<Layer> {
667        let layer_id = spec.layer_id.clone();
668        self.command(methods::LAYER_CREATE, &spec)?;
669        Ok(self.layer(layer_id))
670    }
671
672    /// A handle to an existing layer.
673    pub fn layer(&self, layer_id: impl Into<String>) -> Layer {
674        Layer {
675            host: self.clone(),
676            layer_id: layer_id.into(),
677        }
678    }
679
680    // -- surfaces --------------------------------------------------------------
681
682    /// Opens a Slint surface (sidebar, window or modal).
683    pub fn open_surface(&self, spec: SurfaceSpec) -> HostResult<Surface> {
684        let opened: SurfaceOpened = self.call(methods::SURFACE_OPEN, &spec)?;
685        Ok(self.surface(opened.surface_id))
686    }
687
688    /// A handle to a surface opened earlier.
689    pub fn surface(&self, surface_id: impl Into<String>) -> Surface {
690        Surface {
691            host: self.clone(),
692            surface_id: surface_id.into(),
693        }
694    }
695
696    // -- dialogs ---------------------------------------------------------------
697
698    /// Asks a yes/no question; the answer arrives as
699    /// [`HostEvent::ConfirmResult`] with the returned request id.
700    pub fn confirm(&self, args: ConfirmArgs) -> HostResult<String> {
701        self.call::<_, RequestId>(methods::DIALOG_CONFIRM, &args)
702            .map(|r| r.request_id)
703    }
704
705    /// Shows an open-file dialog; the result arrives as
706    /// [`HostEvent::DialogResult`] with the returned request id.
707    pub fn open_file_dialog(&self, args: FileDialogArgs) -> HostResult<String> {
708        self.call::<_, RequestId>(methods::DIALOG_OPEN_FILE, &args)
709            .map(|r| r.request_id)
710    }
711
712    /// Shows a save-file dialog; the result arrives as
713    /// [`HostEvent::DialogResult`] with the returned request id.
714    pub fn save_file_dialog(&self, args: FileDialogArgs) -> HostResult<String> {
715        self.call::<_, RequestId>(methods::DIALOG_SAVE_FILE, &args)
716            .map(|r| r.request_id)
717    }
718
719    // -- models ----------------------------------------------------------------
720
721    /// Makes a model available in eov's model store: answered at once when
722    /// it is stored already, otherwise downloaded once the user agrees and
723    /// verified against its SHA-256. The answer arrives as
724    /// [`HostEvent::ModelFetched`] with the returned request id. Hosts
725    /// without a model store answer [`HostError::is_unsupported`].
726    pub fn fetch_model(&self, args: ModelFetchArgs) -> HostResult<String> {
727        self.call::<_, RequestId>(methods::MODEL_FETCH, &args)
728            .map(|r| r.request_id)
729    }
730
731    /// The stored model whose main file has this SHA-256, if any.
732    pub fn resolve_model(&self, sha256: &str) -> HostResult<Option<ModelRecord>> {
733        self.call(
734            methods::MODEL_RESOLVE,
735            &ModelResolveArgs {
736                sha256: sha256.to_ascii_lowercase(),
737            },
738        )
739    }
740
741    /// Every model in eov's model store.
742    pub fn models(&self) -> HostResult<Vec<ModelRecord>> {
743        self.call(methods::MODEL_LIST, &Map::new())
744    }
745
746    // -- navigation --------------------------------------------------------------
747
748    pub fn set_view(&self, args: ViewSetArgs) -> HostResult<()> {
749        self.command(methods::VIEW_SET, &args)
750    }
751
752    /// Pans a pane (default: the focused one) by logical screen pixels.
753    pub fn pan(&self, pane: Option<PaneId>, dx: f64, dy: f64) -> HostResult<()> {
754        self.command(methods::VIEW_PAN, &ViewPanArgs { pane, dx, dy })
755    }
756
757    /// Zooms a pane by `factor` (> 1 zooms in) around its centre.
758    pub fn zoom(&self, pane: Option<PaneId>, factor: f64) -> HostResult<()> {
759        self.command(
760            methods::VIEW_ZOOM,
761            &ViewZoomArgs {
762                pane,
763                factor,
764                anchor_x: None,
765                anchor_y: None,
766                animate: false,
767            },
768        )
769    }
770
771    pub fn fit(&self, pane: Option<PaneId>) -> HostResult<()> {
772        self.command(methods::VIEW_FIT, &PaneArgs { pane })
773    }
774
775    /// Turns a pane's view (default: the focused one) about its centre:
776    /// `rotation_deg` clockwise (any angle), then mirrored left to right if
777    /// `flipped`. Level-0 coordinates are unaffected.
778    pub fn set_view_orientation(
779        &self,
780        pane: Option<PaneId>,
781        rotation_deg: f64,
782        flipped: bool,
783    ) -> HostResult<()> {
784        self.command(
785            methods::VIEW_ORIENTATION,
786            &ViewOrientationArgs {
787                pane,
788                rotation_deg,
789                flipped,
790            },
791        )
792    }
793
794    /// How a pane displays its slide (tone adjustments, normalisation), so
795    /// overlays made from slide pixels can match it.
796    pub fn display_adjustments(&self, pane: Option<PaneId>) -> HostResult<DisplayAdjustments> {
797        self.call(methods::VIEW_DISPLAY, &PaneArgs { pane })
798    }
799
800    /// Frames a level-0 rectangle in a pane.
801    pub fn frame(&self, pane: Option<PaneId>, rect: Rect) -> HostResult<()> {
802        self.command(
803            methods::VIEW_FRAME,
804            &ViewFrameArgs {
805                pane,
806                rect,
807                padding: None,
808            },
809        )
810    }
811
812    pub fn cycle_pane(&self, offset: i32) -> HostResult<()> {
813        self.command(methods::APP_CYCLE_PANE, &OffsetArgs { offset })
814    }
815
816    pub fn cycle_tab(&self, offset: i32) -> HostResult<()> {
817        self.command(methods::APP_CYCLE_TAB, &OffsetArgs { offset })
818    }
819
820    pub fn series(&self, action: SeriesAction) -> HostResult<()> {
821        self.command(methods::APP_SERIES, &SeriesArgs { action })
822    }
823
824    /// Asks the host to redraw every pane (e.g. after a filter's output
825    /// changed).
826    pub fn request_render(&self) -> HostResult<()> {
827        self.command(methods::RENDER_REQUEST, &Map::new())
828    }
829
830    // -- undo --------------------------------------------------------------------
831
832    /// Records an undoable change. Ctrl/⌘+Z later sends
833    /// [`HostEvent::Undo`] with `entry_id`.
834    pub fn push_undo(
835        &self,
836        entry_id: impl Into<String>,
837        file_id: Option<FileId>,
838        label: impl Into<String>,
839    ) -> HostResult<()> {
840        self.command(
841            methods::UNDO_PUSH,
842            &UndoPushArgs {
843                entry_id: entry_id.into(),
844                file_id,
845                label: label.into(),
846            },
847        )
848    }
849
850    /// Forgets the plugin's history entries (of one file, or all).
851    pub fn clear_undo(&self, file_id: Option<FileId>) -> HostResult<()> {
852        self.command(methods::UNDO_CLEAR, &UndoClearArgs { file_id })
853    }
854
855    // -- filters -----------------------------------------------------------------
856
857    pub fn register_filter(&self, spec: FilterSpec) -> HostResult<()> {
858        self.command(methods::FILTER_REGISTER, &spec)
859    }
860
861    pub fn set_filter_enabled(&self, filter_id: &str, enabled: bool) -> HostResult<()> {
862        self.command(
863            methods::FILTER_SET_ENABLED,
864            &FilterEnableArgs {
865                filter_id: filter_id.into(),
866                enabled,
867            },
868        )
869    }
870
871    pub fn unregister_filter(&self, filter_id: &str) -> HostResult<()> {
872        self.command(
873            methods::FILTER_UNREGISTER,
874            &IdArgs {
875                id: filter_id.into(),
876            },
877        )
878    }
879
880    // -- settings ------------------------------------------------------------------
881
882    /// Reads a persisted setting.
883    pub fn setting<T: DeserializeOwned>(&self, key: &str) -> HostResult<Option<T>> {
884        let value: Value = self.call(methods::SETTINGS_GET, &KeyArgs { key: key.into() })?;
885        if value.is_null() {
886            return Ok(None);
887        }
888        serde_json::from_value(value)
889            .map(Some)
890            .map_err(|e| HostError::new(FfiErrorKind::Failed, format!("setting '{key}': {e}")))
891    }
892
893    /// Persists a setting.
894    pub fn set_setting<T: Serialize + ?Sized>(&self, key: &str, value: &T) -> HostResult<()> {
895        let value = serde_json::to_value(value)
896            .map_err(|e| HostError::new(FfiErrorKind::InvalidArguments, e.to_string()))?;
897        self.command(
898            methods::SETTINGS_SET,
899            &SettingsSetArgs {
900                key: key.into(),
901                value,
902            },
903        )
904    }
905
906    pub fn remove_setting(&self, key: &str) -> HostResult<()> {
907        self.command(
908            methods::SETTINGS_SET,
909            &SettingsSetArgs {
910                key: key.into(),
911                value: Value::Null,
912            },
913        )
914    }
915
916    // -- jobs ------------------------------------------------------------------------
917
918    /// Shows a background job with progress in the host UI.
919    pub fn start_job(&self, title: impl Into<String>, cancellable: bool) -> HostResult<Job> {
920        let started: JobStarted = self.call(
921            methods::JOB_START,
922            &JobStartArgs {
923                title: title.into(),
924                cancellable,
925            },
926        )?;
927        Ok(Job {
928            host: self.clone(),
929            job_id: started.job_id,
930            finished: false,
931        })
932    }
933
934    // -- miscellaneous -----------------------------------------------------------------
935
936    pub fn copy_text(&self, text: impl Into<String>) -> HostResult<()> {
937        self.command(methods::CLIPBOARD_SET_TEXT, &TextArgs { text: text.into() })
938    }
939
940    /// Asks for [`HostEvent::Posted`] with `token` to be delivered on the UI
941    /// thread.
942    pub fn post(&self, token: impl Into<String>) -> HostResult<()> {
943        self.command(
944            methods::POST,
945            &PostArgs {
946                token: token.into(),
947            },
948        )
949    }
950
951    /// Restricts the optional events delivered to this plugin (see
952    /// [`crate::protocol::event_names`]).
953    pub fn subscribe(&self, events: &[&str]) -> HostResult<()> {
954        self.command(
955            methods::EVENTS_SUBSCRIBE,
956            &SubscribeArgs {
957                events: events.iter().map(|e| e.to_string()).collect(),
958            },
959        )
960    }
961}
962
963/// A handle to an overlay layer.
964#[derive(Clone)]
965pub struct Layer {
966    host: Host,
967    layer_id: String,
968}
969
970impl Layer {
971    pub fn id(&self) -> &str {
972        &self.layer_id
973    }
974
975    /// Adds or replaces objects.
976    pub fn upsert(&self, objects: Vec<OverlayObject>) -> HostResult<()> {
977        self.host.command(
978            methods::LAYER_UPSERT,
979            &UpsertObjectsArgs {
980                layer_id: self.layer_id.clone(),
981                objects,
982                replace_all: false,
983            },
984        )
985    }
986
987    /// Atomically replaces every object of the layer.
988    pub fn replace_all(&self, objects: Vec<OverlayObject>) -> HostResult<()> {
989        self.host.command(
990            methods::LAYER_UPSERT,
991            &UpsertObjectsArgs {
992                layer_id: self.layer_id.clone(),
993                objects,
994                replace_all: true,
995            },
996        )
997    }
998
999    pub fn remove(&self, object_ids: Vec<String>) -> HostResult<()> {
1000        self.host.command(
1001            methods::LAYER_REMOVE_OBJECTS,
1002            &RemoveObjectsArgs {
1003                layer_id: self.layer_id.clone(),
1004                object_ids,
1005            },
1006        )
1007    }
1008
1009    pub fn clear(&self) -> HostResult<()> {
1010        self.host.command(
1011            methods::LAYER_CLEAR,
1012            &IdArgs {
1013                id: self.layer_id.clone(),
1014            },
1015        )
1016    }
1017
1018    /// Changes layer properties; set `layer_id` is filled in.
1019    pub fn update(&self, mut update: LayerUpdate) -> HostResult<()> {
1020        update.layer_id = self.layer_id.clone();
1021        self.host.command(methods::LAYER_UPDATE, &update)
1022    }
1023
1024    pub fn set_visible(&self, visible: bool) -> HostResult<()> {
1025        self.update(LayerUpdate {
1026            visible: Some(visible),
1027            ..Default::default()
1028        })
1029    }
1030
1031    /// Replaces the host-side selection within this layer.
1032    pub fn select(&self, object_ids: Vec<String>) -> HostResult<()> {
1033        self.host.command(
1034            methods::LAYER_SELECT,
1035            &SelectArgs {
1036                layer_id: self.layer_id.clone(),
1037                object_ids,
1038            },
1039        )
1040    }
1041
1042    /// Adds or replaces a raster object (heat map) stretched over `rect`.
1043    pub fn put_raster(
1044        &self,
1045        object_id: impl Into<String>,
1046        rect: Rect,
1047        image: Image,
1048        smooth: bool,
1049    ) -> HostResult<()> {
1050        from_ffi(self.host.ffi.put_raster(RasterUpload {
1051            layer_id: RString::from(self.layer_id.as_str()),
1052            object_id: RString::from(object_id.into()),
1053            x: rect.x,
1054            y: rect.y,
1055            width: rect.width,
1056            height: rect.height,
1057            pixels: image.into_pixels(),
1058            smooth,
1059        }))
1060    }
1061
1062    /// Draws these objects with the layer's hover style (an empty list
1063    /// clears it), e.g. while a row of the plugin's own list is hovered.
1064    pub fn highlight(&self, object_ids: Vec<String>) -> HostResult<()> {
1065        self.host.command(
1066            methods::LAYER_HIGHLIGHT,
1067            &SelectArgs {
1068                layer_id: self.layer_id.clone(),
1069                object_ids,
1070            },
1071        )
1072    }
1073
1074    /// Hides the layer below `min_zoom` screen pixels per level-0 pixel
1075    /// (`None`: every zoom) without recreating it.
1076    pub fn set_min_zoom(&self, min_zoom: Option<f64>) -> HostResult<()> {
1077        self.host.command(
1078            methods::LAYER_SET_MIN_ZOOM,
1079            &MinZoomArgs {
1080                layer_id: self.layer_id.clone(),
1081                min_zoom,
1082            },
1083        )
1084    }
1085
1086    /// Shows the layer only in `panes` (`None`: in every pane). Unlike
1087    /// [`set_visible_in_pane`](Self::set_visible_in_pane) this also covers
1088    /// panes opened later; call it right after creating the layer.
1089    pub fn set_panes(&self, panes: Option<Vec<PaneId>>) -> HostResult<()> {
1090        self.host.command(
1091            methods::LAYER_SET_PANES,
1092            &PaneFilterArgs {
1093                layer_id: self.layer_id.clone(),
1094                panes,
1095            },
1096        )
1097    }
1098
1099    /// Shows or hides the layer in one pane only; the layer's own
1100    /// visibility still applies.
1101    pub fn set_visible_in_pane(&self, pane: PaneId, visible: bool) -> HostResult<()> {
1102        self.host.command(
1103            methods::LAYER_SET_PANE_VISIBILITY,
1104            &PaneVisibilityArgs {
1105                layer_id: self.layer_id.clone(),
1106                pane,
1107                visible,
1108            },
1109        )
1110    }
1111
1112    /// Deletes the layer and its objects.
1113    pub fn remove_layer(self) -> HostResult<()> {
1114        self.host.command(
1115            methods::LAYER_REMOVE,
1116            &IdArgs {
1117                id: self.layer_id.clone(),
1118            },
1119        )
1120    }
1121}
1122
1123/// A handle to an open surface.
1124#[derive(Clone)]
1125pub struct Surface {
1126    host: Host,
1127    surface_id: String,
1128}
1129
1130impl Surface {
1131    pub fn id(&self) -> &str {
1132        &self.surface_id
1133    }
1134
1135    /// Sets one property (by its Slint name).
1136    pub fn set(&self, name: &str, value: impl Serialize) -> HostResult<()> {
1137        let value = serde_json::to_value(value)
1138            .map_err(|e| HostError::new(FfiErrorKind::InvalidArguments, e.to_string()))?;
1139        let mut properties = Map::new();
1140        properties.insert(name.to_string(), value);
1141        self.set_many(properties)
1142    }
1143
1144    /// Sets several properties. A value the surface already shows is left
1145    /// alone (so its bindings stay); setting a field back to a value the
1146    /// user edited away from does apply.
1147    pub fn set_many(&self, properties: Map<String, Value>) -> HostResult<()> {
1148        self.host.command(
1149            methods::SURFACE_SET,
1150            &SurfaceProperties {
1151                surface_id: self.surface_id.clone(),
1152                properties,
1153            },
1154        )
1155    }
1156
1157    pub fn is_open(&self) -> bool {
1158        self.host
1159            .call::<_, bool>(
1160                methods::SURFACE_IS_OPEN,
1161                &IdArgs {
1162                    id: self.surface_id.clone(),
1163                },
1164            )
1165            .unwrap_or(false)
1166    }
1167
1168    pub fn close(&self) -> HostResult<()> {
1169        self.host.command(
1170            methods::SURFACE_CLOSE,
1171            &IdArgs {
1172                id: self.surface_id.clone(),
1173            },
1174        )
1175    }
1176}
1177
1178/// A background job shown in the host UI. Dropping an unfinished job marks
1179/// it finished.
1180pub struct Job {
1181    host: Host,
1182    job_id: String,
1183    finished: bool,
1184}
1185
1186impl Job {
1187    pub fn id(&self) -> &str {
1188        &self.job_id
1189    }
1190
1191    /// Reports progress (`None` = indeterminate).
1192    pub fn update(&self, fraction: Option<f32>, message: Option<&str>) {
1193        let _ = self.host.command(
1194            methods::JOB_UPDATE,
1195            &JobUpdateArgs {
1196                job_id: self.job_id.clone(),
1197                fraction: fraction.map(|f| f.clamp(0.0, 1.0)),
1198                message: message.map(str::to_string),
1199            },
1200        );
1201    }
1202
1203    /// Marks the job done, or failed with `error`.
1204    pub fn finish(mut self, error: Option<String>) {
1205        self.finish_inner(error);
1206    }
1207
1208    fn finish_inner(&mut self, error: Option<String>) {
1209        if self.finished {
1210            return;
1211        }
1212        self.finished = true;
1213        let _ = self.host.command(
1214            methods::JOB_FINISH,
1215            &JobFinishArgs {
1216                job_id: self.job_id.clone(),
1217                error,
1218            },
1219        );
1220    }
1221}
1222
1223impl Drop for Job {
1224    fn drop(&mut self) {
1225        self.finish_inner(None);
1226    }
1227}
1228
1229// ---------------------------------------------------------------------------
1230// FFI adapter (used by `export_plugin!`)
1231// ---------------------------------------------------------------------------
1232
1233fn panic_message(payload: &(dyn Any + Send)) -> String {
1234    if let Some(text) = payload.downcast_ref::<&str>() {
1235        (*text).to_string()
1236    } else if let Some(text) = payload.downcast_ref::<String>() {
1237        text.clone()
1238    } else {
1239        "unknown panic payload".to_string()
1240    }
1241}
1242
1243/// Runs `f`, turning panics into [`FfiErrorKind::Panicked`] errors.
1244fn guarded<T>(f: impl FnOnce() -> Result<T, FfiError>) -> FfiResult<T> {
1245    match catch_unwind(AssertUnwindSafe(f)) {
1246        Ok(Ok(value)) => ROk(value),
1247        Ok(Err(error)) => RErr(error),
1248        Err(payload) => RErr(FfiError::new(
1249            FfiErrorKind::Panicked,
1250            format!("plugin panicked: {}", panic_message(payload.as_ref())),
1251        )),
1252    }
1253}
1254
1255#[doc(hidden)]
1256pub struct Adapter<P: Plugin> {
1257    /// Shared with the slide source ([`slide_source`]).
1258    plugin: Arc<P>,
1259}
1260
1261impl<P: Plugin> Adapter<P> {
1262    fn dispatch(&self, event_json: &str) -> Result<String, FfiError> {
1263        let event: HostEvent = serde_json::from_str(event_json).map_err(|e| {
1264            FfiError::new(FfiErrorKind::InvalidArguments, format!("bad event: {e}"))
1265        })?;
1266        match event {
1267            HostEvent::ContextMenuRequested(context) => {
1268                let items = self.plugin.context_menu(&context);
1269                to_json(&ContextMenuResponse { items })
1270            }
1271            HostEvent::UiCallback {
1272                surface_id,
1273                name,
1274                args,
1275            } => {
1276                let value = self
1277                    .plugin
1278                    .ui_callback(&surface_id, &name, &args)
1279                    .map_err(FfiError::failed)?;
1280                to_json(&value)
1281            }
1282            HostEvent::Unknown => Err(FfiError::new(
1283                FfiErrorKind::Unsupported,
1284                "event not supported by this plugin version",
1285            )),
1286            other => self
1287                .plugin
1288                .on_event(other)
1289                .map(|()| "null".to_string())
1290                .map_err(FfiError::failed),
1291        }
1292    }
1293}
1294
1295fn to_json<T: Serialize>(value: &T) -> Result<String, FfiError> {
1296    serde_json::to_string(value).map_err(|e| FfiError::failed(e.to_string()))
1297}
1298
1299impl<P: Plugin> PluginFfi for Adapter<P> {
1300    fn handle_event(&self, event_json: RStr<'_>) -> FfiResult<RString> {
1301        guarded(|| self.dispatch(event_json.as_str()).map(RString::from))
1302    }
1303
1304    fn apply_filter(&self, filter_id: RStr<'_>, frame: FilterFrame<'_>) -> FfiResult<()> {
1305        guarded(|| {
1306            let FilterFrame {
1307                pixels,
1308                width,
1309                height,
1310                stride,
1311                view,
1312            } = frame;
1313            let mut frame = Frame::new(
1314                pixels.into_mut_slice(),
1315                width,
1316                height,
1317                stride as usize,
1318                view,
1319            )
1320            .ok_or_else(|| {
1321                FfiError::new(
1322                    FfiErrorKind::InvalidArguments,
1323                    format!("frame buffer too small for {width}x{height} (stride {stride})"),
1324                )
1325            })?;
1326            self.plugin
1327                .apply_filter(filter_id.as_str(), &mut frame)
1328                .map_err(FfiError::failed)
1329        })
1330    }
1331
1332    fn shutdown(&self) {
1333        let _ = catch_unwind(AssertUnwindSafe(|| self.plugin.shutdown()));
1334    }
1335}
1336
1337/// Wraps a plugin value in the FFI instance type. It can be downcast, so
1338/// [`slide_source`] finds the plugin again (only this library does that:
1339/// the host never sees the type).
1340#[doc(hidden)]
1341pub fn into_plugin_box<P: Plugin>(plugin: P) -> PluginBox {
1342    PluginFfi_TO::from_value(
1343        Adapter {
1344            plugin: Arc::new(plugin),
1345        },
1346        TD_CanDowncast,
1347    )
1348}
1349
1350/// The slide source of an instance: its
1351/// [`Plugin::open_slide`].
1352extern "C" fn slide_source<P: Plugin>(instance: &PluginBox) -> FfiResult<SlideSourceBox> {
1353    slide_source_of::<P>(instance)
1354}
1355
1356/// [`slide_source`] for the test harness.
1357#[doc(hidden)]
1358pub fn slide_source_of<P: Plugin>(instance: &PluginBox) -> FfiResult<SlideSourceBox> {
1359    guarded(|| {
1360        let adapter = instance
1361            .obj
1362            .downcast_as::<Adapter<P>>()
1363            .map_err(|_| FfiError::failed("the instance was not created by this plugin library"))?;
1364        Ok(SlideSourceFfi_TO::from_value(
1365            SourceAdapter {
1366                plugin: Arc::clone(&adapter.plugin),
1367            },
1368            TD_Opaque,
1369        ))
1370    })
1371}
1372
1373struct SourceAdapter<P: Plugin> {
1374    plugin: Arc<P>,
1375}
1376
1377impl<P: Plugin> SlideSourceFfi for SourceAdapter<P> {
1378    fn open(&self, request_json: RStr<'_>) -> FfiResult<SlideBox> {
1379        guarded(|| {
1380            let request: SlideOpenRequest =
1381                serde_json::from_str(request_json.as_str()).map_err(|e| {
1382                    FfiError::new(FfiErrorKind::InvalidArguments, format!("bad request: {e}"))
1383                })?;
1384            let reader = self.plugin.open_slide(&request).map_err(FfiError::failed)?;
1385            Ok(SlideFfi_TO::from_value(SlideAdapter { reader }, TD_Opaque))
1386        })
1387    }
1388}
1389
1390struct SlideAdapter {
1391    reader: Box<dyn SlideReader>,
1392}
1393
1394impl SlideFfi for SlideAdapter {
1395    fn info(&self) -> FfiResult<RString> {
1396        guarded(|| to_json(&self.reader.info()).map(RString::from))
1397    }
1398
1399    fn read_region(&self, region: SlideRegion, out: RSliceMut<'_, u8>) -> FfiResult<()> {
1400        guarded(|| {
1401            let out = out.into_mut_slice();
1402            let expected = region.width as usize * region.height as usize * 4;
1403            if out.len() != expected {
1404                return Err(FfiError::new(
1405                    FfiErrorKind::InvalidArguments,
1406                    format!(
1407                        "the buffer holds {} bytes; {}×{} RGBA needs {expected}",
1408                        out.len(),
1409                        region.width,
1410                        region.height
1411                    ),
1412                ));
1413            }
1414            self.reader
1415                .read_region(&region, out)
1416                .map_err(FfiError::failed)
1417        })
1418    }
1419
1420    fn read_associated_image(&self, name: RStr<'_>) -> FfiResult<Pixels> {
1421        guarded(|| {
1422            let image = self
1423                .reader
1424                .read_associated_image(name.as_str())
1425                .map_err(FfiError::failed)?;
1426            Ok(Pixels {
1427                width: image.width,
1428                height: image.height,
1429                data: image.data.into(),
1430            })
1431        })
1432    }
1433
1434    fn call(&self, method: RStr<'_>, _args_json: RStr<'_>) -> FfiResult<RString> {
1435        RErr(FfiError::new(
1436            FfiErrorKind::Unsupported,
1437            format!("the slide has no method '{}'", method.as_str()),
1438        ))
1439    }
1440}
1441
1442/// Creates a plugin through the same code path the host uses.
1443#[doc(hidden)]
1444pub fn create_plugin<P: Plugin>(host: HostBox, init_json: &str) -> Result<PluginBox, FfiError> {
1445    guarded(|| {
1446        let init: PluginInit = serde_json::from_str(init_json)
1447            .map_err(|e| FfiError::new(FfiErrorKind::InvalidArguments, format!("bad init: {e}")))?;
1448        let plugin = P::create(Host::from_ffi(host), init).map_err(FfiError::failed)?;
1449        Ok(into_plugin_box(plugin))
1450    })
1451    .into_result()
1452}
1453
1454extern "C" fn create_instance<P: Plugin>(
1455    host: HostBox,
1456    init_json: RStr<'_>,
1457) -> FfiResult<PluginBox> {
1458    create_plugin::<P>(host, init_json.as_str()).into()
1459}
1460
1461/// The root module of a plugin library (used by [`crate::export_plugin!`]).
1462#[doc(hidden)]
1463pub fn root_module<P: Plugin>() -> PluginModuleRef {
1464    PluginModule {
1465        abi_version: abi::ABI_VERSION,
1466        api_version: RStr::from_str(abi::API_VERSION),
1467        create: create_instance::<P>,
1468        slide_source: slide_source::<P>,
1469    }
1470    .leak_into_prefix()
1471}
1472
1473/// Exports a [`Plugin`] implementation as an eov plugin library.
1474///
1475/// Use it once, at the crate root of a `cdylib` crate.
1476#[macro_export]
1477macro_rules! export_plugin {
1478    ($plugin:ty) => {
1479        #[doc(hidden)]
1480        #[unsafe(no_mangle)]
1481        #[allow(non_upper_case_globals)]
1482        pub static _1as_0lib_1header_0root_bmodule_bloader: $crate::__private::LibHeader = {
1483            extern "C" fn __eov_erased_root_module() -> $crate::__private::RootModuleResult {
1484                fn __eov_root_module() -> $crate::abi::PluginModuleRef {
1485                    $crate::sdk::root_module::<$plugin>()
1486                }
1487                $crate::__private::call_root_module_loader(__eov_root_module)
1488            }
1489            unsafe {
1490                $crate::__private::LibHeader::from_constructor::<$crate::abi::PluginModuleRef>(
1491                    __eov_erased_root_module,
1492                    $crate::__private::CheckTypeLayout::Yes,
1493                )
1494            }
1495        };
1496    };
1497}