1use crate::anchor::Anchor;
4use crate::geom::{DisplayId, LogicalPoint, LogicalRect};
5use crate::ids::AnnotationId;
6use crate::position::Position;
7use crate::validate::{Validate, ValidationError};
8use serde::{Deserialize, Serialize};
9
10fn is_false(b: &bool) -> bool {
11 !*b
12}
13
14fn validate_ttl(ttl_ms: Option<u64>) -> Result<(), ValidationError> {
20 match ttl_ms {
21 Some(0) => Err(ValidationError::ZeroTtl),
22 _ => Ok(()),
23 }
24}
25
26#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
28#[serde(tag = "type", rename_all = "snake_case")]
29pub enum ClientMessage {
30 SessionStart(SessionStart),
32 Point(Point),
34 Highlight(Highlight),
36 Textbox(Textbox),
38 Draw(Draw),
40 Arrow(Arrow),
42 Clear(Clear),
44 Focus(Focus),
46 AwaitWindow(AwaitWindow),
48 SessionEnd,
50}
51
52impl Validate for ClientMessage {
53 fn validate(&self) -> Result<(), ValidationError> {
54 match self {
55 Self::SessionStart(m) => m.validate(),
56 Self::Point(m) => m.validate(),
57 Self::Highlight(m) => m.validate(),
58 Self::Textbox(m) => m.validate(),
59 Self::Draw(m) => m.validate(),
60 Self::Arrow(m) => m.validate(),
61 Self::Clear(m) => m.validate(),
62 Self::Focus(m) => m.validate(),
63 Self::AwaitWindow(m) => m.validate(),
64 Self::SessionEnd => Ok(()),
65 }
66 }
67}
68
69#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
81pub struct Focus {
82 pub app: String,
88}
89
90impl Validate for Focus {
91 fn validate(&self) -> Result<(), ValidationError> {
92 if self.app.trim().is_empty() {
93 return Err(ValidationError::Empty { field: "app" });
94 }
95 Ok(())
96 }
97}
98
99#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
110pub struct AwaitWindow {
111 pub app: String,
113 #[serde(default, skip_serializing_if = "Option::is_none")]
119 pub timeout_ms: Option<u64>,
120}
121
122impl Validate for AwaitWindow {
123 fn validate(&self) -> Result<(), ValidationError> {
124 if self.app.trim().is_empty() {
125 return Err(ValidationError::Empty { field: "app" });
126 }
127 if self.timeout_ms == Some(0) {
130 return Err(ValidationError::ZeroTtl);
131 }
132 Ok(())
133 }
134}
135
136#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
138pub struct SessionStart {
139 pub client_name: String,
141}
142
143impl Validate for SessionStart {
144 fn validate(&self) -> Result<(), ValidationError> {
145 if self.client_name.trim().is_empty() {
146 return Err(ValidationError::Empty {
147 field: "client_name",
148 });
149 }
150 Ok(())
151 }
152}
153
154#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
159pub struct Point {
160 #[serde(default, skip_serializing_if = "Option::is_none")]
162 pub x: Option<f64>,
163 #[serde(default, skip_serializing_if = "Option::is_none")]
165 pub y: Option<f64>,
166 #[serde(default, skip_serializing_if = "Option::is_none")]
171 pub at: Option<String>,
172 #[serde(default, skip_serializing_if = "Option::is_none")]
174 pub query: Option<String>,
175 pub display_id: DisplayId,
177 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub label: Option<String>,
180 #[serde(default, skip_serializing_if = "Option::is_none")]
184 pub ttl_ms: Option<u64>,
185}
186
187#[derive(Debug, Clone, Copy, PartialEq)]
189pub enum PointTarget<'a> {
190 Coords(LogicalPoint),
192 Named(Position),
194 Query(&'a str),
196}
197
198impl Point {
199 pub const fn at(x: f64, y: f64, display_id: DisplayId) -> Self {
201 Self {
202 x: Some(x),
203 y: Some(y),
204 at: None,
205 query: None,
206 display_id,
207 label: None,
208 ttl_ms: None,
209 }
210 }
211
212 pub fn query(query: impl Into<String>, display_id: DisplayId) -> Self {
214 Self {
215 x: None,
216 y: None,
217 at: None,
218 query: Some(query.into()),
219 display_id,
220 label: None,
221 ttl_ms: None,
222 }
223 }
224
225 pub fn named(at: impl Into<String>, display_id: DisplayId) -> Self {
227 Self {
228 x: None,
229 y: None,
230 at: Some(at.into()),
231 query: None,
232 display_id,
233 label: None,
234 ttl_ms: None,
235 }
236 }
237
238 #[must_use]
240 pub fn with_label(mut self, label: impl Into<String>) -> Self {
241 self.label = Some(label.into());
242 self
243 }
244
245 #[must_use]
247 pub fn with_ttl_ms(mut self, ttl_ms: Option<u64>) -> Self {
248 self.ttl_ms = ttl_ms;
249 self
250 }
251
252 pub fn target(&self) -> Result<PointTarget<'_>, ValidationError> {
258 const EXPECTED: &str = "x and y, or at, or query";
259
260 let coords = self.x.is_some() || self.y.is_some();
261 let named = self.at.is_some();
262 let queried = self.query.is_some();
263
264 match (coords, named, queried) {
265 (false, false, false) => {
266 return Err(ValidationError::MissingTarget {
267 message: "point",
268 expected: EXPECTED,
269 });
270 }
271 (true, true, _) | (true, _, true) | (_, true, true) => {
273 return Err(ValidationError::AmbiguousTarget {
274 message: "point",
275 expected: EXPECTED,
276 });
277 }
278 _ => {}
279 }
280
281 if let Some(at) = self.at.as_deref() {
282 return Position::parse(at).map(PointTarget::Named);
283 }
284
285 if let Some(query) = self.query.as_deref() {
286 return if query.trim().is_empty() {
287 Err(ValidationError::Empty { field: "query" })
288 } else {
289 Ok(PointTarget::Query(query))
290 };
291 }
292
293 match (self.x, self.y) {
294 (Some(x), Some(y)) => {
295 let p = LogicalPoint::new(x, y);
296 if !p.is_finite() {
297 return Err(ValidationError::NonFiniteCoordinate { field: "x, y" });
298 }
299 Ok(PointTarget::Coords(p))
300 }
301 _ => Err(ValidationError::AmbiguousTarget {
304 message: "point",
305 expected: EXPECTED,
306 }),
307 }
308 }
309}
310
311impl Validate for Point {
312 fn validate(&self) -> Result<(), ValidationError> {
313 validate_ttl(self.ttl_ms)?;
314 self.target().map(|_| ())
315 }
316}
317
318#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
320pub struct Highlight {
321 #[serde(default, skip_serializing_if = "Option::is_none")]
323 pub rect: Option<LogicalRect>,
324 #[serde(default, skip_serializing_if = "Option::is_none")]
326 pub query: Option<String>,
327 pub display_id: DisplayId,
329 #[serde(default, skip_serializing_if = "Option::is_none")]
331 pub label: Option<String>,
332 #[serde(default, skip_serializing_if = "Option::is_none")]
336 pub ttl_ms: Option<u64>,
337}
338
339#[derive(Debug, Clone, Copy, PartialEq)]
341pub enum HighlightTarget<'a> {
342 Rect(LogicalRect),
344 Query(&'a str),
346}
347
348impl Highlight {
349 pub const fn over(rect: LogicalRect, display_id: DisplayId) -> Self {
351 Self {
352 rect: Some(rect),
353 query: None,
354 display_id,
355 label: None,
356 ttl_ms: None,
357 }
358 }
359
360 pub fn query(query: impl Into<String>, display_id: DisplayId) -> Self {
362 Self {
363 rect: None,
364 query: Some(query.into()),
365 display_id,
366 label: None,
367 ttl_ms: None,
368 }
369 }
370
371 #[must_use]
373 pub fn with_label(mut self, label: impl Into<String>) -> Self {
374 self.label = Some(label.into());
375 self
376 }
377
378 #[must_use]
380 pub fn with_ttl_ms(mut self, ttl_ms: Option<u64>) -> Self {
381 self.ttl_ms = ttl_ms;
382 self
383 }
384
385 pub fn target(&self) -> Result<HighlightTarget<'_>, ValidationError> {
387 const EXPECTED: &str = "rect or query";
388 match (self.rect, self.query.as_deref()) {
389 (Some(rect), None) => {
390 if !rect.is_valid() {
391 return Err(ValidationError::InvalidRect { field: "rect" });
392 }
393 Ok(HighlightTarget::Rect(rect))
394 }
395 (None, Some(q)) if !q.trim().is_empty() => Ok(HighlightTarget::Query(q)),
396 (None, Some(_)) => Err(ValidationError::Empty { field: "query" }),
397 (None, None) => Err(ValidationError::MissingTarget {
398 message: "highlight",
399 expected: EXPECTED,
400 }),
401 (Some(_), Some(_)) => Err(ValidationError::AmbiguousTarget {
402 message: "highlight",
403 expected: EXPECTED,
404 }),
405 }
406 }
407}
408
409impl Validate for Highlight {
410 fn validate(&self) -> Result<(), ValidationError> {
411 validate_ttl(self.ttl_ms)?;
412 self.target().map(|_| ())
413 }
414}
415
416#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
421pub struct Textbox {
422 #[serde(default, skip_serializing_if = "Option::is_none")]
424 pub anchor: Option<Anchor>,
425 #[serde(default, skip_serializing_if = "Option::is_none")]
427 pub rect: Option<LogicalRect>,
428 #[serde(default, skip_serializing_if = "Option::is_none")]
430 pub display_id: Option<DisplayId>,
431 pub text: String,
433 #[serde(default, skip_serializing_if = "Option::is_none")]
437 pub style: Option<TextboxStyle>,
438 #[serde(default, skip_serializing_if = "Option::is_none")]
442 pub ttl_ms: Option<u64>,
443}
444
445#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
452#[serde(rename_all = "snake_case")]
453pub enum TextboxStyle {
454 #[default]
456 Note,
457 Guide,
460}
461
462impl Textbox {
463 pub fn new(anchor: Anchor, text: impl Into<String>) -> Self {
465 Self {
466 anchor: Some(anchor),
467 rect: None,
468 display_id: None,
469 text: text.into(),
470 style: None,
471 ttl_ms: None,
472 }
473 }
474
475 #[must_use]
477 pub fn with_style(mut self, style: TextboxStyle) -> Self {
478 self.style = Some(style);
479 self
480 }
481
482 #[must_use]
484 pub fn with_ttl_ms(mut self, ttl_ms: Option<u64>) -> Self {
485 self.ttl_ms = ttl_ms;
486 self
487 }
488
489 pub fn resolved_anchor(&self) -> Result<Anchor, ValidationError> {
491 const EXPECTED: &str = "anchor, or rect with display_id";
492 match (&self.anchor, self.rect, self.display_id) {
493 (Some(anchor), None, None) => {
494 if !anchor.screen_rect.is_valid() {
495 return Err(ValidationError::InvalidRect {
496 field: "anchor.screen_rect",
497 });
498 }
499 Ok(anchor.clone())
500 }
501 (None, Some(rect), Some(display_id)) => {
502 if !rect.is_valid() {
503 return Err(ValidationError::InvalidRect { field: "rect" });
504 }
505 Ok(Anchor::new(rect, display_id))
506 }
507 (None, None, _) => Err(ValidationError::MissingTarget {
508 message: "textbox",
509 expected: EXPECTED,
510 }),
511 _ => Err(ValidationError::AmbiguousTarget {
512 message: "textbox",
513 expected: EXPECTED,
514 }),
515 }
516 }
517}
518
519impl Validate for Textbox {
520 fn validate(&self) -> Result<(), ValidationError> {
521 validate_ttl(self.ttl_ms)?;
522 if self.text.trim().is_empty() {
523 return Err(ValidationError::Empty { field: "text" });
524 }
525 self.resolved_anchor().map(|_| ())
526 }
527}
528
529#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
531pub struct Draw {
532 pub display_id: DisplayId,
534 pub path: Vec<[f64; 2]>,
536 #[serde(default, skip_serializing_if = "Option::is_none")]
538 pub style: Option<StrokeStyle>,
539 #[serde(default, skip_serializing_if = "Option::is_none")]
543 pub ttl_ms: Option<u64>,
544}
545
546impl Draw {
547 pub fn new(display_id: DisplayId, path: Vec<[f64; 2]>) -> Self {
549 Self {
550 display_id,
551 path,
552 style: None,
553 ttl_ms: None,
554 }
555 }
556
557 #[must_use]
559 pub fn with_ttl_ms(mut self, ttl_ms: Option<u64>) -> Self {
560 self.ttl_ms = ttl_ms;
561 self
562 }
563
564 pub fn points(&self) -> impl Iterator<Item = LogicalPoint> + '_ {
566 self.path.iter().map(|&[x, y]| LogicalPoint::new(x, y))
567 }
568}
569
570impl Validate for Draw {
571 fn validate(&self) -> Result<(), ValidationError> {
572 validate_ttl(self.ttl_ms)?;
573 if self.path.len() < 2 {
574 return Err(ValidationError::PathTooShort {
575 got: self.path.len(),
576 });
577 }
578 if !self.points().all(|p| p.is_finite()) {
579 return Err(ValidationError::NonFiniteCoordinate { field: "path" });
580 }
581 Ok(())
582 }
583}
584
585#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
587pub struct StrokeStyle {
588 #[serde(default, skip_serializing_if = "Option::is_none")]
590 pub width: Option<f64>,
591 #[serde(default, skip_serializing_if = "Option::is_none")]
596 pub color: Option<String>,
597}
598
599#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
608pub struct Arrow {
609 pub display_id: DisplayId,
611 pub from: ArrowEnd,
613 pub to: ArrowEnd,
615 #[serde(default, skip_serializing_if = "Option::is_none")]
621 pub bow: Option<f64>,
622 #[serde(default, skip_serializing_if = "Option::is_none")]
624 pub style: Option<StrokeStyle>,
625 #[serde(default, skip_serializing_if = "Option::is_none")]
629 pub ttl_ms: Option<u64>,
630}
631
632#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
638#[serde(
639 untagged,
640 expecting = "an [x, y] pair, or a position like `top-left` or `50%,30%`"
641)]
642pub enum ArrowEnd {
643 Coords([f64; 2]),
645 Named(String),
647}
648
649#[derive(Debug, Clone, Copy, PartialEq)]
651pub enum ArrowTarget {
652 Coords(LogicalPoint),
654 Named(Position),
656}
657
658impl ArrowEnd {
659 pub const fn coords(x: f64, y: f64) -> Self {
661 Self::Coords([x, y])
662 }
663
664 pub fn named(at: impl Into<String>) -> Self {
666 Self::Named(at.into())
667 }
668
669 pub fn target(&self) -> Result<ArrowTarget, ValidationError> {
671 match self {
672 Self::Coords([x, y]) => {
673 let p = LogicalPoint::new(*x, *y);
674 if !p.is_finite() {
675 return Err(ValidationError::NonFiniteCoordinate { field: "from, to" });
676 }
677 Ok(ArrowTarget::Coords(p))
678 }
679 Self::Named(at) => Position::parse(at).map(ArrowTarget::Named),
680 }
681 }
682}
683
684impl Arrow {
685 pub fn new(display_id: DisplayId, from: ArrowEnd, to: ArrowEnd) -> Self {
687 Self {
688 display_id,
689 from,
690 to,
691 bow: None,
692 style: None,
693 ttl_ms: None,
694 }
695 }
696
697 #[must_use]
699 pub fn with_bow(mut self, bow: f64) -> Self {
700 self.bow = Some(bow);
701 self
702 }
703
704 #[must_use]
706 pub fn with_ttl_ms(mut self, ttl_ms: Option<u64>) -> Self {
707 self.ttl_ms = ttl_ms;
708 self
709 }
710}
711
712impl Validate for Arrow {
713 fn validate(&self) -> Result<(), ValidationError> {
714 validate_ttl(self.ttl_ms)?;
715 let from = self.from.target()?;
716 let to = self.to.target()?;
717 if from == to {
721 return Err(ValidationError::ZeroLengthArrow);
722 }
723 if let Some(bow) = self.bow
724 && (!bow.is_finite() || bow.abs() > 1.0)
725 {
726 return Err(ValidationError::BowOutOfRange {
727 got: bow.to_string(),
728 });
729 }
730 Ok(())
731 }
732}
733
734#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
736pub struct Clear {
737 #[serde(default, skip_serializing_if = "Option::is_none")]
739 pub annotation_id: Option<AnnotationId>,
740 #[serde(default, skip_serializing_if = "is_false")]
742 pub all: bool,
743}
744
745impl Clear {
746 pub const fn all() -> Self {
748 Self {
749 annotation_id: None,
750 all: true,
751 }
752 }
753
754 pub const fn one(annotation_id: AnnotationId) -> Self {
756 Self {
757 annotation_id: Some(annotation_id),
758 all: false,
759 }
760 }
761}
762
763impl Validate for Clear {
764 fn validate(&self) -> Result<(), ValidationError> {
765 const EXPECTED: &str = "annotation_id or all";
766 match (&self.annotation_id, self.all) {
767 (Some(_), false) | (None, true) => Ok(()),
768 (None, false) => Err(ValidationError::MissingTarget {
769 message: "clear",
770 expected: EXPECTED,
771 }),
772 (Some(_), true) => Err(ValidationError::AmbiguousTarget {
773 message: "clear",
774 expected: EXPECTED,
775 }),
776 }
777 }
778}