Skip to main content

eov_plugin_api/
protocol.rs

1//! The message protocol spoken between the eov host and plugins.
2//!
3//! The binary ABI ([`crate::abi`]) is deliberately tiny: almost every
4//! interaction is a JSON message whose schema is defined here as serde types
5//! shared by both sides. This keeps the ABI stable while the protocol grows:
6//!
7//! - new optional fields are added with `#[serde(default)]`, so older peers
8//!   ignore them and newer peers tolerate their absence;
9//! - new event variants deserialize as [`HostEvent::Unknown`] in older plugins;
10//! - new host methods are answered with an `unknown method` error by older
11//!   hosts, so plugins can feature-detect them.
12//!
13//! # Coordinates
14//!
15//! All image coordinates are **level-0 pixels** of the slide (`x` to the right,
16//! `y` down, origin at the top-left of the level-0 canvas as OpenSlide reports
17//! it). Screen coordinates are logical pixels relative to the top-left corner of
18//! the pane. `zoom` is screen pixels per level-0 pixel.
19//!
20//! # Threading contract
21//!
22//! - [`HostEvent`]s are delivered on the host's UI thread, one at a time, with
23//!   no host locks held. Handlers must return quickly (aim for < 5 ms); long
24//!   work belongs on a plugin-owned thread.
25//! - Every host method may be called from any thread at any time. Calls never
26//!   block on the UI thread: queries answer from a recent published snapshot
27//!   and mutations are queued and applied on the UI thread in call order.
28//! - CPU filters may run on any render worker thread, concurrently for
29//!   different panes.
30
31use serde::{Deserialize, Serialize};
32use serde_json::{Map, Value};
33use std::collections::BTreeMap;
34
35/// Host-assigned identifier of an open slide, stable for the session.
36pub type FileId = i64;
37
38/// Host-assigned, stable identifier of a viewer pane (not its position).
39pub type PaneId = u32;
40
41// ---------------------------------------------------------------------------
42// Initialization
43// ---------------------------------------------------------------------------
44
45/// Information handed to a plugin when it is created.
46#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
47pub struct PluginInit {
48    /// The plugin id from its manifest.
49    pub plugin_id: String,
50    /// The plugin version from its manifest.
51    pub plugin_version: String,
52    /// Host application name (`"eov"`).
53    pub host_name: String,
54    /// Host application version.
55    pub host_version: String,
56    /// The `eov-plugin-api` version the host was built with.
57    pub api_version: String,
58    /// Root of the extracted plugin package (read-only).
59    pub plugin_root: String,
60    /// Durable, writable per-plugin data directory (created by the host).
61    pub data_dir: String,
62    /// Disposable, writable per-plugin cache directory (created by the host).
63    pub cache_dir: String,
64    /// Persisted per-plugin settings (see `settings.*` methods).
65    #[serde(default)]
66    pub settings: Map<String, Value>,
67    /// Where eov before 1.0 kept per-user files (e.g. `~/.config/eov`), for
68    /// migrating data a plugin stored there. Read it; don't write it.
69    #[serde(default)]
70    pub legacy_config_dir: Option<String>,
71    /// The plugin runs without a window, for `eov batch` (see
72    /// [`methods::BATCH_REGISTER`]): toolbar buttons, tools, layers and
73    /// surfaces are accepted but not shown, so skip expensive UI set-up.
74    #[serde(default)]
75    pub headless: bool,
76}
77
78// ---------------------------------------------------------------------------
79// Shared value types
80// ---------------------------------------------------------------------------
81
82/// An axis-aligned rectangle in level-0 pixels.
83#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
84pub struct Rect {
85    pub x: f64,
86    pub y: f64,
87    pub width: f64,
88    pub height: f64,
89}
90
91/// One pyramid level of a slide.
92///
93/// `downsample` is the level-0 size divided by this level's size as the
94/// format reports it. It is **not** always a power of two (Aperio pyramids
95/// commonly go 1, 4, 16).
96#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
97pub struct LevelInfo {
98    pub level: u32,
99    pub width: u64,
100    pub height: u64,
101    pub downsample: f64,
102}
103
104/// Metadata of an open slide.
105#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
106pub struct FileInfo {
107    pub file_id: FileId,
108    /// Path as text (lossy for non-UTF-8 paths; read pixels through the host).
109    pub path: String,
110    pub filename: String,
111    /// Level-0 dimensions.
112    pub width: u64,
113    pub height: u64,
114    #[serde(default)]
115    pub levels: Vec<LevelInfo>,
116    #[serde(default)]
117    pub mpp_x: Option<f64>,
118    #[serde(default)]
119    pub mpp_y: Option<f64>,
120    #[serde(default)]
121    pub objective_power: Option<f64>,
122    #[serde(default)]
123    pub vendor: Option<String>,
124    #[serde(default)]
125    pub scan_date: Option<String>,
126    /// Bounding box of the scanned area (`openslide.bounds-*`), if reported.
127    #[serde(default)]
128    pub bounds: Option<Rect>,
129    /// A stable identity of the slide content (e.g. derived from
130    /// `openslide.quickhash-1`), suitable as a database key.
131    #[serde(default)]
132    pub identity: Option<String>,
133    /// Names of associated images (`label`, `macro`, `thumbnail`, …).
134    #[serde(default)]
135    pub associated_images: Vec<String>,
136    /// The slide has an ICC colour profile. eov converts its colours to
137    /// sRGB for display and export (unless the user turns that off, see
138    /// [`DisplayAdjustments::color_managed`]); region reads and filter
139    /// frames always carry the slide's own, unconverted colours.
140    #[serde(default)]
141    pub has_icc_profile: bool,
142    /// Stain label parsed from slide metadata (e.g. `"H&E"`), if any.
143    #[serde(default)]
144    pub stain: Option<String>,
145    /// Channel names of a multichannel slide (fluorescence or multiplexed
146    /// immunofluorescence OME-TIFF), in file order; empty for RGB slides.
147    ///
148    /// Pixels from `read_region` are always RGBA: the visible channels
149    /// composited with the colours, windows and gammas the user set in the
150    /// Channels panel, the same image the viewer shows. Raw channel values
151    /// are not available through plugin API 1.x.
152    #[serde(default)]
153    pub channel_names: Vec<String>,
154}
155
156/// The visible state of a pane showing a slide.
157#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
158pub struct ViewInfo {
159    pub pane: PaneId,
160    pub file_id: FileId,
161    /// Level-0 coordinates of the pane centre.
162    pub center_x: f64,
163    pub center_y: f64,
164    /// Screen (logical) pixels per level-0 pixel.
165    pub zoom: f64,
166    /// Pane size in logical pixels.
167    pub width: f64,
168    pub height: f64,
169    /// Physical pixels per logical pixel of the window.
170    #[serde(default = "default_scale_factor")]
171    pub scale_factor: f64,
172    /// Clockwise view rotation in degrees, `0 <= rotation_deg < 360`: any
173    /// angle (eov keeps it to a millionth of a degree; quarter turns are
174    /// exactly 90, 180 and 270). Map points with
175    /// [`image_to_screen`](Self::image_to_screen) and
176    /// [`screen_to_image`](Self::screen_to_image); `visible` is the turned
177    /// area's bounding box.
178    #[serde(default)]
179    pub rotation_deg: f64,
180    /// The view is mirrored left to right, after the rotation.
181    #[serde(default)]
182    pub flipped: bool,
183    /// Level-0 bounding box of the visible area.
184    pub visible: Rect,
185}
186
187fn default_scale_factor() -> f64 {
188    1.0
189}
190
191// `Default` is written out here, as for `MenuItem` and `ToolbarButtonSpec`,
192// so that it is what a message leaving the optional fields out deserializes
193// to: a derived one sets `false`/`0` where the wire format defaults to
194// `true`/`1`, and plugins build their values with `..Default::default()`.
195impl Default for ViewInfo {
196    fn default() -> Self {
197        Self {
198            pane: Default::default(),
199            file_id: Default::default(),
200            center_x: 0.0,
201            center_y: 0.0,
202            zoom: 0.0,
203            width: 0.0,
204            height: 0.0,
205            scale_factor: default_scale_factor(),
206            rotation_deg: 0.0,
207            flipped: false,
208            visible: Rect::default(),
209        }
210    }
211}
212
213impl ViewInfo {
214    /// An image-space direction as it points on the pane (rotation, then
215    /// mirror).
216    fn turn(&self, x: f64, y: f64) -> (f64, f64) {
217        let (sin, cos) = self.rotation_deg.to_radians().sin_cos();
218        let (tx, ty) = (x * cos - y * sin, x * sin + y * cos);
219        if self.flipped { (-tx, ty) } else { (tx, ty) }
220    }
221
222    /// Logical pane position of level-0 point `(x, y)`, accounting for the
223    /// view's rotation and mirror.
224    pub fn image_to_screen(&self, x: f64, y: f64) -> (f64, f64) {
225        let (dx, dy) = self.turn(x - self.center_x, y - self.center_y);
226        (
227            self.width / 2.0 + dx * self.zoom,
228            self.height / 2.0 + dy * self.zoom,
229        )
230    }
231
232    /// The level-0 point at logical pane position `(x, y)`.
233    pub fn screen_to_image(&self, x: f64, y: f64) -> (f64, f64) {
234        let zoom = if self.zoom > 0.0 { self.zoom } else { 1.0 };
235        let (mut dx, dy) = (
236            (x - self.width / 2.0) / zoom,
237            (y - self.height / 2.0) / zoom,
238        );
239        if self.flipped {
240            dx = -dx;
241        }
242        let (sin, cos) = (-self.rotation_deg).to_radians().sin_cos();
243        (
244            self.center_x + dx * cos - dy * sin,
245            self.center_y + dx * sin + dy * cos,
246        )
247    }
248}
249
250/// One pane in display order.
251#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
252pub struct PaneInfo {
253    pub pane: PaneId,
254    /// Position from the left, starting at 0.
255    pub index: u32,
256    #[serde(default)]
257    pub file_id: Option<FileId>,
258    #[serde(default)]
259    pub view: Option<ViewInfo>,
260}
261
262/// Reference to a tool: the owning plugin (`None` for host tools) and its id.
263#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
264pub struct ToolRef {
265    #[serde(default)]
266    pub plugin_id: Option<String>,
267    pub tool_id: String,
268}
269
270/// A consistent, recent view of the host state.
271#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
272pub struct HostSnapshot {
273    pub host_version: String,
274    /// Whether an eov window has keyboard focus.
275    #[serde(default)]
276    pub window_focused: bool,
277    #[serde(default)]
278    pub render_backend: String,
279    #[serde(default)]
280    pub filtering_mode: String,
281    #[serde(default)]
282    pub focused_pane: Option<PaneId>,
283    #[serde(default)]
284    pub panes: Vec<PaneInfo>,
285    #[serde(default)]
286    pub files: Vec<FileInfo>,
287    #[serde(default)]
288    pub active_tool: Option<ToolRef>,
289}
290
291impl HostSnapshot {
292    /// The view of the focused pane, if it shows a slide.
293    pub fn focused_view(&self) -> Option<&ViewInfo> {
294        let pane = self.focused_pane?;
295        self.panes.iter().find(|p| p.pane == pane)?.view.as_ref()
296    }
297
298    /// Metadata of an open file.
299    pub fn file(&self, file_id: FileId) -> Option<&FileInfo> {
300        self.files.iter().find(|f| f.file_id == file_id)
301    }
302}
303
304/// Keyboard modifiers held during an input event.
305#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
306pub struct Modifiers {
307    #[serde(default)]
308    pub shift: bool,
309    /// The physical Control key.
310    #[serde(default)]
311    pub control: bool,
312    #[serde(default)]
313    pub alt: bool,
314    /// Command (macOS) / Windows / Super key.
315    #[serde(default)]
316    pub meta: bool,
317    /// The platform's command modifier: ⌘ on macOS, Control elsewhere.
318    #[serde(default)]
319    pub primary: bool,
320}
321
322#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
323#[serde(rename_all = "snake_case")]
324pub enum PointerButton {
325    #[default]
326    None,
327    Left,
328    Right,
329    Middle,
330}
331
332#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
333#[serde(rename_all = "snake_case")]
334pub enum PointerKind {
335    Down,
336    Move,
337    Up,
338    /// Second press of a double click (delivered after the matching `Down`).
339    DoubleClick,
340    Wheel,
341    /// The pointer left the pane.
342    Leave,
343}
344
345/// A pointer event for a plugin-owned custom tool.
346#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
347pub struct PointerEvent {
348    pub kind: PointerKind,
349    #[serde(default)]
350    pub button: PointerButton,
351    pub image_x: f64,
352    pub image_y: f64,
353    pub screen_x: f64,
354    pub screen_y: f64,
355    #[serde(default)]
356    pub modifiers: Modifiers,
357    /// Wheel delta in logical pixels (positive = away from the user).
358    #[serde(default)]
359    pub wheel_delta: f64,
360}
361
362/// A geometric shape in level-0 pixel coordinates.
363#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
364#[serde(tag = "kind", rename_all = "snake_case")]
365pub enum Shape {
366    Point {
367        x: f64,
368        y: f64,
369    },
370    Polyline {
371        points: Vec<[f64; 2]>,
372    },
373    Polygon {
374        exterior: Vec<[f64; 2]>,
375        #[serde(default)]
376        holes: Vec<Vec<[f64; 2]>>,
377    },
378    Rectangle {
379        x: f64,
380        y: f64,
381        width: f64,
382        height: f64,
383    },
384    Ellipse {
385        cx: f64,
386        cy: f64,
387        rx: f64,
388        ry: f64,
389    },
390    /// Text anchored at its top-left corner; drawn at a constant screen size
391    /// (`Style::font_size`, `Style::text_color`).
392    Text {
393        x: f64,
394        y: f64,
395        text: String,
396    },
397}
398
399impl Shape {
400    /// Whether every coordinate is finite and the shape has enough vertices
401    /// (polylines ≥ 2, polygon rings ≥ 3) and non-negative extents.
402    pub fn is_valid(&self) -> bool {
403        let finite = |p: &[f64; 2]| p[0].is_finite() && p[1].is_finite();
404        match self {
405            Shape::Point { x, y } | Shape::Text { x, y, .. } => x.is_finite() && y.is_finite(),
406            Shape::Polyline { points } => points.len() >= 2 && points.iter().all(finite),
407            Shape::Polygon { exterior, holes } => {
408                exterior.len() >= 3
409                    && exterior.iter().all(finite)
410                    && holes
411                        .iter()
412                        .all(|ring| ring.len() >= 3 && ring.iter().all(finite))
413            }
414            Shape::Rectangle {
415                x,
416                y,
417                width,
418                height,
419            } => {
420                [x, y, width, height].iter().all(|v| v.is_finite())
421                    && *width >= 0.0
422                    && *height >= 0.0
423            }
424            Shape::Ellipse { cx, cy, rx, ry } => {
425                [cx, cy, rx, ry].iter().all(|v| v.is_finite()) && *rx >= 0.0 && *ry >= 0.0
426            }
427        }
428    }
429
430    /// Level-0 bounding box. Text has a zero-size box at its anchor.
431    pub fn bounds(&self) -> Rect {
432        fn of_points<'a>(points: impl Iterator<Item = &'a [f64; 2]>) -> Rect {
433            let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
434            for p in points {
435                x0 = x0.min(p[0]);
436                y0 = y0.min(p[1]);
437                x1 = x1.max(p[0]);
438                y1 = y1.max(p[1]);
439            }
440            if x0 > x1 {
441                return Rect::default();
442            }
443            Rect {
444                x: x0,
445                y: y0,
446                width: x1 - x0,
447                height: y1 - y0,
448            }
449        }
450        match self {
451            Shape::Point { x, y } | Shape::Text { x, y, .. } => Rect {
452                x: *x,
453                y: *y,
454                width: 0.0,
455                height: 0.0,
456            },
457            Shape::Polyline { points } => of_points(points.iter()),
458            Shape::Polygon { exterior, .. } => of_points(exterior.iter()),
459            Shape::Rectangle {
460                x,
461                y,
462                width,
463                height,
464            } => Rect {
465                x: *x,
466                y: *y,
467                width: *width,
468                height: *height,
469            },
470            Shape::Ellipse { cx, cy, rx, ry } => Rect {
471                x: cx - rx,
472                y: cy - ry,
473                width: rx * 2.0,
474                height: ry * 2.0,
475            },
476        }
477    }
478}
479
480/// Identifies an overlay object: a plugin-scoped layer id plus an object id.
481#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
482pub struct ObjectRef {
483    pub layer_id: String,
484    pub object_id: String,
485}
486
487/// A vector object in an overlay layer.
488#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
489pub struct OverlayObject {
490    /// Unique within the layer; upserting an existing id replaces it.
491    pub object_id: String,
492    pub shape: Shape,
493    /// Overrides the layer style for this object.
494    #[serde(default)]
495    pub style: Option<Style>,
496    /// Text drawn next to the object (constant screen size).
497    #[serde(default)]
498    pub label: Option<String>,
499    /// Shown when the pointer rests on the object.
500    #[serde(default)]
501    pub tooltip: Option<String>,
502    /// Overrides the layer's `editable` flag for this object.
503    #[serde(default)]
504    pub editable: Option<bool>,
505}
506
507impl OverlayObject {
508    pub fn new(object_id: impl Into<String>, shape: Shape) -> Self {
509        Self {
510            object_id: object_id.into(),
511            shape,
512            style: None,
513            label: None,
514            tooltip: None,
515            editable: None,
516        }
517    }
518
519    pub fn with_style(mut self, style: Style) -> Self {
520        self.style = Some(style);
521        self
522    }
523
524    pub fn with_label(mut self, label: impl Into<String>) -> Self {
525        self.label = Some(label.into());
526        self
527    }
528
529    pub fn with_tooltip(mut self, tooltip: impl Into<String>) -> Self {
530        self.tooltip = Some(tooltip.into());
531        self
532    }
533
534    pub fn with_editable(mut self, editable: bool) -> Self {
535        self.editable = Some(editable);
536        self
537    }
538}
539
540/// A measurement made with the host's measurement tools.
541#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
542pub struct MeasurementInfo {
543    pub measurement_id: String,
544    pub file_id: FileId,
545    pub shape: Shape,
546    /// Length (lines/polylines) or perimeter (closed shapes) in µm, when the
547    /// slide is calibrated.
548    #[serde(default)]
549    pub length_um: Option<f64>,
550    /// Area in µm² for closed shapes, when calibrated.
551    #[serde(default)]
552    pub area_um2: Option<f64>,
553    /// Angle in degrees for angle measurements.
554    #[serde(default)]
555    pub angle_deg: Option<f64>,
556}
557
558/// An entry of a menu (context menu, HUD drop-down). Enabled unless
559/// `enabled` says otherwise, also when built with `..Default::default()`.
560#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
561pub struct MenuItem {
562    pub item_id: String,
563    pub label: String,
564    /// Built-in icon name (`"copy"`, `"export"`, `"delete"`, `"point"`,
565    /// `"measure"`, `"plugin"`, `"open"`) or empty; other names show none.
566    #[serde(default)]
567    pub icon: String,
568    #[serde(default = "default_true")]
569    pub enabled: bool,
570    /// Draw a check mark (for toggles / radio groups).
571    #[serde(default)]
572    pub checked: Option<bool>,
573    /// Display-only shortcut text (e.g. `"Del"`).
574    #[serde(default)]
575    pub shortcut: String,
576    #[serde(default)]
577    pub separator_after: bool,
578}
579
580fn default_true() -> bool {
581    true
582}
583
584impl Default for MenuItem {
585    fn default() -> Self {
586        Self {
587            item_id: String::new(),
588            label: String::new(),
589            icon: String::new(),
590            enabled: default_true(),
591            checked: None,
592            shortcut: String::new(),
593            separator_after: false,
594        }
595    }
596}
597
598/// The name of a key as [`Hotkey::key`] and [`ToolSpec::keys`] write it,
599/// from the raw text of [`HostEvent::Key`]: a character in lower case
600/// (`"a"`, `"+"`) or a named key (`"Escape"`, `"Enter"`, `"Tab"`,
601/// `"Backspace"`, `"Delete"`, `"Space"`, `"ArrowLeft"`, `"F2"`, `"Home"`,
602/// `"PageUp"`, …).
603pub fn key_name(text: &str) -> String {
604    let mut chars = text.chars();
605    let (Some(c), None) = (chars.next(), chars.next()) else {
606        return text.to_lowercase();
607    };
608    match c {
609        '\u{8}' => "Backspace".into(),
610        '\t' => "Tab".into(),
611        '\n' | '\r' => "Enter".into(),
612        '\u{1b}' => "Escape".into(),
613        '\u{7f}' => "Delete".into(),
614        ' ' => "Space".into(),
615        '\u{F700}' => "ArrowUp".into(),
616        '\u{F701}' => "ArrowDown".into(),
617        '\u{F702}' => "ArrowLeft".into(),
618        '\u{F703}' => "ArrowRight".into(),
619        '\u{F704}'..='\u{F71B}' => format!("F{}", c as u32 - 0xF704 + 1),
620        '\u{F729}' => "Home".into(),
621        '\u{F72B}' => "End".into(),
622        '\u{F72C}' => "PageUp".into(),
623        '\u{F72D}' => "PageDown".into(),
624        c => c.to_lowercase().collect(),
625    }
626}
627
628/// A hotkey binding. `key` is a single character (case-insensitive) or a
629/// named key such as `"F2"`, `"Delete"`, `"Escape"` (see [`key_name`]).
630#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
631pub struct Hotkey {
632    pub key: String,
633    #[serde(default)]
634    pub modifiers: Modifiers,
635    /// Hold-to-use: the tool is active only while the key is held.
636    #[serde(default)]
637    pub momentary: bool,
638}
639
640/// A plugin key binding (see [`methods::HOTKEY_REGISTER`]).
641#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
642pub struct HotkeySpec {
643    pub hotkey_id: String,
644    pub hotkey: Hotkey,
645    /// What the key does, for listings of key bindings.
646    #[serde(default)]
647    pub description: String,
648}
649
650#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
651#[serde(rename_all = "snake_case")]
652pub enum LogLevel {
653    Trace,
654    Debug,
655    #[default]
656    Info,
657    Warn,
658    Error,
659}
660
661// ---------------------------------------------------------------------------
662// Overlay styles and layers
663// ---------------------------------------------------------------------------
664
665/// An RGBA colour, each channel 0–255.
666#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
667pub struct Rgba(pub u8, pub u8, pub u8, pub u8);
668
669impl Rgba {
670    pub const TRANSPARENT: Self = Self(0, 0, 0, 0);
671
672    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
673        Self(r, g, b, 255)
674    }
675
676    pub const fn with_alpha(self, alpha: u8) -> Self {
677        Self(self.0, self.1, self.2, alpha)
678    }
679
680    /// Packs into `0xRRGGBBAA`.
681    pub const fn to_u32(self) -> u32 {
682        ((self.0 as u32) << 24) | ((self.1 as u32) << 16) | ((self.2 as u32) << 8) | self.3 as u32
683    }
684
685    /// Unpacks `0xRRGGBBAA`.
686    pub const fn from_u32(value: u32) -> Self {
687        Self(
688            (value >> 24) as u8,
689            (value >> 16) as u8,
690            (value >> 8) as u8,
691            value as u8,
692        )
693    }
694
695    /// Parses `#RRGGBB` or `#RRGGBBAA`.
696    pub fn from_hex(text: &str) -> Option<Self> {
697        let hex = text.strip_prefix('#')?;
698        if !hex.chars().all(|c| c.is_ascii_hexdigit()) {
699            return None;
700        }
701        let byte = |i: usize| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok();
702        match hex.len() {
703            6 => Some(Self(byte(0)?, byte(2)?, byte(4)?, 255)),
704            8 => Some(Self(byte(0)?, byte(2)?, byte(4)?, byte(6)?)),
705            _ => None,
706        }
707    }
708
709    pub fn to_hex(self) -> String {
710        if self.3 == 255 {
711            format!("#{:02X}{:02X}{:02X}", self.0, self.1, self.2)
712        } else {
713            format!("#{:02X}{:02X}{:02X}{:02X}", self.0, self.1, self.2, self.3)
714        }
715    }
716}
717
718#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
719#[serde(rename_all = "snake_case")]
720pub enum Dash {
721    #[default]
722    Solid,
723    Dashed,
724    Dotted,
725}
726
727/// The unit an object's stroke width or point size is expressed in.
728#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
729#[serde(rename_all = "snake_case")]
730pub enum SizeUnit {
731    /// Logical screen pixels (constant on screen at every zoom).
732    #[default]
733    Screen,
734    /// Micrometres on the slide (scales with zoom; needs MPP).
735    Micrometre,
736    /// Level-0 pixels (scales with zoom).
737    Image,
738}
739
740/// Visual style of overlay objects.
741#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
742pub struct Style {
743    #[serde(default)]
744    pub fill: Rgba,
745    #[serde(default = "default_stroke")]
746    pub stroke: Rgba,
747    #[serde(default = "default_stroke_width")]
748    pub stroke_width: f32,
749    #[serde(default)]
750    pub dash: Dash,
751    /// Radius of point markers.
752    #[serde(default = "default_point_radius")]
753    pub point_radius: f32,
754    /// Unit of `stroke_width` and `point_radius`.
755    #[serde(default)]
756    pub size_unit: SizeUnit,
757    /// Text colour for labels and text objects.
758    #[serde(default = "default_text_color")]
759    pub text_color: Rgba,
760    #[serde(default = "default_font_size")]
761    pub font_size: f32,
762}
763
764fn default_stroke() -> Rgba {
765    Rgba::rgb(0x2E, 0xCC, 0x71)
766}
767fn default_stroke_width() -> f32 {
768    1.5
769}
770fn default_point_radius() -> f32 {
771    5.0
772}
773fn default_text_color() -> Rgba {
774    Rgba::rgb(255, 255, 255)
775}
776fn default_font_size() -> f32 {
777    12.0
778}
779
780impl Default for Style {
781    fn default() -> Self {
782        Self {
783            fill: Rgba::TRANSPARENT,
784            stroke: default_stroke(),
785            stroke_width: default_stroke_width(),
786            dash: Dash::Solid,
787            point_radius: default_point_radius(),
788            size_unit: SizeUnit::Screen,
789            text_color: default_text_color(),
790            font_size: default_font_size(),
791        }
792    }
793}
794
795/// Declares an overlay layer. Layers belong to one open file and are drawn
796/// only in panes showing it; they are discarded when the file closes.
797#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
798pub struct LayerSpec {
799    /// Plugin-scoped layer id. Ids are unique per plugin across all open
800    /// slides, so include the file id when a layer exists for each slide
801    /// (e.g. `format!("cells-{file_id}")`).
802    pub layer_id: String,
803    pub file_id: FileId,
804    #[serde(default)]
805    pub name: String,
806    /// Draw order; higher is on top. Host layers use the range -100..=100.
807    #[serde(default)]
808    pub z: i32,
809    #[serde(default = "default_true")]
810    pub visible: bool,
811    /// 0.0–1.0, applied to the whole layer.
812    #[serde(default = "default_opacity")]
813    pub opacity: f32,
814    /// Objects can be hovered and clicked (`ObjectClicked`, `ObjectHovered`).
815    #[serde(default)]
816    pub interactive: bool,
817    /// Objects flagged editable can be reshaped with the host's editing
818    /// gestures (`ObjectEdited`).
819    #[serde(default)]
820    pub editable: bool,
821    #[serde(default)]
822    pub style: Style,
823    /// Override used for selected objects (default: a highlight of `style`).
824    #[serde(default)]
825    pub selected_style: Option<Style>,
826    /// Override used for the hovered object.
827    #[serde(default)]
828    pub hover_style: Option<Style>,
829    /// Hide the layer below this zoom (screen px per level-0 px).
830    #[serde(default)]
831    pub min_zoom: Option<f64>,
832}
833
834fn default_opacity() -> f32 {
835    1.0
836}
837
838impl LayerSpec {
839    /// A visible, non-interactive layer with the default style.
840    pub fn new(layer_id: impl Into<String>, file_id: FileId) -> Self {
841        Self {
842            layer_id: layer_id.into(),
843            file_id,
844            name: String::new(),
845            z: 0,
846            visible: true,
847            opacity: 1.0,
848            interactive: false,
849            editable: false,
850            style: Style::default(),
851            selected_style: None,
852            hover_style: None,
853            min_zoom: None,
854        }
855    }
856
857    pub fn named(mut self, name: impl Into<String>) -> Self {
858        self.name = name.into();
859        self
860    }
861
862    pub fn with_style(mut self, style: Style) -> Self {
863        self.style = style;
864        self
865    }
866
867    pub fn interactive(mut self, interactive: bool) -> Self {
868        self.interactive = interactive;
869        self
870    }
871
872    pub fn editable(mut self, editable: bool) -> Self {
873        self.editable = editable;
874        self
875    }
876
877    pub fn at_z(mut self, z: i32) -> Self {
878        self.z = z;
879        self
880    }
881}
882
883/// Partial update of a layer; `None` leaves a field unchanged.
884#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
885pub struct LayerUpdate {
886    pub layer_id: String,
887    #[serde(default)]
888    pub name: Option<String>,
889    #[serde(default)]
890    pub z: Option<i32>,
891    #[serde(default)]
892    pub visible: Option<bool>,
893    #[serde(default)]
894    pub opacity: Option<f32>,
895    #[serde(default)]
896    pub interactive: Option<bool>,
897    #[serde(default)]
898    pub editable: Option<bool>,
899    #[serde(default)]
900    pub style: Option<Style>,
901    #[serde(default)]
902    pub selected_style: Option<Style>,
903    #[serde(default)]
904    pub hover_style: Option<Style>,
905}
906
907// ---------------------------------------------------------------------------
908// UI contributions
909// ---------------------------------------------------------------------------
910
911/// A button in the main window toolbar. Enabled unless `enabled` says
912/// otherwise, also when built with `..Default::default()`.
913#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
914pub struct ToolbarButtonSpec {
915    pub button_id: String,
916    pub tooltip: String,
917    /// Inline SVG.
918    pub icon_svg: String,
919    #[serde(default)]
920    pub toggled_icon_svg: Option<String>,
921    /// Render as active/pressed.
922    #[serde(default)]
923    pub active: bool,
924    #[serde(default = "default_true")]
925    pub enabled: bool,
926    /// Optional hotkey that clicks the button.
927    #[serde(default)]
928    pub hotkey: Option<Hotkey>,
929    /// Ordering among this plugin's buttons.
930    #[serde(default)]
931    pub order: i32,
932}
933
934impl Default for ToolbarButtonSpec {
935    fn default() -> Self {
936        Self {
937            button_id: String::new(),
938            tooltip: String::new(),
939            icon_svg: String::new(),
940            toggled_icon_svg: None,
941            active: false,
942            enabled: default_true(),
943            hotkey: None,
944            order: 0,
945        }
946    }
947}
948
949/// Partial update of a toolbar or HUD button.
950#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
951pub struct ButtonUpdate {
952    pub button_id: String,
953    /// Restrict the update to one pane (HUD buttons only).
954    #[serde(default)]
955    pub pane: Option<PaneId>,
956    #[serde(default)]
957    pub active: Option<bool>,
958    #[serde(default)]
959    pub enabled: Option<bool>,
960    #[serde(default)]
961    pub tooltip: Option<String>,
962    #[serde(default)]
963    pub icon_svg: Option<String>,
964    #[serde(default)]
965    pub menu: Option<Vec<MenuItem>>,
966}
967
968/// A button in every viewport's HUD toolbar. When `menu` is non-empty the
969/// button opens a drop-down and clicks report the chosen `item_id`.
970#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
971pub struct HudButtonSpec {
972    pub button_id: String,
973    pub tooltip: String,
974    pub icon_svg: String,
975    #[serde(default)]
976    pub toggled_icon_svg: Option<String>,
977    #[serde(default)]
978    pub active: bool,
979    #[serde(default)]
980    pub menu: Vec<MenuItem>,
981    #[serde(default)]
982    pub order: i32,
983}
984
985/// What the host does while a tool is active.
986#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
987#[serde(rename_all = "snake_case")]
988pub enum ToolKind {
989    /// Click places a point → `ShapeDrawn(Point)`.
990    Point,
991    /// Click adds vertices, double-click/Enter finishes → `Polyline`.
992    Polyline,
993    /// Click adds vertices; clicking the first vertex, double-click or Enter
994    /// closes → `Polygon`.
995    Polygon,
996    /// Drag a rectangle → `Rectangle`.
997    Rectangle,
998    /// Drag an ellipse → `Ellipse`.
999    Ellipse,
1000    /// Drag a free-hand outline (simplified) → `Polygon`.
1001    Freehand,
1002    /// No host gestures: the plugin receives raw `Pointer`/`Key` events.
1003    Custom,
1004    /// No drawing; clicks select objects and enable host editing gestures
1005    /// on the plugin's editable layers.
1006    Select,
1007}
1008
1009#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1010#[serde(rename_all = "snake_case")]
1011pub enum Cursor {
1012    #[default]
1013    Default,
1014    Crosshair,
1015    Pointer,
1016    Move,
1017    Text,
1018    NotAllowed,
1019}
1020
1021/// A tool contributed by a plugin. It appears in the toolbar's tool group.
1022#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1023pub struct ToolSpec {
1024    pub tool_id: String,
1025    pub label: String,
1026    pub icon_svg: String,
1027    pub kind: ToolKind,
1028    #[serde(default)]
1029    pub hotkey: Option<Hotkey>,
1030    #[serde(default)]
1031    pub cursor: Cursor,
1032    /// Layers (of this plugin) whose editable objects may be reshaped while
1033    /// the tool is active. Empty = all of the plugin's editable layers.
1034    #[serde(default)]
1035    pub edit_layers: Vec<String>,
1036    /// Style of the in-progress shape preview.
1037    #[serde(default)]
1038    pub preview_style: Option<Style>,
1039    /// Douglas–Peucker tolerance (screen px) for `Freehand`.
1040    #[serde(default = "default_freehand_tolerance")]
1041    pub freehand_tolerance_px: f32,
1042    #[serde(default)]
1043    pub order: i32,
1044    /// For a `Custom` tool: the keys it handles, by [`key_name`]
1045    /// (case-insensitive). Other keys keep working as they do without the
1046    /// tool (eov's shortcuts, other tools' keys, plugin hotkeys; Escape
1047    /// leaves the tool). Unset: the tool gets every key but Tab and
1048    /// Ctrl/⌘ shortcuts.
1049    #[serde(default)]
1050    pub keys: Option<Vec<String>>,
1051}
1052
1053fn default_freehand_tolerance() -> f32 {
1054    1.5
1055}
1056
1057impl ToolSpec {
1058    pub fn new(
1059        tool_id: impl Into<String>,
1060        label: impl Into<String>,
1061        icon_svg: impl Into<String>,
1062        kind: ToolKind,
1063    ) -> Self {
1064        Self {
1065            tool_id: tool_id.into(),
1066            label: label.into(),
1067            icon_svg: icon_svg.into(),
1068            kind,
1069            hotkey: None,
1070            cursor: Cursor::Crosshair,
1071            edit_layers: Vec::new(),
1072            preview_style: None,
1073            freehand_tolerance_px: default_freehand_tolerance(),
1074            order: 0,
1075            keys: None,
1076        }
1077    }
1078
1079    pub fn with_hotkey(mut self, hotkey: Hotkey) -> Self {
1080        self.hotkey = Some(hotkey);
1081        self
1082    }
1083}
1084
1085#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1086#[serde(rename_all = "snake_case")]
1087pub enum SurfaceKind {
1088    /// Docked panel at the side of the main window (one visible at a time).
1089    Sidebar,
1090    /// Separate top-level window.
1091    Window,
1092    /// Modal dialog over the main window.
1093    Modal,
1094}
1095
1096/// A Slint UI surface. `ui_path` is relative to the plugin root.
1097#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1098pub struct SurfaceSpec {
1099    pub kind: SurfaceKind,
1100    pub ui_path: String,
1101    pub component: String,
1102    /// A window's title, like its minimum size, is its component's: inherit
1103    /// `Window` and set `title`, `min-width` and `min-height` there. eov 1.x
1104    /// only passes this to a `title` property the component declares, if any.
1105    #[serde(default)]
1106    pub title: Option<String>,
1107    /// Preferred size in logical pixels (sidebar: width only). Windows are
1108    /// never opened larger than eov's main window.
1109    #[serde(default)]
1110    pub width: Option<f32>,
1111    #[serde(default)]
1112    pub height: Option<f32>,
1113    /// Unused by eov 1.x (see `title`).
1114    #[serde(default)]
1115    pub min_width: Option<f32>,
1116    /// Unused by eov 1.x (see `title`).
1117    #[serde(default)]
1118    pub min_height: Option<f32>,
1119    /// Initial property values (by Slint property name).
1120    #[serde(default)]
1121    pub properties: Map<String, Value>,
1122    /// Keep keyboard shortcuts away from the host while this surface has
1123    /// keyboard focus (text entry).
1124    #[serde(default = "default_true")]
1125    pub capture_keyboard: bool,
1126}
1127
1128impl SurfaceSpec {
1129    /// A surface showing `component` from `ui_path` (relative to the plugin
1130    /// root).
1131    pub fn new(
1132        kind: SurfaceKind,
1133        ui_path: impl Into<String>,
1134        component: impl Into<String>,
1135    ) -> Self {
1136        Self {
1137            kind,
1138            ui_path: ui_path.into(),
1139            component: component.into(),
1140            title: None,
1141            width: None,
1142            height: None,
1143            min_width: None,
1144            min_height: None,
1145            properties: Map::new(),
1146            capture_keyboard: true,
1147        }
1148    }
1149
1150    pub fn with_title(mut self, title: impl Into<String>) -> Self {
1151        self.title = Some(title.into());
1152        self
1153    }
1154
1155    pub fn with_size(mut self, width: f32, height: Option<f32>) -> Self {
1156        self.width = Some(width);
1157        self.height = height;
1158        self
1159    }
1160
1161    pub fn with_property(mut self, name: impl Into<String>, value: Value) -> Self {
1162        self.properties.insert(name.into(), value);
1163        self
1164    }
1165}
1166
1167impl Hotkey {
1168    /// A plain key without modifiers.
1169    pub fn key(key: impl Into<String>) -> Self {
1170        Self {
1171            key: key.into(),
1172            modifiers: Modifiers::default(),
1173            momentary: false,
1174        }
1175    }
1176}
1177
1178#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1179pub struct FileFilter {
1180    pub name: String,
1181    /// Extensions without the leading dot.
1182    pub extensions: Vec<String>,
1183}
1184
1185/// A viewport filter (CPU post-processing of rendered frames).
1186#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1187pub struct FilterSpec {
1188    /// Plugin-scoped filter id.
1189    pub filter_id: String,
1190    pub name: String,
1191    /// Lower runs first. Ties are broken by plugin id, then filter id.
1192    #[serde(default)]
1193    pub priority: i32,
1194    #[serde(default)]
1195    pub enabled: bool,
1196}
1197
1198#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1199#[serde(rename_all = "snake_case")]
1200pub enum NotifyLevel {
1201    #[default]
1202    Info,
1203    Success,
1204    Warning,
1205    Error,
1206}
1207
1208// ---------------------------------------------------------------------------
1209// Host → plugin events
1210// ---------------------------------------------------------------------------
1211
1212/// Messages the host sends to a plugin's `handle_event`.
1213///
1214/// Unless documented otherwise the response is ignored (return `null`).
1215#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1216#[serde(tag = "type", rename_all = "snake_case")]
1217#[non_exhaustive]
1218pub enum HostEvent {
1219    /// The host finished starting up; every plugin has been created and the
1220    /// main window exists. Restore surfaces and layers here.
1221    Ready {
1222        /// This plugin's sidebar was open when eov last exited; re-open it
1223        /// to restore the user's layout.
1224        #[serde(default)]
1225        restore_sidebar: bool,
1226    },
1227    /// The application is exiting. Flush state; no further events follow.
1228    Shutdown,
1229    FileOpened {
1230        file: FileInfo,
1231    },
1232    /// The file is closed; its layers were discarded.
1233    FileClosed {
1234        file_id: FileId,
1235    },
1236    /// The focused pane changed, or the file shown in it.
1237    ActiveChanged {
1238        #[serde(default)]
1239        pane: Option<PaneId>,
1240        #[serde(default)]
1241        file_id: Option<FileId>,
1242    },
1243    /// A pane's view settled after navigation (debounced).
1244    ViewChanged {
1245        view: ViewInfo,
1246    },
1247    WindowFocusChanged {
1248        focused: bool,
1249    },
1250    ToolbarButtonClicked {
1251        button_id: String,
1252    },
1253    HudButtonClicked {
1254        button_id: String,
1255        #[serde(default)]
1256        item_id: Option<String>,
1257        pane: PaneId,
1258        #[serde(default)]
1259        view: Option<ViewInfo>,
1260    },
1261    /// The context menu is opening. Respond with [`ContextMenuResponse`].
1262    ContextMenuRequested(MenuContext),
1263    /// One of the plugin's context-menu items was chosen.
1264    ContextMenuItemSelected {
1265        item_id: String,
1266        context: MenuContext,
1267    },
1268    ToolActivated {
1269        tool_id: String,
1270    },
1271    ToolDeactivated {
1272        tool_id: String,
1273    },
1274    /// A host-drawn shape for one of the plugin's tools was completed.
1275    ShapeDrawn {
1276        tool_id: String,
1277        pane: PaneId,
1278        file_id: FileId,
1279        shape: Shape,
1280        #[serde(default)]
1281        modifiers: Modifiers,
1282    },
1283    /// Raw pointer input for an active `Custom` tool.
1284    Pointer {
1285        tool_id: String,
1286        pane: PaneId,
1287        file_id: FileId,
1288        event: PointerEvent,
1289    },
1290    /// Key input for an active `Custom` tool, or a plugin hotkey. `key` is
1291    /// the raw key text; [`key_name`] names it.
1292    Key {
1293        #[serde(default)]
1294        tool_id: Option<String>,
1295        #[serde(default)]
1296        pane: Option<PaneId>,
1297        key: String,
1298        #[serde(default)]
1299        modifiers: Modifiers,
1300        pressed: bool,
1301        #[serde(default)]
1302        repeat: bool,
1303    },
1304    ObjectClicked {
1305        object: ObjectRef,
1306        pane: PaneId,
1307        #[serde(default)]
1308        button: PointerButton,
1309        #[serde(default)]
1310        modifiers: Modifiers,
1311        /// 1 for a click, 2 for a double click.
1312        #[serde(default = "default_click_count")]
1313        click_count: u32,
1314    },
1315    ObjectHovered {
1316        #[serde(default)]
1317        object: Option<ObjectRef>,
1318        pane: PaneId,
1319    },
1320    /// A host editing gesture reshaped an editable object. The host already
1321    /// shows the new geometry; persist it (or upsert the old one to revert).
1322    ObjectEdited {
1323        object: ObjectRef,
1324        shape: Shape,
1325    },
1326    /// The user asked to delete objects (Delete key or context menu).
1327    ObjectsDeleteRequested {
1328        objects: Vec<ObjectRef>,
1329    },
1330    /// The host-side selection of the plugin's objects changed (click,
1331    /// Escape, layer removal). `objects` is the complete new selection.
1332    SelectionChanged {
1333        objects: Vec<ObjectRef>,
1334    },
1335    /// Delivered on the UI thread in response to the `post` method.
1336    Posted {
1337        token: String,
1338    },
1339    /// A click in Navigate/Select mode hit none of the plugin's objects.
1340    EmptyAreaClicked {
1341        pane: PaneId,
1342        #[serde(default)]
1343        file_id: Option<FileId>,
1344        #[serde(default)]
1345        modifiers: Modifiers,
1346    },
1347    /// Undo the plugin-pushed history entry.
1348    Undo {
1349        entry_id: String,
1350    },
1351    Redo {
1352        entry_id: String,
1353    },
1354    /// A callback declared in a surface's `.slint` file was invoked.
1355    UiCallback {
1356        surface_id: String,
1357        name: String,
1358        #[serde(default)]
1359        args: Vec<Value>,
1360    },
1361    /// The user closed a surface (window close button, Escape on a modal).
1362    SurfaceClosed {
1363        surface_id: String,
1364    },
1365    /// Result of `dialog.open_file` / `dialog.save_file`; empty = cancelled.
1366    DialogResult {
1367        request_id: String,
1368        #[serde(default)]
1369        paths: Vec<String>,
1370    },
1371    ConfirmResult {
1372        request_id: String,
1373        confirmed: bool,
1374    },
1375    JobCancelRequested {
1376        job_id: String,
1377    },
1378    /// The user toggled one of the plugin's filters in the host UI.
1379    FilterToggled {
1380        filter_id: String,
1381        enabled: bool,
1382    },
1383    /// The host dropped some of the plugin's undo entries (the history is
1384    /// bounded, and a new change discards the redo history of its slide):
1385    /// they will never be undone or redone, so their data can be freed.
1386    UndoDropped {
1387        entry_ids: Vec<String>,
1388    },
1389    /// A hotkey registered with [`methods::HOTKEY_REGISTER`] was pressed.
1390    HotkeyPressed {
1391        hotkey_id: String,
1392        /// The focused pane, if any.
1393        #[serde(default)]
1394        pane: Option<PaneId>,
1395    },
1396    /// Part of a registration was refused, e.g. a hotkey that eov or
1397    /// another plugin already uses (`what`: `"hotkey"`; `id`: the button,
1398    /// tool or hotkey id).
1399    RegistrationRefused {
1400        what: String,
1401        id: String,
1402        reason: String,
1403    },
1404    /// How a pane displays its slide changed (see
1405    /// [`methods::VIEW_DISPLAY`]).
1406    DisplayChanged {
1407        pane: PaneId,
1408        display: DisplayAdjustments,
1409    },
1410    /// A slide's region of interest was drawn, changed or removed (`None`).
1411    RoiChanged {
1412        file_id: FileId,
1413        #[serde(default)]
1414        roi: Option<Rect>,
1415    },
1416    /// A headless batch run (`eov batch run`, see
1417    /// [`methods::BATCH_REGISTER`]) asks for `file` to be analysed with
1418    /// `command_id`, writing results under `output_dir`. Slides come one at
1419    /// a time; work may continue on the plugin's own threads, and the run
1420    /// waits until [`methods::BATCH_FINISH`] names `run_id`.
1421    BatchRun {
1422        run_id: String,
1423        command_id: String,
1424        file: FileInfo,
1425        /// An existing, writable folder for this slide's results.
1426        output_dir: String,
1427        /// `--param name=value` values (JSON when they parse, else
1428        /// strings), over the command's defaults.
1429        #[serde(default)]
1430        params: Map<String, Value>,
1431    },
1432    /// The answer to [`methods::MODEL_FETCH`]: the model is stored and
1433    /// verified (`path` and `model`), or it is not (`error`). The host has
1434    /// already told the user why a download failed or was refused; plugins
1435    /// need not repeat it. `cancelled` is set when the user declined the
1436    /// download or cancelled it (and `error` says so).
1437    ModelFetched {
1438        request_id: String,
1439        /// The model's main file.
1440        #[serde(default)]
1441        path: Option<String>,
1442        #[serde(default)]
1443        model: Option<ModelRecord>,
1444        #[serde(default)]
1445        error: Option<String>,
1446        #[serde(default)]
1447        cancelled: bool,
1448    },
1449    /// Sent by newer hosts for events this plugin version does not know.
1450    #[serde(other)]
1451    Unknown,
1452}
1453
1454fn default_click_count() -> u32 {
1455    1
1456}
1457
1458/// Where a context menu was opened.
1459#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1460pub struct MenuContext {
1461    pub pane: PaneId,
1462    pub view: ViewInfo,
1463    /// Level-0 coordinates under the pointer.
1464    pub image_x: f64,
1465    pub image_y: f64,
1466    /// The plugin's topmost object under the pointer, if any.
1467    #[serde(default)]
1468    pub hit: Option<ObjectRef>,
1469    /// The plugin's currently selected objects.
1470    #[serde(default)]
1471    pub selection: Vec<ObjectRef>,
1472}
1473
1474/// Response to [`HostEvent::ContextMenuRequested`].
1475#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1476pub struct ContextMenuResponse {
1477    #[serde(default)]
1478    pub items: Vec<MenuItem>,
1479}
1480
1481// ---------------------------------------------------------------------------
1482// Plugin → host methods
1483// ---------------------------------------------------------------------------
1484
1485/// Names of the methods a plugin can invoke through `HostApi::call`.
1486///
1487/// Arguments and results are JSON; the argument type of each method is noted.
1488pub mod methods {
1489    /// `LogArgs` → `null`
1490    pub const LOG: &str = "log";
1491    /// `NotifyArgs` → `null`. Shows a toast and records it in the log.
1492    pub const NOTIFY: &str = "notify";
1493    /// `StatusArgs` → `null`. Plugin-owned status bar segment.
1494    pub const STATUS: &str = "status";
1495    /// `{}` → `HostSnapshot`
1496    pub const SNAPSHOT: &str = "snapshot";
1497    /// `FileArgs` → `FileInfo`
1498    pub const FILE_INFO: &str = "file.info";
1499    /// `FileArgs` → `{ "<name>": "<value>" }` (all slide properties)
1500    pub const FILE_PROPERTIES: &str = "file.properties";
1501    /// `OpenFileArgs` → `null`
1502    pub const FILE_OPEN: &str = "file.open";
1503
1504    /// `ToolbarButtonSpec` → `null`
1505    pub const TOOLBAR_ADD: &str = "toolbar.add";
1506    /// `ButtonUpdate` → `null`
1507    pub const TOOLBAR_UPDATE: &str = "toolbar.update";
1508    /// `IdArgs { id: button_id }` → `null`
1509    pub const TOOLBAR_REMOVE: &str = "toolbar.remove";
1510    /// `HudButtonSpec` → `null`
1511    pub const HUD_ADD: &str = "hud.add";
1512    /// `ButtonUpdate` → `null`
1513    pub const HUD_UPDATE: &str = "hud.update";
1514    /// `IdArgs { id: button_id }` → `null`
1515    pub const HUD_REMOVE: &str = "hud.remove";
1516
1517    /// `HotkeySpec` → `null`. A key binding of its own, not tied to a
1518    /// toolbar button or tool; presses arrive as `HotkeyPressed`.
1519    pub const HOTKEY_REGISTER: &str = "hotkey.register";
1520    /// `IdArgs { id: hotkey_id }` → `null`
1521    pub const HOTKEY_UNREGISTER: &str = "hotkey.unregister";
1522    /// `ToolSpec` → `null`
1523    pub const TOOL_REGISTER: &str = "tool.register";
1524    /// `IdArgs { id: tool_id }` → `null`
1525    pub const TOOL_UNREGISTER: &str = "tool.unregister";
1526    /// `IdArgs { id: tool_id }` → `null`
1527    pub const TOOL_ACTIVATE: &str = "tool.activate";
1528    /// `{}` → `null`. Returns to Navigate if one of this plugin's tools is active.
1529    pub const TOOL_DEACTIVATE: &str = "tool.deactivate";
1530
1531    /// `LayerSpec` → `null` (replaces an existing layer with the same id)
1532    pub const LAYER_CREATE: &str = "layer.create";
1533    /// `LayerUpdate` → `null`
1534    pub const LAYER_UPDATE: &str = "layer.update";
1535    /// `IdArgs { id: layer_id }` → `null`
1536    pub const LAYER_REMOVE: &str = "layer.remove";
1537    /// `SelectArgs` → `null`
1538    pub const LAYER_SELECT: &str = "layer.select";
1539    /// `UpsertObjectsArgs` → `null`. Parsed and indexed on the calling
1540    /// thread; call it from a worker thread for large batches.
1541    pub const LAYER_UPSERT: &str = "layer.upsert";
1542    /// `RemoveObjectsArgs` → `null`
1543    pub const LAYER_REMOVE_OBJECTS: &str = "layer.remove_objects";
1544    /// `IdArgs { id: layer_id }` → `null`. Removes every object.
1545    pub const LAYER_CLEAR: &str = "layer.clear";
1546    /// `BadgeArgs` → `null`. Shows (or with `text: None` removes) a short
1547    /// notice fixed to the corner of every pane showing a slide, which does
1548    /// not move with the view (e.g. "Predicted — research use only").
1549    pub const BADGE_SET: &str = "badge.set";
1550    /// `SelectArgs` → `null`. Draws these objects with the layer's hover
1551    /// style (an empty list clears it), e.g. while a list row is hovered.
1552    pub const LAYER_HIGHLIGHT: &str = "layer.highlight";
1553    /// `MinZoomArgs` → `null`. Hides the layer below a zoom level.
1554    pub const LAYER_SET_MIN_ZOOM: &str = "layer.set_min_zoom";
1555    /// `PaneVisibilityArgs` → `null`. Shows or hides the layer in one pane
1556    /// (on top of the layer's own visibility).
1557    pub const LAYER_SET_PANE_VISIBILITY: &str = "layer.set_pane_visibility";
1558    /// `PaneFilterArgs` → `null`. Shows the layer only in these panes
1559    /// (`None`: in every pane), including panes opened later.
1560    pub const LAYER_SET_PANES: &str = "layer.set_panes";
1561
1562    /// `SurfaceSpec` → `SurfaceOpened`
1563    pub const SURFACE_OPEN: &str = "surface.open";
1564    /// `SurfaceProperties` → `null`. Values the surface already shows are left alone.
1565    pub const SURFACE_SET: &str = "surface.set";
1566    /// `IdArgs { id: surface_id }` → `null`
1567    pub const SURFACE_CLOSE: &str = "surface.close";
1568    /// `IdArgs { id: surface_id }` → `bool`
1569    pub const SURFACE_IS_OPEN: &str = "surface.is_open";
1570
1571    /// `ConfirmArgs` → `RequestId` (result arrives as `ConfirmResult`)
1572    pub const DIALOG_CONFIRM: &str = "dialog.confirm";
1573    /// `FileDialogArgs` → `RequestId` (result arrives as `DialogResult`)
1574    pub const DIALOG_OPEN_FILE: &str = "dialog.open_file";
1575    /// `FileDialogArgs` → `RequestId` (result arrives as `DialogResult`)
1576    pub const DIALOG_SAVE_FILE: &str = "dialog.save_file";
1577
1578    /// `ViewSetArgs` → `null`
1579    pub const VIEW_SET: &str = "view.set";
1580    /// `ViewPanArgs` → `null`
1581    pub const VIEW_PAN: &str = "view.pan";
1582    /// `ViewZoomArgs` → `null`
1583    pub const VIEW_ZOOM: &str = "view.zoom";
1584    /// `PaneArgs` → `null`
1585    pub const VIEW_FIT: &str = "view.fit";
1586    /// `ViewFrameArgs` → `null`
1587    pub const VIEW_FRAME: &str = "view.frame";
1588    /// `ViewOrientationArgs` → `null`: turns a pane's view, by any angle
1589    /// (it must be finite), about the pane centre.
1590    pub const VIEW_ORIENTATION: &str = "view.orientation";
1591    /// `PaneArgs` → `DisplayAdjustments`: how the pane renders the slide,
1592    /// so overlays derived from slide pixels can match it.
1593    pub const VIEW_DISPLAY: &str = "view.display";
1594
1595    /// `BatchCommandSpec` → `null`: offers a command for headless batch
1596    /// runs over many slides (`eov batch run <plugin>:<command> SLIDES`).
1597    /// Register it in `create`; slides then arrive as
1598    /// [`HostEvent::BatchRun`](super::HostEvent::BatchRun).
1599    pub const BATCH_REGISTER: &str = "batch.register";
1600    /// `BatchProgressArgs` → `null`: how far a batch run's slide is.
1601    pub const BATCH_PROGRESS: &str = "batch.progress";
1602    /// `BatchFinishArgs` → `null`: a batch run's slide is done.
1603    pub const BATCH_FINISH: &str = "batch.finish";
1604
1605    /// `OffsetArgs` → `null`
1606    pub const APP_CYCLE_PANE: &str = "app.cycle_pane";
1607    /// `OffsetArgs` → `null`
1608    pub const APP_CYCLE_TAB: &str = "app.cycle_tab";
1609    /// `SeriesArgs` → `null`
1610    pub const APP_SERIES: &str = "app.series";
1611    /// `{}` → `null`
1612    pub const RENDER_REQUEST: &str = "render.request";
1613
1614    /// `UndoPushArgs` → `null`
1615    pub const UNDO_PUSH: &str = "undo.push";
1616    /// `UndoClearArgs` → `null`
1617    pub const UNDO_CLEAR: &str = "undo.clear";
1618
1619    /// `FilterSpec` → `null`
1620    pub const FILTER_REGISTER: &str = "filter.register";
1621    /// `FilterEnableArgs` → `null`
1622    pub const FILTER_SET_ENABLED: &str = "filter.set_enabled";
1623    /// `IdArgs { id: filter_id }` → `null`
1624    pub const FILTER_UNREGISTER: &str = "filter.unregister";
1625
1626    /// `KeyArgs` → value or `null`
1627    pub const SETTINGS_GET: &str = "settings.get";
1628    /// `SettingsSetArgs` → `null` (persisted by the host)
1629    pub const SETTINGS_SET: &str = "settings.set";
1630
1631    /// `JobStartArgs` → `JobStarted`
1632    pub const JOB_START: &str = "job.start";
1633    /// `JobUpdateArgs` → `null`
1634    pub const JOB_UPDATE: &str = "job.update";
1635    /// `JobFinishArgs` → `null`
1636    pub const JOB_FINISH: &str = "job.finish";
1637
1638    /// `TextArgs` → `null`
1639    pub const CLIPBOARD_SET_TEXT: &str = "clipboard.set_text";
1640
1641    /// `FileArgs` → `Option<Rect>` (the host region of interest of a slide)
1642    pub const ROI_GET: &str = "roi.get";
1643    /// `FileArgs` → `Vec<MeasurementInfo>`
1644    pub const MEASUREMENTS_LIST: &str = "measurements.list";
1645
1646    /// `ModelFetchArgs` → `RequestId`: makes a model available in eov's
1647    /// model store, downloading it (after the user agrees, with progress in
1648    /// the status bar) when it is not stored yet, and verifying every file
1649    /// against its SHA-256. The answer arrives as
1650    /// [`HostEvent::ModelFetched`](super::HostEvent::ModelFetched).
1651    pub const MODEL_FETCH: &str = "model.fetch";
1652    /// `ModelResolveArgs` → `Option<ModelRecord>`: the stored model whose
1653    /// main file has this SHA-256, if any (never downloads).
1654    pub const MODEL_RESOLVE: &str = "model.resolve";
1655    /// `{}` → `Vec<ModelRecord>`: every stored model.
1656    pub const MODEL_LIST: &str = "model.list";
1657
1658    /// `PostArgs` → `null`. Delivers `Posted { token }` on the UI thread.
1659    pub const POST: &str = "post";
1660    /// `SubscribeArgs` → `null`. Restricts the events delivered to the
1661    /// plugin; by default every event is delivered.
1662    pub const EVENTS_SUBSCRIBE: &str = "events.subscribe";
1663}
1664
1665/// The `type` tags of [`HostEvent`] variants, for `events.subscribe`.
1666///
1667/// Lifecycle events (`ready`, `shutdown`) and responses to the plugin's own
1668/// requests (dialogs, confirmations, UI callbacks, undo/redo, posts) are always
1669/// delivered.
1670pub mod event_names {
1671    pub const FILE_OPENED: &str = "file_opened";
1672    pub const FILE_CLOSED: &str = "file_closed";
1673    pub const ACTIVE_CHANGED: &str = "active_changed";
1674    pub const VIEW_CHANGED: &str = "view_changed";
1675    pub const WINDOW_FOCUS_CHANGED: &str = "window_focus_changed";
1676    pub const OBJECT_HOVERED: &str = "object_hovered";
1677    pub const EMPTY_AREA_CLICKED: &str = "empty_area_clicked";
1678    pub const CONTEXT_MENU_REQUESTED: &str = "context_menu_requested";
1679    pub const ROI_CHANGED: &str = "roi_changed";
1680    pub const HOTKEY_PRESSED: &str = "hotkey_pressed";
1681    pub const DISPLAY_CHANGED: &str = "display_changed";
1682}
1683
1684#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1685pub struct LogArgs {
1686    pub level: LogLevel,
1687    pub message: String,
1688}
1689
1690#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1691pub struct NotifyArgs {
1692    #[serde(default)]
1693    pub level: NotifyLevel,
1694    pub message: String,
1695    /// Optional longer text (shown on demand, e.g. an error chain).
1696    #[serde(default)]
1697    pub detail: Option<String>,
1698}
1699
1700#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1701pub struct StatusArgs {
1702    /// `None` clears the plugin's status segment.
1703    #[serde(default)]
1704    pub text: Option<String>,
1705}
1706
1707#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1708pub struct FileArgs {
1709    pub file_id: FileId,
1710}
1711
1712#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1713pub struct OpenFileArgs {
1714    pub path: String,
1715}
1716
1717#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1718pub struct IdArgs {
1719    pub id: String,
1720}
1721
1722/// A command a plugin offers for headless batch runs (see
1723/// [`methods::BATCH_REGISTER`]).
1724#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1725pub struct BatchCommandSpec {
1726    /// `^[a-z0-9][a-z0-9_-]{0,63}$`
1727    pub command_id: String,
1728    /// One line, for `eov batch list`.
1729    pub description: String,
1730    /// The parameters it takes, for `--param name=value`.
1731    #[serde(default)]
1732    pub params: Vec<BatchParam>,
1733}
1734
1735/// A parameter of a [`BatchCommandSpec`].
1736#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1737pub struct BatchParam {
1738    pub name: String,
1739    #[serde(default)]
1740    pub description: String,
1741    /// Used when the run does not set it (`null`: no default).
1742    #[serde(default)]
1743    pub default: Value,
1744}
1745
1746/// Arguments of [`methods::BATCH_PROGRESS`].
1747#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1748pub struct BatchProgressArgs {
1749    pub run_id: String,
1750    /// 0–1, when known.
1751    #[serde(default)]
1752    pub fraction: Option<f32>,
1753    #[serde(default)]
1754    pub message: Option<String>,
1755}
1756
1757/// Arguments of [`methods::BATCH_FINISH`].
1758#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1759pub struct BatchFinishArgs {
1760    pub run_id: String,
1761    /// `false` when the slide could not be analysed (`message` says why).
1762    pub ok: bool,
1763    #[serde(default)]
1764    pub message: Option<String>,
1765    /// The files written, relative to the slide's `output_dir`.
1766    #[serde(default)]
1767    pub outputs: Vec<String>,
1768    /// Results and provenance for the run manifest: counts, scores, the
1769    /// model and its hash, the level or resolution read, the device…
1770    #[serde(default)]
1771    pub summary: Value,
1772}
1773
1774/// Arguments of [`methods::BADGE_SET`].
1775#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1776pub struct BadgeArgs {
1777    pub badge_id: String,
1778    /// The slide whose panes show it; `None`: every pane with a slide.
1779    #[serde(default)]
1780    pub file_id: Option<FileId>,
1781    /// At most 200 characters; `None` removes the badge.
1782    #[serde(default)]
1783    pub text: Option<String>,
1784}
1785
1786/// Arguments of [`methods::LAYER_SET_MIN_ZOOM`].
1787#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1788pub struct MinZoomArgs {
1789    pub layer_id: String,
1790    /// Screen pixels per level-0 pixel below which the layer is not drawn;
1791    /// `None` draws it at every zoom.
1792    #[serde(default)]
1793    pub min_zoom: Option<f64>,
1794}
1795
1796/// Arguments of [`methods::LAYER_SET_PANE_VISIBILITY`].
1797#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1798pub struct PaneVisibilityArgs {
1799    pub layer_id: String,
1800    pub pane: PaneId,
1801    pub visible: bool,
1802}
1803
1804/// Arguments of [`methods::LAYER_SET_PANES`].
1805#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1806pub struct PaneFilterArgs {
1807    pub layer_id: String,
1808    /// The only panes that show the layer; `None` shows it in every pane.
1809    #[serde(default)]
1810    pub panes: Option<Vec<PaneId>>,
1811}
1812
1813/// How a pane displays its slide (the answer of [`methods::VIEW_DISPLAY`]).
1814#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1815pub struct DisplayAdjustments {
1816    /// 1.0 is unchanged.
1817    pub gamma: f32,
1818    /// Added to every channel (0.0 is unchanged; −1…1).
1819    pub brightness: f32,
1820    /// 1.0 is unchanged.
1821    pub contrast: f32,
1822    /// Sharpening amount (0.0 is off).
1823    pub sharpness: f32,
1824    /// Stain normalisation method (`"macenko"`, `"vahadane"`), if any.
1825    #[serde(default)]
1826    pub stain_normalization: Option<String>,
1827    /// Whether any colour processing is applied.
1828    pub modified: bool,
1829    /// What the viewer shows as its colour badge (empty when unmodified).
1830    #[serde(default)]
1831    pub badge: String,
1832    /// The pane converts the slide's colours from its ICC profile to sRGB
1833    /// (colour management), after every other adjustment and after plugin
1834    /// filters. Region reads and filter frames are never converted: to
1835    /// match an overlay derived from slide pixels to the screen exactly,
1836    /// convert it with the slide's profile too.
1837    #[serde(default)]
1838    pub color_managed: bool,
1839}
1840
1841impl Default for DisplayAdjustments {
1842    fn default() -> Self {
1843        Self {
1844            gamma: 1.0,
1845            brightness: 0.0,
1846            contrast: 1.0,
1847            sharpness: 0.0,
1848            stain_normalization: None,
1849            modified: false,
1850            badge: String::new(),
1851            color_managed: false,
1852        }
1853    }
1854}
1855
1856#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1857pub struct SelectArgs {
1858    pub layer_id: String,
1859    pub object_ids: Vec<String>,
1860}
1861
1862#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1863pub struct UpsertObjectsArgs {
1864    pub layer_id: String,
1865    pub objects: Vec<OverlayObject>,
1866    /// Remove every existing object first (atomic replace).
1867    #[serde(default)]
1868    pub replace_all: bool,
1869}
1870
1871#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1872pub struct RemoveObjectsArgs {
1873    pub layer_id: String,
1874    pub object_ids: Vec<String>,
1875}
1876
1877#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1878pub struct PostArgs {
1879    pub token: String,
1880}
1881
1882#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1883pub struct SubscribeArgs {
1884    /// Event `type` tags (see [`event_names`]).
1885    pub events: Vec<String>,
1886}
1887
1888#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1889pub struct SurfaceOpened {
1890    pub surface_id: String,
1891}
1892
1893#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1894pub struct SurfaceProperties {
1895    pub surface_id: String,
1896    pub properties: Map<String, Value>,
1897}
1898
1899#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1900pub struct ConfirmArgs {
1901    pub title: String,
1902    pub message: String,
1903    #[serde(default = "default_confirm_label")]
1904    pub confirm_label: String,
1905    #[serde(default = "default_cancel_label")]
1906    pub cancel_label: String,
1907    /// Style the confirm button as destructive.
1908    #[serde(default)]
1909    pub destructive: bool,
1910}
1911
1912fn default_confirm_label() -> String {
1913    "OK".to_string()
1914}
1915fn default_cancel_label() -> String {
1916    "Cancel".to_string()
1917}
1918
1919#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1920pub struct FileDialogArgs {
1921    #[serde(default)]
1922    pub title: Option<String>,
1923    #[serde(default)]
1924    pub filters: Vec<FileFilter>,
1925    /// Suggested file name (save dialogs).
1926    #[serde(default)]
1927    pub default_name: Option<String>,
1928    /// Pick directories instead of files (open dialogs).
1929    #[serde(default)]
1930    pub directory: bool,
1931    /// Allow several selections (open dialogs).
1932    #[serde(default)]
1933    pub multiple: bool,
1934}
1935
1936#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1937pub struct RequestId {
1938    pub request_id: String,
1939}
1940
1941#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
1942pub struct PaneArgs {
1943    /// Defaults to the focused pane.
1944    #[serde(default)]
1945    pub pane: Option<PaneId>,
1946}
1947
1948#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1949pub struct ViewSetArgs {
1950    #[serde(default)]
1951    pub pane: Option<PaneId>,
1952    pub center_x: f64,
1953    pub center_y: f64,
1954    pub zoom: f64,
1955    #[serde(default)]
1956    pub animate: bool,
1957}
1958
1959#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1960pub struct ViewPanArgs {
1961    #[serde(default)]
1962    pub pane: Option<PaneId>,
1963    /// Logical screen pixels.
1964    pub dx: f64,
1965    pub dy: f64,
1966}
1967
1968#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1969pub struct ViewZoomArgs {
1970    #[serde(default)]
1971    pub pane: Option<PaneId>,
1972    /// > 1 zooms in.
1973    pub factor: f64,
1974    /// Screen anchor; defaults to the pane centre.
1975    #[serde(default)]
1976    pub anchor_x: Option<f64>,
1977    #[serde(default)]
1978    pub anchor_y: Option<f64>,
1979    #[serde(default)]
1980    pub animate: bool,
1981}
1982
1983#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1984pub struct ViewOrientationArgs {
1985    #[serde(default)]
1986    pub pane: Option<PaneId>,
1987    /// Clockwise rotation in degrees: any finite angle (normalised to
1988    /// `0..360`).
1989    pub rotation_deg: f64,
1990    /// Mirror left to right after the rotation.
1991    #[serde(default)]
1992    pub flipped: bool,
1993}
1994
1995#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1996pub struct ViewFrameArgs {
1997    #[serde(default)]
1998    pub pane: Option<PaneId>,
1999    pub rect: Rect,
2000    /// Fraction of the pane kept as margin (default 0.1).
2001    #[serde(default)]
2002    pub padding: Option<f64>,
2003}
2004
2005#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
2006pub struct OffsetArgs {
2007    pub offset: i32,
2008}
2009
2010#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2011#[serde(rename_all = "snake_case")]
2012pub enum SeriesAction {
2013    Toggle,
2014    Next,
2015    Previous,
2016    OpenSelected,
2017}
2018
2019#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
2020pub struct SeriesArgs {
2021    pub action: SeriesAction,
2022}
2023
2024#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2025pub struct UndoPushArgs {
2026    /// Plugin-chosen id, echoed back in `Undo`/`Redo`.
2027    pub entry_id: String,
2028    /// The slide the change applies to (scopes Ctrl+Z to that slide).
2029    #[serde(default)]
2030    pub file_id: Option<FileId>,
2031    /// Shown in menus ("Undo Add Point").
2032    pub label: String,
2033}
2034
2035#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
2036pub struct UndoClearArgs {
2037    /// Clear entries of one file; `None` clears all of the plugin's entries.
2038    #[serde(default)]
2039    pub file_id: Option<FileId>,
2040}
2041
2042#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2043pub struct FilterEnableArgs {
2044    pub filter_id: String,
2045    pub enabled: bool,
2046}
2047
2048#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2049pub struct KeyArgs {
2050    pub key: String,
2051}
2052
2053#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2054pub struct SettingsSetArgs {
2055    pub key: String,
2056    /// `null` removes the key.
2057    pub value: Value,
2058}
2059
2060#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2061pub struct JobStartArgs {
2062    pub title: String,
2063    #[serde(default)]
2064    pub cancellable: bool,
2065}
2066
2067#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2068pub struct JobStarted {
2069    pub job_id: String,
2070}
2071
2072#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2073pub struct JobUpdateArgs {
2074    pub job_id: String,
2075    /// 0.0–1.0, or `None` for indeterminate.
2076    #[serde(default)]
2077    pub fraction: Option<f32>,
2078    #[serde(default)]
2079    pub message: Option<String>,
2080}
2081
2082#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2083pub struct JobFinishArgs {
2084    pub job_id: String,
2085    /// `Some` marks the job failed and shows the error.
2086    #[serde(default)]
2087    pub error: Option<String>,
2088}
2089
2090#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2091pub struct TextArgs {
2092    pub text: String,
2093}
2094
2095/// A file a model needs next to its main file, such as the external
2096/// weights of an ONNX model (`model.onnx.data`).
2097#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
2098pub struct ModelFileSpec {
2099    /// Lower-case hex SHA-256 of the file.
2100    pub sha256: String,
2101    /// Where to download it: absolute, or relative to the main file's URL.
2102    /// `None`: the main file's folder with `file_name`.
2103    #[serde(default)]
2104    pub url: Option<String>,
2105    /// The name it is stored under. Required when `url` is `None`;
2106    /// otherwise the URL's last path segment by default.
2107    #[serde(default)]
2108    pub file_name: Option<String>,
2109    /// Its size in bytes, when known: checked, and a download stops as
2110    /// soon as it would be larger.
2111    #[serde(default)]
2112    pub size: Option<u64>,
2113}
2114
2115/// Arguments of [`methods::MODEL_FETCH`]. Models are stored by the
2116/// SHA-256 of their main file, so the same model is downloaded once for
2117/// every plugin and every eov of this user.
2118#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
2119pub struct ModelFetchArgs {
2120    /// Where to download the main file. The administrator's policy can
2121    /// provide a site copy by SHA-256 (it then wins), so `None` is allowed;
2122    /// without either, only a model already stored can be answered.
2123    #[serde(default)]
2124    pub url: Option<String>,
2125    /// Lower-case hex SHA-256 of the main file.
2126    pub sha256: String,
2127    /// Its size in bytes, when known (checked; caps the download).
2128    #[serde(default)]
2129    pub size: Option<u64>,
2130    /// The name the main file is stored under (default: the URL's last
2131    /// path segment).
2132    #[serde(default)]
2133    pub file_name: Option<String>,
2134    /// What the model is called, shown when asking the user and recorded.
2135    #[serde(default)]
2136    pub name: Option<String>,
2137    #[serde(default)]
2138    pub version: Option<String>,
2139    /// Files stored in the same folder as the main file.
2140    #[serde(default)]
2141    pub companions: Vec<ModelFileSpec>,
2142}
2143
2144/// Arguments of [`methods::MODEL_RESOLVE`].
2145#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
2146pub struct ModelResolveArgs {
2147    /// SHA-256 of the main file.
2148    pub sha256: String,
2149}
2150
2151/// A companion file of a stored model.
2152#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
2153pub struct ModelCompanion {
2154    pub file_name: String,
2155    pub sha256: String,
2156    pub size: u64,
2157    /// Its absolute path (next to the main file).
2158    #[serde(default)]
2159    pub path: String,
2160}
2161
2162/// A model in eov's model store (`eov model list`).
2163#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
2164pub struct ModelRecord {
2165    /// SHA-256 of the main file: the model's identity in the store.
2166    pub sha256: String,
2167    /// Absolute path of the main file.
2168    pub path: String,
2169    pub file_name: String,
2170    /// Size of the main file in bytes.
2171    pub size: u64,
2172    #[serde(default)]
2173    pub name: Option<String>,
2174    #[serde(default)]
2175    pub version: Option<String>,
2176    /// Where it was downloaded from (without credentials or query);
2177    /// `None` for a file imported with `eov model import`.
2178    #[serde(default)]
2179    pub source: Option<String>,
2180    /// When it was stored (UTC, RFC 3339).
2181    #[serde(default)]
2182    pub fetched_at: Option<String>,
2183    /// The plugin that asked for it, or `eov` for the command line.
2184    #[serde(default)]
2185    pub requested_by: Option<String>,
2186    #[serde(default)]
2187    pub companions: Vec<ModelCompanion>,
2188    /// Provided read-only by the administrator (`model_dirs` in the
2189    /// policy).
2190    #[serde(default)]
2191    pub read_only: bool,
2192}
2193
2194impl ModelRecord {
2195    /// Whether the record holds a companion with this SHA-256 and name.
2196    pub fn has_companion(&self, sha256: &str, file_name: &str) -> bool {
2197        self.companions
2198            .iter()
2199            .any(|c| c.sha256.eq_ignore_ascii_case(sha256) && c.file_name == file_name)
2200    }
2201}
2202
2203/// Whether `text` is a SHA-256 in hex (64 digits, either case).
2204pub fn is_sha256_hex(text: &str) -> bool {
2205    text.len() == 64 && text.bytes().all(|b| b.is_ascii_hexdigit())
2206}
2207
2208/// Checks a name a model file is stored under: one plain file name that
2209/// every platform accepts.
2210pub fn check_model_file_name(name: &str) -> Result<(), String> {
2211    // Windows device names, with or without an extension.
2212    let stem = name.split('.').next().unwrap_or_default();
2213    let reserved = ["CON", "PRN", "AUX", "NUL"]
2214        .iter()
2215        .any(|r| stem.eq_ignore_ascii_case(r))
2216        || (stem.len() == 4
2217            && stem.is_ascii()
2218            && ["COM", "LPT"]
2219                .iter()
2220                .any(|p| stem[..3].eq_ignore_ascii_case(p))
2221            && stem.as_bytes()[3].is_ascii_digit());
2222    if name.is_empty()
2223        || name.len() > 200
2224        || name.starts_with('.')
2225        || name.ends_with('.')
2226        || name.ends_with(' ')
2227        || name.chars().any(|c| {
2228            c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|')
2229        })
2230        || reserved
2231    {
2232        return Err(format!(
2233            "'{name}' cannot be a model's file name (use a plain name such as model.onnx)"
2234        ));
2235    }
2236    Ok(())
2237}
2238
2239impl ModelFileSpec {
2240    fn check(&self, what: &str) -> Result<(), String> {
2241        if !is_sha256_hex(&self.sha256) {
2242            return Err(format!(
2243                "the {what}'s sha256 must be 64 hex digits, not '{}'",
2244                self.sha256
2245            ));
2246        }
2247        if let Some(name) = &self.file_name {
2248            check_model_file_name(name)?;
2249        }
2250        if self.size == Some(0) {
2251            return Err(format!("the {what}'s size cannot be 0"));
2252        }
2253        Ok(())
2254    }
2255}
2256
2257impl ModelFetchArgs {
2258    /// Checks what the host checks before it accepts a request (URLs are
2259    /// checked by the host).
2260    pub fn validate(&self) -> Result<(), String> {
2261        ModelFileSpec {
2262            sha256: self.sha256.clone(),
2263            url: self.url.clone(),
2264            file_name: self.file_name.clone(),
2265            size: self.size,
2266        }
2267        .check("model")?;
2268        let mut names: Vec<&str> = self.file_name.iter().map(String::as_str).collect();
2269        for companion in &self.companions {
2270            companion.check("companion")?;
2271            let name = companion.file_name.as_deref();
2272            if companion.url.is_none() && name.is_none() {
2273                return Err("a companion without a url needs a file_name".to_string());
2274            }
2275            if let Some(name) = name {
2276                if names.iter().any(|n| n.eq_ignore_ascii_case(name)) {
2277                    return Err(format!("two files of the model are named '{name}'"));
2278                }
2279                names.push(name);
2280            }
2281        }
2282        if self.companions.len() > 64 {
2283            return Err("a model has at most 64 companion files".to_string());
2284        }
2285        Ok(())
2286    }
2287}
2288
2289/// Slide-wide JSON map type used by `file.properties`.
2290pub type PropertyMap = BTreeMap<String, String>;
2291
2292// ---------------------------------------------------------------------------
2293// Slide formats
2294// ---------------------------------------------------------------------------
2295
2296/// Most pyramid levels a [`SlideInfo`] may list.
2297pub const MAX_SLIDE_LEVELS: usize = 64;
2298
2299/// Longest side, in pixels, of a slide eov accepts (2^24 = 16,777,216).
2300pub const MAX_SLIDE_SIDE: u64 = 1 << 24;
2301
2302/// Most associated images a [`SlideInfo`] may list.
2303pub const MAX_ASSOCIATED_IMAGES: usize = 32;
2304
2305/// Most pixels of one associated image (2^28).
2306pub const MAX_ASSOCIATED_IMAGE_PIXELS: u64 = 1 << 28;
2307
2308/// What the host asks a plugin's slide source to open
2309/// ([`crate::abi::SlideSourceFfi::open`], `Plugin::open_slide` in the SDK).
2310#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
2311pub struct SlideOpenRequest {
2312    /// The `id` of the manifest's `[[slide_formats]]` entry whose extension
2313    /// or URI scheme matched.
2314    pub format_id: String,
2315    /// The slide: an absolute file path, or the URI as the user gave it.
2316    pub location: String,
2317    /// Whether `location` is a URI (`scheme://…`) rather than a file path.
2318    #[serde(default)]
2319    pub is_uri: bool,
2320}
2321
2322/// One pyramid level of a slide a plugin opened.
2323#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
2324pub struct SlideLevel {
2325    pub width: u64,
2326    pub height: u64,
2327    /// Level-0 size divided by this level's size (1 for level 0). When
2328    /// absent it is computed from the sizes, as OpenSlide does (the mean of
2329    /// the two ratios).
2330    #[serde(default)]
2331    pub downsample: Option<f64>,
2332    /// The format's native tile size, if it has a tile grid (a hint: eov
2333    /// aligns its reads with it).
2334    #[serde(default)]
2335    pub tile_width: Option<u32>,
2336    #[serde(default)]
2337    pub tile_height: Option<u32>,
2338}
2339
2340/// An associated image (`label`, `macro`, `thumbnail`, …) of a slide.
2341///
2342/// The label often shows the accession number or the patient's name; eov
2343/// treats it as protected health information (it can be hidden, and
2344/// de-identified copies leave it out).
2345#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
2346pub struct AssociatedImageInfo {
2347    pub name: String,
2348    pub width: u32,
2349    pub height: u32,
2350}
2351
2352/// The metadata of a slide a plugin opened
2353/// ([`crate::abi::SlideFfi::info`], `SlideReader::info` in the SDK).
2354///
2355/// eov refuses a slide whose levels or associated images are inconsistent
2356/// (see [`validate`](Self::validate)), and ignores optional values it
2357/// cannot use (a pixel size that is not a positive number, a tile size
2358/// above 8192, bounds outside the slide, …).
2359#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
2360pub struct SlideInfo {
2361    /// The pyramid, full resolution first: sizes never grow and downsamples
2362    /// never shrink from one level to the next.
2363    pub levels: Vec<SlideLevel>,
2364    /// The scanner vendor or format (`"philips"`, `"olympus"`); the format
2365    /// id when absent.
2366    #[serde(default)]
2367    pub vendor: Option<String>,
2368    /// Micrometres per level-0 pixel.
2369    #[serde(default)]
2370    pub mpp_x: Option<f64>,
2371    #[serde(default)]
2372    pub mpp_y: Option<f64>,
2373    /// The objective's magnification (20, 40, 2.5, …).
2374    #[serde(default)]
2375    pub objective_power: Option<f64>,
2376    /// The scan date as the format records it.
2377    #[serde(default)]
2378    pub scan_date: Option<String>,
2379    #[serde(default)]
2380    pub comment: Option<String>,
2381    /// The stain (`"H&E"`), if the format records it.
2382    #[serde(default)]
2383    pub stain: Option<String>,
2384    /// Colour of areas without image data, `[r, g, b]`; white when absent.
2385    #[serde(default)]
2386    pub background: Option<[u8; 3]>,
2387    /// The level-0 rectangle that holds image data, if smaller than the
2388    /// slide (for fitting the view and thumbnails).
2389    #[serde(default)]
2390    pub bounds: Option<Rect>,
2391    /// Every property of the slide, shown in Slide Information. Keys under
2392    /// `openslide.` and `eov.` are set by eov from the fields above.
2393    #[serde(default)]
2394    pub properties: PropertyMap,
2395    #[serde(default)]
2396    pub associated_images: Vec<AssociatedImageInfo>,
2397    /// For slides opened from a URI, which have no file eov could hash: a
2398    /// stable, globally unique id of the image (e.g.
2399    /// `omero:omero.example.org:image:1234`), the key bookmarks,
2400    /// annotations and results are kept under. Without it the URI is the
2401    /// key. Ignored for files, which are identified by their content.
2402    #[serde(default)]
2403    pub identity: Option<String>,
2404    /// Other files the slide consists of (absolute, or relative to the
2405    /// opened file's folder), hashed into its identity together with the
2406    /// opened file, e.g. the `.ets` files of a VSI slide.
2407    #[serde(default)]
2408    pub member_files: Vec<String>,
2409}
2410
2411impl SlideInfo {
2412    /// The checks eov refuses a slide for: 1–[`MAX_SLIDE_LEVELS`] levels,
2413    /// sides of 1–[`MAX_SLIDE_SIDE`] pixels that never grow, finite
2414    /// downsamples that never shrink (1 for level 0) and lie within a
2415    /// factor of two of the size ratio, and at most
2416    /// [`MAX_ASSOCIATED_IMAGES`] uniquely named associated images of at
2417    /// most [`MAX_ASSOCIATED_IMAGE_PIXELS`] pixels.
2418    pub fn validate(&self) -> Result<(), String> {
2419        let count = self.levels.len();
2420        if count == 0 || count > MAX_SLIDE_LEVELS {
2421            return Err(format!(
2422                "a slide has 1–{MAX_SLIDE_LEVELS} levels, not {count}"
2423            ));
2424        }
2425        let base = self.levels[0];
2426        let mut previous: Option<(SlideLevel, f64)> = None;
2427        for (index, level) in self.levels.iter().enumerate() {
2428            if level.width == 0
2429                || level.height == 0
2430                || level.width > MAX_SLIDE_SIDE
2431                || level.height > MAX_SLIDE_SIDE
2432            {
2433                return Err(format!(
2434                    "level {index} is {}×{}; sides must be 1–{MAX_SLIDE_SIDE} pixels",
2435                    level.width, level.height
2436                ));
2437            }
2438            let ratio = (base.width as f64 / level.width as f64
2439                + base.height as f64 / level.height as f64)
2440                / 2.0;
2441            let downsample = level.downsample.unwrap_or(ratio);
2442            if !downsample.is_finite() || downsample < 1.0 {
2443                return Err(format!(
2444                    "level {index} has downsample {downsample}; it must be a number of at least 1"
2445                ));
2446            }
2447            if index == 0 && (downsample - 1.0).abs() > 1e-6 {
2448                return Err(format!("level 0 has downsample {downsample}, not 1"));
2449            }
2450            if downsample > ratio * 2.0 || downsample < ratio / 2.0 {
2451                return Err(format!(
2452                    "level {index} is {}×{} but has downsample {downsample}",
2453                    level.width, level.height
2454                ));
2455            }
2456            if let Some((prev, prev_downsample)) = previous {
2457                if level.width > prev.width || level.height > prev.height {
2458                    return Err(format!(
2459                        "level {index} ({}×{}) is larger than level {} ({}×{})",
2460                        level.width,
2461                        level.height,
2462                        index - 1,
2463                        prev.width,
2464                        prev.height
2465                    ));
2466                }
2467                if downsample < prev_downsample {
2468                    return Err(format!(
2469                        "level {index} has a smaller downsample than level {}",
2470                        index - 1
2471                    ));
2472                }
2473            }
2474            previous = Some((*level, downsample));
2475        }
2476        if self.associated_images.len() > MAX_ASSOCIATED_IMAGES {
2477            return Err(format!(
2478                "a slide has at most {MAX_ASSOCIATED_IMAGES} associated images"
2479            ));
2480        }
2481        let mut names = std::collections::BTreeSet::new();
2482        for image in &self.associated_images {
2483            let name = image.name.as_str();
2484            if name.is_empty() || name.chars().count() > 64 || name.chars().any(char::is_control) {
2485                return Err(format!(
2486                    "associated image names are 1–64 printable characters, not {name:?}"
2487                ));
2488            }
2489            if !names.insert(name) {
2490                return Err(format!("associated image {name:?} is listed twice"));
2491            }
2492            let pixels = u64::from(image.width) * u64::from(image.height);
2493            if pixels == 0 || pixels > MAX_ASSOCIATED_IMAGE_PIXELS {
2494                return Err(format!(
2495                    "associated image {name:?} is {}×{}",
2496                    image.width, image.height
2497                ));
2498            }
2499        }
2500        Ok(())
2501    }
2502}
2503
2504#[cfg(test)]
2505mod tests {
2506    use super::*;
2507
2508    #[test]
2509    fn views_map_screen_and_image_through_their_turn() {
2510        let mut view = ViewInfo {
2511            center_x: 100.0,
2512            center_y: 50.0,
2513            zoom: 2.0,
2514            width: 300.0,
2515            height: 200.0,
2516            ..Default::default()
2517        };
2518        assert_eq!(view.image_to_screen(110.0, 50.0), (170.0, 100.0));
2519        // Turned clockwise, a point right of the centre shows below it.
2520        view.rotation_deg = 90.0;
2521        let (x, y) = view.image_to_screen(110.0, 50.0);
2522        assert!((x - 150.0).abs() < 1e-9 && (y - 120.0).abs() < 1e-9);
2523        for rotation in [0.0, 90.0, 180.0, 270.0, 37.5, 301.25] {
2524            for flipped in [false, true] {
2525                view.rotation_deg = rotation;
2526                view.flipped = flipped;
2527                let (sx, sy) = view.image_to_screen(37.0, 81.0);
2528                let (ix, iy) = view.screen_to_image(sx, sy);
2529                assert!((ix - 37.0).abs() < 1e-9 && (iy - 81.0).abs() < 1e-9);
2530            }
2531        }
2532        // Views from older hosts read as upright.
2533        let old: ViewInfo = serde_json::from_str(
2534            r#"{"pane":1,"file_id":1,"center_x":0,"center_y":0,"zoom":1,"width":1,"height":1,"visible":{"x":0,"y":0,"width":1,"height":1}}"#,
2535        )
2536        .unwrap();
2537        assert_eq!((old.rotation_deg, old.flipped), (0.0, false));
2538    }
2539
2540    #[test]
2541    fn unknown_events_deserialize_to_unknown() {
2542        let event: HostEvent =
2543            serde_json::from_str(r#"{"type":"something_from_the_future","x":1}"#).unwrap();
2544        assert_eq!(event, HostEvent::Unknown);
2545    }
2546
2547    #[test]
2548    fn events_round_trip() {
2549        let event = HostEvent::ShapeDrawn {
2550            tool_id: "poly".into(),
2551            pane: 3,
2552            file_id: 7,
2553            shape: Shape::Polygon {
2554                exterior: vec![[0.0, 0.0], [10.0, 0.0], [5.0, 8.0]],
2555                holes: vec![],
2556            },
2557            modifiers: Modifiers::default(),
2558        };
2559        let text = serde_json::to_string(&event).unwrap();
2560        assert!(text.contains(r#""type":"shape_drawn""#), "{text}");
2561        assert!(text.contains(r#""kind":"polygon""#), "{text}");
2562        assert_eq!(serde_json::from_str::<HostEvent>(&text).unwrap(), event);
2563    }
2564
2565    #[test]
2566    fn optional_fields_may_be_absent() {
2567        let event: HostEvent = serde_json::from_str(
2568            r#"{"type":"object_clicked","object":{"layer_id":"l","object_id":"o"},"pane":1}"#,
2569        )
2570        .unwrap();
2571        match event {
2572            HostEvent::ObjectClicked {
2573                click_count,
2574                button,
2575                ..
2576            } => {
2577                assert_eq!(click_count, 1);
2578                assert_eq!(button, PointerButton::None);
2579            }
2580            other => panic!("unexpected {other:?}"),
2581        }
2582        let spec: LayerSpec = serde_json::from_str(r#"{"layer_id":"a","file_id":1}"#).unwrap();
2583        assert!(spec.visible);
2584        assert_eq!(spec.opacity, 1.0);
2585        assert_eq!(spec.style, Style::default());
2586    }
2587
2588    /// `..Default::default()` builds what a message without the optional
2589    /// fields deserializes to. Plugins build their buttons and menu items
2590    /// that way, and derived defaults (`enabled: false`) left every plugin
2591    /// toolbar button disabled.
2592    #[test]
2593    fn defaults_are_what_absent_fields_deserialize_to() {
2594        let button: ToolbarButtonSpec =
2595            serde_json::from_str(r#"{"button_id":"","tooltip":"","icon_svg":""}"#).unwrap();
2596        assert_eq!(button, ToolbarButtonSpec::default());
2597        assert!(button.enabled);
2598        let item: MenuItem = serde_json::from_str(r#"{"item_id":"","label":""}"#).unwrap();
2599        assert_eq!(item, MenuItem::default());
2600        assert!(item.enabled);
2601        let view: ViewInfo = serde_json::from_str(
2602            r#"{"pane":0,"file_id":0,"center_x":0,"center_y":0,"zoom":0,"width":0,"height":0,
2603                "visible":{"x":0,"y":0,"width":0,"height":0}}"#,
2604        )
2605        .unwrap();
2606        assert_eq!(view, ViewInfo::default());
2607        assert_eq!(view.scale_factor, 1.0);
2608
2609        // Built from the default, a button still says it is enabled on the
2610        // wire, and an explicit `false` still disables it.
2611        let sent = serde_json::to_value(ToolbarButtonSpec {
2612            button_id: "b".into(),
2613            ..Default::default()
2614        })
2615        .unwrap();
2616        assert_eq!(sent["enabled"], true);
2617        let disabled: ToolbarButtonSpec =
2618            serde_json::from_str(r#"{"button_id":"b","tooltip":"","icon_svg":"","enabled":false}"#)
2619                .unwrap();
2620        assert!(!disabled.enabled);
2621    }
2622
2623    #[test]
2624    fn channel_names_are_optional_both_ways() {
2625        // An older host sends no channel names.
2626        let file: FileInfo = serde_json::from_str(
2627            r#"{"file_id":1,"path":"/s.svs","filename":"s.svs","width":10,"height":20}"#,
2628        )
2629        .unwrap();
2630        assert!(file.channel_names.is_empty());
2631        // A newer host's field round-trips, and older plugins ignore it.
2632        let file = FileInfo {
2633            channel_names: vec!["DAPI".into(), "CD45".into()],
2634            ..file
2635        };
2636        let text = serde_json::to_string(&file).unwrap();
2637        assert!(
2638            text.contains(r#""channel_names":["DAPI","CD45"]"#),
2639            "{text}"
2640        );
2641        assert_eq!(serde_json::from_str::<FileInfo>(&text).unwrap(), file);
2642    }
2643
2644    fn level(width: u64, height: u64, downsample: Option<f64>) -> SlideLevel {
2645        SlideLevel {
2646            width,
2647            height,
2648            downsample,
2649            ..SlideLevel::default()
2650        }
2651    }
2652
2653    #[test]
2654    fn slide_infos_are_validated_as_eov_does() {
2655        let good = SlideInfo {
2656            levels: vec![
2657                level(1000, 800, None),
2658                level(250, 200, Some(4.0)),
2659                level(63, 50, None),
2660            ],
2661            associated_images: vec![AssociatedImageInfo {
2662                name: "label".into(),
2663                width: 10,
2664                height: 10,
2665            }],
2666            ..SlideInfo::default()
2667        };
2668        assert_eq!(good.validate(), Ok(()));
2669        // Sparse JSON is enough.
2670        let parsed: SlideInfo =
2671            serde_json::from_str(r#"{"levels":[{"width":10,"height":10}]}"#).unwrap();
2672        assert_eq!(parsed.validate(), Ok(()));
2673
2674        let bad = |change: &dyn Fn(&mut SlideInfo)| {
2675            let mut info = good.clone();
2676            change(&mut info);
2677            info.validate().unwrap_err()
2678        };
2679        assert!(bad(&|i| i.levels.clear()).contains("levels"));
2680        assert!(bad(&|i| i.levels[0].width = 0).contains("sides"));
2681        assert!(bad(&|i| i.levels[0].height = MAX_SLIDE_SIDE + 1).contains("sides"));
2682        assert!(bad(&|i| i.levels[1].width = 2000).contains("larger"));
2683        assert!(bad(&|i| i.levels[0].downsample = Some(2.0)).contains("level 0"));
2684        assert!(bad(&|i| i.levels[1].downsample = Some(f64::NAN)).contains("downsample"));
2685        assert!(bad(&|i| i.levels[1].downsample = Some(40.0)).contains("downsample 40"));
2686        // A level of the previous one's size with a smaller downsample.
2687        assert!(bad(&|i| i.levels[2] = level(250, 200, Some(3.9))).contains("smaller downsample"));
2688        assert!(bad(&|i| i.levels[2].downsample = Some(3.5)).contains("downsample 3.5"));
2689        assert!(
2690            bad(&|i| i.associated_images.push(i.associated_images[0].clone())).contains("twice")
2691        );
2692        assert!(bad(&|i| i.associated_images[0].width = 0).contains("label"));
2693        assert!(bad(&|i| i.associated_images[0].name = String::new()).contains("names"));
2694    }
2695
2696    #[test]
2697    fn model_events_and_requests_are_additive() {
2698        // Only the request id is required, so later fields stay optional.
2699        let event: HostEvent =
2700            serde_json::from_str(r#"{"type":"model_fetched","request_id":"model-1"}"#).unwrap();
2701        assert_eq!(
2702            event,
2703            HostEvent::ModelFetched {
2704                request_id: "model-1".into(),
2705                path: None,
2706                model: None,
2707                error: None,
2708                cancelled: false,
2709            }
2710        );
2711        let args: ModelFetchArgs = serde_json::from_str(
2712            r#"{"sha256":"70a8deef1f01716efbc87feb181ea398425d08b5e4984ad9d4ab2b83fd354f92"}"#,
2713        )
2714        .unwrap();
2715        assert!(args.validate().is_ok());
2716        let record: ModelRecord =
2717            serde_json::from_str(r#"{"sha256":"a","path":"/m","file_name":"m","size":1}"#).unwrap();
2718        assert!(record.companions.is_empty() && !record.read_only);
2719    }
2720
2721    #[test]
2722    fn model_requests_are_validated() {
2723        let sha = "70a8deef1f01716efbc87feb181ea398425d08b5e4984ad9d4ab2b83fd354f92";
2724        let base = ModelFetchArgs {
2725            sha256: sha.into(),
2726            ..Default::default()
2727        };
2728        assert!(base.validate().is_ok());
2729        let upper = ModelFetchArgs {
2730            sha256: sha.to_ascii_uppercase(),
2731            ..base.clone()
2732        };
2733        assert!(upper.validate().is_ok(), "either case is hex");
2734        for bad in [
2735            ModelFetchArgs {
2736                sha256: "70a8".into(),
2737                ..base.clone()
2738            },
2739            ModelFetchArgs {
2740                size: Some(0),
2741                ..base.clone()
2742            },
2743            ModelFetchArgs {
2744                file_name: Some("../escape.onnx".into()),
2745                ..base.clone()
2746            },
2747            ModelFetchArgs {
2748                file_name: Some("m.onnx".into()),
2749                companions: vec![ModelFileSpec {
2750                    sha256: sha.into(),
2751                    file_name: Some("M.ONNX".into()),
2752                    ..Default::default()
2753                }],
2754                ..base.clone()
2755            },
2756        ] {
2757            assert!(bad.validate().is_err(), "{bad:?}");
2758        }
2759        for name in [
2760            "",
2761            ".hidden",
2762            "a/b",
2763            "a\\b",
2764            "c:x",
2765            "CON",
2766            "com1.onnx",
2767            "x.",
2768            "x\n",
2769        ] {
2770            assert!(check_model_file_name(name).is_err(), "{name:?}");
2771        }
2772        for name in [
2773            "model.onnx",
2774            "HistoVae_reconstruct.onnx.data",
2775            "console.onnx",
2776            "aaé.onnx",
2777        ] {
2778            assert!(check_model_file_name(name).is_ok(), "{name:?}");
2779        }
2780    }
2781
2782    #[test]
2783    fn rgba_hex_round_trip() {
2784        assert_eq!(Rgba::from_hex("#FF8000"), Some(Rgba(255, 128, 0, 255)));
2785        assert_eq!(Rgba::from_hex("#ff800080"), Some(Rgba(255, 128, 0, 128)));
2786        assert_eq!(Rgba::from_hex("FF8000"), None);
2787        assert_eq!(Rgba::from_hex("#aé0000"), None);
2788        assert_eq!(Rgba(1, 2, 3, 255).to_hex(), "#010203");
2789        assert_eq!(Rgba::from_u32(Rgba(9, 8, 7, 6).to_u32()), Rgba(9, 8, 7, 6));
2790    }
2791}