Skip to main content

arin_protocol/
geom.rs

1//! Logical geometry.
2//!
3//! Everything here is in logical points and is meaningless without the [`DisplayId`] it
4//! travels with. Retina screenshots come back at 2x while the overlay draws in points,
5//! and mixed-DPI multi-monitor setups make implicit conversion unrecoverable. Clients
6//! working from a screenshot divide by the scale reported in an ack before sending.
7
8use serde::{Deserialize, Serialize};
9
10/// Identifies a display. Stable for the lifetime of a session.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
12#[serde(transparent)]
13pub struct DisplayId(pub u32);
14
15impl DisplayId {
16    /// What a client uses when the user did not name a display.
17    ///
18    /// Not part of the wire contract, and the daemon never substitutes it: every
19    /// positioned message still carries an explicit `display_id`, because a mixed-DPI
20    /// setup makes an implicit display unrecoverable. This is only what a client fills in
21    /// on the way out, so it lives here rather than being spelled `1` in each of them.
22    ///
23    /// The id macOS gives the main display, which is `1` in practice rather than by
24    /// guarantee. `arin displays` lists what a machine actually has.
25    pub const DEFAULT: Self = Self(1);
26}
27
28impl std::fmt::Display for DisplayId {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        write!(f, "{}", self.0)
31    }
32}
33
34/// A point in logical coordinates, relative to the origin of its display.
35#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
36pub struct LogicalPoint {
37    /// Horizontal offset in logical points.
38    pub x: f64,
39    /// Vertical offset in logical points.
40    pub y: f64,
41}
42
43impl LogicalPoint {
44    /// Construct a point.
45    pub const fn new(x: f64, y: f64) -> Self {
46        Self { x, y }
47    }
48
49    /// Whether both components are finite.
50    pub fn is_finite(&self) -> bool {
51        self.x.is_finite() && self.y.is_finite()
52    }
53}
54
55/// A rectangle in logical coordinates.
56///
57/// Serialized as `[x, y, width, height]`, not as an object.
58#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
59#[serde(from = "[f64; 4]", into = "[f64; 4]")]
60pub struct LogicalRect {
61    /// Left edge.
62    pub x: f64,
63    /// Top edge.
64    pub y: f64,
65    /// Extent along x. Must be positive.
66    pub width: f64,
67    /// Extent along y. Must be positive.
68    pub height: f64,
69}
70
71impl LogicalRect {
72    /// Construct a rectangle.
73    pub const fn new(x: f64, y: f64, width: f64, height: f64) -> Self {
74        Self {
75            x,
76            y,
77            width,
78            height,
79        }
80    }
81
82    /// Whether every component is finite and the extents are positive.
83    ///
84    /// Zero-area rects are rejected: they render as nothing, so they are always a bug in
85    /// the caller rather than an intentional annotation.
86    pub fn is_valid(&self) -> bool {
87        self.x.is_finite()
88            && self.y.is_finite()
89            && self.width.is_finite()
90            && self.height.is_finite()
91            && self.width > 0.0
92            && self.height > 0.0
93    }
94
95    /// The centre of the rectangle.
96    pub fn center(&self) -> LogicalPoint {
97        LogicalPoint::new(self.x + self.width / 2.0, self.y + self.height / 2.0)
98    }
99
100    /// This rectangle if it is drawable, `None` if it is not.
101    ///
102    /// For the callers that treat a region as an optional refinement rather than the
103    /// answer. Something derived from a measurement, a model's guess, or arithmetic on
104    /// either can come out degenerate, and dropping it is better than propagating a rect
105    /// that renders as nothing.
106    pub fn into_valid(self) -> Option<Self> {
107        self.is_valid().then_some(self)
108    }
109
110    /// The smallest rectangle containing every one of these points.
111    ///
112    /// Always drawable. An empty run of points has no extent to describe and a straight
113    /// one has none in a single axis, and both come back a point wide rather than as a
114    /// rect that renders as nothing.
115    pub fn containing(points: &[LogicalPoint]) -> Self {
116        let Some(first) = points.first() else {
117            return Self::new(0.0, 0.0, 1.0, 1.0);
118        };
119        let (mut min_x, mut min_y) = (first.x, first.y);
120        let (mut max_x, mut max_y) = (first.x, first.y);
121        for point in points {
122            min_x = min_x.min(point.x);
123            min_y = min_y.min(point.y);
124            max_x = max_x.max(point.x);
125            max_y = max_y.max(point.y);
126        }
127        Self::new(
128            min_x,
129            min_y,
130            (max_x - min_x).max(1.0),
131            (max_y - min_y).max(1.0),
132        )
133    }
134}
135
136impl From<[f64; 4]> for LogicalRect {
137    fn from([x, y, width, height]: [f64; 4]) -> Self {
138        Self::new(x, y, width, height)
139    }
140}
141
142impl From<LogicalRect> for [f64; 4] {
143    fn from(r: LogicalRect) -> Self {
144        [r.x, r.y, r.width, r.height]
145    }
146}
147
148/// Display metadata, returned on acks so clients can convert screenshot pixels.
149#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
150pub struct DisplayInfo {
151    /// The display this describes.
152    pub id: DisplayId,
153    /// Backing scale factor. 2.0 on a Retina panel.
154    pub scale: f64,
155    /// Display size in logical points, as `[width, height]`.
156    pub logical_size: [f64; 2],
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    #[test]
164    fn a_bounding_rect_covers_every_point() {
165        let rect = LogicalRect::containing(&[
166            LogicalPoint::new(40.0, 90.0),
167            LogicalPoint::new(10.0, 200.0),
168            LogicalPoint::new(75.0, 55.0),
169        ]);
170        assert_eq!(rect, LogicalRect::new(10.0, 55.0, 65.0, 145.0));
171        assert!(rect.is_valid());
172    }
173
174    /// Callers anchor marks to these, and an anchor of no extent renders as nothing.
175    #[test]
176    fn a_bounding_rect_is_always_drawable() {
177        let flat = LogicalRect::containing(&[
178            LogicalPoint::new(10.0, 40.0),
179            LogicalPoint::new(90.0, 40.0),
180        ]);
181        assert!(flat.is_valid(), "a straight path came back with no height");
182        assert!(LogicalRect::containing(&[]).is_valid());
183    }
184
185    #[test]
186    fn rects_are_arrays_on_the_wire() {
187        let rect = LogicalRect::new(100.0, 200.0, 340.0, 90.0);
188        assert_eq!(
189            serde_json::to_string(&rect).unwrap(),
190            "[100.0,200.0,340.0,90.0]"
191        );
192        assert_eq!(
193            serde_json::from_str::<LogicalRect>("[100,200,340,90]").unwrap(),
194            rect
195        );
196    }
197
198    #[test]
199    fn zero_area_rects_are_invalid() {
200        assert!(LogicalRect::new(0.0, 0.0, 10.0, 10.0).is_valid());
201        assert!(!LogicalRect::new(0.0, 0.0, 0.0, 10.0).is_valid());
202        assert!(!LogicalRect::new(0.0, 0.0, 10.0, -1.0).is_valid());
203        assert!(!LogicalRect::new(f64::NAN, 0.0, 10.0, 10.0).is_valid());
204    }
205
206    #[test]
207    fn center_is_the_midpoint() {
208        let rect = LogicalRect::new(100.0, 200.0, 340.0, 90.0);
209        assert_eq!(rect.center(), LogicalPoint::new(270.0, 245.0));
210    }
211}