use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::collections::BTreeMap;
pub type FileId = i64;
pub type PaneId = u32;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PluginInit {
pub plugin_id: String,
pub plugin_version: String,
pub host_name: String,
pub host_version: String,
pub api_version: String,
pub plugin_root: String,
pub data_dir: String,
pub cache_dir: String,
#[serde(default)]
pub settings: Map<String, Value>,
#[serde(default)]
pub legacy_config_dir: Option<String>,
#[serde(default)]
pub headless: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
pub struct Rect {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct LevelInfo {
pub level: u32,
pub width: u64,
pub height: u64,
pub downsample: f64,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct FileInfo {
pub file_id: FileId,
pub path: String,
pub filename: String,
pub width: u64,
pub height: u64,
#[serde(default)]
pub levels: Vec<LevelInfo>,
#[serde(default)]
pub mpp_x: Option<f64>,
#[serde(default)]
pub mpp_y: Option<f64>,
#[serde(default)]
pub objective_power: Option<f64>,
#[serde(default)]
pub vendor: Option<String>,
#[serde(default)]
pub scan_date: Option<String>,
#[serde(default)]
pub bounds: Option<Rect>,
#[serde(default)]
pub identity: Option<String>,
#[serde(default)]
pub associated_images: Vec<String>,
#[serde(default)]
pub has_icc_profile: bool,
#[serde(default)]
pub stain: Option<String>,
#[serde(default)]
pub channel_names: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ViewInfo {
pub pane: PaneId,
pub file_id: FileId,
pub center_x: f64,
pub center_y: f64,
pub zoom: f64,
pub width: f64,
pub height: f64,
#[serde(default = "default_scale_factor")]
pub scale_factor: f64,
#[serde(default)]
pub rotation_deg: f64,
#[serde(default)]
pub flipped: bool,
pub visible: Rect,
}
fn default_scale_factor() -> f64 {
1.0
}
impl Default for ViewInfo {
fn default() -> Self {
Self {
pane: Default::default(),
file_id: Default::default(),
center_x: 0.0,
center_y: 0.0,
zoom: 0.0,
width: 0.0,
height: 0.0,
scale_factor: default_scale_factor(),
rotation_deg: 0.0,
flipped: false,
visible: Rect::default(),
}
}
}
impl ViewInfo {
fn turn(&self, x: f64, y: f64) -> (f64, f64) {
let (sin, cos) = self.rotation_deg.to_radians().sin_cos();
let (tx, ty) = (x * cos - y * sin, x * sin + y * cos);
if self.flipped { (-tx, ty) } else { (tx, ty) }
}
pub fn image_to_screen(&self, x: f64, y: f64) -> (f64, f64) {
let (dx, dy) = self.turn(x - self.center_x, y - self.center_y);
(
self.width / 2.0 + dx * self.zoom,
self.height / 2.0 + dy * self.zoom,
)
}
pub fn screen_to_image(&self, x: f64, y: f64) -> (f64, f64) {
let zoom = if self.zoom > 0.0 { self.zoom } else { 1.0 };
let (mut dx, dy) = (
(x - self.width / 2.0) / zoom,
(y - self.height / 2.0) / zoom,
);
if self.flipped {
dx = -dx;
}
let (sin, cos) = (-self.rotation_deg).to_radians().sin_cos();
(
self.center_x + dx * cos - dy * sin,
self.center_y + dx * sin + dy * cos,
)
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct PaneInfo {
pub pane: PaneId,
pub index: u32,
#[serde(default)]
pub file_id: Option<FileId>,
#[serde(default)]
pub view: Option<ViewInfo>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ToolRef {
#[serde(default)]
pub plugin_id: Option<String>,
pub tool_id: String,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct HostSnapshot {
pub host_version: String,
#[serde(default)]
pub window_focused: bool,
#[serde(default)]
pub render_backend: String,
#[serde(default)]
pub filtering_mode: String,
#[serde(default)]
pub focused_pane: Option<PaneId>,
#[serde(default)]
pub panes: Vec<PaneInfo>,
#[serde(default)]
pub files: Vec<FileInfo>,
#[serde(default)]
pub active_tool: Option<ToolRef>,
}
impl HostSnapshot {
pub fn focused_view(&self) -> Option<&ViewInfo> {
let pane = self.focused_pane?;
self.panes.iter().find(|p| p.pane == pane)?.view.as_ref()
}
pub fn file(&self, file_id: FileId) -> Option<&FileInfo> {
self.files.iter().find(|f| f.file_id == file_id)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Modifiers {
#[serde(default)]
pub shift: bool,
#[serde(default)]
pub control: bool,
#[serde(default)]
pub alt: bool,
#[serde(default)]
pub meta: bool,
#[serde(default)]
pub primary: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PointerButton {
#[default]
None,
Left,
Right,
Middle,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PointerKind {
Down,
Move,
Up,
DoubleClick,
Wheel,
Leave,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct PointerEvent {
pub kind: PointerKind,
#[serde(default)]
pub button: PointerButton,
pub image_x: f64,
pub image_y: f64,
pub screen_x: f64,
pub screen_y: f64,
#[serde(default)]
pub modifiers: Modifiers,
#[serde(default)]
pub wheel_delta: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Shape {
Point {
x: f64,
y: f64,
},
Polyline {
points: Vec<[f64; 2]>,
},
Polygon {
exterior: Vec<[f64; 2]>,
#[serde(default)]
holes: Vec<Vec<[f64; 2]>>,
},
Rectangle {
x: f64,
y: f64,
width: f64,
height: f64,
},
Ellipse {
cx: f64,
cy: f64,
rx: f64,
ry: f64,
},
Text {
x: f64,
y: f64,
text: String,
},
}
impl Shape {
pub fn is_valid(&self) -> bool {
let finite = |p: &[f64; 2]| p[0].is_finite() && p[1].is_finite();
match self {
Shape::Point { x, y } | Shape::Text { x, y, .. } => x.is_finite() && y.is_finite(),
Shape::Polyline { points } => points.len() >= 2 && points.iter().all(finite),
Shape::Polygon { exterior, holes } => {
exterior.len() >= 3
&& exterior.iter().all(finite)
&& holes
.iter()
.all(|ring| ring.len() >= 3 && ring.iter().all(finite))
}
Shape::Rectangle {
x,
y,
width,
height,
} => {
[x, y, width, height].iter().all(|v| v.is_finite())
&& *width >= 0.0
&& *height >= 0.0
}
Shape::Ellipse { cx, cy, rx, ry } => {
[cx, cy, rx, ry].iter().all(|v| v.is_finite()) && *rx >= 0.0 && *ry >= 0.0
}
}
}
pub fn bounds(&self) -> Rect {
fn of_points<'a>(points: impl Iterator<Item = &'a [f64; 2]>) -> Rect {
let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
for p in points {
x0 = x0.min(p[0]);
y0 = y0.min(p[1]);
x1 = x1.max(p[0]);
y1 = y1.max(p[1]);
}
if x0 > x1 {
return Rect::default();
}
Rect {
x: x0,
y: y0,
width: x1 - x0,
height: y1 - y0,
}
}
match self {
Shape::Point { x, y } | Shape::Text { x, y, .. } => Rect {
x: *x,
y: *y,
width: 0.0,
height: 0.0,
},
Shape::Polyline { points } => of_points(points.iter()),
Shape::Polygon { exterior, .. } => of_points(exterior.iter()),
Shape::Rectangle {
x,
y,
width,
height,
} => Rect {
x: *x,
y: *y,
width: *width,
height: *height,
},
Shape::Ellipse { cx, cy, rx, ry } => Rect {
x: cx - rx,
y: cy - ry,
width: rx * 2.0,
height: ry * 2.0,
},
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ObjectRef {
pub layer_id: String,
pub object_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OverlayObject {
pub object_id: String,
pub shape: Shape,
#[serde(default)]
pub style: Option<Style>,
#[serde(default)]
pub label: Option<String>,
#[serde(default)]
pub tooltip: Option<String>,
#[serde(default)]
pub editable: Option<bool>,
}
impl OverlayObject {
pub fn new(object_id: impl Into<String>, shape: Shape) -> Self {
Self {
object_id: object_id.into(),
shape,
style: None,
label: None,
tooltip: None,
editable: None,
}
}
pub fn with_style(mut self, style: Style) -> Self {
self.style = Some(style);
self
}
pub fn with_label(mut self, label: impl Into<String>) -> Self {
self.label = Some(label.into());
self
}
pub fn with_tooltip(mut self, tooltip: impl Into<String>) -> Self {
self.tooltip = Some(tooltip.into());
self
}
pub fn with_editable(mut self, editable: bool) -> Self {
self.editable = Some(editable);
self
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MeasurementInfo {
pub measurement_id: String,
pub file_id: FileId,
pub shape: Shape,
#[serde(default)]
pub length_um: Option<f64>,
#[serde(default)]
pub area_um2: Option<f64>,
#[serde(default)]
pub angle_deg: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MenuItem {
pub item_id: String,
pub label: String,
#[serde(default)]
pub icon: String,
#[serde(default = "default_true")]
pub enabled: bool,
#[serde(default)]
pub checked: Option<bool>,
#[serde(default)]
pub shortcut: String,
#[serde(default)]
pub separator_after: bool,
}
fn default_true() -> bool {
true
}
impl Default for MenuItem {
fn default() -> Self {
Self {
item_id: String::new(),
label: String::new(),
icon: String::new(),
enabled: default_true(),
checked: None,
shortcut: String::new(),
separator_after: false,
}
}
}
pub fn key_name(text: &str) -> String {
let mut chars = text.chars();
let (Some(c), None) = (chars.next(), chars.next()) else {
return text.to_lowercase();
};
match c {
'\u{8}' => "Backspace".into(),
'\t' => "Tab".into(),
'\n' | '\r' => "Enter".into(),
'\u{1b}' => "Escape".into(),
'\u{7f}' => "Delete".into(),
' ' => "Space".into(),
'\u{F700}' => "ArrowUp".into(),
'\u{F701}' => "ArrowDown".into(),
'\u{F702}' => "ArrowLeft".into(),
'\u{F703}' => "ArrowRight".into(),
'\u{F704}'..='\u{F71B}' => format!("F{}", c as u32 - 0xF704 + 1),
'\u{F729}' => "Home".into(),
'\u{F72B}' => "End".into(),
'\u{F72C}' => "PageUp".into(),
'\u{F72D}' => "PageDown".into(),
c => c.to_lowercase().collect(),
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Hotkey {
pub key: String,
#[serde(default)]
pub modifiers: Modifiers,
#[serde(default)]
pub momentary: bool,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct HotkeySpec {
pub hotkey_id: String,
pub hotkey: Hotkey,
#[serde(default)]
pub description: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LogLevel {
Trace,
Debug,
#[default]
Info,
Warn,
Error,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Rgba(pub u8, pub u8, pub u8, pub u8);
impl Rgba {
pub const TRANSPARENT: Self = Self(0, 0, 0, 0);
pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
Self(r, g, b, 255)
}
pub const fn with_alpha(self, alpha: u8) -> Self {
Self(self.0, self.1, self.2, alpha)
}
pub const fn to_u32(self) -> u32 {
((self.0 as u32) << 24) | ((self.1 as u32) << 16) | ((self.2 as u32) << 8) | self.3 as u32
}
pub const fn from_u32(value: u32) -> Self {
Self(
(value >> 24) as u8,
(value >> 16) as u8,
(value >> 8) as u8,
value as u8,
)
}
pub fn from_hex(text: &str) -> Option<Self> {
let hex = text.strip_prefix('#')?;
if !hex.chars().all(|c| c.is_ascii_hexdigit()) {
return None;
}
let byte = |i: usize| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok();
match hex.len() {
6 => Some(Self(byte(0)?, byte(2)?, byte(4)?, 255)),
8 => Some(Self(byte(0)?, byte(2)?, byte(4)?, byte(6)?)),
_ => None,
}
}
pub fn to_hex(self) -> String {
if self.3 == 255 {
format!("#{:02X}{:02X}{:02X}", self.0, self.1, self.2)
} else {
format!("#{:02X}{:02X}{:02X}{:02X}", self.0, self.1, self.2, self.3)
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Dash {
#[default]
Solid,
Dashed,
Dotted,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SizeUnit {
#[default]
Screen,
Micrometre,
Image,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Style {
#[serde(default)]
pub fill: Rgba,
#[serde(default = "default_stroke")]
pub stroke: Rgba,
#[serde(default = "default_stroke_width")]
pub stroke_width: f32,
#[serde(default)]
pub dash: Dash,
#[serde(default = "default_point_radius")]
pub point_radius: f32,
#[serde(default)]
pub size_unit: SizeUnit,
#[serde(default = "default_text_color")]
pub text_color: Rgba,
#[serde(default = "default_font_size")]
pub font_size: f32,
}
fn default_stroke() -> Rgba {
Rgba::rgb(0x2E, 0xCC, 0x71)
}
fn default_stroke_width() -> f32 {
1.5
}
fn default_point_radius() -> f32 {
5.0
}
fn default_text_color() -> Rgba {
Rgba::rgb(255, 255, 255)
}
fn default_font_size() -> f32 {
12.0
}
impl Default for Style {
fn default() -> Self {
Self {
fill: Rgba::TRANSPARENT,
stroke: default_stroke(),
stroke_width: default_stroke_width(),
dash: Dash::Solid,
point_radius: default_point_radius(),
size_unit: SizeUnit::Screen,
text_color: default_text_color(),
font_size: default_font_size(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LayerSpec {
pub layer_id: String,
pub file_id: FileId,
#[serde(default)]
pub name: String,
#[serde(default)]
pub z: i32,
#[serde(default = "default_true")]
pub visible: bool,
#[serde(default = "default_opacity")]
pub opacity: f32,
#[serde(default)]
pub interactive: bool,
#[serde(default)]
pub editable: bool,
#[serde(default)]
pub style: Style,
#[serde(default)]
pub selected_style: Option<Style>,
#[serde(default)]
pub hover_style: Option<Style>,
#[serde(default)]
pub min_zoom: Option<f64>,
}
fn default_opacity() -> f32 {
1.0
}
impl LayerSpec {
pub fn new(layer_id: impl Into<String>, file_id: FileId) -> Self {
Self {
layer_id: layer_id.into(),
file_id,
name: String::new(),
z: 0,
visible: true,
opacity: 1.0,
interactive: false,
editable: false,
style: Style::default(),
selected_style: None,
hover_style: None,
min_zoom: None,
}
}
pub fn named(mut self, name: impl Into<String>) -> Self {
self.name = name.into();
self
}
pub fn with_style(mut self, style: Style) -> Self {
self.style = style;
self
}
pub fn interactive(mut self, interactive: bool) -> Self {
self.interactive = interactive;
self
}
pub fn editable(mut self, editable: bool) -> Self {
self.editable = editable;
self
}
pub fn at_z(mut self, z: i32) -> Self {
self.z = z;
self
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct LayerUpdate {
pub layer_id: String,
#[serde(default)]
pub name: Option<String>,
#[serde(default)]
pub z: Option<i32>,
#[serde(default)]
pub visible: Option<bool>,
#[serde(default)]
pub opacity: Option<f32>,
#[serde(default)]
pub interactive: Option<bool>,
#[serde(default)]
pub editable: Option<bool>,
#[serde(default)]
pub style: Option<Style>,
#[serde(default)]
pub selected_style: Option<Style>,
#[serde(default)]
pub hover_style: Option<Style>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolbarButtonSpec {
pub button_id: String,
pub tooltip: String,
pub icon_svg: String,
#[serde(default)]
pub toggled_icon_svg: Option<String>,
#[serde(default)]
pub active: bool,
#[serde(default = "default_true")]
pub enabled: bool,
#[serde(default)]
pub hotkey: Option<Hotkey>,
#[serde(default)]
pub order: i32,
}
impl Default for ToolbarButtonSpec {
fn default() -> Self {
Self {
button_id: String::new(),
tooltip: String::new(),
icon_svg: String::new(),
toggled_icon_svg: None,
active: false,
enabled: default_true(),
hotkey: None,
order: 0,
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ButtonUpdate {
pub button_id: String,
#[serde(default)]
pub pane: Option<PaneId>,
#[serde(default)]
pub active: Option<bool>,
#[serde(default)]
pub enabled: Option<bool>,
#[serde(default)]
pub tooltip: Option<String>,
#[serde(default)]
pub icon_svg: Option<String>,
#[serde(default)]
pub menu: Option<Vec<MenuItem>>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct HudButtonSpec {
pub button_id: String,
pub tooltip: String,
pub icon_svg: String,
#[serde(default)]
pub toggled_icon_svg: Option<String>,
#[serde(default)]
pub active: bool,
#[serde(default)]
pub menu: Vec<MenuItem>,
#[serde(default)]
pub order: i32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolKind {
Point,
Polyline,
Polygon,
Rectangle,
Ellipse,
Freehand,
Custom,
Select,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Cursor {
#[default]
Default,
Crosshair,
Pointer,
Move,
Text,
NotAllowed,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolSpec {
pub tool_id: String,
pub label: String,
pub icon_svg: String,
pub kind: ToolKind,
#[serde(default)]
pub hotkey: Option<Hotkey>,
#[serde(default)]
pub cursor: Cursor,
#[serde(default)]
pub edit_layers: Vec<String>,
#[serde(default)]
pub preview_style: Option<Style>,
#[serde(default = "default_freehand_tolerance")]
pub freehand_tolerance_px: f32,
#[serde(default)]
pub order: i32,
#[serde(default)]
pub keys: Option<Vec<String>>,
}
fn default_freehand_tolerance() -> f32 {
1.5
}
impl ToolSpec {
pub fn new(
tool_id: impl Into<String>,
label: impl Into<String>,
icon_svg: impl Into<String>,
kind: ToolKind,
) -> Self {
Self {
tool_id: tool_id.into(),
label: label.into(),
icon_svg: icon_svg.into(),
kind,
hotkey: None,
cursor: Cursor::Crosshair,
edit_layers: Vec::new(),
preview_style: None,
freehand_tolerance_px: default_freehand_tolerance(),
order: 0,
keys: None,
}
}
pub fn with_hotkey(mut self, hotkey: Hotkey) -> Self {
self.hotkey = Some(hotkey);
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SurfaceKind {
Sidebar,
Window,
Modal,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SurfaceSpec {
pub kind: SurfaceKind,
pub ui_path: String,
pub component: String,
#[serde(default)]
pub title: Option<String>,
#[serde(default)]
pub width: Option<f32>,
#[serde(default)]
pub height: Option<f32>,
#[serde(default)]
pub min_width: Option<f32>,
#[serde(default)]
pub min_height: Option<f32>,
#[serde(default)]
pub properties: Map<String, Value>,
#[serde(default = "default_true")]
pub capture_keyboard: bool,
}
impl SurfaceSpec {
pub fn new(
kind: SurfaceKind,
ui_path: impl Into<String>,
component: impl Into<String>,
) -> Self {
Self {
kind,
ui_path: ui_path.into(),
component: component.into(),
title: None,
width: None,
height: None,
min_width: None,
min_height: None,
properties: Map::new(),
capture_keyboard: true,
}
}
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
pub fn with_size(mut self, width: f32, height: Option<f32>) -> Self {
self.width = Some(width);
self.height = height;
self
}
pub fn with_property(mut self, name: impl Into<String>, value: Value) -> Self {
self.properties.insert(name.into(), value);
self
}
}
impl Hotkey {
pub fn key(key: impl Into<String>) -> Self {
Self {
key: key.into(),
modifiers: Modifiers::default(),
momentary: false,
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct FileFilter {
pub name: String,
pub extensions: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FilterSpec {
pub filter_id: String,
pub name: String,
#[serde(default)]
pub priority: i32,
#[serde(default)]
pub enabled: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NotifyLevel {
#[default]
Info,
Success,
Warning,
Error,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum HostEvent {
Ready {
#[serde(default)]
restore_sidebar: bool,
},
Shutdown,
FileOpened {
file: FileInfo,
},
FileClosed {
file_id: FileId,
},
ActiveChanged {
#[serde(default)]
pane: Option<PaneId>,
#[serde(default)]
file_id: Option<FileId>,
},
ViewChanged {
view: ViewInfo,
},
WindowFocusChanged {
focused: bool,
},
ToolbarButtonClicked {
button_id: String,
},
HudButtonClicked {
button_id: String,
#[serde(default)]
item_id: Option<String>,
pane: PaneId,
#[serde(default)]
view: Option<ViewInfo>,
},
ContextMenuRequested(MenuContext),
ContextMenuItemSelected {
item_id: String,
context: MenuContext,
},
ToolActivated {
tool_id: String,
},
ToolDeactivated {
tool_id: String,
},
ShapeDrawn {
tool_id: String,
pane: PaneId,
file_id: FileId,
shape: Shape,
#[serde(default)]
modifiers: Modifiers,
},
Pointer {
tool_id: String,
pane: PaneId,
file_id: FileId,
event: PointerEvent,
},
Key {
#[serde(default)]
tool_id: Option<String>,
#[serde(default)]
pane: Option<PaneId>,
key: String,
#[serde(default)]
modifiers: Modifiers,
pressed: bool,
#[serde(default)]
repeat: bool,
},
ObjectClicked {
object: ObjectRef,
pane: PaneId,
#[serde(default)]
button: PointerButton,
#[serde(default)]
modifiers: Modifiers,
#[serde(default = "default_click_count")]
click_count: u32,
},
ObjectHovered {
#[serde(default)]
object: Option<ObjectRef>,
pane: PaneId,
},
ObjectEdited {
object: ObjectRef,
shape: Shape,
},
ObjectsDeleteRequested {
objects: Vec<ObjectRef>,
},
SelectionChanged {
objects: Vec<ObjectRef>,
},
Posted {
token: String,
},
EmptyAreaClicked {
pane: PaneId,
#[serde(default)]
file_id: Option<FileId>,
#[serde(default)]
modifiers: Modifiers,
},
Undo {
entry_id: String,
},
Redo {
entry_id: String,
},
UiCallback {
surface_id: String,
name: String,
#[serde(default)]
args: Vec<Value>,
},
SurfaceClosed {
surface_id: String,
},
DialogResult {
request_id: String,
#[serde(default)]
paths: Vec<String>,
},
ConfirmResult {
request_id: String,
confirmed: bool,
},
JobCancelRequested {
job_id: String,
},
FilterToggled {
filter_id: String,
enabled: bool,
},
UndoDropped {
entry_ids: Vec<String>,
},
HotkeyPressed {
hotkey_id: String,
#[serde(default)]
pane: Option<PaneId>,
},
RegistrationRefused {
what: String,
id: String,
reason: String,
},
DisplayChanged {
pane: PaneId,
display: DisplayAdjustments,
},
RoiChanged {
file_id: FileId,
#[serde(default)]
roi: Option<Rect>,
},
BatchRun {
run_id: String,
command_id: String,
file: FileInfo,
output_dir: String,
#[serde(default)]
params: Map<String, Value>,
},
ModelFetched {
request_id: String,
#[serde(default)]
path: Option<String>,
#[serde(default)]
model: Option<ModelRecord>,
#[serde(default)]
error: Option<String>,
#[serde(default)]
cancelled: bool,
},
#[serde(other)]
Unknown,
}
fn default_click_count() -> u32 {
1
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MenuContext {
pub pane: PaneId,
pub view: ViewInfo,
pub image_x: f64,
pub image_y: f64,
#[serde(default)]
pub hit: Option<ObjectRef>,
#[serde(default)]
pub selection: Vec<ObjectRef>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ContextMenuResponse {
#[serde(default)]
pub items: Vec<MenuItem>,
}
pub mod methods {
pub const LOG: &str = "log";
pub const NOTIFY: &str = "notify";
pub const STATUS: &str = "status";
pub const SNAPSHOT: &str = "snapshot";
pub const FILE_INFO: &str = "file.info";
pub const FILE_PROPERTIES: &str = "file.properties";
pub const FILE_OPEN: &str = "file.open";
pub const TOOLBAR_ADD: &str = "toolbar.add";
pub const TOOLBAR_UPDATE: &str = "toolbar.update";
pub const TOOLBAR_REMOVE: &str = "toolbar.remove";
pub const HUD_ADD: &str = "hud.add";
pub const HUD_UPDATE: &str = "hud.update";
pub const HUD_REMOVE: &str = "hud.remove";
pub const HOTKEY_REGISTER: &str = "hotkey.register";
pub const HOTKEY_UNREGISTER: &str = "hotkey.unregister";
pub const TOOL_REGISTER: &str = "tool.register";
pub const TOOL_UNREGISTER: &str = "tool.unregister";
pub const TOOL_ACTIVATE: &str = "tool.activate";
pub const TOOL_DEACTIVATE: &str = "tool.deactivate";
pub const LAYER_CREATE: &str = "layer.create";
pub const LAYER_UPDATE: &str = "layer.update";
pub const LAYER_REMOVE: &str = "layer.remove";
pub const LAYER_SELECT: &str = "layer.select";
pub const LAYER_UPSERT: &str = "layer.upsert";
pub const LAYER_REMOVE_OBJECTS: &str = "layer.remove_objects";
pub const LAYER_CLEAR: &str = "layer.clear";
pub const BADGE_SET: &str = "badge.set";
pub const LAYER_HIGHLIGHT: &str = "layer.highlight";
pub const LAYER_SET_MIN_ZOOM: &str = "layer.set_min_zoom";
pub const LAYER_SET_PANE_VISIBILITY: &str = "layer.set_pane_visibility";
pub const LAYER_SET_PANES: &str = "layer.set_panes";
pub const SURFACE_OPEN: &str = "surface.open";
pub const SURFACE_SET: &str = "surface.set";
pub const SURFACE_CLOSE: &str = "surface.close";
pub const SURFACE_IS_OPEN: &str = "surface.is_open";
pub const DIALOG_CONFIRM: &str = "dialog.confirm";
pub const DIALOG_OPEN_FILE: &str = "dialog.open_file";
pub const DIALOG_SAVE_FILE: &str = "dialog.save_file";
pub const VIEW_SET: &str = "view.set";
pub const VIEW_PAN: &str = "view.pan";
pub const VIEW_ZOOM: &str = "view.zoom";
pub const VIEW_FIT: &str = "view.fit";
pub const VIEW_FRAME: &str = "view.frame";
pub const VIEW_ORIENTATION: &str = "view.orientation";
pub const VIEW_DISPLAY: &str = "view.display";
pub const BATCH_REGISTER: &str = "batch.register";
pub const BATCH_PROGRESS: &str = "batch.progress";
pub const BATCH_FINISH: &str = "batch.finish";
pub const APP_CYCLE_PANE: &str = "app.cycle_pane";
pub const APP_CYCLE_TAB: &str = "app.cycle_tab";
pub const APP_SERIES: &str = "app.series";
pub const RENDER_REQUEST: &str = "render.request";
pub const UNDO_PUSH: &str = "undo.push";
pub const UNDO_CLEAR: &str = "undo.clear";
pub const FILTER_REGISTER: &str = "filter.register";
pub const FILTER_SET_ENABLED: &str = "filter.set_enabled";
pub const FILTER_UNREGISTER: &str = "filter.unregister";
pub const SETTINGS_GET: &str = "settings.get";
pub const SETTINGS_SET: &str = "settings.set";
pub const JOB_START: &str = "job.start";
pub const JOB_UPDATE: &str = "job.update";
pub const JOB_FINISH: &str = "job.finish";
pub const CLIPBOARD_SET_TEXT: &str = "clipboard.set_text";
pub const ROI_GET: &str = "roi.get";
pub const MEASUREMENTS_LIST: &str = "measurements.list";
pub const MODEL_FETCH: &str = "model.fetch";
pub const MODEL_RESOLVE: &str = "model.resolve";
pub const MODEL_LIST: &str = "model.list";
pub const POST: &str = "post";
pub const EVENTS_SUBSCRIBE: &str = "events.subscribe";
}
pub mod event_names {
pub const FILE_OPENED: &str = "file_opened";
pub const FILE_CLOSED: &str = "file_closed";
pub const ACTIVE_CHANGED: &str = "active_changed";
pub const VIEW_CHANGED: &str = "view_changed";
pub const WINDOW_FOCUS_CHANGED: &str = "window_focus_changed";
pub const OBJECT_HOVERED: &str = "object_hovered";
pub const EMPTY_AREA_CLICKED: &str = "empty_area_clicked";
pub const CONTEXT_MENU_REQUESTED: &str = "context_menu_requested";
pub const ROI_CHANGED: &str = "roi_changed";
pub const HOTKEY_PRESSED: &str = "hotkey_pressed";
pub const DISPLAY_CHANGED: &str = "display_changed";
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LogArgs {
pub level: LogLevel,
pub message: String,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct NotifyArgs {
#[serde(default)]
pub level: NotifyLevel,
pub message: String,
#[serde(default)]
pub detail: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct StatusArgs {
#[serde(default)]
pub text: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct FileArgs {
pub file_id: FileId,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OpenFileArgs {
pub path: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct IdArgs {
pub id: String,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct BatchCommandSpec {
pub command_id: String,
pub description: String,
#[serde(default)]
pub params: Vec<BatchParam>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct BatchParam {
pub name: String,
#[serde(default)]
pub description: String,
#[serde(default)]
pub default: Value,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct BatchProgressArgs {
pub run_id: String,
#[serde(default)]
pub fraction: Option<f32>,
#[serde(default)]
pub message: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct BatchFinishArgs {
pub run_id: String,
pub ok: bool,
#[serde(default)]
pub message: Option<String>,
#[serde(default)]
pub outputs: Vec<String>,
#[serde(default)]
pub summary: Value,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct BadgeArgs {
pub badge_id: String,
#[serde(default)]
pub file_id: Option<FileId>,
#[serde(default)]
pub text: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct MinZoomArgs {
pub layer_id: String,
#[serde(default)]
pub min_zoom: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct PaneVisibilityArgs {
pub layer_id: String,
pub pane: PaneId,
pub visible: bool,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct PaneFilterArgs {
pub layer_id: String,
#[serde(default)]
pub panes: Option<Vec<PaneId>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DisplayAdjustments {
pub gamma: f32,
pub brightness: f32,
pub contrast: f32,
pub sharpness: f32,
#[serde(default)]
pub stain_normalization: Option<String>,
pub modified: bool,
#[serde(default)]
pub badge: String,
#[serde(default)]
pub color_managed: bool,
}
impl Default for DisplayAdjustments {
fn default() -> Self {
Self {
gamma: 1.0,
brightness: 0.0,
contrast: 1.0,
sharpness: 0.0,
stain_normalization: None,
modified: false,
badge: String::new(),
color_managed: false,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SelectArgs {
pub layer_id: String,
pub object_ids: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UpsertObjectsArgs {
pub layer_id: String,
pub objects: Vec<OverlayObject>,
#[serde(default)]
pub replace_all: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RemoveObjectsArgs {
pub layer_id: String,
pub object_ids: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PostArgs {
pub token: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SubscribeArgs {
pub events: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SurfaceOpened {
pub surface_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SurfaceProperties {
pub surface_id: String,
pub properties: Map<String, Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ConfirmArgs {
pub title: String,
pub message: String,
#[serde(default = "default_confirm_label")]
pub confirm_label: String,
#[serde(default = "default_cancel_label")]
pub cancel_label: String,
#[serde(default)]
pub destructive: bool,
}
fn default_confirm_label() -> String {
"OK".to_string()
}
fn default_cancel_label() -> String {
"Cancel".to_string()
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct FileDialogArgs {
#[serde(default)]
pub title: Option<String>,
#[serde(default)]
pub filters: Vec<FileFilter>,
#[serde(default)]
pub default_name: Option<String>,
#[serde(default)]
pub directory: bool,
#[serde(default)]
pub multiple: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RequestId {
pub request_id: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
pub struct PaneArgs {
#[serde(default)]
pub pane: Option<PaneId>,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ViewSetArgs {
#[serde(default)]
pub pane: Option<PaneId>,
pub center_x: f64,
pub center_y: f64,
pub zoom: f64,
#[serde(default)]
pub animate: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ViewPanArgs {
#[serde(default)]
pub pane: Option<PaneId>,
pub dx: f64,
pub dy: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ViewZoomArgs {
#[serde(default)]
pub pane: Option<PaneId>,
pub factor: f64,
#[serde(default)]
pub anchor_x: Option<f64>,
#[serde(default)]
pub anchor_y: Option<f64>,
#[serde(default)]
pub animate: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ViewOrientationArgs {
#[serde(default)]
pub pane: Option<PaneId>,
pub rotation_deg: f64,
#[serde(default)]
pub flipped: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ViewFrameArgs {
#[serde(default)]
pub pane: Option<PaneId>,
pub rect: Rect,
#[serde(default)]
pub padding: Option<f64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct OffsetArgs {
pub offset: i32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SeriesAction {
Toggle,
Next,
Previous,
OpenSelected,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct SeriesArgs {
pub action: SeriesAction,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UndoPushArgs {
pub entry_id: String,
#[serde(default)]
pub file_id: Option<FileId>,
pub label: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
pub struct UndoClearArgs {
#[serde(default)]
pub file_id: Option<FileId>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FilterEnableArgs {
pub filter_id: String,
pub enabled: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct KeyArgs {
pub key: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SettingsSetArgs {
pub key: String,
pub value: Value,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JobStartArgs {
pub title: String,
#[serde(default)]
pub cancellable: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JobStarted {
pub job_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JobUpdateArgs {
pub job_id: String,
#[serde(default)]
pub fraction: Option<f32>,
#[serde(default)]
pub message: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JobFinishArgs {
pub job_id: String,
#[serde(default)]
pub error: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TextArgs {
pub text: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct ModelFileSpec {
pub sha256: String,
#[serde(default)]
pub url: Option<String>,
#[serde(default)]
pub file_name: Option<String>,
#[serde(default)]
pub size: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct ModelFetchArgs {
#[serde(default)]
pub url: Option<String>,
pub sha256: String,
#[serde(default)]
pub size: Option<u64>,
#[serde(default)]
pub file_name: Option<String>,
#[serde(default)]
pub name: Option<String>,
#[serde(default)]
pub version: Option<String>,
#[serde(default)]
pub companions: Vec<ModelFileSpec>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct ModelResolveArgs {
pub sha256: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct ModelCompanion {
pub file_name: String,
pub sha256: String,
pub size: u64,
#[serde(default)]
pub path: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct ModelRecord {
pub sha256: String,
pub path: String,
pub file_name: String,
pub size: u64,
#[serde(default)]
pub name: Option<String>,
#[serde(default)]
pub version: Option<String>,
#[serde(default)]
pub source: Option<String>,
#[serde(default)]
pub fetched_at: Option<String>,
#[serde(default)]
pub requested_by: Option<String>,
#[serde(default)]
pub companions: Vec<ModelCompanion>,
#[serde(default)]
pub read_only: bool,
}
impl ModelRecord {
pub fn has_companion(&self, sha256: &str, file_name: &str) -> bool {
self.companions
.iter()
.any(|c| c.sha256.eq_ignore_ascii_case(sha256) && c.file_name == file_name)
}
}
pub fn is_sha256_hex(text: &str) -> bool {
text.len() == 64 && text.bytes().all(|b| b.is_ascii_hexdigit())
}
pub fn check_model_file_name(name: &str) -> Result<(), String> {
let stem = name.split('.').next().unwrap_or_default();
let reserved = ["CON", "PRN", "AUX", "NUL"]
.iter()
.any(|r| stem.eq_ignore_ascii_case(r))
|| (stem.len() == 4
&& stem.is_ascii()
&& ["COM", "LPT"]
.iter()
.any(|p| stem[..3].eq_ignore_ascii_case(p))
&& stem.as_bytes()[3].is_ascii_digit());
if name.is_empty()
|| name.len() > 200
|| name.starts_with('.')
|| name.ends_with('.')
|| name.ends_with(' ')
|| name.chars().any(|c| {
c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|')
})
|| reserved
{
return Err(format!(
"'{name}' cannot be a model's file name (use a plain name such as model.onnx)"
));
}
Ok(())
}
impl ModelFileSpec {
fn check(&self, what: &str) -> Result<(), String> {
if !is_sha256_hex(&self.sha256) {
return Err(format!(
"the {what}'s sha256 must be 64 hex digits, not '{}'",
self.sha256
));
}
if let Some(name) = &self.file_name {
check_model_file_name(name)?;
}
if self.size == Some(0) {
return Err(format!("the {what}'s size cannot be 0"));
}
Ok(())
}
}
impl ModelFetchArgs {
pub fn validate(&self) -> Result<(), String> {
ModelFileSpec {
sha256: self.sha256.clone(),
url: self.url.clone(),
file_name: self.file_name.clone(),
size: self.size,
}
.check("model")?;
let mut names: Vec<&str> = self.file_name.iter().map(String::as_str).collect();
for companion in &self.companions {
companion.check("companion")?;
let name = companion.file_name.as_deref();
if companion.url.is_none() && name.is_none() {
return Err("a companion without a url needs a file_name".to_string());
}
if let Some(name) = name {
if names.iter().any(|n| n.eq_ignore_ascii_case(name)) {
return Err(format!("two files of the model are named '{name}'"));
}
names.push(name);
}
}
if self.companions.len() > 64 {
return Err("a model has at most 64 companion files".to_string());
}
Ok(())
}
}
pub type PropertyMap = BTreeMap<String, String>;
pub const MAX_SLIDE_LEVELS: usize = 64;
pub const MAX_SLIDE_SIDE: u64 = 1 << 24;
pub const MAX_ASSOCIATED_IMAGES: usize = 32;
pub const MAX_ASSOCIATED_IMAGE_PIXELS: u64 = 1 << 28;
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct SlideOpenRequest {
pub format_id: String,
pub location: String,
#[serde(default)]
pub is_uri: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
pub struct SlideLevel {
pub width: u64,
pub height: u64,
#[serde(default)]
pub downsample: Option<f64>,
#[serde(default)]
pub tile_width: Option<u32>,
#[serde(default)]
pub tile_height: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct AssociatedImageInfo {
pub name: String,
pub width: u32,
pub height: u32,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct SlideInfo {
pub levels: Vec<SlideLevel>,
#[serde(default)]
pub vendor: Option<String>,
#[serde(default)]
pub mpp_x: Option<f64>,
#[serde(default)]
pub mpp_y: Option<f64>,
#[serde(default)]
pub objective_power: Option<f64>,
#[serde(default)]
pub scan_date: Option<String>,
#[serde(default)]
pub comment: Option<String>,
#[serde(default)]
pub stain: Option<String>,
#[serde(default)]
pub background: Option<[u8; 3]>,
#[serde(default)]
pub bounds: Option<Rect>,
#[serde(default)]
pub properties: PropertyMap,
#[serde(default)]
pub associated_images: Vec<AssociatedImageInfo>,
#[serde(default)]
pub identity: Option<String>,
#[serde(default)]
pub member_files: Vec<String>,
}
impl SlideInfo {
pub fn validate(&self) -> Result<(), String> {
let count = self.levels.len();
if count == 0 || count > MAX_SLIDE_LEVELS {
return Err(format!(
"a slide has 1–{MAX_SLIDE_LEVELS} levels, not {count}"
));
}
let base = self.levels[0];
let mut previous: Option<(SlideLevel, f64)> = None;
for (index, level) in self.levels.iter().enumerate() {
if level.width == 0
|| level.height == 0
|| level.width > MAX_SLIDE_SIDE
|| level.height > MAX_SLIDE_SIDE
{
return Err(format!(
"level {index} is {}×{}; sides must be 1–{MAX_SLIDE_SIDE} pixels",
level.width, level.height
));
}
let ratio = (base.width as f64 / level.width as f64
+ base.height as f64 / level.height as f64)
/ 2.0;
let downsample = level.downsample.unwrap_or(ratio);
if !downsample.is_finite() || downsample < 1.0 {
return Err(format!(
"level {index} has downsample {downsample}; it must be a number of at least 1"
));
}
if index == 0 && (downsample - 1.0).abs() > 1e-6 {
return Err(format!("level 0 has downsample {downsample}, not 1"));
}
if downsample > ratio * 2.0 || downsample < ratio / 2.0 {
return Err(format!(
"level {index} is {}×{} but has downsample {downsample}",
level.width, level.height
));
}
if let Some((prev, prev_downsample)) = previous {
if level.width > prev.width || level.height > prev.height {
return Err(format!(
"level {index} ({}×{}) is larger than level {} ({}×{})",
level.width,
level.height,
index - 1,
prev.width,
prev.height
));
}
if downsample < prev_downsample {
return Err(format!(
"level {index} has a smaller downsample than level {}",
index - 1
));
}
}
previous = Some((*level, downsample));
}
if self.associated_images.len() > MAX_ASSOCIATED_IMAGES {
return Err(format!(
"a slide has at most {MAX_ASSOCIATED_IMAGES} associated images"
));
}
let mut names = std::collections::BTreeSet::new();
for image in &self.associated_images {
let name = image.name.as_str();
if name.is_empty() || name.chars().count() > 64 || name.chars().any(char::is_control) {
return Err(format!(
"associated image names are 1–64 printable characters, not {name:?}"
));
}
if !names.insert(name) {
return Err(format!("associated image {name:?} is listed twice"));
}
let pixels = u64::from(image.width) * u64::from(image.height);
if pixels == 0 || pixels > MAX_ASSOCIATED_IMAGE_PIXELS {
return Err(format!(
"associated image {name:?} is {}×{}",
image.width, image.height
));
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn views_map_screen_and_image_through_their_turn() {
let mut view = ViewInfo {
center_x: 100.0,
center_y: 50.0,
zoom: 2.0,
width: 300.0,
height: 200.0,
..Default::default()
};
assert_eq!(view.image_to_screen(110.0, 50.0), (170.0, 100.0));
view.rotation_deg = 90.0;
let (x, y) = view.image_to_screen(110.0, 50.0);
assert!((x - 150.0).abs() < 1e-9 && (y - 120.0).abs() < 1e-9);
for rotation in [0.0, 90.0, 180.0, 270.0, 37.5, 301.25] {
for flipped in [false, true] {
view.rotation_deg = rotation;
view.flipped = flipped;
let (sx, sy) = view.image_to_screen(37.0, 81.0);
let (ix, iy) = view.screen_to_image(sx, sy);
assert!((ix - 37.0).abs() < 1e-9 && (iy - 81.0).abs() < 1e-9);
}
}
let old: ViewInfo = serde_json::from_str(
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}}"#,
)
.unwrap();
assert_eq!((old.rotation_deg, old.flipped), (0.0, false));
}
#[test]
fn unknown_events_deserialize_to_unknown() {
let event: HostEvent =
serde_json::from_str(r#"{"type":"something_from_the_future","x":1}"#).unwrap();
assert_eq!(event, HostEvent::Unknown);
}
#[test]
fn events_round_trip() {
let event = HostEvent::ShapeDrawn {
tool_id: "poly".into(),
pane: 3,
file_id: 7,
shape: Shape::Polygon {
exterior: vec![[0.0, 0.0], [10.0, 0.0], [5.0, 8.0]],
holes: vec![],
},
modifiers: Modifiers::default(),
};
let text = serde_json::to_string(&event).unwrap();
assert!(text.contains(r#""type":"shape_drawn""#), "{text}");
assert!(text.contains(r#""kind":"polygon""#), "{text}");
assert_eq!(serde_json::from_str::<HostEvent>(&text).unwrap(), event);
}
#[test]
fn optional_fields_may_be_absent() {
let event: HostEvent = serde_json::from_str(
r#"{"type":"object_clicked","object":{"layer_id":"l","object_id":"o"},"pane":1}"#,
)
.unwrap();
match event {
HostEvent::ObjectClicked {
click_count,
button,
..
} => {
assert_eq!(click_count, 1);
assert_eq!(button, PointerButton::None);
}
other => panic!("unexpected {other:?}"),
}
let spec: LayerSpec = serde_json::from_str(r#"{"layer_id":"a","file_id":1}"#).unwrap();
assert!(spec.visible);
assert_eq!(spec.opacity, 1.0);
assert_eq!(spec.style, Style::default());
}
#[test]
fn defaults_are_what_absent_fields_deserialize_to() {
let button: ToolbarButtonSpec =
serde_json::from_str(r#"{"button_id":"","tooltip":"","icon_svg":""}"#).unwrap();
assert_eq!(button, ToolbarButtonSpec::default());
assert!(button.enabled);
let item: MenuItem = serde_json::from_str(r#"{"item_id":"","label":""}"#).unwrap();
assert_eq!(item, MenuItem::default());
assert!(item.enabled);
let view: ViewInfo = serde_json::from_str(
r#"{"pane":0,"file_id":0,"center_x":0,"center_y":0,"zoom":0,"width":0,"height":0,
"visible":{"x":0,"y":0,"width":0,"height":0}}"#,
)
.unwrap();
assert_eq!(view, ViewInfo::default());
assert_eq!(view.scale_factor, 1.0);
let sent = serde_json::to_value(ToolbarButtonSpec {
button_id: "b".into(),
..Default::default()
})
.unwrap();
assert_eq!(sent["enabled"], true);
let disabled: ToolbarButtonSpec =
serde_json::from_str(r#"{"button_id":"b","tooltip":"","icon_svg":"","enabled":false}"#)
.unwrap();
assert!(!disabled.enabled);
}
#[test]
fn channel_names_are_optional_both_ways() {
let file: FileInfo = serde_json::from_str(
r#"{"file_id":1,"path":"/s.svs","filename":"s.svs","width":10,"height":20}"#,
)
.unwrap();
assert!(file.channel_names.is_empty());
let file = FileInfo {
channel_names: vec!["DAPI".into(), "CD45".into()],
..file
};
let text = serde_json::to_string(&file).unwrap();
assert!(
text.contains(r#""channel_names":["DAPI","CD45"]"#),
"{text}"
);
assert_eq!(serde_json::from_str::<FileInfo>(&text).unwrap(), file);
}
fn level(width: u64, height: u64, downsample: Option<f64>) -> SlideLevel {
SlideLevel {
width,
height,
downsample,
..SlideLevel::default()
}
}
#[test]
fn slide_infos_are_validated_as_eov_does() {
let good = SlideInfo {
levels: vec![
level(1000, 800, None),
level(250, 200, Some(4.0)),
level(63, 50, None),
],
associated_images: vec![AssociatedImageInfo {
name: "label".into(),
width: 10,
height: 10,
}],
..SlideInfo::default()
};
assert_eq!(good.validate(), Ok(()));
let parsed: SlideInfo =
serde_json::from_str(r#"{"levels":[{"width":10,"height":10}]}"#).unwrap();
assert_eq!(parsed.validate(), Ok(()));
let bad = |change: &dyn Fn(&mut SlideInfo)| {
let mut info = good.clone();
change(&mut info);
info.validate().unwrap_err()
};
assert!(bad(&|i| i.levels.clear()).contains("levels"));
assert!(bad(&|i| i.levels[0].width = 0).contains("sides"));
assert!(bad(&|i| i.levels[0].height = MAX_SLIDE_SIDE + 1).contains("sides"));
assert!(bad(&|i| i.levels[1].width = 2000).contains("larger"));
assert!(bad(&|i| i.levels[0].downsample = Some(2.0)).contains("level 0"));
assert!(bad(&|i| i.levels[1].downsample = Some(f64::NAN)).contains("downsample"));
assert!(bad(&|i| i.levels[1].downsample = Some(40.0)).contains("downsample 40"));
assert!(bad(&|i| i.levels[2] = level(250, 200, Some(3.9))).contains("smaller downsample"));
assert!(bad(&|i| i.levels[2].downsample = Some(3.5)).contains("downsample 3.5"));
assert!(
bad(&|i| i.associated_images.push(i.associated_images[0].clone())).contains("twice")
);
assert!(bad(&|i| i.associated_images[0].width = 0).contains("label"));
assert!(bad(&|i| i.associated_images[0].name = String::new()).contains("names"));
}
#[test]
fn model_events_and_requests_are_additive() {
let event: HostEvent =
serde_json::from_str(r#"{"type":"model_fetched","request_id":"model-1"}"#).unwrap();
assert_eq!(
event,
HostEvent::ModelFetched {
request_id: "model-1".into(),
path: None,
model: None,
error: None,
cancelled: false,
}
);
let args: ModelFetchArgs = serde_json::from_str(
r#"{"sha256":"70a8deef1f01716efbc87feb181ea398425d08b5e4984ad9d4ab2b83fd354f92"}"#,
)
.unwrap();
assert!(args.validate().is_ok());
let record: ModelRecord =
serde_json::from_str(r#"{"sha256":"a","path":"/m","file_name":"m","size":1}"#).unwrap();
assert!(record.companions.is_empty() && !record.read_only);
}
#[test]
fn model_requests_are_validated() {
let sha = "70a8deef1f01716efbc87feb181ea398425d08b5e4984ad9d4ab2b83fd354f92";
let base = ModelFetchArgs {
sha256: sha.into(),
..Default::default()
};
assert!(base.validate().is_ok());
let upper = ModelFetchArgs {
sha256: sha.to_ascii_uppercase(),
..base.clone()
};
assert!(upper.validate().is_ok(), "either case is hex");
for bad in [
ModelFetchArgs {
sha256: "70a8".into(),
..base.clone()
},
ModelFetchArgs {
size: Some(0),
..base.clone()
},
ModelFetchArgs {
file_name: Some("../escape.onnx".into()),
..base.clone()
},
ModelFetchArgs {
file_name: Some("m.onnx".into()),
companions: vec![ModelFileSpec {
sha256: sha.into(),
file_name: Some("M.ONNX".into()),
..Default::default()
}],
..base.clone()
},
] {
assert!(bad.validate().is_err(), "{bad:?}");
}
for name in [
"",
".hidden",
"a/b",
"a\\b",
"c:x",
"CON",
"com1.onnx",
"x.",
"x\n",
] {
assert!(check_model_file_name(name).is_err(), "{name:?}");
}
for name in [
"model.onnx",
"HistoVae_reconstruct.onnx.data",
"console.onnx",
"aaé.onnx",
] {
assert!(check_model_file_name(name).is_ok(), "{name:?}");
}
}
#[test]
fn rgba_hex_round_trip() {
assert_eq!(Rgba::from_hex("#FF8000"), Some(Rgba(255, 128, 0, 255)));
assert_eq!(Rgba::from_hex("#ff800080"), Some(Rgba(255, 128, 0, 128)));
assert_eq!(Rgba::from_hex("FF8000"), None);
assert_eq!(Rgba::from_hex("#aé0000"), None);
assert_eq!(Rgba(1, 2, 3, 255).to_hex(), "#010203");
assert_eq!(Rgba::from_u32(Rgba(9, 8, 7, 6).to_u32()), Rgba(9, 8, 7, 6));
}
}