1use serde::{Deserialize, Serialize};
32use serde_json::{Map, Value};
33use std::collections::BTreeMap;
34
35pub type FileId = i64;
37
38pub type PaneId = u32;
40
41#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
47pub struct PluginInit {
48 pub plugin_id: String,
50 pub plugin_version: String,
52 pub host_name: String,
54 pub host_version: String,
56 pub api_version: String,
58 pub plugin_root: String,
60 pub data_dir: String,
62 pub cache_dir: String,
64 #[serde(default)]
66 pub settings: Map<String, Value>,
67 #[serde(default)]
70 pub legacy_config_dir: Option<String>,
71 #[serde(default)]
75 pub headless: bool,
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
84pub struct Rect {
85 pub x: f64,
86 pub y: f64,
87 pub width: f64,
88 pub height: f64,
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
97pub struct LevelInfo {
98 pub level: u32,
99 pub width: u64,
100 pub height: u64,
101 pub downsample: f64,
102}
103
104#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
106pub struct FileInfo {
107 pub file_id: FileId,
108 pub path: String,
110 pub filename: String,
111 pub width: u64,
113 pub height: u64,
114 #[serde(default)]
115 pub levels: Vec<LevelInfo>,
116 #[serde(default)]
117 pub mpp_x: Option<f64>,
118 #[serde(default)]
119 pub mpp_y: Option<f64>,
120 #[serde(default)]
121 pub objective_power: Option<f64>,
122 #[serde(default)]
123 pub vendor: Option<String>,
124 #[serde(default)]
125 pub scan_date: Option<String>,
126 #[serde(default)]
128 pub bounds: Option<Rect>,
129 #[serde(default)]
132 pub identity: Option<String>,
133 #[serde(default)]
135 pub associated_images: Vec<String>,
136 #[serde(default)]
141 pub has_icc_profile: bool,
142 #[serde(default)]
144 pub stain: Option<String>,
145 #[serde(default)]
153 pub channel_names: Vec<String>,
154}
155
156#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
158pub struct ViewInfo {
159 pub pane: PaneId,
160 pub file_id: FileId,
161 pub center_x: f64,
163 pub center_y: f64,
164 pub zoom: f64,
166 pub width: f64,
168 pub height: f64,
169 #[serde(default = "default_scale_factor")]
171 pub scale_factor: f64,
172 #[serde(default)]
179 pub rotation_deg: f64,
180 #[serde(default)]
182 pub flipped: bool,
183 pub visible: Rect,
185}
186
187fn default_scale_factor() -> f64 {
188 1.0
189}
190
191impl Default for ViewInfo {
196 fn default() -> Self {
197 Self {
198 pane: Default::default(),
199 file_id: Default::default(),
200 center_x: 0.0,
201 center_y: 0.0,
202 zoom: 0.0,
203 width: 0.0,
204 height: 0.0,
205 scale_factor: default_scale_factor(),
206 rotation_deg: 0.0,
207 flipped: false,
208 visible: Rect::default(),
209 }
210 }
211}
212
213impl ViewInfo {
214 fn turn(&self, x: f64, y: f64) -> (f64, f64) {
217 let (sin, cos) = self.rotation_deg.to_radians().sin_cos();
218 let (tx, ty) = (x * cos - y * sin, x * sin + y * cos);
219 if self.flipped { (-tx, ty) } else { (tx, ty) }
220 }
221
222 pub fn image_to_screen(&self, x: f64, y: f64) -> (f64, f64) {
225 let (dx, dy) = self.turn(x - self.center_x, y - self.center_y);
226 (
227 self.width / 2.0 + dx * self.zoom,
228 self.height / 2.0 + dy * self.zoom,
229 )
230 }
231
232 pub fn screen_to_image(&self, x: f64, y: f64) -> (f64, f64) {
234 let zoom = if self.zoom > 0.0 { self.zoom } else { 1.0 };
235 let (mut dx, dy) = (
236 (x - self.width / 2.0) / zoom,
237 (y - self.height / 2.0) / zoom,
238 );
239 if self.flipped {
240 dx = -dx;
241 }
242 let (sin, cos) = (-self.rotation_deg).to_radians().sin_cos();
243 (
244 self.center_x + dx * cos - dy * sin,
245 self.center_y + dx * sin + dy * cos,
246 )
247 }
248}
249
250#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
252pub struct PaneInfo {
253 pub pane: PaneId,
254 pub index: u32,
256 #[serde(default)]
257 pub file_id: Option<FileId>,
258 #[serde(default)]
259 pub view: Option<ViewInfo>,
260}
261
262#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
264pub struct ToolRef {
265 #[serde(default)]
266 pub plugin_id: Option<String>,
267 pub tool_id: String,
268}
269
270#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
272pub struct HostSnapshot {
273 pub host_version: String,
274 #[serde(default)]
276 pub window_focused: bool,
277 #[serde(default)]
278 pub render_backend: String,
279 #[serde(default)]
280 pub filtering_mode: String,
281 #[serde(default)]
282 pub focused_pane: Option<PaneId>,
283 #[serde(default)]
284 pub panes: Vec<PaneInfo>,
285 #[serde(default)]
286 pub files: Vec<FileInfo>,
287 #[serde(default)]
288 pub active_tool: Option<ToolRef>,
289}
290
291impl HostSnapshot {
292 pub fn focused_view(&self) -> Option<&ViewInfo> {
294 let pane = self.focused_pane?;
295 self.panes.iter().find(|p| p.pane == pane)?.view.as_ref()
296 }
297
298 pub fn file(&self, file_id: FileId) -> Option<&FileInfo> {
300 self.files.iter().find(|f| f.file_id == file_id)
301 }
302}
303
304#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
306pub struct Modifiers {
307 #[serde(default)]
308 pub shift: bool,
309 #[serde(default)]
311 pub control: bool,
312 #[serde(default)]
313 pub alt: bool,
314 #[serde(default)]
316 pub meta: bool,
317 #[serde(default)]
319 pub primary: bool,
320}
321
322#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
323#[serde(rename_all = "snake_case")]
324pub enum PointerButton {
325 #[default]
326 None,
327 Left,
328 Right,
329 Middle,
330}
331
332#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
333#[serde(rename_all = "snake_case")]
334pub enum PointerKind {
335 Down,
336 Move,
337 Up,
338 DoubleClick,
340 Wheel,
341 Leave,
343}
344
345#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
347pub struct PointerEvent {
348 pub kind: PointerKind,
349 #[serde(default)]
350 pub button: PointerButton,
351 pub image_x: f64,
352 pub image_y: f64,
353 pub screen_x: f64,
354 pub screen_y: f64,
355 #[serde(default)]
356 pub modifiers: Modifiers,
357 #[serde(default)]
359 pub wheel_delta: f64,
360}
361
362#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
364#[serde(tag = "kind", rename_all = "snake_case")]
365pub enum Shape {
366 Point {
367 x: f64,
368 y: f64,
369 },
370 Polyline {
371 points: Vec<[f64; 2]>,
372 },
373 Polygon {
374 exterior: Vec<[f64; 2]>,
375 #[serde(default)]
376 holes: Vec<Vec<[f64; 2]>>,
377 },
378 Rectangle {
379 x: f64,
380 y: f64,
381 width: f64,
382 height: f64,
383 },
384 Ellipse {
385 cx: f64,
386 cy: f64,
387 rx: f64,
388 ry: f64,
389 },
390 Text {
393 x: f64,
394 y: f64,
395 text: String,
396 },
397}
398
399impl Shape {
400 pub fn is_valid(&self) -> bool {
403 let finite = |p: &[f64; 2]| p[0].is_finite() && p[1].is_finite();
404 match self {
405 Shape::Point { x, y } | Shape::Text { x, y, .. } => x.is_finite() && y.is_finite(),
406 Shape::Polyline { points } => points.len() >= 2 && points.iter().all(finite),
407 Shape::Polygon { exterior, holes } => {
408 exterior.len() >= 3
409 && exterior.iter().all(finite)
410 && holes
411 .iter()
412 .all(|ring| ring.len() >= 3 && ring.iter().all(finite))
413 }
414 Shape::Rectangle {
415 x,
416 y,
417 width,
418 height,
419 } => {
420 [x, y, width, height].iter().all(|v| v.is_finite())
421 && *width >= 0.0
422 && *height >= 0.0
423 }
424 Shape::Ellipse { cx, cy, rx, ry } => {
425 [cx, cy, rx, ry].iter().all(|v| v.is_finite()) && *rx >= 0.0 && *ry >= 0.0
426 }
427 }
428 }
429
430 pub fn bounds(&self) -> Rect {
432 fn of_points<'a>(points: impl Iterator<Item = &'a [f64; 2]>) -> Rect {
433 let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
434 for p in points {
435 x0 = x0.min(p[0]);
436 y0 = y0.min(p[1]);
437 x1 = x1.max(p[0]);
438 y1 = y1.max(p[1]);
439 }
440 if x0 > x1 {
441 return Rect::default();
442 }
443 Rect {
444 x: x0,
445 y: y0,
446 width: x1 - x0,
447 height: y1 - y0,
448 }
449 }
450 match self {
451 Shape::Point { x, y } | Shape::Text { x, y, .. } => Rect {
452 x: *x,
453 y: *y,
454 width: 0.0,
455 height: 0.0,
456 },
457 Shape::Polyline { points } => of_points(points.iter()),
458 Shape::Polygon { exterior, .. } => of_points(exterior.iter()),
459 Shape::Rectangle {
460 x,
461 y,
462 width,
463 height,
464 } => Rect {
465 x: *x,
466 y: *y,
467 width: *width,
468 height: *height,
469 },
470 Shape::Ellipse { cx, cy, rx, ry } => Rect {
471 x: cx - rx,
472 y: cy - ry,
473 width: rx * 2.0,
474 height: ry * 2.0,
475 },
476 }
477 }
478}
479
480#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
482pub struct ObjectRef {
483 pub layer_id: String,
484 pub object_id: String,
485}
486
487#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
489pub struct OverlayObject {
490 pub object_id: String,
492 pub shape: Shape,
493 #[serde(default)]
495 pub style: Option<Style>,
496 #[serde(default)]
498 pub label: Option<String>,
499 #[serde(default)]
501 pub tooltip: Option<String>,
502 #[serde(default)]
504 pub editable: Option<bool>,
505}
506
507impl OverlayObject {
508 pub fn new(object_id: impl Into<String>, shape: Shape) -> Self {
509 Self {
510 object_id: object_id.into(),
511 shape,
512 style: None,
513 label: None,
514 tooltip: None,
515 editable: None,
516 }
517 }
518
519 pub fn with_style(mut self, style: Style) -> Self {
520 self.style = Some(style);
521 self
522 }
523
524 pub fn with_label(mut self, label: impl Into<String>) -> Self {
525 self.label = Some(label.into());
526 self
527 }
528
529 pub fn with_tooltip(mut self, tooltip: impl Into<String>) -> Self {
530 self.tooltip = Some(tooltip.into());
531 self
532 }
533
534 pub fn with_editable(mut self, editable: bool) -> Self {
535 self.editable = Some(editable);
536 self
537 }
538}
539
540#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
542pub struct MeasurementInfo {
543 pub measurement_id: String,
544 pub file_id: FileId,
545 pub shape: Shape,
546 #[serde(default)]
549 pub length_um: Option<f64>,
550 #[serde(default)]
552 pub area_um2: Option<f64>,
553 #[serde(default)]
555 pub angle_deg: Option<f64>,
556}
557
558#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
561pub struct MenuItem {
562 pub item_id: String,
563 pub label: String,
564 #[serde(default)]
567 pub icon: String,
568 #[serde(default = "default_true")]
569 pub enabled: bool,
570 #[serde(default)]
572 pub checked: Option<bool>,
573 #[serde(default)]
575 pub shortcut: String,
576 #[serde(default)]
577 pub separator_after: bool,
578}
579
580fn default_true() -> bool {
581 true
582}
583
584impl Default for MenuItem {
585 fn default() -> Self {
586 Self {
587 item_id: String::new(),
588 label: String::new(),
589 icon: String::new(),
590 enabled: default_true(),
591 checked: None,
592 shortcut: String::new(),
593 separator_after: false,
594 }
595 }
596}
597
598pub fn key_name(text: &str) -> String {
604 let mut chars = text.chars();
605 let (Some(c), None) = (chars.next(), chars.next()) else {
606 return text.to_lowercase();
607 };
608 match c {
609 '\u{8}' => "Backspace".into(),
610 '\t' => "Tab".into(),
611 '\n' | '\r' => "Enter".into(),
612 '\u{1b}' => "Escape".into(),
613 '\u{7f}' => "Delete".into(),
614 ' ' => "Space".into(),
615 '\u{F700}' => "ArrowUp".into(),
616 '\u{F701}' => "ArrowDown".into(),
617 '\u{F702}' => "ArrowLeft".into(),
618 '\u{F703}' => "ArrowRight".into(),
619 '\u{F704}'..='\u{F71B}' => format!("F{}", c as u32 - 0xF704 + 1),
620 '\u{F729}' => "Home".into(),
621 '\u{F72B}' => "End".into(),
622 '\u{F72C}' => "PageUp".into(),
623 '\u{F72D}' => "PageDown".into(),
624 c => c.to_lowercase().collect(),
625 }
626}
627
628#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
631pub struct Hotkey {
632 pub key: String,
633 #[serde(default)]
634 pub modifiers: Modifiers,
635 #[serde(default)]
637 pub momentary: bool,
638}
639
640#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
642pub struct HotkeySpec {
643 pub hotkey_id: String,
644 pub hotkey: Hotkey,
645 #[serde(default)]
647 pub description: String,
648}
649
650#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
651#[serde(rename_all = "snake_case")]
652pub enum LogLevel {
653 Trace,
654 Debug,
655 #[default]
656 Info,
657 Warn,
658 Error,
659}
660
661#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
667pub struct Rgba(pub u8, pub u8, pub u8, pub u8);
668
669impl Rgba {
670 pub const TRANSPARENT: Self = Self(0, 0, 0, 0);
671
672 pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
673 Self(r, g, b, 255)
674 }
675
676 pub const fn with_alpha(self, alpha: u8) -> Self {
677 Self(self.0, self.1, self.2, alpha)
678 }
679
680 pub const fn to_u32(self) -> u32 {
682 ((self.0 as u32) << 24) | ((self.1 as u32) << 16) | ((self.2 as u32) << 8) | self.3 as u32
683 }
684
685 pub const fn from_u32(value: u32) -> Self {
687 Self(
688 (value >> 24) as u8,
689 (value >> 16) as u8,
690 (value >> 8) as u8,
691 value as u8,
692 )
693 }
694
695 pub fn from_hex(text: &str) -> Option<Self> {
697 let hex = text.strip_prefix('#')?;
698 if !hex.chars().all(|c| c.is_ascii_hexdigit()) {
699 return None;
700 }
701 let byte = |i: usize| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok();
702 match hex.len() {
703 6 => Some(Self(byte(0)?, byte(2)?, byte(4)?, 255)),
704 8 => Some(Self(byte(0)?, byte(2)?, byte(4)?, byte(6)?)),
705 _ => None,
706 }
707 }
708
709 pub fn to_hex(self) -> String {
710 if self.3 == 255 {
711 format!("#{:02X}{:02X}{:02X}", self.0, self.1, self.2)
712 } else {
713 format!("#{:02X}{:02X}{:02X}{:02X}", self.0, self.1, self.2, self.3)
714 }
715 }
716}
717
718#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
719#[serde(rename_all = "snake_case")]
720pub enum Dash {
721 #[default]
722 Solid,
723 Dashed,
724 Dotted,
725}
726
727#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
729#[serde(rename_all = "snake_case")]
730pub enum SizeUnit {
731 #[default]
733 Screen,
734 Micrometre,
736 Image,
738}
739
740#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
742pub struct Style {
743 #[serde(default)]
744 pub fill: Rgba,
745 #[serde(default = "default_stroke")]
746 pub stroke: Rgba,
747 #[serde(default = "default_stroke_width")]
748 pub stroke_width: f32,
749 #[serde(default)]
750 pub dash: Dash,
751 #[serde(default = "default_point_radius")]
753 pub point_radius: f32,
754 #[serde(default)]
756 pub size_unit: SizeUnit,
757 #[serde(default = "default_text_color")]
759 pub text_color: Rgba,
760 #[serde(default = "default_font_size")]
761 pub font_size: f32,
762}
763
764fn default_stroke() -> Rgba {
765 Rgba::rgb(0x2E, 0xCC, 0x71)
766}
767fn default_stroke_width() -> f32 {
768 1.5
769}
770fn default_point_radius() -> f32 {
771 5.0
772}
773fn default_text_color() -> Rgba {
774 Rgba::rgb(255, 255, 255)
775}
776fn default_font_size() -> f32 {
777 12.0
778}
779
780impl Default for Style {
781 fn default() -> Self {
782 Self {
783 fill: Rgba::TRANSPARENT,
784 stroke: default_stroke(),
785 stroke_width: default_stroke_width(),
786 dash: Dash::Solid,
787 point_radius: default_point_radius(),
788 size_unit: SizeUnit::Screen,
789 text_color: default_text_color(),
790 font_size: default_font_size(),
791 }
792 }
793}
794
795#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
798pub struct LayerSpec {
799 pub layer_id: String,
803 pub file_id: FileId,
804 #[serde(default)]
805 pub name: String,
806 #[serde(default)]
808 pub z: i32,
809 #[serde(default = "default_true")]
810 pub visible: bool,
811 #[serde(default = "default_opacity")]
813 pub opacity: f32,
814 #[serde(default)]
816 pub interactive: bool,
817 #[serde(default)]
820 pub editable: bool,
821 #[serde(default)]
822 pub style: Style,
823 #[serde(default)]
825 pub selected_style: Option<Style>,
826 #[serde(default)]
828 pub hover_style: Option<Style>,
829 #[serde(default)]
831 pub min_zoom: Option<f64>,
832}
833
834fn default_opacity() -> f32 {
835 1.0
836}
837
838impl LayerSpec {
839 pub fn new(layer_id: impl Into<String>, file_id: FileId) -> Self {
841 Self {
842 layer_id: layer_id.into(),
843 file_id,
844 name: String::new(),
845 z: 0,
846 visible: true,
847 opacity: 1.0,
848 interactive: false,
849 editable: false,
850 style: Style::default(),
851 selected_style: None,
852 hover_style: None,
853 min_zoom: None,
854 }
855 }
856
857 pub fn named(mut self, name: impl Into<String>) -> Self {
858 self.name = name.into();
859 self
860 }
861
862 pub fn with_style(mut self, style: Style) -> Self {
863 self.style = style;
864 self
865 }
866
867 pub fn interactive(mut self, interactive: bool) -> Self {
868 self.interactive = interactive;
869 self
870 }
871
872 pub fn editable(mut self, editable: bool) -> Self {
873 self.editable = editable;
874 self
875 }
876
877 pub fn at_z(mut self, z: i32) -> Self {
878 self.z = z;
879 self
880 }
881}
882
883#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
885pub struct LayerUpdate {
886 pub layer_id: String,
887 #[serde(default)]
888 pub name: Option<String>,
889 #[serde(default)]
890 pub z: Option<i32>,
891 #[serde(default)]
892 pub visible: Option<bool>,
893 #[serde(default)]
894 pub opacity: Option<f32>,
895 #[serde(default)]
896 pub interactive: Option<bool>,
897 #[serde(default)]
898 pub editable: Option<bool>,
899 #[serde(default)]
900 pub style: Option<Style>,
901 #[serde(default)]
902 pub selected_style: Option<Style>,
903 #[serde(default)]
904 pub hover_style: Option<Style>,
905}
906
907#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
914pub struct ToolbarButtonSpec {
915 pub button_id: String,
916 pub tooltip: String,
917 pub icon_svg: String,
919 #[serde(default)]
920 pub toggled_icon_svg: Option<String>,
921 #[serde(default)]
923 pub active: bool,
924 #[serde(default = "default_true")]
925 pub enabled: bool,
926 #[serde(default)]
928 pub hotkey: Option<Hotkey>,
929 #[serde(default)]
931 pub order: i32,
932}
933
934impl Default for ToolbarButtonSpec {
935 fn default() -> Self {
936 Self {
937 button_id: String::new(),
938 tooltip: String::new(),
939 icon_svg: String::new(),
940 toggled_icon_svg: None,
941 active: false,
942 enabled: default_true(),
943 hotkey: None,
944 order: 0,
945 }
946 }
947}
948
949#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
951pub struct ButtonUpdate {
952 pub button_id: String,
953 #[serde(default)]
955 pub pane: Option<PaneId>,
956 #[serde(default)]
957 pub active: Option<bool>,
958 #[serde(default)]
959 pub enabled: Option<bool>,
960 #[serde(default)]
961 pub tooltip: Option<String>,
962 #[serde(default)]
963 pub icon_svg: Option<String>,
964 #[serde(default)]
965 pub menu: Option<Vec<MenuItem>>,
966}
967
968#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
971pub struct HudButtonSpec {
972 pub button_id: String,
973 pub tooltip: String,
974 pub icon_svg: String,
975 #[serde(default)]
976 pub toggled_icon_svg: Option<String>,
977 #[serde(default)]
978 pub active: bool,
979 #[serde(default)]
980 pub menu: Vec<MenuItem>,
981 #[serde(default)]
982 pub order: i32,
983}
984
985#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
987#[serde(rename_all = "snake_case")]
988pub enum ToolKind {
989 Point,
991 Polyline,
993 Polygon,
996 Rectangle,
998 Ellipse,
1000 Freehand,
1002 Custom,
1004 Select,
1007}
1008
1009#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1010#[serde(rename_all = "snake_case")]
1011pub enum Cursor {
1012 #[default]
1013 Default,
1014 Crosshair,
1015 Pointer,
1016 Move,
1017 Text,
1018 NotAllowed,
1019}
1020
1021#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1023pub struct ToolSpec {
1024 pub tool_id: String,
1025 pub label: String,
1026 pub icon_svg: String,
1027 pub kind: ToolKind,
1028 #[serde(default)]
1029 pub hotkey: Option<Hotkey>,
1030 #[serde(default)]
1031 pub cursor: Cursor,
1032 #[serde(default)]
1035 pub edit_layers: Vec<String>,
1036 #[serde(default)]
1038 pub preview_style: Option<Style>,
1039 #[serde(default = "default_freehand_tolerance")]
1041 pub freehand_tolerance_px: f32,
1042 #[serde(default)]
1043 pub order: i32,
1044 #[serde(default)]
1050 pub keys: Option<Vec<String>>,
1051}
1052
1053fn default_freehand_tolerance() -> f32 {
1054 1.5
1055}
1056
1057impl ToolSpec {
1058 pub fn new(
1059 tool_id: impl Into<String>,
1060 label: impl Into<String>,
1061 icon_svg: impl Into<String>,
1062 kind: ToolKind,
1063 ) -> Self {
1064 Self {
1065 tool_id: tool_id.into(),
1066 label: label.into(),
1067 icon_svg: icon_svg.into(),
1068 kind,
1069 hotkey: None,
1070 cursor: Cursor::Crosshair,
1071 edit_layers: Vec::new(),
1072 preview_style: None,
1073 freehand_tolerance_px: default_freehand_tolerance(),
1074 order: 0,
1075 keys: None,
1076 }
1077 }
1078
1079 pub fn with_hotkey(mut self, hotkey: Hotkey) -> Self {
1080 self.hotkey = Some(hotkey);
1081 self
1082 }
1083}
1084
1085#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1086#[serde(rename_all = "snake_case")]
1087pub enum SurfaceKind {
1088 Sidebar,
1090 Window,
1092 Modal,
1094}
1095
1096#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1098pub struct SurfaceSpec {
1099 pub kind: SurfaceKind,
1100 pub ui_path: String,
1101 pub component: String,
1102 #[serde(default)]
1106 pub title: Option<String>,
1107 #[serde(default)]
1110 pub width: Option<f32>,
1111 #[serde(default)]
1112 pub height: Option<f32>,
1113 #[serde(default)]
1115 pub min_width: Option<f32>,
1116 #[serde(default)]
1118 pub min_height: Option<f32>,
1119 #[serde(default)]
1121 pub properties: Map<String, Value>,
1122 #[serde(default = "default_true")]
1125 pub capture_keyboard: bool,
1126}
1127
1128impl SurfaceSpec {
1129 pub fn new(
1132 kind: SurfaceKind,
1133 ui_path: impl Into<String>,
1134 component: impl Into<String>,
1135 ) -> Self {
1136 Self {
1137 kind,
1138 ui_path: ui_path.into(),
1139 component: component.into(),
1140 title: None,
1141 width: None,
1142 height: None,
1143 min_width: None,
1144 min_height: None,
1145 properties: Map::new(),
1146 capture_keyboard: true,
1147 }
1148 }
1149
1150 pub fn with_title(mut self, title: impl Into<String>) -> Self {
1151 self.title = Some(title.into());
1152 self
1153 }
1154
1155 pub fn with_size(mut self, width: f32, height: Option<f32>) -> Self {
1156 self.width = Some(width);
1157 self.height = height;
1158 self
1159 }
1160
1161 pub fn with_property(mut self, name: impl Into<String>, value: Value) -> Self {
1162 self.properties.insert(name.into(), value);
1163 self
1164 }
1165}
1166
1167impl Hotkey {
1168 pub fn key(key: impl Into<String>) -> Self {
1170 Self {
1171 key: key.into(),
1172 modifiers: Modifiers::default(),
1173 momentary: false,
1174 }
1175 }
1176}
1177
1178#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1179pub struct FileFilter {
1180 pub name: String,
1181 pub extensions: Vec<String>,
1183}
1184
1185#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1187pub struct FilterSpec {
1188 pub filter_id: String,
1190 pub name: String,
1191 #[serde(default)]
1193 pub priority: i32,
1194 #[serde(default)]
1195 pub enabled: bool,
1196}
1197
1198#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1199#[serde(rename_all = "snake_case")]
1200pub enum NotifyLevel {
1201 #[default]
1202 Info,
1203 Success,
1204 Warning,
1205 Error,
1206}
1207
1208#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1216#[serde(tag = "type", rename_all = "snake_case")]
1217#[non_exhaustive]
1218pub enum HostEvent {
1219 Ready {
1222 #[serde(default)]
1225 restore_sidebar: bool,
1226 },
1227 Shutdown,
1229 FileOpened {
1230 file: FileInfo,
1231 },
1232 FileClosed {
1234 file_id: FileId,
1235 },
1236 ActiveChanged {
1238 #[serde(default)]
1239 pane: Option<PaneId>,
1240 #[serde(default)]
1241 file_id: Option<FileId>,
1242 },
1243 ViewChanged {
1245 view: ViewInfo,
1246 },
1247 WindowFocusChanged {
1248 focused: bool,
1249 },
1250 ToolbarButtonClicked {
1251 button_id: String,
1252 },
1253 HudButtonClicked {
1254 button_id: String,
1255 #[serde(default)]
1256 item_id: Option<String>,
1257 pane: PaneId,
1258 #[serde(default)]
1259 view: Option<ViewInfo>,
1260 },
1261 ContextMenuRequested(MenuContext),
1263 ContextMenuItemSelected {
1265 item_id: String,
1266 context: MenuContext,
1267 },
1268 ToolActivated {
1269 tool_id: String,
1270 },
1271 ToolDeactivated {
1272 tool_id: String,
1273 },
1274 ShapeDrawn {
1276 tool_id: String,
1277 pane: PaneId,
1278 file_id: FileId,
1279 shape: Shape,
1280 #[serde(default)]
1281 modifiers: Modifiers,
1282 },
1283 Pointer {
1285 tool_id: String,
1286 pane: PaneId,
1287 file_id: FileId,
1288 event: PointerEvent,
1289 },
1290 Key {
1293 #[serde(default)]
1294 tool_id: Option<String>,
1295 #[serde(default)]
1296 pane: Option<PaneId>,
1297 key: String,
1298 #[serde(default)]
1299 modifiers: Modifiers,
1300 pressed: bool,
1301 #[serde(default)]
1302 repeat: bool,
1303 },
1304 ObjectClicked {
1305 object: ObjectRef,
1306 pane: PaneId,
1307 #[serde(default)]
1308 button: PointerButton,
1309 #[serde(default)]
1310 modifiers: Modifiers,
1311 #[serde(default = "default_click_count")]
1313 click_count: u32,
1314 },
1315 ObjectHovered {
1316 #[serde(default)]
1317 object: Option<ObjectRef>,
1318 pane: PaneId,
1319 },
1320 ObjectEdited {
1323 object: ObjectRef,
1324 shape: Shape,
1325 },
1326 ObjectsDeleteRequested {
1328 objects: Vec<ObjectRef>,
1329 },
1330 SelectionChanged {
1333 objects: Vec<ObjectRef>,
1334 },
1335 Posted {
1337 token: String,
1338 },
1339 EmptyAreaClicked {
1341 pane: PaneId,
1342 #[serde(default)]
1343 file_id: Option<FileId>,
1344 #[serde(default)]
1345 modifiers: Modifiers,
1346 },
1347 Undo {
1349 entry_id: String,
1350 },
1351 Redo {
1352 entry_id: String,
1353 },
1354 UiCallback {
1356 surface_id: String,
1357 name: String,
1358 #[serde(default)]
1359 args: Vec<Value>,
1360 },
1361 SurfaceClosed {
1363 surface_id: String,
1364 },
1365 DialogResult {
1367 request_id: String,
1368 #[serde(default)]
1369 paths: Vec<String>,
1370 },
1371 ConfirmResult {
1372 request_id: String,
1373 confirmed: bool,
1374 },
1375 JobCancelRequested {
1376 job_id: String,
1377 },
1378 FilterToggled {
1380 filter_id: String,
1381 enabled: bool,
1382 },
1383 UndoDropped {
1387 entry_ids: Vec<String>,
1388 },
1389 HotkeyPressed {
1391 hotkey_id: String,
1392 #[serde(default)]
1394 pane: Option<PaneId>,
1395 },
1396 RegistrationRefused {
1400 what: String,
1401 id: String,
1402 reason: String,
1403 },
1404 DisplayChanged {
1407 pane: PaneId,
1408 display: DisplayAdjustments,
1409 },
1410 RoiChanged {
1412 file_id: FileId,
1413 #[serde(default)]
1414 roi: Option<Rect>,
1415 },
1416 BatchRun {
1422 run_id: String,
1423 command_id: String,
1424 file: FileInfo,
1425 output_dir: String,
1427 #[serde(default)]
1430 params: Map<String, Value>,
1431 },
1432 ModelFetched {
1438 request_id: String,
1439 #[serde(default)]
1441 path: Option<String>,
1442 #[serde(default)]
1443 model: Option<ModelRecord>,
1444 #[serde(default)]
1445 error: Option<String>,
1446 #[serde(default)]
1447 cancelled: bool,
1448 },
1449 #[serde(other)]
1451 Unknown,
1452}
1453
1454fn default_click_count() -> u32 {
1455 1
1456}
1457
1458#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1460pub struct MenuContext {
1461 pub pane: PaneId,
1462 pub view: ViewInfo,
1463 pub image_x: f64,
1465 pub image_y: f64,
1466 #[serde(default)]
1468 pub hit: Option<ObjectRef>,
1469 #[serde(default)]
1471 pub selection: Vec<ObjectRef>,
1472}
1473
1474#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1476pub struct ContextMenuResponse {
1477 #[serde(default)]
1478 pub items: Vec<MenuItem>,
1479}
1480
1481pub mod methods {
1489 pub const LOG: &str = "log";
1491 pub const NOTIFY: &str = "notify";
1493 pub const STATUS: &str = "status";
1495 pub const SNAPSHOT: &str = "snapshot";
1497 pub const FILE_INFO: &str = "file.info";
1499 pub const FILE_PROPERTIES: &str = "file.properties";
1501 pub const FILE_OPEN: &str = "file.open";
1503
1504 pub const TOOLBAR_ADD: &str = "toolbar.add";
1506 pub const TOOLBAR_UPDATE: &str = "toolbar.update";
1508 pub const TOOLBAR_REMOVE: &str = "toolbar.remove";
1510 pub const HUD_ADD: &str = "hud.add";
1512 pub const HUD_UPDATE: &str = "hud.update";
1514 pub const HUD_REMOVE: &str = "hud.remove";
1516
1517 pub const HOTKEY_REGISTER: &str = "hotkey.register";
1520 pub const HOTKEY_UNREGISTER: &str = "hotkey.unregister";
1522 pub const TOOL_REGISTER: &str = "tool.register";
1524 pub const TOOL_UNREGISTER: &str = "tool.unregister";
1526 pub const TOOL_ACTIVATE: &str = "tool.activate";
1528 pub const TOOL_DEACTIVATE: &str = "tool.deactivate";
1530
1531 pub const LAYER_CREATE: &str = "layer.create";
1533 pub const LAYER_UPDATE: &str = "layer.update";
1535 pub const LAYER_REMOVE: &str = "layer.remove";
1537 pub const LAYER_SELECT: &str = "layer.select";
1539 pub const LAYER_UPSERT: &str = "layer.upsert";
1542 pub const LAYER_REMOVE_OBJECTS: &str = "layer.remove_objects";
1544 pub const LAYER_CLEAR: &str = "layer.clear";
1546 pub const BADGE_SET: &str = "badge.set";
1550 pub const LAYER_HIGHLIGHT: &str = "layer.highlight";
1553 pub const LAYER_SET_MIN_ZOOM: &str = "layer.set_min_zoom";
1555 pub const LAYER_SET_PANE_VISIBILITY: &str = "layer.set_pane_visibility";
1558 pub const LAYER_SET_PANES: &str = "layer.set_panes";
1561
1562 pub const SURFACE_OPEN: &str = "surface.open";
1564 pub const SURFACE_SET: &str = "surface.set";
1566 pub const SURFACE_CLOSE: &str = "surface.close";
1568 pub const SURFACE_IS_OPEN: &str = "surface.is_open";
1570
1571 pub const DIALOG_CONFIRM: &str = "dialog.confirm";
1573 pub const DIALOG_OPEN_FILE: &str = "dialog.open_file";
1575 pub const DIALOG_SAVE_FILE: &str = "dialog.save_file";
1577
1578 pub const VIEW_SET: &str = "view.set";
1580 pub const VIEW_PAN: &str = "view.pan";
1582 pub const VIEW_ZOOM: &str = "view.zoom";
1584 pub const VIEW_FIT: &str = "view.fit";
1586 pub const VIEW_FRAME: &str = "view.frame";
1588 pub const VIEW_ORIENTATION: &str = "view.orientation";
1591 pub const VIEW_DISPLAY: &str = "view.display";
1594
1595 pub const BATCH_REGISTER: &str = "batch.register";
1600 pub const BATCH_PROGRESS: &str = "batch.progress";
1602 pub const BATCH_FINISH: &str = "batch.finish";
1604
1605 pub const APP_CYCLE_PANE: &str = "app.cycle_pane";
1607 pub const APP_CYCLE_TAB: &str = "app.cycle_tab";
1609 pub const APP_SERIES: &str = "app.series";
1611 pub const RENDER_REQUEST: &str = "render.request";
1613
1614 pub const UNDO_PUSH: &str = "undo.push";
1616 pub const UNDO_CLEAR: &str = "undo.clear";
1618
1619 pub const FILTER_REGISTER: &str = "filter.register";
1621 pub const FILTER_SET_ENABLED: &str = "filter.set_enabled";
1623 pub const FILTER_UNREGISTER: &str = "filter.unregister";
1625
1626 pub const SETTINGS_GET: &str = "settings.get";
1628 pub const SETTINGS_SET: &str = "settings.set";
1630
1631 pub const JOB_START: &str = "job.start";
1633 pub const JOB_UPDATE: &str = "job.update";
1635 pub const JOB_FINISH: &str = "job.finish";
1637
1638 pub const CLIPBOARD_SET_TEXT: &str = "clipboard.set_text";
1640
1641 pub const ROI_GET: &str = "roi.get";
1643 pub const MEASUREMENTS_LIST: &str = "measurements.list";
1645
1646 pub const MODEL_FETCH: &str = "model.fetch";
1652 pub const MODEL_RESOLVE: &str = "model.resolve";
1655 pub const MODEL_LIST: &str = "model.list";
1657
1658 pub const POST: &str = "post";
1660 pub const EVENTS_SUBSCRIBE: &str = "events.subscribe";
1663}
1664
1665pub mod event_names {
1671 pub const FILE_OPENED: &str = "file_opened";
1672 pub const FILE_CLOSED: &str = "file_closed";
1673 pub const ACTIVE_CHANGED: &str = "active_changed";
1674 pub const VIEW_CHANGED: &str = "view_changed";
1675 pub const WINDOW_FOCUS_CHANGED: &str = "window_focus_changed";
1676 pub const OBJECT_HOVERED: &str = "object_hovered";
1677 pub const EMPTY_AREA_CLICKED: &str = "empty_area_clicked";
1678 pub const CONTEXT_MENU_REQUESTED: &str = "context_menu_requested";
1679 pub const ROI_CHANGED: &str = "roi_changed";
1680 pub const HOTKEY_PRESSED: &str = "hotkey_pressed";
1681 pub const DISPLAY_CHANGED: &str = "display_changed";
1682}
1683
1684#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1685pub struct LogArgs {
1686 pub level: LogLevel,
1687 pub message: String,
1688}
1689
1690#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1691pub struct NotifyArgs {
1692 #[serde(default)]
1693 pub level: NotifyLevel,
1694 pub message: String,
1695 #[serde(default)]
1697 pub detail: Option<String>,
1698}
1699
1700#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1701pub struct StatusArgs {
1702 #[serde(default)]
1704 pub text: Option<String>,
1705}
1706
1707#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1708pub struct FileArgs {
1709 pub file_id: FileId,
1710}
1711
1712#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1713pub struct OpenFileArgs {
1714 pub path: String,
1715}
1716
1717#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1718pub struct IdArgs {
1719 pub id: String,
1720}
1721
1722#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1725pub struct BatchCommandSpec {
1726 pub command_id: String,
1728 pub description: String,
1730 #[serde(default)]
1732 pub params: Vec<BatchParam>,
1733}
1734
1735#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1737pub struct BatchParam {
1738 pub name: String,
1739 #[serde(default)]
1740 pub description: String,
1741 #[serde(default)]
1743 pub default: Value,
1744}
1745
1746#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1748pub struct BatchProgressArgs {
1749 pub run_id: String,
1750 #[serde(default)]
1752 pub fraction: Option<f32>,
1753 #[serde(default)]
1754 pub message: Option<String>,
1755}
1756
1757#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1759pub struct BatchFinishArgs {
1760 pub run_id: String,
1761 pub ok: bool,
1763 #[serde(default)]
1764 pub message: Option<String>,
1765 #[serde(default)]
1767 pub outputs: Vec<String>,
1768 #[serde(default)]
1771 pub summary: Value,
1772}
1773
1774#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1776pub struct BadgeArgs {
1777 pub badge_id: String,
1778 #[serde(default)]
1780 pub file_id: Option<FileId>,
1781 #[serde(default)]
1783 pub text: Option<String>,
1784}
1785
1786#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1788pub struct MinZoomArgs {
1789 pub layer_id: String,
1790 #[serde(default)]
1793 pub min_zoom: Option<f64>,
1794}
1795
1796#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1798pub struct PaneVisibilityArgs {
1799 pub layer_id: String,
1800 pub pane: PaneId,
1801 pub visible: bool,
1802}
1803
1804#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1806pub struct PaneFilterArgs {
1807 pub layer_id: String,
1808 #[serde(default)]
1810 pub panes: Option<Vec<PaneId>>,
1811}
1812
1813#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1815pub struct DisplayAdjustments {
1816 pub gamma: f32,
1818 pub brightness: f32,
1820 pub contrast: f32,
1822 pub sharpness: f32,
1824 #[serde(default)]
1826 pub stain_normalization: Option<String>,
1827 pub modified: bool,
1829 #[serde(default)]
1831 pub badge: String,
1832 #[serde(default)]
1838 pub color_managed: bool,
1839}
1840
1841impl Default for DisplayAdjustments {
1842 fn default() -> Self {
1843 Self {
1844 gamma: 1.0,
1845 brightness: 0.0,
1846 contrast: 1.0,
1847 sharpness: 0.0,
1848 stain_normalization: None,
1849 modified: false,
1850 badge: String::new(),
1851 color_managed: false,
1852 }
1853 }
1854}
1855
1856#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1857pub struct SelectArgs {
1858 pub layer_id: String,
1859 pub object_ids: Vec<String>,
1860}
1861
1862#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1863pub struct UpsertObjectsArgs {
1864 pub layer_id: String,
1865 pub objects: Vec<OverlayObject>,
1866 #[serde(default)]
1868 pub replace_all: bool,
1869}
1870
1871#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1872pub struct RemoveObjectsArgs {
1873 pub layer_id: String,
1874 pub object_ids: Vec<String>,
1875}
1876
1877#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1878pub struct PostArgs {
1879 pub token: String,
1880}
1881
1882#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1883pub struct SubscribeArgs {
1884 pub events: Vec<String>,
1886}
1887
1888#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1889pub struct SurfaceOpened {
1890 pub surface_id: String,
1891}
1892
1893#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1894pub struct SurfaceProperties {
1895 pub surface_id: String,
1896 pub properties: Map<String, Value>,
1897}
1898
1899#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1900pub struct ConfirmArgs {
1901 pub title: String,
1902 pub message: String,
1903 #[serde(default = "default_confirm_label")]
1904 pub confirm_label: String,
1905 #[serde(default = "default_cancel_label")]
1906 pub cancel_label: String,
1907 #[serde(default)]
1909 pub destructive: bool,
1910}
1911
1912fn default_confirm_label() -> String {
1913 "OK".to_string()
1914}
1915fn default_cancel_label() -> String {
1916 "Cancel".to_string()
1917}
1918
1919#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1920pub struct FileDialogArgs {
1921 #[serde(default)]
1922 pub title: Option<String>,
1923 #[serde(default)]
1924 pub filters: Vec<FileFilter>,
1925 #[serde(default)]
1927 pub default_name: Option<String>,
1928 #[serde(default)]
1930 pub directory: bool,
1931 #[serde(default)]
1933 pub multiple: bool,
1934}
1935
1936#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1937pub struct RequestId {
1938 pub request_id: String,
1939}
1940
1941#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
1942pub struct PaneArgs {
1943 #[serde(default)]
1945 pub pane: Option<PaneId>,
1946}
1947
1948#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1949pub struct ViewSetArgs {
1950 #[serde(default)]
1951 pub pane: Option<PaneId>,
1952 pub center_x: f64,
1953 pub center_y: f64,
1954 pub zoom: f64,
1955 #[serde(default)]
1956 pub animate: bool,
1957}
1958
1959#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1960pub struct ViewPanArgs {
1961 #[serde(default)]
1962 pub pane: Option<PaneId>,
1963 pub dx: f64,
1965 pub dy: f64,
1966}
1967
1968#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1969pub struct ViewZoomArgs {
1970 #[serde(default)]
1971 pub pane: Option<PaneId>,
1972 pub factor: f64,
1974 #[serde(default)]
1976 pub anchor_x: Option<f64>,
1977 #[serde(default)]
1978 pub anchor_y: Option<f64>,
1979 #[serde(default)]
1980 pub animate: bool,
1981}
1982
1983#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1984pub struct ViewOrientationArgs {
1985 #[serde(default)]
1986 pub pane: Option<PaneId>,
1987 pub rotation_deg: f64,
1990 #[serde(default)]
1992 pub flipped: bool,
1993}
1994
1995#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1996pub struct ViewFrameArgs {
1997 #[serde(default)]
1998 pub pane: Option<PaneId>,
1999 pub rect: Rect,
2000 #[serde(default)]
2002 pub padding: Option<f64>,
2003}
2004
2005#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
2006pub struct OffsetArgs {
2007 pub offset: i32,
2008}
2009
2010#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2011#[serde(rename_all = "snake_case")]
2012pub enum SeriesAction {
2013 Toggle,
2014 Next,
2015 Previous,
2016 OpenSelected,
2017}
2018
2019#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
2020pub struct SeriesArgs {
2021 pub action: SeriesAction,
2022}
2023
2024#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2025pub struct UndoPushArgs {
2026 pub entry_id: String,
2028 #[serde(default)]
2030 pub file_id: Option<FileId>,
2031 pub label: String,
2033}
2034
2035#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
2036pub struct UndoClearArgs {
2037 #[serde(default)]
2039 pub file_id: Option<FileId>,
2040}
2041
2042#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2043pub struct FilterEnableArgs {
2044 pub filter_id: String,
2045 pub enabled: bool,
2046}
2047
2048#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2049pub struct KeyArgs {
2050 pub key: String,
2051}
2052
2053#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2054pub struct SettingsSetArgs {
2055 pub key: String,
2056 pub value: Value,
2058}
2059
2060#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2061pub struct JobStartArgs {
2062 pub title: String,
2063 #[serde(default)]
2064 pub cancellable: bool,
2065}
2066
2067#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2068pub struct JobStarted {
2069 pub job_id: String,
2070}
2071
2072#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2073pub struct JobUpdateArgs {
2074 pub job_id: String,
2075 #[serde(default)]
2077 pub fraction: Option<f32>,
2078 #[serde(default)]
2079 pub message: Option<String>,
2080}
2081
2082#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2083pub struct JobFinishArgs {
2084 pub job_id: String,
2085 #[serde(default)]
2087 pub error: Option<String>,
2088}
2089
2090#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2091pub struct TextArgs {
2092 pub text: String,
2093}
2094
2095#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
2098pub struct ModelFileSpec {
2099 pub sha256: String,
2101 #[serde(default)]
2104 pub url: Option<String>,
2105 #[serde(default)]
2108 pub file_name: Option<String>,
2109 #[serde(default)]
2112 pub size: Option<u64>,
2113}
2114
2115#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
2119pub struct ModelFetchArgs {
2120 #[serde(default)]
2124 pub url: Option<String>,
2125 pub sha256: String,
2127 #[serde(default)]
2129 pub size: Option<u64>,
2130 #[serde(default)]
2133 pub file_name: Option<String>,
2134 #[serde(default)]
2136 pub name: Option<String>,
2137 #[serde(default)]
2138 pub version: Option<String>,
2139 #[serde(default)]
2141 pub companions: Vec<ModelFileSpec>,
2142}
2143
2144#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
2146pub struct ModelResolveArgs {
2147 pub sha256: String,
2149}
2150
2151#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
2153pub struct ModelCompanion {
2154 pub file_name: String,
2155 pub sha256: String,
2156 pub size: u64,
2157 #[serde(default)]
2159 pub path: String,
2160}
2161
2162#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
2164pub struct ModelRecord {
2165 pub sha256: String,
2167 pub path: String,
2169 pub file_name: String,
2170 pub size: u64,
2172 #[serde(default)]
2173 pub name: Option<String>,
2174 #[serde(default)]
2175 pub version: Option<String>,
2176 #[serde(default)]
2179 pub source: Option<String>,
2180 #[serde(default)]
2182 pub fetched_at: Option<String>,
2183 #[serde(default)]
2185 pub requested_by: Option<String>,
2186 #[serde(default)]
2187 pub companions: Vec<ModelCompanion>,
2188 #[serde(default)]
2191 pub read_only: bool,
2192}
2193
2194impl ModelRecord {
2195 pub fn has_companion(&self, sha256: &str, file_name: &str) -> bool {
2197 self.companions
2198 .iter()
2199 .any(|c| c.sha256.eq_ignore_ascii_case(sha256) && c.file_name == file_name)
2200 }
2201}
2202
2203pub fn is_sha256_hex(text: &str) -> bool {
2205 text.len() == 64 && text.bytes().all(|b| b.is_ascii_hexdigit())
2206}
2207
2208pub fn check_model_file_name(name: &str) -> Result<(), String> {
2211 let stem = name.split('.').next().unwrap_or_default();
2213 let reserved = ["CON", "PRN", "AUX", "NUL"]
2214 .iter()
2215 .any(|r| stem.eq_ignore_ascii_case(r))
2216 || (stem.len() == 4
2217 && stem.is_ascii()
2218 && ["COM", "LPT"]
2219 .iter()
2220 .any(|p| stem[..3].eq_ignore_ascii_case(p))
2221 && stem.as_bytes()[3].is_ascii_digit());
2222 if name.is_empty()
2223 || name.len() > 200
2224 || name.starts_with('.')
2225 || name.ends_with('.')
2226 || name.ends_with(' ')
2227 || name.chars().any(|c| {
2228 c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|')
2229 })
2230 || reserved
2231 {
2232 return Err(format!(
2233 "'{name}' cannot be a model's file name (use a plain name such as model.onnx)"
2234 ));
2235 }
2236 Ok(())
2237}
2238
2239impl ModelFileSpec {
2240 fn check(&self, what: &str) -> Result<(), String> {
2241 if !is_sha256_hex(&self.sha256) {
2242 return Err(format!(
2243 "the {what}'s sha256 must be 64 hex digits, not '{}'",
2244 self.sha256
2245 ));
2246 }
2247 if let Some(name) = &self.file_name {
2248 check_model_file_name(name)?;
2249 }
2250 if self.size == Some(0) {
2251 return Err(format!("the {what}'s size cannot be 0"));
2252 }
2253 Ok(())
2254 }
2255}
2256
2257impl ModelFetchArgs {
2258 pub fn validate(&self) -> Result<(), String> {
2261 ModelFileSpec {
2262 sha256: self.sha256.clone(),
2263 url: self.url.clone(),
2264 file_name: self.file_name.clone(),
2265 size: self.size,
2266 }
2267 .check("model")?;
2268 let mut names: Vec<&str> = self.file_name.iter().map(String::as_str).collect();
2269 for companion in &self.companions {
2270 companion.check("companion")?;
2271 let name = companion.file_name.as_deref();
2272 if companion.url.is_none() && name.is_none() {
2273 return Err("a companion without a url needs a file_name".to_string());
2274 }
2275 if let Some(name) = name {
2276 if names.iter().any(|n| n.eq_ignore_ascii_case(name)) {
2277 return Err(format!("two files of the model are named '{name}'"));
2278 }
2279 names.push(name);
2280 }
2281 }
2282 if self.companions.len() > 64 {
2283 return Err("a model has at most 64 companion files".to_string());
2284 }
2285 Ok(())
2286 }
2287}
2288
2289pub type PropertyMap = BTreeMap<String, String>;
2291
2292pub const MAX_SLIDE_LEVELS: usize = 64;
2298
2299pub const MAX_SLIDE_SIDE: u64 = 1 << 24;
2301
2302pub const MAX_ASSOCIATED_IMAGES: usize = 32;
2304
2305pub const MAX_ASSOCIATED_IMAGE_PIXELS: u64 = 1 << 28;
2307
2308#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
2311pub struct SlideOpenRequest {
2312 pub format_id: String,
2315 pub location: String,
2317 #[serde(default)]
2319 pub is_uri: bool,
2320}
2321
2322#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
2324pub struct SlideLevel {
2325 pub width: u64,
2326 pub height: u64,
2327 #[serde(default)]
2331 pub downsample: Option<f64>,
2332 #[serde(default)]
2335 pub tile_width: Option<u32>,
2336 #[serde(default)]
2337 pub tile_height: Option<u32>,
2338}
2339
2340#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
2346pub struct AssociatedImageInfo {
2347 pub name: String,
2348 pub width: u32,
2349 pub height: u32,
2350}
2351
2352#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
2360pub struct SlideInfo {
2361 pub levels: Vec<SlideLevel>,
2364 #[serde(default)]
2367 pub vendor: Option<String>,
2368 #[serde(default)]
2370 pub mpp_x: Option<f64>,
2371 #[serde(default)]
2372 pub mpp_y: Option<f64>,
2373 #[serde(default)]
2375 pub objective_power: Option<f64>,
2376 #[serde(default)]
2378 pub scan_date: Option<String>,
2379 #[serde(default)]
2380 pub comment: Option<String>,
2381 #[serde(default)]
2383 pub stain: Option<String>,
2384 #[serde(default)]
2386 pub background: Option<[u8; 3]>,
2387 #[serde(default)]
2390 pub bounds: Option<Rect>,
2391 #[serde(default)]
2394 pub properties: PropertyMap,
2395 #[serde(default)]
2396 pub associated_images: Vec<AssociatedImageInfo>,
2397 #[serde(default)]
2403 pub identity: Option<String>,
2404 #[serde(default)]
2408 pub member_files: Vec<String>,
2409}
2410
2411impl SlideInfo {
2412 pub fn validate(&self) -> Result<(), String> {
2419 let count = self.levels.len();
2420 if count == 0 || count > MAX_SLIDE_LEVELS {
2421 return Err(format!(
2422 "a slide has 1–{MAX_SLIDE_LEVELS} levels, not {count}"
2423 ));
2424 }
2425 let base = self.levels[0];
2426 let mut previous: Option<(SlideLevel, f64)> = None;
2427 for (index, level) in self.levels.iter().enumerate() {
2428 if level.width == 0
2429 || level.height == 0
2430 || level.width > MAX_SLIDE_SIDE
2431 || level.height > MAX_SLIDE_SIDE
2432 {
2433 return Err(format!(
2434 "level {index} is {}×{}; sides must be 1–{MAX_SLIDE_SIDE} pixels",
2435 level.width, level.height
2436 ));
2437 }
2438 let ratio = (base.width as f64 / level.width as f64
2439 + base.height as f64 / level.height as f64)
2440 / 2.0;
2441 let downsample = level.downsample.unwrap_or(ratio);
2442 if !downsample.is_finite() || downsample < 1.0 {
2443 return Err(format!(
2444 "level {index} has downsample {downsample}; it must be a number of at least 1"
2445 ));
2446 }
2447 if index == 0 && (downsample - 1.0).abs() > 1e-6 {
2448 return Err(format!("level 0 has downsample {downsample}, not 1"));
2449 }
2450 if downsample > ratio * 2.0 || downsample < ratio / 2.0 {
2451 return Err(format!(
2452 "level {index} is {}×{} but has downsample {downsample}",
2453 level.width, level.height
2454 ));
2455 }
2456 if let Some((prev, prev_downsample)) = previous {
2457 if level.width > prev.width || level.height > prev.height {
2458 return Err(format!(
2459 "level {index} ({}×{}) is larger than level {} ({}×{})",
2460 level.width,
2461 level.height,
2462 index - 1,
2463 prev.width,
2464 prev.height
2465 ));
2466 }
2467 if downsample < prev_downsample {
2468 return Err(format!(
2469 "level {index} has a smaller downsample than level {}",
2470 index - 1
2471 ));
2472 }
2473 }
2474 previous = Some((*level, downsample));
2475 }
2476 if self.associated_images.len() > MAX_ASSOCIATED_IMAGES {
2477 return Err(format!(
2478 "a slide has at most {MAX_ASSOCIATED_IMAGES} associated images"
2479 ));
2480 }
2481 let mut names = std::collections::BTreeSet::new();
2482 for image in &self.associated_images {
2483 let name = image.name.as_str();
2484 if name.is_empty() || name.chars().count() > 64 || name.chars().any(char::is_control) {
2485 return Err(format!(
2486 "associated image names are 1–64 printable characters, not {name:?}"
2487 ));
2488 }
2489 if !names.insert(name) {
2490 return Err(format!("associated image {name:?} is listed twice"));
2491 }
2492 let pixels = u64::from(image.width) * u64::from(image.height);
2493 if pixels == 0 || pixels > MAX_ASSOCIATED_IMAGE_PIXELS {
2494 return Err(format!(
2495 "associated image {name:?} is {}×{}",
2496 image.width, image.height
2497 ));
2498 }
2499 }
2500 Ok(())
2501 }
2502}
2503
2504#[cfg(test)]
2505mod tests {
2506 use super::*;
2507
2508 #[test]
2509 fn views_map_screen_and_image_through_their_turn() {
2510 let mut view = ViewInfo {
2511 center_x: 100.0,
2512 center_y: 50.0,
2513 zoom: 2.0,
2514 width: 300.0,
2515 height: 200.0,
2516 ..Default::default()
2517 };
2518 assert_eq!(view.image_to_screen(110.0, 50.0), (170.0, 100.0));
2519 view.rotation_deg = 90.0;
2521 let (x, y) = view.image_to_screen(110.0, 50.0);
2522 assert!((x - 150.0).abs() < 1e-9 && (y - 120.0).abs() < 1e-9);
2523 for rotation in [0.0, 90.0, 180.0, 270.0, 37.5, 301.25] {
2524 for flipped in [false, true] {
2525 view.rotation_deg = rotation;
2526 view.flipped = flipped;
2527 let (sx, sy) = view.image_to_screen(37.0, 81.0);
2528 let (ix, iy) = view.screen_to_image(sx, sy);
2529 assert!((ix - 37.0).abs() < 1e-9 && (iy - 81.0).abs() < 1e-9);
2530 }
2531 }
2532 let old: ViewInfo = serde_json::from_str(
2534 r#"{"pane":1,"file_id":1,"center_x":0,"center_y":0,"zoom":1,"width":1,"height":1,"visible":{"x":0,"y":0,"width":1,"height":1}}"#,
2535 )
2536 .unwrap();
2537 assert_eq!((old.rotation_deg, old.flipped), (0.0, false));
2538 }
2539
2540 #[test]
2541 fn unknown_events_deserialize_to_unknown() {
2542 let event: HostEvent =
2543 serde_json::from_str(r#"{"type":"something_from_the_future","x":1}"#).unwrap();
2544 assert_eq!(event, HostEvent::Unknown);
2545 }
2546
2547 #[test]
2548 fn events_round_trip() {
2549 let event = HostEvent::ShapeDrawn {
2550 tool_id: "poly".into(),
2551 pane: 3,
2552 file_id: 7,
2553 shape: Shape::Polygon {
2554 exterior: vec![[0.0, 0.0], [10.0, 0.0], [5.0, 8.0]],
2555 holes: vec![],
2556 },
2557 modifiers: Modifiers::default(),
2558 };
2559 let text = serde_json::to_string(&event).unwrap();
2560 assert!(text.contains(r#""type":"shape_drawn""#), "{text}");
2561 assert!(text.contains(r#""kind":"polygon""#), "{text}");
2562 assert_eq!(serde_json::from_str::<HostEvent>(&text).unwrap(), event);
2563 }
2564
2565 #[test]
2566 fn optional_fields_may_be_absent() {
2567 let event: HostEvent = serde_json::from_str(
2568 r#"{"type":"object_clicked","object":{"layer_id":"l","object_id":"o"},"pane":1}"#,
2569 )
2570 .unwrap();
2571 match event {
2572 HostEvent::ObjectClicked {
2573 click_count,
2574 button,
2575 ..
2576 } => {
2577 assert_eq!(click_count, 1);
2578 assert_eq!(button, PointerButton::None);
2579 }
2580 other => panic!("unexpected {other:?}"),
2581 }
2582 let spec: LayerSpec = serde_json::from_str(r#"{"layer_id":"a","file_id":1}"#).unwrap();
2583 assert!(spec.visible);
2584 assert_eq!(spec.opacity, 1.0);
2585 assert_eq!(spec.style, Style::default());
2586 }
2587
2588 #[test]
2593 fn defaults_are_what_absent_fields_deserialize_to() {
2594 let button: ToolbarButtonSpec =
2595 serde_json::from_str(r#"{"button_id":"","tooltip":"","icon_svg":""}"#).unwrap();
2596 assert_eq!(button, ToolbarButtonSpec::default());
2597 assert!(button.enabled);
2598 let item: MenuItem = serde_json::from_str(r#"{"item_id":"","label":""}"#).unwrap();
2599 assert_eq!(item, MenuItem::default());
2600 assert!(item.enabled);
2601 let view: ViewInfo = serde_json::from_str(
2602 r#"{"pane":0,"file_id":0,"center_x":0,"center_y":0,"zoom":0,"width":0,"height":0,
2603 "visible":{"x":0,"y":0,"width":0,"height":0}}"#,
2604 )
2605 .unwrap();
2606 assert_eq!(view, ViewInfo::default());
2607 assert_eq!(view.scale_factor, 1.0);
2608
2609 let sent = serde_json::to_value(ToolbarButtonSpec {
2612 button_id: "b".into(),
2613 ..Default::default()
2614 })
2615 .unwrap();
2616 assert_eq!(sent["enabled"], true);
2617 let disabled: ToolbarButtonSpec =
2618 serde_json::from_str(r#"{"button_id":"b","tooltip":"","icon_svg":"","enabled":false}"#)
2619 .unwrap();
2620 assert!(!disabled.enabled);
2621 }
2622
2623 #[test]
2624 fn channel_names_are_optional_both_ways() {
2625 let file: FileInfo = serde_json::from_str(
2627 r#"{"file_id":1,"path":"/s.svs","filename":"s.svs","width":10,"height":20}"#,
2628 )
2629 .unwrap();
2630 assert!(file.channel_names.is_empty());
2631 let file = FileInfo {
2633 channel_names: vec!["DAPI".into(), "CD45".into()],
2634 ..file
2635 };
2636 let text = serde_json::to_string(&file).unwrap();
2637 assert!(
2638 text.contains(r#""channel_names":["DAPI","CD45"]"#),
2639 "{text}"
2640 );
2641 assert_eq!(serde_json::from_str::<FileInfo>(&text).unwrap(), file);
2642 }
2643
2644 fn level(width: u64, height: u64, downsample: Option<f64>) -> SlideLevel {
2645 SlideLevel {
2646 width,
2647 height,
2648 downsample,
2649 ..SlideLevel::default()
2650 }
2651 }
2652
2653 #[test]
2654 fn slide_infos_are_validated_as_eov_does() {
2655 let good = SlideInfo {
2656 levels: vec![
2657 level(1000, 800, None),
2658 level(250, 200, Some(4.0)),
2659 level(63, 50, None),
2660 ],
2661 associated_images: vec![AssociatedImageInfo {
2662 name: "label".into(),
2663 width: 10,
2664 height: 10,
2665 }],
2666 ..SlideInfo::default()
2667 };
2668 assert_eq!(good.validate(), Ok(()));
2669 let parsed: SlideInfo =
2671 serde_json::from_str(r#"{"levels":[{"width":10,"height":10}]}"#).unwrap();
2672 assert_eq!(parsed.validate(), Ok(()));
2673
2674 let bad = |change: &dyn Fn(&mut SlideInfo)| {
2675 let mut info = good.clone();
2676 change(&mut info);
2677 info.validate().unwrap_err()
2678 };
2679 assert!(bad(&|i| i.levels.clear()).contains("levels"));
2680 assert!(bad(&|i| i.levels[0].width = 0).contains("sides"));
2681 assert!(bad(&|i| i.levels[0].height = MAX_SLIDE_SIDE + 1).contains("sides"));
2682 assert!(bad(&|i| i.levels[1].width = 2000).contains("larger"));
2683 assert!(bad(&|i| i.levels[0].downsample = Some(2.0)).contains("level 0"));
2684 assert!(bad(&|i| i.levels[1].downsample = Some(f64::NAN)).contains("downsample"));
2685 assert!(bad(&|i| i.levels[1].downsample = Some(40.0)).contains("downsample 40"));
2686 assert!(bad(&|i| i.levels[2] = level(250, 200, Some(3.9))).contains("smaller downsample"));
2688 assert!(bad(&|i| i.levels[2].downsample = Some(3.5)).contains("downsample 3.5"));
2689 assert!(
2690 bad(&|i| i.associated_images.push(i.associated_images[0].clone())).contains("twice")
2691 );
2692 assert!(bad(&|i| i.associated_images[0].width = 0).contains("label"));
2693 assert!(bad(&|i| i.associated_images[0].name = String::new()).contains("names"));
2694 }
2695
2696 #[test]
2697 fn model_events_and_requests_are_additive() {
2698 let event: HostEvent =
2700 serde_json::from_str(r#"{"type":"model_fetched","request_id":"model-1"}"#).unwrap();
2701 assert_eq!(
2702 event,
2703 HostEvent::ModelFetched {
2704 request_id: "model-1".into(),
2705 path: None,
2706 model: None,
2707 error: None,
2708 cancelled: false,
2709 }
2710 );
2711 let args: ModelFetchArgs = serde_json::from_str(
2712 r#"{"sha256":"70a8deef1f01716efbc87feb181ea398425d08b5e4984ad9d4ab2b83fd354f92"}"#,
2713 )
2714 .unwrap();
2715 assert!(args.validate().is_ok());
2716 let record: ModelRecord =
2717 serde_json::from_str(r#"{"sha256":"a","path":"/m","file_name":"m","size":1}"#).unwrap();
2718 assert!(record.companions.is_empty() && !record.read_only);
2719 }
2720
2721 #[test]
2722 fn model_requests_are_validated() {
2723 let sha = "70a8deef1f01716efbc87feb181ea398425d08b5e4984ad9d4ab2b83fd354f92";
2724 let base = ModelFetchArgs {
2725 sha256: sha.into(),
2726 ..Default::default()
2727 };
2728 assert!(base.validate().is_ok());
2729 let upper = ModelFetchArgs {
2730 sha256: sha.to_ascii_uppercase(),
2731 ..base.clone()
2732 };
2733 assert!(upper.validate().is_ok(), "either case is hex");
2734 for bad in [
2735 ModelFetchArgs {
2736 sha256: "70a8".into(),
2737 ..base.clone()
2738 },
2739 ModelFetchArgs {
2740 size: Some(0),
2741 ..base.clone()
2742 },
2743 ModelFetchArgs {
2744 file_name: Some("../escape.onnx".into()),
2745 ..base.clone()
2746 },
2747 ModelFetchArgs {
2748 file_name: Some("m.onnx".into()),
2749 companions: vec![ModelFileSpec {
2750 sha256: sha.into(),
2751 file_name: Some("M.ONNX".into()),
2752 ..Default::default()
2753 }],
2754 ..base.clone()
2755 },
2756 ] {
2757 assert!(bad.validate().is_err(), "{bad:?}");
2758 }
2759 for name in [
2760 "",
2761 ".hidden",
2762 "a/b",
2763 "a\\b",
2764 "c:x",
2765 "CON",
2766 "com1.onnx",
2767 "x.",
2768 "x\n",
2769 ] {
2770 assert!(check_model_file_name(name).is_err(), "{name:?}");
2771 }
2772 for name in [
2773 "model.onnx",
2774 "HistoVae_reconstruct.onnx.data",
2775 "console.onnx",
2776 "aaé.onnx",
2777 ] {
2778 assert!(check_model_file_name(name).is_ok(), "{name:?}");
2779 }
2780 }
2781
2782 #[test]
2783 fn rgba_hex_round_trip() {
2784 assert_eq!(Rgba::from_hex("#FF8000"), Some(Rgba(255, 128, 0, 255)));
2785 assert_eq!(Rgba::from_hex("#ff800080"), Some(Rgba(255, 128, 0, 128)));
2786 assert_eq!(Rgba::from_hex("FF8000"), None);
2787 assert_eq!(Rgba::from_hex("#aé0000"), None);
2788 assert_eq!(Rgba(1, 2, 3, 255).to_hex(), "#010203");
2789 assert_eq!(Rgba::from_u32(Rgba(9, 8, 7, 6).to_u32()), Rgba(9, 8, 7, 6));
2790 }
2791}