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    /// Remove annotations owned by this session.
41    Clear(Clear),
42    /// Close the session. Annotations fade shortly after.
43    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/// Open a session.
61#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
62pub struct SessionStart {
63    /// Free-form client identifier, for example `"claude-code"`. Shown in diagnostics.
64    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/// Put the orb on a target.
79///
80/// Two forms. Clients that ground coordinates themselves send `x` and `y`. Clients that
81/// cannot send `query` instead, which needs a configured resolver.
82#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
83pub struct Point {
84    /// Horizontal position in logical points. Paired with `y`.
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub x: Option<f64>,
87    /// Vertical position in logical points. Paired with `x`.
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub y: Option<f64>,
90    /// A position named relative to the display, such as `top-left` or `50%,30%`.
91    ///
92    /// For clients that have not measured the screen and so cannot name a coordinate.
93    /// Resolved by the daemon, which is the only party that knows the geometry.
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub at: Option<String>,
96    /// Natural language description of the target, resolved by the daemon.
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub query: Option<String>,
99    /// The display the coordinates, position, or query apply to.
100    pub display_id: DisplayId,
101    /// Short caption rendered next to the orb.
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub label: Option<String>,
104    /// How long the mark should live, in milliseconds.
105    ///
106    /// Omit to draw until cleared, invalidated, or the session ends.
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub ttl_ms: Option<u64>,
109}
110
111/// Which form of [`Point`] a client sent.
112#[derive(Debug, Clone, Copy, PartialEq)]
113pub enum PointTarget<'a> {
114    /// The client did its own grounding.
115    Coords(LogicalPoint),
116    /// A position relative to the display, which only the daemon can turn into a point.
117    Named(Position),
118    /// The daemon must resolve this.
119    Query(&'a str),
120}
121
122impl Point {
123    /// At explicit coordinates.
124    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    /// From a natural language description. Requires a resolver.
137    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    /// At a position named relative to the display, such as `top-left` or `50%,30%`.
150    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    /// Attach a caption.
163    #[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    /// Set how long the mark lives, in milliseconds.
170    #[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    /// Which form was sent.
177    ///
178    /// Exactly one of the three. Half a coordinate pair, or two forms at once, is an
179    /// error rather than a guess: every one of those is a client bug, and drawing
180    /// somewhere plausible would hide it.
181    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            // More than one form supplied.
196            (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            // Half a pair. Guessing the other half would put the mark somewhere the
226            // client never asked for.
227            _ => 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/// Outline a region.
243#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
244pub struct Highlight {
245    /// The region in logical points, as `[x, y, width, height]`.
246    #[serde(default, skip_serializing_if = "Option::is_none")]
247    pub rect: Option<LogicalRect>,
248    /// Natural language description of the region, resolved by the daemon.
249    #[serde(default, skip_serializing_if = "Option::is_none")]
250    pub query: Option<String>,
251    /// The display the rect or query applies to.
252    pub display_id: DisplayId,
253    /// Short caption rendered against the region.
254    #[serde(default, skip_serializing_if = "Option::is_none")]
255    pub label: Option<String>,
256    /// How long the mark should live, in milliseconds.
257    ///
258    /// Omit to draw until cleared, invalidated, or the session ends.
259    #[serde(default, skip_serializing_if = "Option::is_none")]
260    pub ttl_ms: Option<u64>,
261}
262
263/// Which form of [`Highlight`] a client sent.
264#[derive(Debug, Clone, Copy, PartialEq)]
265pub enum HighlightTarget<'a> {
266    /// The client did its own grounding.
267    Rect(LogicalRect),
268    /// The daemon must resolve this.
269    Query(&'a str),
270}
271
272impl Highlight {
273    /// Over an explicit rect.
274    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    /// From a natural language description. Requires a resolver.
285    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    /// Attach a caption.
296    #[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    /// Set how long the mark lives, in milliseconds.
303    #[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    /// Which form was sent.
310    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/// Place a text box.
341///
342/// Display only. Arin never renders an editable input, and the overlay is fully click
343/// through. This is not negotiable within 0.x.
344#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
345pub struct Textbox {
346    /// Where to pin the box. Preferred form.
347    #[serde(default, skip_serializing_if = "Option::is_none")]
348    pub anchor: Option<Anchor>,
349    /// Shorthand for an anchor, used with `display_id`.
350    #[serde(default, skip_serializing_if = "Option::is_none")]
351    pub rect: Option<LogicalRect>,
352    /// Required when `rect` is used instead of `anchor`.
353    #[serde(default, skip_serializing_if = "Option::is_none")]
354    pub display_id: Option<DisplayId>,
355    /// The text to render.
356    pub text: String,
357    /// How long the box should live, in milliseconds.
358    ///
359    /// Omit to draw until cleared, invalidated, or the session ends.
360    #[serde(default, skip_serializing_if = "Option::is_none")]
361    pub ttl_ms: Option<u64>,
362}
363
364impl Textbox {
365    /// Pin text to a region.
366    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    /// Set how long the box lives, in milliseconds.
377    #[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    /// The anchor, whichever form was sent.
384    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/// Draw a freehand path.
424#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
425pub struct Draw {
426    /// The display the path is drawn on.
427    pub display_id: DisplayId,
428    /// Ordered vertices in logical points, each as `[x, y]`.
429    pub path: Vec<[f64; 2]>,
430    /// Stroke appearance. Daemon defaults apply when absent.
431    #[serde(default, skip_serializing_if = "Option::is_none")]
432    pub style: Option<StrokeStyle>,
433    /// How long the path should live, in milliseconds.
434    ///
435    /// Omit to draw until cleared, invalidated, or the session ends.
436    #[serde(default, skip_serializing_if = "Option::is_none")]
437    pub ttl_ms: Option<u64>,
438}
439
440impl Draw {
441    /// A path on a display.
442    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    /// Set how long the path lives, in milliseconds.
452    #[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    /// The path as logical points.
459    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/// Stroke appearance for a freehand path.
480#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
481pub struct StrokeStyle {
482    /// Stroke width in logical points.
483    #[serde(default, skip_serializing_if = "Option::is_none")]
484    pub width: Option<f64>,
485    /// Stroke colour as `#RRGGBB`.
486    ///
487    /// Omit to let the contrast picker choose against the target region. Blue is
488    /// reserved for the orb and is excluded from automatic selection.
489    #[serde(default, skip_serializing_if = "Option::is_none")]
490    pub color: Option<String>,
491}
492
493/// Remove annotations. Only ever affects the calling session's own annotations.
494#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
495pub struct Clear {
496    /// Clear one annotation.
497    #[serde(default, skip_serializing_if = "Option::is_none")]
498    pub annotation_id: Option<AnnotationId>,
499    /// Clear every annotation in this session.
500    #[serde(default, skip_serializing_if = "is_false")]
501    pub all: bool,
502}
503
504impl Clear {
505    /// Clear every annotation in the session.
506    pub const fn all() -> Self {
507        Self {
508            annotation_id: None,
509            all: true,
510        }
511    }
512
513    /// Clear one annotation.
514    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}