adk_vision/geometry/screen.rs
1//! [`ScreenSpace`]: logical screen points for actuation, from screenshot pixels.
2
3use serde::{Deserialize, Serialize};
4
5use super::BBox;
6
7/// Logical screen points for actuation, from source pixels of a screenshot.
8///
9/// A screenshot of a 1512×982-point display at device pixel ratio 2 is 3024×1964 pixels;
10/// [`to_points`](Self::to_points) halves the coordinates before a click. A screen action's
11/// target is derived through this type from a region of a screenshot whose digest the
12/// action records (V-I14).
13///
14/// # Example
15///
16/// ```
17/// use adk_vision::ScreenSpace;
18///
19/// let screen = ScreenSpace::new("built-in", [0.0, 0.0], 2.0);
20/// assert_eq!(screen.to_points([3024.0, 1964.0]), [1512.0, 982.0]);
21/// ```
22#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
23#[serde(rename_all = "camelCase")]
24pub struct ScreenSpace {
25 /// The display the screenshot shows.
26 pub display: String,
27 /// The display's top-left corner in the global point space.
28 pub origin: [f32; 2],
29 /// Pixels per point.
30 pub device_pixel_ratio: f32,
31}
32
33impl ScreenSpace {
34 /// A display at `origin` with its device pixel ratio.
35 pub fn new(display: impl Into<String>, origin: [f32; 2], device_pixel_ratio: f32) -> Self {
36 Self { display: display.into(), origin, device_pixel_ratio }
37 }
38
39 fn ratio(&self) -> f32 {
40 if self.device_pixel_ratio > 0.0 { self.device_pixel_ratio } else { 1.0 }
41 }
42
43 /// Maps a screenshot pixel to logical screen points.
44 pub fn to_points(&self, pixel: [f32; 2]) -> [f32; 2] {
45 let r = self.ratio();
46 [self.origin[0] + pixel[0] / r, self.origin[1] + pixel[1] / r]
47 }
48
49 /// Maps logical screen points to a screenshot pixel.
50 pub fn to_pixels(&self, point: [f32; 2]) -> [f32; 2] {
51 let r = self.ratio();
52 [(point[0] - self.origin[0]) * r, (point[1] - self.origin[1]) * r]
53 }
54
55 /// Maps a box in screenshot pixels to logical screen points.
56 pub fn bbox_to_points(&self, bbox: &BBox) -> BBox {
57 let a = self.to_points([bbox.x0, bbox.y0]);
58 let b = self.to_points([bbox.x1, bbox.y1]);
59 BBox::new(a[0], a[1], b[0], b[1])
60 }
61}