1use serde::{Deserialize, Serialize};
40use serde_json::{Map, Value};
41use std::collections::BTreeMap;
42
43pub type FileId = i64;
45
46pub type PaneId = u32;
48
49#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
55pub struct PluginInit {
56 pub plugin_id: String,
58 pub plugin_version: String,
60 pub host_name: String,
62 pub host_version: String,
64 pub api_version: String,
66 pub plugin_root: String,
68 pub data_dir: String,
70 pub cache_dir: String,
72 #[serde(default)]
74 pub settings: Map<String, Value>,
75 #[serde(default)]
78 pub legacy_config_dir: Option<String>,
79 #[serde(default)]
83 pub headless: bool,
84 #[serde(default, skip_serializing_if = "Option::is_none")]
91 pub language: Option<String>,
92}
93
94#[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#[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#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
122pub struct FileInfo {
123 pub file_id: FileId,
124 pub path: String,
126 pub filename: String,
127 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 #[serde(default)]
144 pub bounds: Option<Rect>,
145 #[serde(default)]
148 pub identity: Option<String>,
149 #[serde(default)]
151 pub associated_images: Vec<String>,
152 #[serde(default)]
157 pub has_icc_profile: bool,
158 #[serde(default)]
160 pub stain: Option<String>,
161 #[serde(default)]
169 pub channel_names: Vec<String>,
170}
171
172#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
174pub struct ViewInfo {
175 pub pane: PaneId,
176 pub file_id: FileId,
177 pub center_x: f64,
179 pub center_y: f64,
180 pub zoom: f64,
182 pub width: f64,
184 pub height: f64,
185 #[serde(default = "default_scale_factor")]
187 pub scale_factor: f64,
188 #[serde(default)]
195 pub rotation_deg: f64,
196 #[serde(default)]
198 pub flipped: bool,
199 pub visible: Rect,
201}
202
203fn default_scale_factor() -> f64 {
204 1.0
205}
206
207impl 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 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 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 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#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
268pub struct PaneInfo {
269 pub pane: PaneId,
270 pub index: u32,
272 #[serde(default)]
273 pub file_id: Option<FileId>,
274 #[serde(default)]
275 pub view: Option<ViewInfo>,
276}
277
278#[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#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
288pub struct HostSnapshot {
289 pub host_version: String,
290 #[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 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 pub fn file(&self, file_id: FileId) -> Option<&FileInfo> {
316 self.files.iter().find(|f| f.file_id == file_id)
317 }
318}
319
320#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
322pub struct Modifiers {
323 #[serde(default)]
324 pub shift: bool,
325 #[serde(default)]
327 pub control: bool,
328 #[serde(default)]
329 pub alt: bool,
330 #[serde(default)]
332 pub meta: bool,
333 #[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 DoubleClick,
356 Wheel,
357 Leave,
359}
360
361#[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 #[serde(default)]
375 pub wheel_delta: f64,
376}
377
378#[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 {
409 x: f64,
410 y: f64,
411 text: String,
412 },
413}
414
415impl Shape {
416 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 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#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
498pub struct ObjectRef {
499 pub layer_id: String,
500 pub object_id: String,
501}
502
503#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
505pub struct OverlayObject {
506 pub object_id: String,
508 pub shape: Shape,
509 #[serde(default)]
511 pub style: Option<Style>,
512 #[serde(default)]
514 pub label: Option<String>,
515 #[serde(default, skip_serializing_if = "Option::is_none")]
523 pub export_label: Option<String>,
524 #[serde(default)]
526 pub tooltip: Option<String>,
527 #[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 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
591pub struct MeasurementInfo {
592 pub measurement_id: String,
593 pub file_id: FileId,
594 pub shape: Shape,
595 #[serde(default)]
598 pub length_um: Option<f64>,
599 #[serde(default)]
601 pub area_um2: Option<f64>,
602 #[serde(default)]
604 pub angle_deg: Option<f64>,
605}
606
607#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
610pub struct MenuItem {
611 pub item_id: String,
612 pub label: String,
613 #[serde(default)]
616 pub icon: String,
617 #[serde(default = "default_true")]
618 pub enabled: bool,
619 #[serde(default)]
621 pub checked: Option<bool>,
622 #[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
647pub 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#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
680pub struct Hotkey {
681 pub key: String,
682 #[serde(default)]
683 pub modifiers: Modifiers,
684 #[serde(default)]
686 pub momentary: bool,
687}
688
689#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
691pub struct HotkeySpec {
692 pub hotkey_id: String,
693 pub hotkey: Hotkey,
694 #[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#[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 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
778#[serde(rename_all = "snake_case")]
779pub enum SizeUnit {
780 #[default]
782 Screen,
783 Micrometre,
785 Image,
787}
788
789#[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 #[serde(default = "default_point_radius")]
802 pub point_radius: f32,
803 #[serde(default)]
805 pub size_unit: SizeUnit,
806 #[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
847pub struct LayerSpec {
848 pub layer_id: String,
852 pub file_id: FileId,
853 #[serde(default)]
854 pub name: String,
855 #[serde(default)]
857 pub z: i32,
858 #[serde(default = "default_true")]
859 pub visible: bool,
860 #[serde(default = "default_opacity")]
862 pub opacity: f32,
863 #[serde(default)]
865 pub interactive: bool,
866 #[serde(default)]
869 pub editable: bool,
870 #[serde(default)]
871 pub style: Style,
872 #[serde(default)]
874 pub selected_style: Option<Style>,
875 #[serde(default)]
877 pub hover_style: Option<Style>,
878 #[serde(default)]
880 pub min_zoom: Option<f64>,
881}
882
883fn default_opacity() -> f32 {
884 1.0
885}
886
887impl LayerSpec {
888 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#[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
963pub struct ToolbarButtonSpec {
964 pub button_id: String,
965 pub tooltip: String,
966 pub icon_svg: String,
968 #[serde(default)]
969 pub toggled_icon_svg: Option<String>,
970 #[serde(default)]
972 pub active: bool,
973 #[serde(default = "default_true")]
974 pub enabled: bool,
975 #[serde(default)]
977 pub hotkey: Option<Hotkey>,
978 #[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#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1000pub struct ButtonUpdate {
1001 pub button_id: String,
1002 #[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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1036#[serde(rename_all = "snake_case")]
1037pub enum ToolKind {
1038 Point,
1040 Polyline,
1042 Polygon,
1045 Rectangle,
1047 Ellipse,
1049 Freehand,
1051 Custom,
1053 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#[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 #[serde(default)]
1084 pub edit_layers: Vec<String>,
1085 #[serde(default)]
1087 pub preview_style: Option<Style>,
1088 #[serde(default = "default_freehand_tolerance")]
1090 pub freehand_tolerance_px: f32,
1091 #[serde(default)]
1092 pub order: i32,
1093 #[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 Sidebar,
1139 Window,
1141 Modal,
1143}
1144
1145#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1147pub struct SurfaceSpec {
1148 pub kind: SurfaceKind,
1149 pub ui_path: String,
1150 pub component: String,
1151 #[serde(default)]
1155 pub title: Option<String>,
1156 #[serde(default)]
1159 pub width: Option<f32>,
1160 #[serde(default)]
1161 pub height: Option<f32>,
1162 #[serde(default)]
1164 pub min_width: Option<f32>,
1165 #[serde(default)]
1167 pub min_height: Option<f32>,
1168 #[serde(default)]
1170 pub properties: Map<String, Value>,
1171 #[serde(default = "default_true")]
1174 pub capture_keyboard: bool,
1175}
1176
1177impl SurfaceSpec {
1178 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 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 pub extensions: Vec<String>,
1232}
1233
1234#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1236pub struct FilterSpec {
1237 pub filter_id: String,
1239 pub name: String,
1240 #[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1265#[serde(tag = "type", rename_all = "snake_case")]
1266#[non_exhaustive]
1267pub enum HostEvent {
1268 Ready {
1271 #[serde(default)]
1274 restore_sidebar: bool,
1275 },
1276 Shutdown,
1278 FileOpened {
1279 file: FileInfo,
1280 },
1281 FileClosed {
1283 file_id: FileId,
1284 },
1285 ActiveChanged {
1287 #[serde(default)]
1288 pane: Option<PaneId>,
1289 #[serde(default)]
1290 file_id: Option<FileId>,
1291 },
1292 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 ContextMenuRequested(MenuContext),
1312 ContextMenuItemSelected {
1314 item_id: String,
1315 context: MenuContext,
1316 },
1317 ToolActivated {
1318 tool_id: String,
1319 },
1320 ToolDeactivated {
1321 tool_id: String,
1322 },
1323 ShapeDrawn {
1325 tool_id: String,
1326 pane: PaneId,
1327 file_id: FileId,
1328 shape: Shape,
1329 #[serde(default)]
1330 modifiers: Modifiers,
1331 },
1332 Pointer {
1334 tool_id: String,
1335 pane: PaneId,
1336 file_id: FileId,
1337 event: PointerEvent,
1338 },
1339 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 #[serde(default = "default_click_count")]
1362 click_count: u32,
1363 },
1364 ObjectHovered {
1365 #[serde(default)]
1366 object: Option<ObjectRef>,
1367 pane: PaneId,
1368 },
1369 ObjectEdited {
1372 object: ObjectRef,
1373 shape: Shape,
1374 },
1375 ObjectsDeleteRequested {
1377 objects: Vec<ObjectRef>,
1378 },
1379 SelectionChanged {
1382 objects: Vec<ObjectRef>,
1383 },
1384 Posted {
1386 token: String,
1387 },
1388 EmptyAreaClicked {
1390 pane: PaneId,
1391 #[serde(default)]
1392 file_id: Option<FileId>,
1393 #[serde(default)]
1394 modifiers: Modifiers,
1395 },
1396 Undo {
1398 entry_id: String,
1399 },
1400 Redo {
1401 entry_id: String,
1402 },
1403 UiCallback {
1405 surface_id: String,
1406 name: String,
1407 #[serde(default)]
1408 args: Vec<Value>,
1409 },
1410 SurfaceClosed {
1412 surface_id: String,
1413 },
1414 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 FilterToggled {
1429 filter_id: String,
1430 enabled: bool,
1431 },
1432 UndoDropped {
1436 entry_ids: Vec<String>,
1437 },
1438 HotkeyPressed {
1440 hotkey_id: String,
1441 #[serde(default)]
1443 pane: Option<PaneId>,
1444 },
1445 RegistrationRefused {
1454 what: String,
1455 id: String,
1456 reason: String,
1458 #[serde(default, skip_serializing_if = "Option::is_none")]
1462 shown_reason: Option<String>,
1463 },
1464 DisplayChanged {
1467 pane: PaneId,
1468 display: DisplayAdjustments,
1469 },
1470 RoiChanged {
1472 file_id: FileId,
1473 #[serde(default)]
1474 roi: Option<Rect>,
1475 },
1476 BatchRun {
1482 run_id: String,
1483 command_id: String,
1484 file: FileInfo,
1485 output_dir: String,
1487 #[serde(default)]
1490 params: Map<String, Value>,
1491 },
1492 ModelFetched {
1498 request_id: String,
1499 #[serde(default)]
1501 path: Option<String>,
1502 #[serde(default)]
1503 model: Option<ModelRecord>,
1504 #[serde(default)]
1509 error: Option<String>,
1510 #[serde(default)]
1511 cancelled: bool,
1512 },
1513 LanguageChanged {
1521 language: String,
1522 },
1523 #[serde(other)]
1525 Unknown,
1526}
1527
1528fn default_click_count() -> u32 {
1529 1
1530}
1531
1532#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1534pub struct MenuContext {
1535 pub pane: PaneId,
1536 pub view: ViewInfo,
1537 pub image_x: f64,
1539 pub image_y: f64,
1540 #[serde(default)]
1542 pub hit: Option<ObjectRef>,
1543 #[serde(default)]
1545 pub selection: Vec<ObjectRef>,
1546}
1547
1548#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1550pub struct ContextMenuResponse {
1551 #[serde(default)]
1552 pub items: Vec<MenuItem>,
1553}
1554
1555pub mod methods {
1563 pub const LOG: &str = "log";
1565 pub const NOTIFY: &str = "notify";
1567 pub const STATUS: &str = "status";
1569 pub const SNAPSHOT: &str = "snapshot";
1571 pub const FILE_INFO: &str = "file.info";
1573 pub const FILE_PROPERTIES: &str = "file.properties";
1575 pub const FILE_OPEN: &str = "file.open";
1577
1578 pub const TOOLBAR_ADD: &str = "toolbar.add";
1580 pub const TOOLBAR_UPDATE: &str = "toolbar.update";
1582 pub const TOOLBAR_REMOVE: &str = "toolbar.remove";
1584 pub const HUD_ADD: &str = "hud.add";
1586 pub const HUD_UPDATE: &str = "hud.update";
1588 pub const HUD_REMOVE: &str = "hud.remove";
1590
1591 pub const HOTKEY_REGISTER: &str = "hotkey.register";
1594 pub const HOTKEY_UNREGISTER: &str = "hotkey.unregister";
1596 pub const TOOL_REGISTER: &str = "tool.register";
1598 pub const TOOL_UNREGISTER: &str = "tool.unregister";
1600 pub const TOOL_ACTIVATE: &str = "tool.activate";
1602 pub const TOOL_DEACTIVATE: &str = "tool.deactivate";
1604
1605 pub const LAYER_CREATE: &str = "layer.create";
1607 pub const LAYER_UPDATE: &str = "layer.update";
1609 pub const LAYER_REMOVE: &str = "layer.remove";
1611 pub const LAYER_SELECT: &str = "layer.select";
1613 pub const LAYER_UPSERT: &str = "layer.upsert";
1616 pub const LAYER_REMOVE_OBJECTS: &str = "layer.remove_objects";
1618 pub const LAYER_CLEAR: &str = "layer.clear";
1620 pub const BADGE_SET: &str = "badge.set";
1624 pub const LAYER_HIGHLIGHT: &str = "layer.highlight";
1627 pub const LAYER_SET_MIN_ZOOM: &str = "layer.set_min_zoom";
1629 pub const LAYER_SET_PANE_VISIBILITY: &str = "layer.set_pane_visibility";
1632 pub const LAYER_SET_PANES: &str = "layer.set_panes";
1635
1636 pub const SURFACE_OPEN: &str = "surface.open";
1638 pub const SURFACE_SET: &str = "surface.set";
1640 pub const SURFACE_CLOSE: &str = "surface.close";
1642 pub const SURFACE_IS_OPEN: &str = "surface.is_open";
1644
1645 pub const DIALOG_CONFIRM: &str = "dialog.confirm";
1647 pub const DIALOG_OPEN_FILE: &str = "dialog.open_file";
1649 pub const DIALOG_SAVE_FILE: &str = "dialog.save_file";
1651
1652 pub const VIEW_SET: &str = "view.set";
1654 pub const VIEW_PAN: &str = "view.pan";
1656 pub const VIEW_ZOOM: &str = "view.zoom";
1658 pub const VIEW_FIT: &str = "view.fit";
1660 pub const VIEW_FRAME: &str = "view.frame";
1662 pub const VIEW_ORIENTATION: &str = "view.orientation";
1665 pub const VIEW_DISPLAY: &str = "view.display";
1668
1669 pub const BATCH_REGISTER: &str = "batch.register";
1674 pub const BATCH_PROGRESS: &str = "batch.progress";
1676 pub const BATCH_FINISH: &str = "batch.finish";
1678
1679 pub const APP_CYCLE_PANE: &str = "app.cycle_pane";
1681 pub const APP_CYCLE_TAB: &str = "app.cycle_tab";
1683 pub const APP_SERIES: &str = "app.series";
1685 pub const RENDER_REQUEST: &str = "render.request";
1687
1688 pub const UNDO_PUSH: &str = "undo.push";
1690 pub const UNDO_CLEAR: &str = "undo.clear";
1692
1693 pub const FILTER_REGISTER: &str = "filter.register";
1695 pub const FILTER_SET_ENABLED: &str = "filter.set_enabled";
1697 pub const FILTER_UNREGISTER: &str = "filter.unregister";
1699
1700 pub const SETTINGS_GET: &str = "settings.get";
1702 pub const SETTINGS_SET: &str = "settings.set";
1704
1705 pub const JOB_START: &str = "job.start";
1707 pub const JOB_UPDATE: &str = "job.update";
1709 pub const JOB_FINISH: &str = "job.finish";
1711
1712 pub const CLIPBOARD_SET_TEXT: &str = "clipboard.set_text";
1714
1715 pub const ROI_GET: &str = "roi.get";
1717 pub const MEASUREMENTS_LIST: &str = "measurements.list";
1719
1720 pub const MODEL_FETCH: &str = "model.fetch";
1726 pub const MODEL_RESOLVE: &str = "model.resolve";
1729 pub const MODEL_LIST: &str = "model.list";
1731
1732 pub const POST: &str = "post";
1734 pub const EVENTS_SUBSCRIBE: &str = "events.subscribe";
1737}
1738
1739pub 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 #[serde(default)]
1771 pub detail: Option<String>,
1772}
1773
1774#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1775pub struct StatusArgs {
1776 #[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#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1799pub struct BatchCommandSpec {
1800 pub command_id: String,
1802 pub description: String,
1804 #[serde(default)]
1806 pub params: Vec<BatchParam>,
1807}
1808
1809#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1811pub struct BatchParam {
1812 pub name: String,
1813 #[serde(default)]
1814 pub description: String,
1815 #[serde(default)]
1817 pub default: Value,
1818}
1819
1820#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1822pub struct BatchProgressArgs {
1823 pub run_id: String,
1824 #[serde(default)]
1826 pub fraction: Option<f32>,
1827 #[serde(default)]
1828 pub message: Option<String>,
1829}
1830
1831#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1833pub struct BatchFinishArgs {
1834 pub run_id: String,
1835 pub ok: bool,
1837 #[serde(default)]
1838 pub message: Option<String>,
1839 #[serde(default)]
1841 pub outputs: Vec<String>,
1842 #[serde(default)]
1845 pub summary: Value,
1846}
1847
1848#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1850pub struct BadgeArgs {
1851 pub badge_id: String,
1852 #[serde(default)]
1854 pub file_id: Option<FileId>,
1855 #[serde(default)]
1857 pub text: Option<String>,
1858}
1859
1860#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1862pub struct MinZoomArgs {
1863 pub layer_id: String,
1864 #[serde(default)]
1867 pub min_zoom: Option<f64>,
1868}
1869
1870#[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#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1880pub struct PaneFilterArgs {
1881 pub layer_id: String,
1882 #[serde(default)]
1884 pub panes: Option<Vec<PaneId>>,
1885}
1886
1887#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1889pub struct DisplayAdjustments {
1890 pub gamma: f32,
1892 pub brightness: f32,
1894 pub contrast: f32,
1896 pub sharpness: f32,
1898 #[serde(default)]
1900 pub stain_normalization: Option<String>,
1901 pub modified: bool,
1903 #[serde(default)]
1908 pub badge: String,
1909 #[serde(default, skip_serializing_if = "Option::is_none")]
1912 pub shown_badge: Option<String>,
1913 #[serde(default, skip_serializing_if = "Option::is_none")]
1918 pub stain_colors: Option<bool>,
1919 #[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 #[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 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 #[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 #[serde(default)]
2016 pub default_name: Option<String>,
2017 #[serde(default)]
2019 pub directory: bool,
2020 #[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 #[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 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 pub factor: f64,
2063 #[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 pub rotation_deg: f64,
2079 #[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 #[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 pub entry_id: String,
2117 #[serde(default)]
2119 pub file_id: Option<FileId>,
2120 pub label: String,
2122}
2123
2124#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
2125pub struct UndoClearArgs {
2126 #[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 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 #[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 #[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#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
2187pub struct ModelFileSpec {
2188 pub sha256: String,
2190 #[serde(default)]
2193 pub url: Option<String>,
2194 #[serde(default)]
2197 pub file_name: Option<String>,
2198 #[serde(default)]
2201 pub size: Option<u64>,
2202}
2203
2204#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
2208pub struct ModelFetchArgs {
2209 #[serde(default)]
2213 pub url: Option<String>,
2214 pub sha256: String,
2216 #[serde(default)]
2218 pub size: Option<u64>,
2219 #[serde(default)]
2222 pub file_name: Option<String>,
2223 #[serde(default)]
2225 pub name: Option<String>,
2226 #[serde(default)]
2227 pub version: Option<String>,
2228 #[serde(default)]
2230 pub companions: Vec<ModelFileSpec>,
2231}
2232
2233#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
2235pub struct ModelResolveArgs {
2236 pub sha256: String,
2238}
2239
2240#[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 #[serde(default)]
2248 pub path: String,
2249}
2250
2251#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
2253pub struct ModelRecord {
2254 pub sha256: String,
2256 pub path: String,
2258 pub file_name: String,
2259 pub size: u64,
2261 #[serde(default)]
2262 pub name: Option<String>,
2263 #[serde(default)]
2264 pub version: Option<String>,
2265 #[serde(default)]
2268 pub source: Option<String>,
2269 #[serde(default)]
2271 pub fetched_at: Option<String>,
2272 #[serde(default)]
2274 pub requested_by: Option<String>,
2275 #[serde(default)]
2276 pub companions: Vec<ModelCompanion>,
2277 #[serde(default)]
2280 pub read_only: bool,
2281}
2282
2283impl ModelRecord {
2284 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
2292pub fn is_sha256_hex(text: &str) -> bool {
2294 text.len() == 64 && text.bytes().all(|b| b.is_ascii_hexdigit())
2295}
2296
2297pub fn check_model_file_name(name: &str) -> Result<(), String> {
2300 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 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
2378pub type PropertyMap = BTreeMap<String, String>;
2380
2381pub const MAX_SLIDE_LEVELS: usize = 64;
2387
2388pub const MAX_SLIDE_SIDE: u64 = 1 << 24;
2390
2391pub const MAX_ASSOCIATED_IMAGES: usize = 32;
2393
2394pub const MAX_ASSOCIATED_IMAGE_PIXELS: u64 = 1 << 28;
2396
2397#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
2400pub struct SlideOpenRequest {
2401 pub format_id: String,
2404 pub location: String,
2406 #[serde(default)]
2408 pub is_uri: bool,
2409}
2410
2411#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
2413pub struct SlideLevel {
2414 pub width: u64,
2415 pub height: u64,
2416 #[serde(default)]
2420 pub downsample: Option<f64>,
2421 #[serde(default)]
2424 pub tile_width: Option<u32>,
2425 #[serde(default)]
2426 pub tile_height: Option<u32>,
2427}
2428
2429#[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#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
2449pub struct SlideInfo {
2450 pub levels: Vec<SlideLevel>,
2453 #[serde(default)]
2456 pub vendor: Option<String>,
2457 #[serde(default)]
2459 pub mpp_x: Option<f64>,
2460 #[serde(default)]
2461 pub mpp_y: Option<f64>,
2462 #[serde(default)]
2464 pub objective_power: Option<f64>,
2465 #[serde(default)]
2467 pub scan_date: Option<String>,
2468 #[serde(default)]
2469 pub comment: Option<String>,
2470 #[serde(default)]
2472 pub stain: Option<String>,
2473 #[serde(default)]
2475 pub background: Option<[u8; 3]>,
2476 #[serde(default)]
2479 pub bounds: Option<Rect>,
2480 #[serde(default)]
2483 pub properties: PropertyMap,
2484 #[serde(default)]
2485 pub associated_images: Vec<AssociatedImageInfo>,
2486 #[serde(default)]
2492 pub identity: Option<String>,
2493 #[serde(default)]
2497 pub member_files: Vec<String>,
2498}
2499
2500impl SlideInfo {
2501 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 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 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 #[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 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 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 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 #[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 #[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 #[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 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 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 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}