Skip to main content

arin_protocol/
client.rs

1//! Client to daemon messages.
2
3use 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
14/// Check a time to live, which every drawing message carries in the same form.
15///
16/// Milliseconds rather than seconds so the wire never has to carry a fraction, and an
17/// integer so it never has to carry a NaN. Absent means the mark lives until it is
18/// cleared or invalidated, which is what the daemon does by default.
19fn validate_ttl(ttl_ms: Option<u64>) -> Result<(), ValidationError> {
20    match ttl_ms {
21        Some(0) => Err(ValidationError::ZeroTtl),
22        _ => Ok(()),
23    }
24}
25
26/// Anything a client can send.
27#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
28#[serde(tag = "type", rename_all = "snake_case")]
29pub enum ClientMessage {
30    /// Open a session. The daemon replies with a session id.
31    SessionStart(SessionStart),
32    /// Put the orb on a target.
33    Point(Point),
34    /// Outline a region.
35    Highlight(Highlight),
36    /// Place a text box. Display only, never an input widget.
37    Textbox(Textbox),
38    /// Draw a freehand path.
39    Draw(Draw),
40    /// Draw an arrow from one position to another.
41    Arrow(Arrow),
42    /// Remove annotations owned by this session.
43    Clear(Clear),
44    /// Bring an application's windows to the front.
45    Focus(Focus),
46    /// Wait until an application's window is showing.
47    AwaitWindow(AwaitWindow),
48    /// Close the session. Annotations fade shortly after.
49    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/// Bring an application's windows to the front.
70///
71/// The one message that changes what is on the user's screen rather than what is drawn over
72/// it, and the only one a daemon may refuse for being switched off rather than malformed.
73///
74/// Arin can only mark the visible desktop, since every desktop on a display shares one set
75/// of coordinates, so a target the user has swiped away from has nowhere to be marked. This
76/// is the ask to switch, carried out.
77///
78/// It names an application rather than a window: a window has no name a client could know,
79/// and choosing between an application's windows needs Accessibility.
80#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
81pub struct Focus {
82    /// The application to bring forward, by visible name or bundle identifier.
83    ///
84    /// `"Slack"` and `"com.tinyspeck.slackmacgap"` both work. Matched against the
85    /// applications that own windows the capture backend can see, so this never reaches an
86    /// application the user does not have open, and never reads a window title to decide.
87    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/// Wait until an application's window is showing, or give up.
100///
101/// The other half of guiding somebody somewhere Arin cannot take them. A mark can say
102/// "switch desktops", and without this nothing knows whether they did, so an agent draws an
103/// instruction and carries on as though it were followed.
104///
105/// A request rather than a pushed event because MCP has no way for a server to interrupt a
106/// model: a client driven by one could not act on an event until its next call anyway.
107///
108/// It never moves anything. The acting half of the handoff is the user's.
109#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
110pub struct AwaitWindow {
111    /// The application to wait for, matched exactly as [`Focus::app`] is.
112    pub app: String,
113    /// How long to wait before giving up, in milliseconds.
114    ///
115    /// Absent leaves it to the daemon, which is what a client that has no opinion should
116    /// send: the useful bound is "about as long as a person takes to find a window", and the
117    /// daemon is better placed to know that than a client is.
118    #[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        // A wait of no time is a question, not a wait, and answering it as though somebody
128        // had waited would report "they never arrived" the instant they were asked to move.
129        if self.timeout_ms == Some(0) {
130            return Err(ValidationError::ZeroTtl);
131        }
132        Ok(())
133    }
134}
135
136/// Open a session.
137#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
138pub struct SessionStart {
139    /// Free-form client identifier, for example `"claude-code"`. Shown in diagnostics.
140    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/// Put the orb on a target.
155///
156/// Two forms. Clients that ground coordinates themselves send `x` and `y`. Clients that
157/// cannot send `query` instead, which needs a configured resolver.
158#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
159pub struct Point {
160    /// Horizontal position in logical points. Paired with `y`.
161    #[serde(default, skip_serializing_if = "Option::is_none")]
162    pub x: Option<f64>,
163    /// Vertical position in logical points. Paired with `x`.
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    pub y: Option<f64>,
166    /// A position named relative to the display, such as `top-left` or `50%,30%`.
167    ///
168    /// For clients that have not measured the screen and so cannot name a coordinate.
169    /// Resolved by the daemon, which is the only party that knows the geometry.
170    #[serde(default, skip_serializing_if = "Option::is_none")]
171    pub at: Option<String>,
172    /// Natural language description of the target, resolved by the daemon.
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    pub query: Option<String>,
175    /// The display the coordinates, position, or query apply to.
176    pub display_id: DisplayId,
177    /// Short caption rendered next to the orb.
178    #[serde(default, skip_serializing_if = "Option::is_none")]
179    pub label: Option<String>,
180    /// How long the mark should live, in milliseconds.
181    ///
182    /// Omit to draw until cleared, invalidated, or the session ends.
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub ttl_ms: Option<u64>,
185}
186
187/// Which form of [`Point`] a client sent.
188#[derive(Debug, Clone, Copy, PartialEq)]
189pub enum PointTarget<'a> {
190    /// The client did its own grounding.
191    Coords(LogicalPoint),
192    /// A position relative to the display, which only the daemon can turn into a point.
193    Named(Position),
194    /// The daemon must resolve this.
195    Query(&'a str),
196}
197
198impl Point {
199    /// At explicit coordinates.
200    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    /// From a natural language description. Requires a resolver.
213    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    /// At a position named relative to the display, such as `top-left` or `50%,30%`.
226    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    /// Attach a caption.
239    #[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    /// Set how long the mark lives, in milliseconds.
246    #[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    /// Which form was sent.
253    ///
254    /// Exactly one of the three. Half a coordinate pair, or two forms at once, is an
255    /// error rather than a guess: every one of those is a client bug, and drawing
256    /// somewhere plausible would hide it.
257    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            // More than one form supplied.
272            (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            // Half a pair. Guessing the other half would put the mark somewhere the
302            // client never asked for.
303            _ => 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/// Outline a region.
319#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
320pub struct Highlight {
321    /// The region in logical points, as `[x, y, width, height]`.
322    #[serde(default, skip_serializing_if = "Option::is_none")]
323    pub rect: Option<LogicalRect>,
324    /// Natural language description of the region, resolved by the daemon.
325    #[serde(default, skip_serializing_if = "Option::is_none")]
326    pub query: Option<String>,
327    /// The display the rect or query applies to.
328    pub display_id: DisplayId,
329    /// Short caption rendered against the region.
330    #[serde(default, skip_serializing_if = "Option::is_none")]
331    pub label: Option<String>,
332    /// How long the mark should live, in milliseconds.
333    ///
334    /// Omit to draw until cleared, invalidated, or the session ends.
335    #[serde(default, skip_serializing_if = "Option::is_none")]
336    pub ttl_ms: Option<u64>,
337}
338
339/// Which form of [`Highlight`] a client sent.
340#[derive(Debug, Clone, Copy, PartialEq)]
341pub enum HighlightTarget<'a> {
342    /// The client did its own grounding.
343    Rect(LogicalRect),
344    /// The daemon must resolve this.
345    Query(&'a str),
346}
347
348impl Highlight {
349    /// Over an explicit rect.
350    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    /// From a natural language description. Requires a resolver.
361    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    /// Attach a caption.
372    #[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    /// Set how long the mark lives, in milliseconds.
379    #[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    /// Which form was sent.
386    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/// Place a text box.
417///
418/// Display only. Arin never renders an editable input, and the overlay is fully click
419/// through. This is not negotiable within 0.x.
420#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
421pub struct Textbox {
422    /// Where to pin the box. Preferred form.
423    #[serde(default, skip_serializing_if = "Option::is_none")]
424    pub anchor: Option<Anchor>,
425    /// Shorthand for an anchor, used with `display_id`.
426    #[serde(default, skip_serializing_if = "Option::is_none")]
427    pub rect: Option<LogicalRect>,
428    /// Required when `rect` is used instead of `anchor`.
429    #[serde(default, skip_serializing_if = "Option::is_none")]
430    pub display_id: Option<DisplayId>,
431    /// The text to render.
432    pub text: String,
433    /// What the text is for, which decides how loudly it is drawn.
434    ///
435    /// Omit for [`TextboxStyle::Note`].
436    #[serde(default, skip_serializing_if = "Option::is_none")]
437    pub style: Option<TextboxStyle>,
438    /// How long the box should live, in milliseconds.
439    ///
440    /// Omit to draw until cleared, invalidated, or the session ends.
441    #[serde(default, skip_serializing_if = "Option::is_none")]
442    pub ttl_ms: Option<u64>,
443}
444
445/// What a text box is for.
446///
447/// Semantic rather than typographic on purpose. A client says what kind of thing it is
448/// writing, and the renderer decides what that looks like, the same split that keeps
449/// colour out of clients' hands. Raw font sizes on the wire would make every client a
450/// typographer and every renderer a chance to drift.
451#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
452#[serde(rename_all = "snake_case")]
453pub enum TextboxStyle {
454    /// An explanation read alongside something else. Quiet, the default.
455    #[default]
456    Note,
457    /// An instruction read at a glance by somebody about to act. Larger and centred,
458    /// because it competes with everything else on a screen mid-action.
459    Guide,
460}
461
462impl Textbox {
463    /// Pin text to a region.
464    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    /// Say what the text is for.
476    #[must_use]
477    pub fn with_style(mut self, style: TextboxStyle) -> Self {
478        self.style = Some(style);
479        self
480    }
481
482    /// Set how long the box lives, in milliseconds.
483    #[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    /// The anchor, whichever form was sent.
490    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/// Draw a freehand path.
530#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
531pub struct Draw {
532    /// The display the path is drawn on.
533    pub display_id: DisplayId,
534    /// Ordered vertices in logical points, each as `[x, y]`.
535    pub path: Vec<[f64; 2]>,
536    /// Stroke appearance. Daemon defaults apply when absent.
537    #[serde(default, skip_serializing_if = "Option::is_none")]
538    pub style: Option<StrokeStyle>,
539    /// How long the path should live, in milliseconds.
540    ///
541    /// Omit to draw until cleared, invalidated, or the session ends.
542    #[serde(default, skip_serializing_if = "Option::is_none")]
543    pub ttl_ms: Option<u64>,
544}
545
546impl Draw {
547    /// A path on a display.
548    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    /// Set how long the path lives, in milliseconds.
558    #[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    /// The path as logical points.
565    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/// Stroke appearance for a freehand path.
586#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
587pub struct StrokeStyle {
588    /// Stroke width in logical points.
589    #[serde(default, skip_serializing_if = "Option::is_none")]
590    pub width: Option<f64>,
591    /// Stroke colour as `#RRGGBB`.
592    ///
593    /// Omit to let the contrast picker choose against the target region. Blue is
594    /// reserved for the orb and is excluded from automatic selection.
595    #[serde(default, skip_serializing_if = "Option::is_none")]
596    pub color: Option<String>,
597}
598
599/// Draw an arrow from one position to another. The head sits at `to`.
600///
601/// Curved by default. A gentle bow is how a person draws an arrow, and it keeps the
602/// shaft out of whatever sits on the straight line between two points, which is often
603/// exactly the content being talked about. `bow: 0` asks for a straight one.
604///
605/// The daemon turns the curve into an ordinary path annotation, so an arrow scrolls,
606/// expires, and picks its colour exactly as a freehand path does.
607#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
608pub struct Arrow {
609    /// The display both ends sit on.
610    pub display_id: DisplayId,
611    /// Where the arrow starts.
612    pub from: ArrowEnd,
613    /// Where the arrow points.
614    pub to: ArrowEnd,
615    /// How far the shaft bows off the straight line, as a signed fraction of its length.
616    ///
617    /// `0` is straight, positive bows to the right of travel, negative to the left, and
618    /// past `1` the shape stops reading as an arrow, so that is where validation stops
619    /// accepting it. Omit for the daemon's natural curve.
620    #[serde(default, skip_serializing_if = "Option::is_none")]
621    pub bow: Option<f64>,
622    /// Stroke appearance. Daemon defaults apply when absent.
623    #[serde(default, skip_serializing_if = "Option::is_none")]
624    pub style: Option<StrokeStyle>,
625    /// How long the arrow should live, in milliseconds.
626    ///
627    /// Omit to draw until cleared, invalidated, or the session ends.
628    #[serde(default, skip_serializing_if = "Option::is_none")]
629    pub ttl_ms: Option<u64>,
630}
631
632/// One end of an arrow.
633///
634/// Either form [`Point`] takes, minus the query: coordinates for a client that measured
635/// the screen, or a named position for one that has not. The forms are different JSON
636/// shapes, a pair against a string, so an end can never be two things at once.
637#[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    /// Logical coordinates, as `[x, y]`.
644    Coords([f64; 2]),
645    /// A position named relative to the display, such as `top-left` or `50%,30%`.
646    Named(String),
647}
648
649/// An [`ArrowEnd`], checked.
650#[derive(Debug, Clone, Copy, PartialEq)]
651pub enum ArrowTarget {
652    /// The client did its own grounding.
653    Coords(LogicalPoint),
654    /// A position relative to the display, which only the daemon can turn into a point.
655    Named(Position),
656}
657
658impl ArrowEnd {
659    /// Coordinates in logical points.
660    pub const fn coords(x: f64, y: f64) -> Self {
661        Self::Coords([x, y])
662    }
663
664    /// A position named relative to the display.
665    pub fn named(at: impl Into<String>) -> Self {
666        Self::Named(at.into())
667    }
668
669    /// Which form this end carries.
670    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    /// From one end to the other.
686    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    /// Set how far the shaft bows off the straight line.
698    #[must_use]
699    pub fn with_bow(mut self, bow: f64) -> Self {
700        self.bow = Some(bow);
701        self
702    }
703
704    /// Set how long the arrow lives, in milliseconds.
705    #[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        // Two identical ends can only be caught here when they are literal. Named ends
718        // resolve against a display this crate has never seen, so the daemon repeats the
719        // check after resolving them.
720        if from == to {
721            return Err(ValidationError::ZeroLengthArrow);
722        }
723        if let Some(bow) = self.bow {
724            if !bow.is_finite() || bow.abs() > 1.0 {
725                return Err(ValidationError::BowOutOfRange {
726                    got: bow.to_string(),
727                });
728            }
729        }
730        Ok(())
731    }
732}
733
734/// Remove annotations. Only ever affects the calling session's own annotations.
735#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
736pub struct Clear {
737    /// Clear one annotation.
738    #[serde(default, skip_serializing_if = "Option::is_none")]
739    pub annotation_id: Option<AnnotationId>,
740    /// Clear every annotation in this session.
741    #[serde(default, skip_serializing_if = "is_false")]
742    pub all: bool,
743}
744
745impl Clear {
746    /// Clear every annotation in the session.
747    pub const fn all() -> Self {
748        Self {
749            annotation_id: None,
750            all: true,
751        }
752    }
753
754    /// Clear one annotation.
755    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}