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 Clear(Clear),
42 SessionEnd,
44}
45
46impl Validate for ClientMessage {
47 fn validate(&self) -> Result<(), ValidationError> {
48 match self {
49 Self::SessionStart(m) => m.validate(),
50 Self::Point(m) => m.validate(),
51 Self::Highlight(m) => m.validate(),
52 Self::Textbox(m) => m.validate(),
53 Self::Draw(m) => m.validate(),
54 Self::Clear(m) => m.validate(),
55 Self::SessionEnd => Ok(()),
56 }
57 }
58}
59
60#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
62pub struct SessionStart {
63 pub client_name: String,
65}
66
67impl Validate for SessionStart {
68 fn validate(&self) -> Result<(), ValidationError> {
69 if self.client_name.trim().is_empty() {
70 return Err(ValidationError::Empty {
71 field: "client_name",
72 });
73 }
74 Ok(())
75 }
76}
77
78#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
83pub struct Point {
84 #[serde(default, skip_serializing_if = "Option::is_none")]
86 pub x: Option<f64>,
87 #[serde(default, skip_serializing_if = "Option::is_none")]
89 pub y: Option<f64>,
90 #[serde(default, skip_serializing_if = "Option::is_none")]
95 pub at: Option<String>,
96 #[serde(default, skip_serializing_if = "Option::is_none")]
98 pub query: Option<String>,
99 pub display_id: DisplayId,
101 #[serde(default, skip_serializing_if = "Option::is_none")]
103 pub label: Option<String>,
104 #[serde(default, skip_serializing_if = "Option::is_none")]
108 pub ttl_ms: Option<u64>,
109}
110
111#[derive(Debug, Clone, Copy, PartialEq)]
113pub enum PointTarget<'a> {
114 Coords(LogicalPoint),
116 Named(Position),
118 Query(&'a str),
120}
121
122impl Point {
123 pub const fn at(x: f64, y: f64, display_id: DisplayId) -> Self {
125 Self {
126 x: Some(x),
127 y: Some(y),
128 at: None,
129 query: None,
130 display_id,
131 label: None,
132 ttl_ms: None,
133 }
134 }
135
136 pub fn query(query: impl Into<String>, display_id: DisplayId) -> Self {
138 Self {
139 x: None,
140 y: None,
141 at: None,
142 query: Some(query.into()),
143 display_id,
144 label: None,
145 ttl_ms: None,
146 }
147 }
148
149 pub fn named(at: impl Into<String>, display_id: DisplayId) -> Self {
151 Self {
152 x: None,
153 y: None,
154 at: Some(at.into()),
155 query: None,
156 display_id,
157 label: None,
158 ttl_ms: None,
159 }
160 }
161
162 #[must_use]
164 pub fn with_label(mut self, label: impl Into<String>) -> Self {
165 self.label = Some(label.into());
166 self
167 }
168
169 #[must_use]
171 pub fn with_ttl_ms(mut self, ttl_ms: Option<u64>) -> Self {
172 self.ttl_ms = ttl_ms;
173 self
174 }
175
176 pub fn target(&self) -> Result<PointTarget<'_>, ValidationError> {
182 const EXPECTED: &str = "x and y, or at, or query";
183
184 let coords = self.x.is_some() || self.y.is_some();
185 let named = self.at.is_some();
186 let queried = self.query.is_some();
187
188 match (coords, named, queried) {
189 (false, false, false) => {
190 return Err(ValidationError::MissingTarget {
191 message: "point",
192 expected: EXPECTED,
193 });
194 }
195 (true, true, _) | (true, _, true) | (_, true, true) => {
197 return Err(ValidationError::AmbiguousTarget {
198 message: "point",
199 expected: EXPECTED,
200 });
201 }
202 _ => {}
203 }
204
205 if let Some(at) = self.at.as_deref() {
206 return Position::parse(at).map(PointTarget::Named);
207 }
208
209 if let Some(query) = self.query.as_deref() {
210 return if query.trim().is_empty() {
211 Err(ValidationError::Empty { field: "query" })
212 } else {
213 Ok(PointTarget::Query(query))
214 };
215 }
216
217 match (self.x, self.y) {
218 (Some(x), Some(y)) => {
219 let p = LogicalPoint::new(x, y);
220 if !p.is_finite() {
221 return Err(ValidationError::NonFiniteCoordinate { field: "x, y" });
222 }
223 Ok(PointTarget::Coords(p))
224 }
225 _ => Err(ValidationError::AmbiguousTarget {
228 message: "point",
229 expected: EXPECTED,
230 }),
231 }
232 }
233}
234
235impl Validate for Point {
236 fn validate(&self) -> Result<(), ValidationError> {
237 validate_ttl(self.ttl_ms)?;
238 self.target().map(|_| ())
239 }
240}
241
242#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
244pub struct Highlight {
245 #[serde(default, skip_serializing_if = "Option::is_none")]
247 pub rect: Option<LogicalRect>,
248 #[serde(default, skip_serializing_if = "Option::is_none")]
250 pub query: Option<String>,
251 pub display_id: DisplayId,
253 #[serde(default, skip_serializing_if = "Option::is_none")]
255 pub label: Option<String>,
256 #[serde(default, skip_serializing_if = "Option::is_none")]
260 pub ttl_ms: Option<u64>,
261}
262
263#[derive(Debug, Clone, Copy, PartialEq)]
265pub enum HighlightTarget<'a> {
266 Rect(LogicalRect),
268 Query(&'a str),
270}
271
272impl Highlight {
273 pub const fn over(rect: LogicalRect, display_id: DisplayId) -> Self {
275 Self {
276 rect: Some(rect),
277 query: None,
278 display_id,
279 label: None,
280 ttl_ms: None,
281 }
282 }
283
284 pub fn query(query: impl Into<String>, display_id: DisplayId) -> Self {
286 Self {
287 rect: None,
288 query: Some(query.into()),
289 display_id,
290 label: None,
291 ttl_ms: None,
292 }
293 }
294
295 #[must_use]
297 pub fn with_label(mut self, label: impl Into<String>) -> Self {
298 self.label = Some(label.into());
299 self
300 }
301
302 #[must_use]
304 pub fn with_ttl_ms(mut self, ttl_ms: Option<u64>) -> Self {
305 self.ttl_ms = ttl_ms;
306 self
307 }
308
309 pub fn target(&self) -> Result<HighlightTarget<'_>, ValidationError> {
311 const EXPECTED: &str = "rect or query";
312 match (self.rect, self.query.as_deref()) {
313 (Some(rect), None) => {
314 if !rect.is_valid() {
315 return Err(ValidationError::InvalidRect { field: "rect" });
316 }
317 Ok(HighlightTarget::Rect(rect))
318 }
319 (None, Some(q)) if !q.trim().is_empty() => Ok(HighlightTarget::Query(q)),
320 (None, Some(_)) => Err(ValidationError::Empty { field: "query" }),
321 (None, None) => Err(ValidationError::MissingTarget {
322 message: "highlight",
323 expected: EXPECTED,
324 }),
325 (Some(_), Some(_)) => Err(ValidationError::AmbiguousTarget {
326 message: "highlight",
327 expected: EXPECTED,
328 }),
329 }
330 }
331}
332
333impl Validate for Highlight {
334 fn validate(&self) -> Result<(), ValidationError> {
335 validate_ttl(self.ttl_ms)?;
336 self.target().map(|_| ())
337 }
338}
339
340#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
345pub struct Textbox {
346 #[serde(default, skip_serializing_if = "Option::is_none")]
348 pub anchor: Option<Anchor>,
349 #[serde(default, skip_serializing_if = "Option::is_none")]
351 pub rect: Option<LogicalRect>,
352 #[serde(default, skip_serializing_if = "Option::is_none")]
354 pub display_id: Option<DisplayId>,
355 pub text: String,
357 #[serde(default, skip_serializing_if = "Option::is_none")]
361 pub ttl_ms: Option<u64>,
362}
363
364impl Textbox {
365 pub fn new(anchor: Anchor, text: impl Into<String>) -> Self {
367 Self {
368 anchor: Some(anchor),
369 rect: None,
370 display_id: None,
371 text: text.into(),
372 ttl_ms: None,
373 }
374 }
375
376 #[must_use]
378 pub fn with_ttl_ms(mut self, ttl_ms: Option<u64>) -> Self {
379 self.ttl_ms = ttl_ms;
380 self
381 }
382
383 pub fn resolved_anchor(&self) -> Result<Anchor, ValidationError> {
385 const EXPECTED: &str = "anchor, or rect with display_id";
386 match (&self.anchor, self.rect, self.display_id) {
387 (Some(anchor), None, None) => {
388 if !anchor.screen_rect.is_valid() {
389 return Err(ValidationError::InvalidRect {
390 field: "anchor.screen_rect",
391 });
392 }
393 Ok(anchor.clone())
394 }
395 (None, Some(rect), Some(display_id)) => {
396 if !rect.is_valid() {
397 return Err(ValidationError::InvalidRect { field: "rect" });
398 }
399 Ok(Anchor::new(rect, display_id))
400 }
401 (None, None, _) => Err(ValidationError::MissingTarget {
402 message: "textbox",
403 expected: EXPECTED,
404 }),
405 _ => Err(ValidationError::AmbiguousTarget {
406 message: "textbox",
407 expected: EXPECTED,
408 }),
409 }
410 }
411}
412
413impl Validate for Textbox {
414 fn validate(&self) -> Result<(), ValidationError> {
415 validate_ttl(self.ttl_ms)?;
416 if self.text.trim().is_empty() {
417 return Err(ValidationError::Empty { field: "text" });
418 }
419 self.resolved_anchor().map(|_| ())
420 }
421}
422
423#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
425pub struct Draw {
426 pub display_id: DisplayId,
428 pub path: Vec<[f64; 2]>,
430 #[serde(default, skip_serializing_if = "Option::is_none")]
432 pub style: Option<StrokeStyle>,
433 #[serde(default, skip_serializing_if = "Option::is_none")]
437 pub ttl_ms: Option<u64>,
438}
439
440impl Draw {
441 pub fn new(display_id: DisplayId, path: Vec<[f64; 2]>) -> Self {
443 Self {
444 display_id,
445 path,
446 style: None,
447 ttl_ms: None,
448 }
449 }
450
451 #[must_use]
453 pub fn with_ttl_ms(mut self, ttl_ms: Option<u64>) -> Self {
454 self.ttl_ms = ttl_ms;
455 self
456 }
457
458 pub fn points(&self) -> impl Iterator<Item = LogicalPoint> + '_ {
460 self.path.iter().map(|&[x, y]| LogicalPoint::new(x, y))
461 }
462}
463
464impl Validate for Draw {
465 fn validate(&self) -> Result<(), ValidationError> {
466 validate_ttl(self.ttl_ms)?;
467 if self.path.len() < 2 {
468 return Err(ValidationError::PathTooShort {
469 got: self.path.len(),
470 });
471 }
472 if !self.points().all(|p| p.is_finite()) {
473 return Err(ValidationError::NonFiniteCoordinate { field: "path" });
474 }
475 Ok(())
476 }
477}
478
479#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
481pub struct StrokeStyle {
482 #[serde(default, skip_serializing_if = "Option::is_none")]
484 pub width: Option<f64>,
485 #[serde(default, skip_serializing_if = "Option::is_none")]
490 pub color: Option<String>,
491}
492
493#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
495pub struct Clear {
496 #[serde(default, skip_serializing_if = "Option::is_none")]
498 pub annotation_id: Option<AnnotationId>,
499 #[serde(default, skip_serializing_if = "is_false")]
501 pub all: bool,
502}
503
504impl Clear {
505 pub const fn all() -> Self {
507 Self {
508 annotation_id: None,
509 all: true,
510 }
511 }
512
513 pub const fn one(annotation_id: AnnotationId) -> Self {
515 Self {
516 annotation_id: Some(annotation_id),
517 all: false,
518 }
519 }
520}
521
522impl Validate for Clear {
523 fn validate(&self) -> Result<(), ValidationError> {
524 const EXPECTED: &str = "annotation_id or all";
525 match (&self.annotation_id, self.all) {
526 (Some(_), false) | (None, true) => Ok(()),
527 (None, false) => Err(ValidationError::MissingTarget {
528 message: "clear",
529 expected: EXPECTED,
530 }),
531 (Some(_), true) => Err(ValidationError::AmbiguousTarget {
532 message: "clear",
533 expected: EXPECTED,
534 }),
535 }
536 }
537}