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