Skip to main content

native_gui_core/
displays.rs

1//! Portable display and monitor metrics.
2//!
3//! The vocabulary a backend reports through [`crate::Backend::displays`]:
4//! stable display identifiers, physical-pixel bounds and work areas, scale
5//! factors, and the primary flag — enough for a display inspector and for
6//! correct multi-monitor placement without any platform types leaking into
7//! the shared model.
8//!
9//! Capability reporting follows the theming pattern: [`DisplayCapabilities`]
10//! is a plain query (`none()` default) while enumeration itself returns the
11//! typed [`crate::GuiError::UnsupportedCapability`] on lanes that cannot
12//! report metrics, so a lane never fabricates monitor geometry.
13//!
14//! DPI/monitor transitions surface as [`crate::UiEvent::DisplayChanged`]; the
15//! event payload is a fresh [`DisplayInfo`] for the window's current display.
16
17#[cfg(feature = "displays")]
18use std::fmt;
19
20/// Physical-pixel rectangle in virtual-desktop coordinates.
21///
22/// `x`/`y` are the rectangle's top-left corner; `width`/`height` are always
23/// non-negative for real displays (the constructor does not enforce it so
24/// tests and fixtures can model hostile data).
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
26#[cfg(feature = "displays")]
27pub struct DisplayRect {
28    /// Left edge in virtual-desktop pixels.
29    pub x: i32,
30    /// Top edge in virtual-desktop pixels.
31    pub y: i32,
32    /// Width in pixels.
33    pub width: i32,
34    /// Height in pixels.
35    pub height: i32,
36}
37
38#[cfg(feature = "displays")]
39impl DisplayRect {
40    /// Creates a rectangle from its top-left corner and size.
41    pub const fn new(x: i32, y: i32, width: i32, height: i32) -> Self {
42        Self {
43            x,
44            y,
45            width,
46            height,
47        }
48    }
49
50    /// Exclusive right edge (`x + width`).
51    pub fn right(&self) -> i32 {
52        self.x + self.width
53    }
54
55    /// Exclusive bottom edge (`y + height`).
56    pub fn bottom(&self) -> i32 {
57        self.y + self.height
58    }
59
60    /// Returns `true` when `(x, y)` lies inside the half-open rectangle.
61    pub fn contains(&self, x: i32, y: i32) -> bool {
62        x >= self.x && x < self.right() && y >= self.y && y < self.bottom()
63    }
64
65    /// Returns `true` when `other` lies entirely inside `self`.
66    pub fn contains_rect(&self, other: &DisplayRect) -> bool {
67        other.x >= self.x
68            && other.y >= self.y
69            && other.right() <= self.right()
70            && other.bottom() <= self.bottom()
71    }
72}
73
74#[cfg(feature = "displays")]
75impl fmt::Display for DisplayRect {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        write!(f, "{}x{}+{}+{}", self.width, self.height, self.x, self.y)
78    }
79}
80
81/// One display's portable metrics.
82#[derive(Debug, Clone, PartialEq)]
83#[cfg(feature = "displays")]
84pub struct DisplayInfo {
85    /// Stable identifier for the display within this backend session
86    /// (Win32 derives it from the device name so it survives re-enumeration).
87    pub id: u32,
88    /// Human-readable device name (Win32: `\\.\DISPLAY1` style).
89    pub name: String,
90    /// Full display bounds in physical pixels.
91    pub bounds: DisplayRect,
92    /// Work area (bounds minus taskbar/dock reserved space).
93    pub work_area: DisplayRect,
94    /// Scale factor relative to 96 DPI (`1.0`, `1.25`, `1.5`, …).
95    pub scale_factor: f64,
96    /// Whether this is the primary display.
97    pub primary: bool,
98}
99
100#[cfg(feature = "displays")]
101impl DisplayInfo {
102    /// Creates display metrics.
103    pub fn new(
104        id: u32,
105        name: &str,
106        bounds: DisplayRect,
107        work_area: DisplayRect,
108        scale_factor: f64,
109        primary: bool,
110    ) -> Self {
111        Self {
112            id,
113            name: name.to_owned(),
114            bounds,
115            work_area,
116            scale_factor,
117            primary,
118        }
119    }
120
121    /// Effective DPI derived from [`DisplayInfo::scale_factor`].
122    pub fn dpi(&self) -> u32 {
123        (self.scale_factor * 96.0).round() as u32
124    }
125}
126
127/// Which display-metric features a backend supports.
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
129pub struct DisplayCapabilities {
130    /// The backend can enumerate connected displays through
131    /// [`crate::Backend::displays`].
132    pub enumeration: bool,
133    /// The backend reports DPI/monitor transitions through
134    /// [`crate::UiEvent::DisplayChanged`].
135    pub dpi_change_events: bool,
136}
137
138impl DisplayCapabilities {
139    /// No enumeration and no change events.
140    pub const fn none() -> Self {
141        Self {
142            enumeration: false,
143            dpi_change_events: false,
144        }
145    }
146
147    /// Enumeration and change events.
148    pub const fn all() -> Self {
149        Self {
150            enumeration: true,
151            dpi_change_events: true,
152        }
153    }
154
155    /// `true` when any display feature is supported.
156    pub const fn is_supported(&self) -> bool {
157        self.enumeration || self.dpi_change_events
158    }
159}
160
161/// Projects a pointer position from the display's native pixel space into
162/// logical (96-DPI) coordinates by dividing by `scale`.
163///
164/// `scale` is the display's scale factor relative to 96 DPI (`1.0` = 100 %,
165/// `1.25` = 125 %, …). Lanes that emit pointer coordinates in physical
166/// pixels (Win32 under Per-Monitor v2) divide by the scale to recover the
167/// logical position the layout engine lays out against; lanes that already emit logical
168/// coordinates (GTK4 gestures, the Mock backend) report a scale of `1.0`,
169/// making this the identity. A scale at or below `1.0` is clamped to `1.0`
170/// so a hostile or unreported scale can never amplify a coordinate.
171///
172/// This is the shared half of the physical-to-logical input isomorphism:
173/// the backend reports the scale through
174/// [`crate::Backend::widget_scale_factor`] and [`crate::Ui`] applies this to
175/// every pointer event it dispatches, so app code always receives logical
176/// coordinates. Call it directly for a raw position that did not come through
177/// [`crate::UiEvent::PointerMove`].
178pub fn logical_pointer_projection(x: f32, y: f32, scale: f64) -> (f32, f32) {
179    let scale = scale.max(1.0) as f32;
180    (x / scale, y / scale)
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    #[test]
188    fn rect_math_and_containment_are_half_open() {
189        let rect = DisplayRect::new(10, 20, 100, 50);
190        assert_eq!(rect.right(), 110);
191        assert_eq!(rect.bottom(), 70);
192        assert!(rect.contains(10, 20));
193        assert!(rect.contains(109, 69));
194        // Right/bottom edges are exclusive.
195        assert!(!rect.contains(110, 69));
196        assert!(!rect.contains(109, 70));
197        assert!(!rect.contains(9, 20));
198        assert!(rect.contains_rect(&DisplayRect::new(10, 20, 100, 50)));
199        assert!(rect.contains_rect(&DisplayRect::new(60, 40, 10, 10)));
200        assert!(!rect.contains_rect(&DisplayRect::new(60, 40, 60, 10)));
201        assert_eq!(rect.to_string(), "100x50+10+20");
202    }
203
204    #[test]
205    fn display_info_derives_dpi_from_scale() {
206        let display = DisplayInfo::new(
207            7,
208            "mock-primary",
209            DisplayRect::new(0, 0, 1920, 1080),
210            DisplayRect::new(0, 0, 1920, 1040),
211            1.25,
212            true,
213        );
214        assert_eq!(display.dpi(), 120);
215        assert!(display.primary);
216        assert_eq!(
217            display.work_area,
218            DisplayRect::new(0, 0, 1920, 1040),
219            "work area keeps its own rectangle"
220        );
221        let secondary = DisplayInfo::new(
222            8,
223            "mock-secondary",
224            DisplayRect::new(1920, 0, 1280, 1024),
225            DisplayRect::new(1920, 0, 1280, 984),
226            1.0,
227            false,
228        );
229        assert_eq!(secondary.dpi(), 96);
230        assert_ne!(display, secondary);
231    }
232
233    #[test]
234    fn capabilities_default_to_none_and_expose_all() {
235        assert_eq!(DisplayCapabilities::default(), DisplayCapabilities::none());
236        assert!(!DisplayCapabilities::default().is_supported());
237        assert!(DisplayCapabilities::all().enumeration);
238        assert!(DisplayCapabilities::all().dpi_change_events);
239        assert!(DisplayCapabilities::all().is_supported());
240        let enumeration_only = DisplayCapabilities {
241            enumeration: true,
242            dpi_change_events: false,
243        };
244        assert!(enumeration_only.is_supported());
245        assert!(!DisplayCapabilities::none().is_supported());
246    }
247
248    #[test]
249    fn logical_pointer_projection_divides_by_scale() {
250        // 125 % display: 125 physical px -> 100 logical px.
251        assert_eq!(
252            logical_pointer_projection(125.0, 250.0, 1.25),
253            (100.0, 200.0)
254        );
255        // 150 % display: 300 physical px -> 200 logical px.
256        assert_eq!(
257            logical_pointer_projection(300.0, 150.0, 1.5),
258            (200.0, 100.0)
259        );
260        // 200 % display: 400 physical px -> 200 logical px.
261        assert_eq!(
262            logical_pointer_projection(400.0, 400.0, 2.0),
263            (200.0, 200.0)
264        );
265    }
266
267    #[test]
268    fn logical_pointer_projection_is_identity_at_100_percent() {
269        assert_eq!(logical_pointer_projection(10.0, 20.0, 1.0), (10.0, 20.0));
270        // Sub-100 % scales clamp to 1.0 (identity) so a hostile scale never
271        // amplifies a coordinate.
272        assert_eq!(logical_pointer_projection(10.0, 20.0, 0.5), (10.0, 20.0));
273        assert_eq!(logical_pointer_projection(10.0, 20.0, 0.0), (10.0, 20.0));
274        assert_eq!(logical_pointer_projection(10.0, 20.0, -3.0), (10.0, 20.0));
275    }
276
277    #[test]
278    fn logical_pointer_projection_preserves_negative_and_zero() {
279        assert_eq!(logical_pointer_projection(-125.0, 0.0, 1.25), (-100.0, 0.0));
280        assert_eq!(logical_pointer_projection(0.0, -250.0, 1.25), (0.0, -200.0));
281    }
282}