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