Skip to main content

crcbl_shell/
monitor.rs

1//! Monitor enumeration: geometry, work area, scale and refresh rate.
2//!
3//! # Why monitor ids are a plain newtype and window ids are generational
4//!
5//! [`WindowId`](crate::WindowId) is a [`Handle`](crcbl_core::Handle) because a
6//! window is an object the engine creates, destroys and then keeps a stale
7//! reference to — the exact failure a generation counter catches. A monitor is
8//! not created by anyone; it is *observed*. The backend enumerates whatever the
9//! server advertises, and the only stale-id hazard is a monitor unplugged
10//! between [`Shell::monitors`](crate::Shell::monitors) and the call that used
11//! its id.
12//!
13//! That hazard is handled by an obligation instead of a generation: **a
14//! [`MonitorId`] is never reused within a shell session.** A backend that
15//! recycles ids (RandR output ids and Wayland registry names both can, after a
16//! hotplug cycle) must map them through its own table. The failure mode is then
17//! a clean [`ShellError::NoSuchMonitor`](crate::ShellError::NoSuchMonitor)
18//! rather than a borderless window appearing on the wrong display.
19//!
20//! # Refresh rate is millihertz
21//!
22//! Because 59.94 Hz exists, is extremely common, and is not 60. An integer
23//! millihertz value is exact for every mode any of these APIs report
24//! (`wl_output.mode` is already millihertz; RandR gives dot clock and totals;
25//! Win32 gives integer Hz, and macOS a `Double`), and it avoids putting a float
26//! in a `PartialEq`-compared struct that a settings screen will diff.
27
28use core::fmt;
29use std::collections::VecDeque;
30
31use crate::PhysicalRect;
32
33/// Identifier of a connected monitor.
34///
35/// Stable for as long as the monitor stays connected, never reused within a
36/// session. See the [module docs](self).
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
38pub struct MonitorId(pub u32);
39
40impl fmt::Display for MonitorId {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        write!(f, "monitor {}", self.0)
43    }
44}
45
46/// What the shell knows about one monitor.
47///
48/// Owned rather than borrowed: enumeration happens at startup and on hotplug,
49/// so the `String` is not worth avoiding, and borrowing from the shell would
50/// infect every consumer with a lifetime — the same argument
51/// `crcbl-hal`'s `AdapterInfo` makes.
52///
53/// Not `Eq`: [`scale_factor`](Self::scale_factor) is an `f64`. A settings
54/// screen diffing two of these gets `PartialEq`, which is the correct relation
55/// for a struct holding a float.
56#[derive(Clone, Debug, PartialEq)]
57pub struct MonitorInfo {
58    /// Stable id for this monitor within the session.
59    pub id: MonitorId,
60
61    /// Human-readable name, e.g. `"DP-2"` or `"Dell U2723QE"`.
62    ///
63    /// For settings UI and logs only. Never key behaviour off it: it is not
64    /// unique (two identical monitors report identical names on some drivers)
65    /// and it is not stable across drivers.
66    pub name: String,
67
68    /// The connector the window system reported for this monitor, e.g.
69    /// `"DP-2"` or `"HDMI-A-1"` — the name to match against another protocol's
70    /// view of the same output, such as wlr-output-management's `head.name`.
71    ///
72    /// `Some` only when the platform reported one: on Wayland the
73    /// `wl_output.name` event (`wl_output` version 4 and later), else
74    /// `zxdg_output_v1.name`; on X11 the RandR output's name. A reported name
75    /// is passed through as is, so it can coincide with a placeholder's
76    /// spelling (Xvfb's one RandR output is named `screen`) or be one no other
77    /// protocol uses (RandR 1.0 emulation's `default`). On Wayland the name can
78    /// arrive after the output first appears; the monitor list is republished
79    /// with it, under a [`MonitorsChanged`](crate::ShellEvent::MonitorsChanged),
80    /// when it does.
81    ///
82    /// `None` whenever [`name`](Self::name) is a placeholder the backend made
83    /// up (`wl-output-N` on Wayland; `output-N`, `CRTC-N`, and `screen` without
84    /// RandR, on X11),
85    /// and always on Win32, AppKit, the web and the headless shell, which have
86    /// no connector name to report.
87    ///
88    /// Like `name`, it is not guaranteed unique and is not a substitute for
89    /// [`id`](Self::id) within this shell.
90    pub connector: Option<String>,
91
92    /// Position and size in the desktop's device-pixel coordinate space.
93    ///
94    /// The origin is wherever the window system puts it, and coordinates are
95    /// signed because a monitor placed left of or above the primary one has
96    /// negative ones.
97    ///
98    /// On Wayland this comes from `xdg_output` logical geometry scaled back to
99    /// pixels by *that output's own* scale; a compositor without `xdg_output`
100    /// falls back to `wl_output.geometry`, whose position is logical while its
101    /// size is physical, so the two only agree at scale 1.
102    ///
103    /// **There is a limit to how meaningful this can be**, and it is worth
104    /// knowing before building a layout on it: on a desktop whose outputs run
105    /// at *different* scales there is no single device-pixel coordinate space
106    /// at all, and these rectangles will not tile — a 1× monitor beside a 2×
107    /// one has two device-pixel spaces, and only the compositor's logical space
108    /// is globally coherent. This type cannot express that, so it reports each
109    /// monitor in its own pixels. Use it to name a monitor and to tell a
110    /// settings screen which one is on the left; do not use it as a desktop
111    /// layout. [`ShellCaps::WINDOW_POSITION`](crate::ShellCaps::WINDOW_POSITION)
112    /// is the bit that says a *window* can be placed, and Wayland never sets
113    /// it.
114    pub bounds: PhysicalRect,
115
116    /// The part of [`bounds`](Self::bounds) not covered by panels, docks or
117    /// taskbars.
118    ///
119    /// What a *windowed* window should be placed within. Equal to `bounds` when
120    /// the backend cannot find out — Wayland has no protocol for it, so the
121    /// Wayland backend will report the full area and nothing may assume
122    /// otherwise.
123    pub work_area: PhysicalRect,
124
125    /// Device pixels per logical unit, e.g. `1.0`, `1.5`, `2.0`.
126    ///
127    /// Fractional values only appear when
128    /// [`ShellCaps::FRACTIONAL_SCALE`](crate::ShellCaps::FRACTIONAL_SCALE) is
129    /// set. Note that a *window's* scale factor is not necessarily any
130    /// monitor's: a window straddling two outputs gets one of them, chosen by
131    /// the compositor, and it can change while the window is dragged — which is
132    /// what [`ShellEvent::ScaleFactorChanged`](crate::ShellEvent::ScaleFactorChanged)
133    /// is for.
134    pub scale_factor: f64,
135
136    /// Refresh rate in millihertz — `60_000` for 60 Hz, `59_940` for 59.94 Hz.
137    ///
138    /// Zero when the backend cannot determine it (a virtual output, a browser
139    /// canvas). See the [module docs](self) for the unit choice.
140    pub refresh_millihertz: u32,
141
142    /// Whether the window system calls this the primary monitor.
143    ///
144    /// Wayland has no such concept, so a Wayland backend marks the first output
145    /// it sees. Use it as a default, never as a guarantee.
146    pub is_primary: bool,
147}
148
149impl MonitorInfo {
150    /// Refresh rate in hertz, for display and frame pacing.
151    #[inline]
152    #[must_use]
153    pub fn refresh_hz(&self) -> f64 {
154        f64::from(self.refresh_millihertz) / 1000.0
155    }
156
157    /// The frame period implied by [`refresh_hz`](Self::refresh_hz), or `None`
158    /// if the rate is unknown.
159    #[must_use]
160    pub fn frame_period(&self) -> Option<core::time::Duration> {
161        if self.refresh_millihertz == 0 {
162            return None;
163        }
164        Some(core::time::Duration::from_secs_f64(
165            1000.0 / f64::from(self.refresh_millihertz),
166        ))
167    }
168
169    /// The monitor's resolution in device pixels.
170    #[inline]
171    #[must_use]
172    pub const fn size(&self) -> crate::PhysicalSize {
173        self.bounds.size()
174    }
175}
176
177/// Queues a [`MonitorRemoved`](crate::ShellEvent::MonitorRemoved) for every
178/// monitor in `old` that `new` no longer lists, in `old`'s order, and returns
179/// their ids.
180///
181/// By id, which every backend keeps for as long as a display stays connected
182/// and never hands out again. The caller publishes `new` and its
183/// [`MonitorsChanged`](crate::ShellEvent::MonitorsChanged) afterwards, and
184/// closes its panels on the returned monitors in between.
185pub(crate) fn queue_removed(
186    old: &[MonitorInfo],
187    new: &[MonitorInfo],
188    queue: &mut VecDeque<crate::ShellEvent>,
189) -> Vec<MonitorId> {
190    let removed: Vec<MonitorId> = old
191        .iter()
192        .map(|monitor| monitor.id)
193        .filter(|id| !new.iter().any(|monitor| monitor.id == *id))
194        .collect();
195    queue.extend(
196        removed
197            .iter()
198            .map(|&monitor| crate::ShellEvent::MonitorRemoved { monitor }),
199    );
200    removed
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206    use crate::PhysicalSize;
207
208    fn monitor() -> MonitorInfo {
209        MonitorInfo {
210            id: MonitorId(1),
211            name: "DP-2".to_string(),
212            connector: Some("DP-2".to_string()),
213            bounds: PhysicalRect::new(0, 0, 3840, 2160),
214            work_area: PhysicalRect::new(0, 32, 3840, 2128),
215            scale_factor: 1.5,
216            refresh_millihertz: 143_998,
217            is_primary: true,
218        }
219    }
220
221    #[test]
222    fn refresh_rates_that_are_not_integers_survive() {
223        let mut info = monitor();
224        info.refresh_millihertz = 59_940;
225        assert!((info.refresh_hz() - 59.94).abs() < 1e-9);
226        let period = info.frame_period().expect("known rate");
227        assert!((period.as_secs_f64() - 1.0 / 59.94).abs() < 1e-9);
228
229        // The awkward one that motivated millihertz in the first place.
230        assert!((monitor().refresh_hz() - 143.998).abs() < 1e-9);
231    }
232
233    #[test]
234    fn an_unknown_refresh_rate_is_absent_not_zero_hz() {
235        let mut info = monitor();
236        info.refresh_millihertz = 0;
237        assert_eq!(info.frame_period(), None);
238        assert_eq!(info.refresh_hz(), 0.0);
239    }
240
241    #[test]
242    fn a_removal_is_an_id_the_new_list_lacks() {
243        let with_id = |id| MonitorInfo {
244            id: MonitorId(id),
245            ..monitor()
246        };
247        let mut queue = VecDeque::new();
248        let removed = queue_removed(
249            &[with_id(1), with_id(2), with_id(3)],
250            &[with_id(2), with_id(4)],
251            &mut queue,
252        );
253        assert_eq!(removed, [MonitorId(1), MonitorId(3)]);
254        assert_eq!(
255            Vec::from(queue),
256            [1, 3].map(|id| crate::ShellEvent::MonitorRemoved {
257                monitor: MonitorId(id)
258            })
259        );
260
261        // A monitor whose geometry changed is the same monitor.
262        let mut queue = VecDeque::new();
263        let mut moved = with_id(1);
264        moved.bounds = PhysicalRect::new(100, 0, 3840, 2160);
265        assert!(queue_removed(&[with_id(1)], &[moved], &mut queue).is_empty());
266        assert!(queue.is_empty());
267    }
268
269    #[test]
270    fn geometry_accessors_agree_with_the_bounds() {
271        let info = monitor();
272        assert_eq!(info.size(), PhysicalSize::new(3840, 2160));
273        assert_eq!(info.work_area.size(), PhysicalSize::new(3840, 2128));
274        assert_eq!(info.id.to_string(), "monitor 1");
275        assert_eq!(
276            monitor().frame_period().map(|period| period.as_millis()),
277            Some(6)
278        );
279    }
280}