eov_plugin_api/abi.rs
1//! The binary interface between eov and plugin libraries.
2//!
3//! Plugin authors do not use this module directly: implement
4//! [`crate::sdk::Plugin`] and export it with [`crate::export_plugin!`].
5//!
6//! # Compatibility rules
7//!
8//! The ABI is deliberately small. Almost everything travels as JSON messages
9//! defined in [`crate::protocol`]; only pixel data crosses as binary.
10//!
11//! - abi_stable 0.11's load-time layout check accepts a library whose
12//! prefix type (a module or a `#[sabi_trait]` vtable) has **more** fields
13//! than the host's copy, but rejects one with **fewer** ("too many
14//! fields": a 1.0 library in a host whose copy has one more field).
15//! - The root module ([`PluginModule`]) is an `abi_stable` *prefix type*.
16//! The host loads it with `LibHeader::init_root_module`, which checks the
17//! `eov-plugin-api` major version and the layout of every type reachable
18//! from the module before any plugin code runs. Because of the rule above
19//! it checks every library against the root module's base layout
20//! ([`v1_0::PluginModule`]: the fields plugin API 1.0 was first built
21//! with, which every 1.x module has), and then the fields added since (so
22//! far [`PluginModule::slide_source`]) with the full layout, only when the
23//! library's module has them. A library built before a field was added
24//! therefore loads unchanged, and a newer one loads into an older eov,
25//! without its additions.
26//! - [`PluginFfi`] and [`HostFfi`] are `#[sabi_trait]` objects. Their
27//! vtables are **frozen for 1.x**: by the rule above, a method appended
28//! to one would make every older plugin fail the check. New capabilities
29//! are JSON methods on [`HostFfi::call`] and new
30//! [`crate::protocol::HostEvent`]s, which older peers answer with
31//! `Unsupported` or receive as `Unknown`; pixel data keeps using the
32//! existing binary calls. The same holds for [`SlideSourceFfi`] and
33//! [`SlideFfi`]: new slide features go through
34//! [`SlideFfi::call`], or through new root-module fields checked the same
35//! way.
36//! - [`ABI_VERSION`] is an additional explicit handshake; it only changes
37//! together with the crate's major version.
38//!
39//! # Slide sources
40//!
41//! A plugin can read slide formats eov does not read itself (Philips
42//! iSyntax, Olympus VSI, Leica LIF, remote sources such as DICOMweb or
43//! OMERO). It declares them in its manifest (`[[slide_formats]]`, see
44//! [`crate::manifest::SlideFormatSpec`]), so eov knows the extensions and URI
45//! schemes without running plugin code, and the SDK exports the root
46//! module's [`PluginModule::slide_source`], which hands the host the
47//! instance's [`SlideSourceFfi`]. Opening a slide returns a [`SlideFfi`]
48//! handle: the metadata as JSON ([`crate::protocol::SlideInfo`]), region
49//! reads into a host buffer and associated images.
50//!
51//! Threading: a slide source and its slides are `Send + Sync` and are
52//! called from worker threads (slide openers, render workers, exports,
53//! batch runs), several at once and on the same handle. eov holds none of
54//! its locks while it calls them. A call that panics fails (the SDK turns
55//! the panic into [`FfiErrorKind::Panicked`]) and the plugin is stopped;
56//! one that returns an error fails only that read.
57
58// `#[sabi_trait]` expands to impls inside an anonymous const, which trips this
59// lint on current compilers; the generated code is correct.
60#![allow(non_local_definitions)]
61
62use abi_stable::{
63 StableAbi, declare_root_module_statics,
64 library::RootModule,
65 package_version_strings, sabi_trait,
66 sabi_types::VersionStrings,
67 std_types::{RBox, RResult, RSliceMut, RStr, RString, RVec},
68};
69
70/// Explicit ABI generation, checked by the host in addition to the
71/// `abi_stable` layout check.
72pub const ABI_VERSION: u32 = 1;
73
74/// The version of `eov-plugin-api` this crate is.
75pub const API_VERSION: &str = env!("CARGO_PKG_VERSION");
76
77/// Largest region, in pixels, a single [`HostFfi::read_region`] may request.
78pub const MAX_REGION_PIXELS: u64 = 8192 * 8192;
79
80/// Largest raster, in pixels, a single [`HostFfi::put_raster`] may upload.
81pub const MAX_RASTER_PIXELS: u64 = 4096 * 4096;
82
83/// Largest region, in pixels, the host asks a [`SlideFfi::read_region`]
84/// for at once (larger reads arrive in parts).
85pub const MAX_SLIDE_READ_PIXELS: u64 = 4096 * 4096;
86
87/// The index of [`PluginModule::slide_source`] among the root module's
88/// fields (the first field added after plugin API 1.0).
89pub const SLIDE_SOURCE_FIELD: usize = 3;
90
91// ---------------------------------------------------------------------------
92// Errors
93// ---------------------------------------------------------------------------
94
95/// Classifies an [`FfiError`].
96#[repr(u32)]
97#[derive(StableAbi, Debug, Clone, Copy, PartialEq, Eq)]
98pub enum FfiErrorKind {
99 /// An ordinary failure; the message says what went wrong.
100 Failed = 0,
101 /// The callee panicked. The host quarantines plugins that panic.
102 Panicked = 1,
103 /// The method or event is not supported by this peer (feature detection).
104 Unsupported = 2,
105 /// The arguments could not be decoded or were out of range.
106 InvalidArguments = 3,
107 /// The plugin was disabled or quarantined; its host handle is revoked.
108 Revoked = 4,
109}
110
111/// An error crossing the plugin boundary.
112#[repr(C)]
113#[derive(StableAbi, Debug, Clone, PartialEq, Eq)]
114pub struct FfiError {
115 /// Raw [`FfiErrorKind`] value. Unknown values (from newer peers) must be
116 /// treated as [`FfiErrorKind::Failed`]; see [`FfiError::kind`].
117 pub kind: u32,
118 pub message: RString,
119}
120
121impl FfiError {
122 pub fn new(kind: FfiErrorKind, message: impl Into<String>) -> Self {
123 Self {
124 kind: kind as u32,
125 message: RString::from(message.into()),
126 }
127 }
128
129 pub fn failed(message: impl Into<String>) -> Self {
130 Self::new(FfiErrorKind::Failed, message)
131 }
132
133 /// The error kind; unknown raw values map to [`FfiErrorKind::Failed`].
134 pub fn kind(&self) -> FfiErrorKind {
135 match self.kind {
136 1 => FfiErrorKind::Panicked,
137 2 => FfiErrorKind::Unsupported,
138 3 => FfiErrorKind::InvalidArguments,
139 4 => FfiErrorKind::Revoked,
140 _ => FfiErrorKind::Failed,
141 }
142 }
143}
144
145impl std::fmt::Display for FfiError {
146 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147 f.write_str(self.message.as_str())
148 }
149}
150
151impl std::error::Error for FfiError {}
152
153pub type FfiResult<T> = RResult<T, FfiError>;
154
155// ---------------------------------------------------------------------------
156// Pixel types
157// ---------------------------------------------------------------------------
158
159/// A request for slide pixels.
160#[repr(C)]
161#[derive(StableAbi, Debug, Clone, Copy, PartialEq)]
162pub struct RegionRequest {
163 pub file_id: i64,
164 /// Pyramid level to read from (see `FileInfo::levels`).
165 pub level: u32,
166 /// Top-left corner in **level-0** pixels. May be negative or extend past
167 /// the slide; pixels outside the scanned area are transparent (or
168 /// `background`).
169 pub x: i64,
170 pub y: i64,
171 /// Size in pixels **of `level`**. `width·height` must not exceed
172 /// [`MAX_REGION_PIXELS`].
173 pub width: u32,
174 pub height: u32,
175 /// `0xRRGGBBAA`. With alpha 0 the result keeps transparency (straight,
176 /// non-premultiplied alpha); otherwise every pixel is composited onto this
177 /// colour and the result is opaque.
178 pub background: u32,
179}
180
181/// An RGBA8 image: straight (non-premultiplied) alpha, row-major, no padding.
182#[repr(C)]
183#[derive(StableAbi, Debug, Clone, PartialEq, Eq)]
184pub struct Pixels {
185 pub width: u32,
186 pub height: u32,
187 pub data: RVec<u8>,
188}
189
190impl Pixels {
191 /// Whether `data` holds exactly `width·height·4` bytes.
192 pub fn is_well_formed(&self) -> bool {
193 (self.width as usize)
194 .checked_mul(self.height as usize)
195 .and_then(|n| n.checked_mul(4))
196 == Some(self.data.len())
197 }
198}
199
200/// A raster overlay object (e.g. a heat map) covering a level-0 rectangle.
201#[repr(C)]
202#[derive(StableAbi, Debug, Clone, PartialEq)]
203pub struct RasterUpload {
204 /// A layer previously created with `layer.create`.
205 pub layer_id: RString,
206 /// Replaces an existing object with the same id.
207 pub object_id: RString,
208 /// The level-0 rectangle the raster is stretched over.
209 pub x: f64,
210 pub y: f64,
211 pub width: f64,
212 pub height: f64,
213 /// At most [`MAX_RASTER_PIXELS`].
214 pub pixels: Pixels,
215 /// Bilinear (`true`) or nearest-neighbour (`false`) magnification.
216 pub smooth: bool,
217}
218
219/// The pane a filter is being applied for.
220#[repr(C)]
221#[derive(StableAbi, Debug, Clone, Copy, PartialEq, Default)]
222pub struct FilterView {
223 pub pane: u32,
224 pub file_id: i64,
225 /// Level-0 coordinates of the pane centre.
226 pub center_x: f64,
227 pub center_y: f64,
228 /// Screen (logical) pixels per level-0 pixel.
229 pub zoom: f64,
230 /// Pane size in logical pixels.
231 pub width: f64,
232 pub height: f64,
233 /// Physical pixels of the frame per logical pixel.
234 pub scale_factor: f64,
235 /// Level-0 bounding box of the visible area.
236 pub visible_x: f64,
237 pub visible_y: f64,
238 pub visible_width: f64,
239 pub visible_height: f64,
240 /// Increases with every rendered frame of this pane.
241 pub frame: u64,
242}
243
244/// A rendered frame handed to a CPU filter, to be modified in place.
245///
246/// Pixels are RGBA8 with straight alpha: the slide's pixels, after eov's
247/// stain and tone adjustments, are opaque, and the rest of the pane is
248/// transparent. eov composites the viewport background and sharpens after
249/// the filters, so a filter never sees or changes the background.
250/// Rows are `stride` bytes apart (`stride >= width·4`).
251#[repr(C)]
252#[derive(StableAbi)]
253pub struct FilterFrame<'a> {
254 pub pixels: RSliceMut<'a, u8>,
255 pub width: u32,
256 pub height: u32,
257 pub stride: u32,
258 pub view: FilterView,
259}
260
261// ---------------------------------------------------------------------------
262// Plugin instance (implemented by plugins, called by the host)
263// ---------------------------------------------------------------------------
264
265/// A live plugin instance.
266///
267/// Created by [`PluginModule::create`]. The host calls `handle_event` on its
268/// UI thread with no host locks held, and `apply_filter` on render worker
269/// threads (possibly concurrently for different panes).
270#[sabi_trait]
271pub trait PluginFfi: Send + Sync {
272 /// Handles a JSON-encoded [`crate::protocol::HostEvent`] and returns a
273 /// JSON response (`null` when the event has none).
274 fn handle_event(&self, event_json: RStr<'_>) -> FfiResult<RString>;
275
276 /// Applies the CPU filter `filter_id` to `frame` in place.
277 fn apply_filter(&self, filter_id: RStr<'_>, frame: FilterFrame<'_>) -> FfiResult<()>;
278
279 /// Releases resources. No other method is called afterwards.
280 #[sabi(last_prefix_field)]
281 fn shutdown(&self);
282}
283
284/// An owned plugin instance.
285pub type PluginBox = PluginFfi_TO<'static, RBox<()>>;
286
287// ---------------------------------------------------------------------------
288// Host API (implemented by the host, called by plugins)
289// ---------------------------------------------------------------------------
290
291/// The host services available to one plugin.
292///
293/// Every method may be called from any thread. None of them blocks on the
294/// host's UI thread: queries are answered from published state and UI
295/// mutations are queued and applied in call order.
296#[sabi_trait]
297pub trait HostFfi: Send + Sync {
298 /// Invokes the JSON method `method` (see [`crate::protocol::methods`]).
299 fn call(&self, method: RStr<'_>, args_json: RStr<'_>) -> FfiResult<RString>;
300
301 /// Reads slide pixels on the calling thread through a plugin-private
302 /// slide handle. Never holds host state locks while decoding.
303 fn read_region(&self, request: RegionRequest) -> FfiResult<Pixels>;
304
305 /// Reads an associated image (`"label"`, `"macro"`, `"thumbnail"`, …).
306 fn read_associated_image(&self, file_id: i64, name: RStr<'_>) -> FfiResult<Pixels>;
307
308 /// Adds or replaces a raster overlay object.
309 #[sabi(last_prefix_field)]
310 fn put_raster(&self, raster: RasterUpload) -> FfiResult<()>;
311}
312
313/// An owned host API handle.
314pub type HostBox = HostFfi_TO<'static, RBox<()>>;
315
316// ---------------------------------------------------------------------------
317// Slide sources (implemented by plugins, called by the host)
318// ---------------------------------------------------------------------------
319
320/// A region of one pyramid level, in pixels **of that level** (unlike
321/// [`RegionRequest`], whose corner is in level-0 pixels).
322///
323/// The host only asks for regions inside the level (`x + width` and
324/// `y + height` within the level's size, as [`crate::protocol::SlideInfo`]
325/// gives it) of at most [`MAX_SLIDE_READ_PIXELS`] pixels; it reads areas
326/// past the edges as "no data" itself.
327#[repr(C)]
328#[derive(StableAbi, Debug, Clone, Copy, PartialEq, Eq, Hash)]
329pub struct SlideRegion {
330 /// Index into [`crate::protocol::SlideInfo::levels`].
331 pub level: u32,
332 /// Top-left corner, in pixels of `level`.
333 pub x: u64,
334 pub y: u64,
335 pub width: u32,
336 pub height: u32,
337}
338
339/// The slide formats one plugin instance reads (see the
340/// [module documentation](self#slide-sources-plugin-api-11)).
341///
342/// `Send + Sync`: the host opens slides from worker threads, several at
343/// once, with none of its locks held.
344#[sabi_trait]
345pub trait SlideSourceFfi: Send + Sync {
346 /// Opens a slide. `request_json` is a JSON
347 /// [`crate::protocol::SlideOpenRequest`]: which of the manifest's
348 /// formats matched, and the file path or URI.
349 #[sabi(last_prefix_field)]
350 fn open(&self, request_json: RStr<'_>) -> FfiResult<SlideBox>;
351}
352
353/// An owned slide source.
354pub type SlideSourceBox = SlideSourceFfi_TO<'static, RBox<()>>;
355
356/// One open slide.
357///
358/// `Send + Sync`: render workers read regions concurrently, from several
359/// threads at once on the same handle, with none of the host's locks held.
360/// The host drops the handle (from any thread, possibly after the plugin's
361/// `shutdown`) when the slide is closed everywhere.
362#[sabi_trait]
363pub trait SlideFfi: Send + Sync {
364 /// The slide's metadata as a JSON [`crate::protocol::SlideInfo`].
365 /// Called once, right after opening; the host validates it.
366 fn info(&self) -> FfiResult<RString>;
367
368 /// Writes `region` into `out`: `region.width·region.height·4` bytes of
369 /// RGBA with straight alpha, rows top to bottom, no padding. `out`
370 /// arrives zeroed, i.e. transparent: pixels without image data may be
371 /// left alone (the host shows them as the slide's background).
372 fn read_region(&self, region: SlideRegion, out: RSliceMut<'_, u8>) -> FfiResult<()>;
373
374 /// Decodes the associated image `name` (one listed in
375 /// [`crate::protocol::SlideInfo::associated_images`], at the size listed
376 /// there) as RGBA with straight alpha.
377 fn read_associated_image(&self, name: RStr<'_>) -> FfiResult<Pixels>;
378
379 /// A JSON method for slide features added later (the vtable is frozen); unknown methods answer [`FfiErrorKind::Unsupported`].
380 #[sabi(last_prefix_field)]
381 fn call(&self, method: RStr<'_>, args_json: RStr<'_>) -> FfiResult<RString>;
382}
383
384/// An owned slide handle.
385pub type SlideBox = SlideFfi_TO<'static, RBox<()>>;
386
387// ---------------------------------------------------------------------------
388// Root module
389// ---------------------------------------------------------------------------
390
391/// The root module every plugin library exports (via
392/// [`crate::export_plugin!`]).
393///
394/// Fields after `create` were added in later 1.x versions; a module built
395/// against an older version does not have them (see the
396/// [compatibility rules](self#compatibility-rules)), so their accessors
397/// return `Option`.
398#[repr(C)]
399#[derive(StableAbi)]
400#[sabi(kind(Prefix(prefix_ref = PluginModuleRef)))]
401#[sabi(missing_field(panic))]
402pub struct PluginModule {
403 /// Must equal the host's [`ABI_VERSION`].
404 pub abi_version: u32,
405 /// The `eov-plugin-api` version the plugin was compiled against.
406 pub api_version: RStr<'static>,
407 /// Creates the plugin instance. `init_json` is a JSON
408 /// [`crate::protocol::PluginInit`].
409 #[sabi(last_prefix_field)]
410 pub create: extern "C" fn(host: HostBox, init_json: RStr<'_>) -> FfiResult<PluginBox>,
411 /// The slide source of an instance this module created (missing in
412 /// libraries built before slide sources were added)
413 /// (the formats of the manifest's `[[slide_formats]]`). The host asks
414 /// for it once, after `create`, for plugins that declare formats.
415 #[sabi(missing_field(option))]
416 pub slide_source: extern "C" fn(instance: &PluginBox) -> FfiResult<SlideSourceBox>,
417}
418
419impl RootModule for PluginModuleRef {
420 declare_root_module_statics! {PluginModuleRef}
421 const BASE_NAME: &'static str = "eov_plugin";
422 const NAME: &'static str = "eov plugin";
423 const VERSION_STRINGS: VersionStrings = package_version_strings!();
424}
425
426/// The root module as plugin API 1.0 defined it, frozen: the layout the
427/// host checks every plugin library against first (see the
428/// [compatibility rules](self#compatibility-rules)). Plugins never use it.
429pub mod v1_0 {
430 use super::{FfiResult, HostBox, PluginBox};
431 use abi_stable::{
432 StableAbi, declare_root_module_statics, library::RootModule, package_version_strings,
433 sabi_types::VersionStrings, std_types::RStr,
434 };
435
436 /// [`super::PluginModule`] without the fields added after 1.0. Its
437 /// name, field names and types must never change.
438 #[repr(C)]
439 #[derive(StableAbi)]
440 #[sabi(kind(Prefix(prefix_ref = PluginModuleRef)))]
441 #[sabi(missing_field(panic))]
442 pub struct PluginModule {
443 pub abi_version: u32,
444 pub api_version: RStr<'static>,
445 #[sabi(last_prefix_field)]
446 pub create: extern "C" fn(host: HostBox, init_json: RStr<'_>) -> FfiResult<PluginBox>,
447 }
448
449 impl RootModule for PluginModuleRef {
450 declare_root_module_statics! {PluginModuleRef}
451 const BASE_NAME: &'static str = "eov_plugin";
452 const NAME: &'static str = "eov plugin";
453 const VERSION_STRINGS: VersionStrings = package_version_strings!();
454 }
455}
456
457/// Returns the expected shared-library file name for a plugin id on the
458/// current platform.
459pub fn plugin_library_filename(id: &str) -> String {
460 if cfg!(target_os = "macos") {
461 format!("lib{id}.dylib")
462 } else if cfg!(target_os = "windows") {
463 format!("{id}.dll")
464 } else {
465 format!("lib{id}.so")
466 }
467}
468
469#[cfg(test)]
470mod tests {
471 use super::*;
472
473 #[test]
474 fn export_macro_uses_abi_stables_loader_symbol() {
475 // `export_plugin!` spells the exported static's name literally so that
476 // plugins do not need a direct `abi_stable` dependency.
477 assert_eq!(
478 abi_stable::library::ROOT_MODULE_LOADER_NAME,
479 crate::sdk::ROOT_MODULE_LOADER_SYMBOL
480 );
481 }
482
483 #[test]
484 fn unknown_error_kinds_degrade_to_failed() {
485 let error = FfiError {
486 kind: 99,
487 message: "x".into(),
488 };
489 assert_eq!(error.kind(), FfiErrorKind::Failed);
490 assert_eq!(
491 FfiError::new(FfiErrorKind::Unsupported, "y").kind(),
492 FfiErrorKind::Unsupported
493 );
494 }
495
496 extern "C" fn refuse(_host: HostBox, _init_json: RStr<'_>) -> FfiResult<PluginBox> {
497 abi_stable::std_types::RErr(FfiError::failed("test module"))
498 }
499
500 extern "C" fn no_source(_instance: &PluginBox) -> FfiResult<SlideSourceBox> {
501 abi_stable::std_types::RErr(FfiError::failed("test module"))
502 }
503
504 /// A root module as a plugin built against plugin API 1.0 exports it.
505 fn module_1_0() -> v1_0::PluginModuleRef {
506 use abi_stable::prefix_type::PrefixTypeTrait;
507 v1_0::PluginModule {
508 abi_version: ABI_VERSION,
509 api_version: RStr::from_str("1.0.0"),
510 create: refuse,
511 }
512 .leak_into_prefix()
513 }
514
515 fn module_1_1() -> PluginModuleRef {
516 use abi_stable::prefix_type::PrefixTypeTrait;
517 PluginModule {
518 abi_version: ABI_VERSION,
519 api_version: RStr::from_str(API_VERSION),
520 create: refuse,
521 slide_source: no_source,
522 }
523 .leak_into_prefix()
524 }
525
526 fn has_slide_source<M: abi_stable::prefix_type::PrefixRefTrait>(module: M) -> bool {
527 module
528 .to_prefix_ref()
529 .field_accessibility()
530 .at(SLIDE_SOURCE_FIELD)
531 .is_accessible()
532 }
533
534 #[test]
535 fn hosts_check_plugins_against_the_frozen_1_0_root_module() {
536 use abi_stable::library::LibHeader;
537 // abi_stable rejects a module with fewer fields than the host's
538 // copy of its type ...
539 let old = LibHeader::from_module(module_1_0());
540 let error = old
541 .init_root_module::<PluginModuleRef>()
542 .err()
543 .expect("a 1.0 module fails the 1.1 layout")
544 .to_string();
545 assert!(error.contains("too many fields"), "{error}");
546 // ... so the host checks the 1.0 layout, which every 1.x module
547 // extends, and looks for the newer fields itself.
548 let loaded = old.init_root_module::<v1_0::PluginModuleRef>().unwrap();
549 assert_eq!(loaded.api_version().as_str(), "1.0.0");
550 assert!(!has_slide_source(loaded));
551
552 // A 1.1 module passes both (the first is what a 1.0 eov checks).
553 let new = LibHeader::from_module(module_1_1());
554 let base = new.init_root_module::<v1_0::PluginModuleRef>().unwrap();
555 assert!(has_slide_source(base));
556 let full = new.init_root_module::<PluginModuleRef>().unwrap();
557 assert!(full.slide_source().is_some());
558 }
559
560 #[test]
561 fn pixels_well_formedness() {
562 let ok = Pixels {
563 width: 2,
564 height: 3,
565 data: vec![0; 24].into(),
566 };
567 assert!(ok.is_well_formed());
568 let bad = Pixels {
569 width: 2,
570 height: 3,
571 data: vec![0; 23].into(),
572 };
573 assert!(!bad.is_well_formed());
574 }
575}