Skip to main content

crcbl_shell/
caps.rs

1//! [`ShellCaps`] — what a backend can actually do, asked as a question about
2//! capability rather than about identity.
3//!
4//! # The regression this exists to prevent
5//!
6//! ```ignore
7//! if cfg!(target_os = "linux") && std::env::var("WAYLAND_DISPLAY").is_ok() {
8//!     // …use the viewport path
9//! }
10//! ```
11//!
12//! That code is wrong three ways and all three are invisible until someone
13//! files a bug: it is wrong on a Wayland compositor that does not implement
14//! `wp_viewporter`, wrong under XWayland, and wrong the day the shell grows a
15//! backend nobody thought about. The windowing rules in `docs/notes/backends.md`
16//! are explicit — "the
17//! renderer picks blit-vs-viewport and windowed-aspect behavior from caps, never
18//! from *am I on Wayland*" — and this module is the mechanism. It mirrors
19//! `crcbl-hal`'s `Features`, where the renderer asks for `DRAW_INDIRECT_COUNT`
20//! rather than for Vulkan.
21//!
22//! # Caps are per-shell, not per-window
23//!
24//! A capability here is a property of the connection and the protocols the
25//! server advertised, so it is fixed for the shell's lifetime and reported by
26//! [`Shell::caps`](crate::Shell::caps) rather than per window. The one thing
27//! that genuinely varies per window — its current size and scale — is
28//! [`WindowState`](crate::WindowState), not a capability.
29//!
30//! There is a real edge here, and it is stated rather than hidden: a Wayland
31//! compositor can bind a global *after* startup, so a protocol could in
32//! principle appear mid-session. Backends must not flip caps bits when that
33//! happens; a renderer that picked the blit path at init cannot be told
34//! halfway through a frame that it should have picked the viewport path.
35//! Capabilities are latched at connection time, and a missing protocol stays
36//! missing until the next run.
37
38bitflags::bitflags! {
39    /// What a shell backend supports.
40    ///
41    /// Each flag names a *behaviour a consumer would otherwise have to guess
42    /// from the platform*. A flag that no consumer would branch on does not
43    /// belong here.
44    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
45    pub struct ShellCaps: u32 {
46        /// The compositor can scale a smaller buffer to the window's size in
47        /// display hardware, so borderless render-scale costs no shader work.
48        ///
49        /// Wayland's `wp_viewporter`; the browser's CSS-sized canvas. Absent on
50        /// X11, where the renderer must do an upscale blit instead. This is the
51        /// exact decision the windowing rules call out as the reason caps
52        /// exist. Nothing asks for it: the engine does its own upscale on every
53        /// platform (`docs/backlog.md`, _The engine owns scaling_).
54        const HW_UPSCALE = 1 << 0;
55
56        /// The window system will enforce an aspect ratio during an interactive
57        /// resize.
58        ///
59        /// X11 `WM_NORMAL_HINTS`, Win32 `WM_SIZING`, macOS
60        /// `setContentAspectRatio`. **Wayland has no aspect hint**, so a
61        /// Wayland backend clears this bit and the renderer letterboxes.
62        /// Letterboxing must work regardless — a tiling window manager ignores
63        /// the hint on every backend that has one — so this flag chooses
64        /// between "good" and "correct", never between "works" and "broken".
65        const ASPECT_HINT_HONORED = 1 << 1;
66
67        /// [`Shell::warp_pointer`](crate::Shell::warp_pointer) moves the
68        /// pointer.
69        ///
70        /// X11 `XWarpPointer`, Win32 `SetCursorPos`. Wayland deliberately
71        /// forbids it (a client that can move the cursor can spoof clicks); the
72        /// engine's answer there is pointer lock plus relative motion, which is
73        /// what a camera wanted anyway.
74        const POINTER_WARP = 1 << 2;
75
76        /// [`PointerMode::Locked`](crate::PointerMode) is available: the
77        /// pointer can be hidden and pinned while relative motion keeps
78        /// flowing.
79        ///
80        /// Wayland `pointer-constraints` + `relative-pointer`, X11 pointer
81        /// grab, Win32 clip-and-recentre, the browser's Pointer Lock API.
82        ///
83        /// The browser is the one that cannot take the lock when asked: it
84        /// grants `requestPointerLock` only inside a user gesture, so
85        /// [`set_pointer_mode`](crate::Shell::set_pointer_mode) there records
86        /// the request and the player's next click completes it. The bit still
87        /// means what it says — the mode is available — and a consumer that
88        /// needs to know whether the pointer is pinned *now* reads the shape of
89        /// the motion events, as
90        /// [`PointerMode::Locked`](crate::PointerMode::Locked) describes.
91        const POINTER_LOCK = 1 << 3;
92
93        /// [`PointerMode::Confined`](crate::PointerMode) is available: the
94        /// pointer stays inside the window but keeps moving visibly.
95        ///
96        /// A separate bit from [`POINTER_LOCK`](Self::POINTER_LOCK) because
97        /// Wayland's `pointer-constraints` advertises lock and confine
98        /// independently, and a strategy game wants confine specifically.
99        const POINTER_CONFINE = 1 << 4;
100
101        /// Relative pointer motion is delivered separately from absolute
102        /// position, unaccelerated and unclamped by the screen edge.
103        ///
104        /// This is what a first-person camera must read;
105        /// the windowing rules make raw motion a P0 feature, not an
106        /// afterthought, on the grounds that an esports-grade engine cannot
107        /// derive aim from clamped absolute positions. Without this bit,
108        /// [`ShellEvent::PointerMotion`](crate::ShellEvent::PointerMotion)
109        /// carries `raw_delta: None` and the camera has to difference absolute
110        /// positions — which is wrong at the screen edge and wrong under
111        /// pointer acceleration.
112        ///
113        /// # The one platform that can decline the bypass
114        ///
115        /// On the desktop backends the unaccelerated stream is a separate
116        /// device interface and either exists or does not. In a browser it is
117        /// an *option* on the lock — `requestPointerLock({ unadjustedMovement:
118        /// true })` — and a browser that does not implement it hands back the
119        /// OS-adjusted deltas instead, either by ignoring the key or by
120        /// rejecting with `NotSupportedError` and being asked again without it.
121        /// The web backend sets this bit because it reads a relative stream and
122        /// asks for it unadjusted, which is the decision a camera branches on:
123        /// differencing absolute positions is wrong there whatever the browser
124        /// answered. It is not a promise that every browser granted the bypass;
125        /// the `web` backend's module docs name which browsers do.
126        const RAW_POINTER_MOTION = 1 << 5;
127
128        /// Composed text arrives as
129        /// [`ShellEvent::TextCommit`](crate::ShellEvent::TextCommit) through a
130        /// real input method, so CJK and dead-key input work.
131        ///
132        /// Without it a backend still emits `TextCommit` for plain typing —
133        /// the event is not IME-only — but complex scripts will not compose.
134        /// Full IME (pre-edit strings, candidate windows) is post-MVP; this bit
135        /// says only that the commit path is wired to an input method.
136        const TEXT_IME = 1 << 6;
137
138        /// Clipboard get/set works. See
139        /// [`clipboard`](crate::clipboard).
140        ///
141        /// Explicitly a capability because the browser gates clipboard reads
142        /// behind a permission prompt and a user gesture, which
143        /// the windowing rules call out by name: the editor UI has to
144        /// degrade gracefully in-browser rather than offering a paste button
145        /// that cannot work.
146        const CLIPBOARD = 1 << 7;
147
148        /// Files dragged onto a window arrive as
149        /// [`ShellEvent::DroppedFile`](crate::ShellEvent::DroppedFile).
150        const DRAG_DROP = 1 << 8;
151
152        /// The shell can create more than one window.
153        ///
154        /// The MVP editor is single-window, and a canvas backend has exactly
155        /// one canvas, so this is not universal. A consumer that wants a
156        /// tear-off panel checks this rather than assuming.
157        const MULTI_WINDOW = 1 << 9;
158
159        /// Window position in desktop coordinates can be read and set.
160        ///
161        /// **Wayland cannot do either** — a client is not told where it is and
162        /// cannot ask to be moved. Anything that wants to restore a window's
163        /// position across sessions (the editor, topic 14's settings store)
164        /// must check this bit and degrade to "the compositor decides".
165        const WINDOW_POSITION = 1 << 10;
166
167        /// The window system draws the title bar and borders.
168        ///
169        /// Wayland with `xdg-decoration` and a compositor that opts in, and
170        /// every other desktop platform. Without it the UI layer has to draw
171        /// its own decorations, which is a layout decision, not a rendering
172        /// detail — so it belongs in caps rather than being discovered by
173        /// noticing the window looks wrong.
174        const SERVER_DECORATIONS = 1 << 11;
175
176        /// Scale factors other than whole integers are reported.
177        ///
178        /// Wayland `fractional-scale-v1` (in 1/120ths), Win32 per-monitor-v2,
179        /// browser `devicePixelRatio`. Without it the shell reports integer
180        /// scales only, and a 125% desktop shows up as 1.0 or 2.0 — which the
181        /// UI needs to know before it decides whether to snap its layout to a
182        /// pixel grid.
183        const FRACTIONAL_SCALE = 1 << 12;
184
185        /// [`Shell::wait_events`](crate::Shell::wait_events) genuinely blocks.
186        ///
187        /// An editor idling at zero frames per second on battery depends on
188        /// it; a game never calls it. Backends that cannot block — the browser
189        /// above all, where blocking the main thread is not a thing that
190        /// happens — leave this clear and their `wait_events` returns
191        /// immediately, which is always a correct implementation.
192        const EVENT_WAIT = 1 << 13;
193
194        /// Fingers arrive as [`ShellEvent::Touch`](crate::ShellEvent::Touch),
195        /// with a contact id and a phase, so more than one can be tracked at a
196        /// time.
197        ///
198        /// **Win32 is the one desktop backend that sets it** (`WM_POINTER*`),
199        /// beside the browser. Clear on the others, and that is a statement
200        /// about the backends rather than about the platforms: a Linux tablet
201        /// has a touchscreen, and X11 (XInput2 `XI_TouchBegin`), Wayland
202        /// (`wl_touch`) and AppKit (`NSTouch`) all have a way to deliver one.
203        /// None of those paths is written, so a game on them sees no contacts
204        /// at all — an input that is *absent*, which is a different thing from
205        /// one that silently fails.
206        ///
207        /// A backend that does set it owes the emulated pointer stream for the
208        /// primary contact as well; [`ShellEvent::Touch`](crate::ShellEvent::Touch)
209        /// says why, and that obligation is what stops a backend turning this on
210        /// from breaking every game that binds only the pointer.
211        const TOUCH = 1 << 14;
212
213        /// [`WindowRole::Panel`](crate::WindowRole::Panel) can be created:
214        /// desktop furniture held against a monitor's edges.
215        const PANEL = 1 << 15;
216
217        /// A panel's [`Reserve::OwnExtent`](crate::Reserve::OwnExtent) is
218        /// honoured: maximised windows stop at the panel.
219        ///
220        /// Separate from [`PANEL`](Self::PANEL) because a window system can
221        /// have panels and still give nothing but its own furniture reserved
222        /// space — macOS, where the panel is created and overlaps what is
223        /// behind it.
224        const PANEL_RESERVE = 1 << 16;
225
226        /// [`WindowRole::Popup`](crate::WindowRole::Popup) can be created:
227        /// a window anchored to another's rectangle.
228        const POPUP = 1 << 17;
229
230        /// [`WindowDesc::transparent`](crate::WindowDesc::transparent) is
231        /// honoured: where the frame's alpha is below one, the desktop shows
232        /// through.
233        ///
234        /// The window system's half. The frame's half is a swapchain that
235        /// carries alpha, premultiplied — which the HAL's surface caps say
236        /// whether the driver offers, and which `crcbl::engine::GpuContext`
237        /// asks for when the window's surface target says it is transparent
238        /// — and a renderer that clears to alpha zero. See
239        /// [`WindowDesc::transparent`](crate::WindowDesc::transparent) for the
240        /// whole recipe.
241        const TRANSPARENT = 1 << 18;
242
243        /// [`Shell::reposition_popup`](crate::Shell::reposition_popup) moves
244        /// and resizes a live popup.
245        ///
246        /// Separate from [`POPUP`](Self::POPUP) because Wayland's
247        /// `xdg_popup.reposition` arrived in `xdg_wm_base` 3, and a compositor
248        /// offering only 1 or 2 has popups that stay where they opened.
249        const POPUP_REPOSITION = 1 << 19;
250
251        /// `Shell::update_accessibility` reaches the platform's assistive
252        /// technologies, and the `Accessibility*` events are raised.
253        ///
254        /// Set only by a backend built with the `accesskit` feature, which is
255        /// where that method and those events are, and an adapter for its
256        /// platform.
257        const ACCESSIBILITY = 1 << 20;
258    }
259}
260
261impl ShellCaps {
262    /// The set a full-featured desktop backend is expected to report.
263    ///
264    /// Not a promise about any particular platform — it is the reference point
265    /// tests and [`HeadlessShell`](crate::HeadlessShell) start from, and the
266    /// value a doc example can name without pretending to know what the machine
267    /// running it supports.
268    pub const DESKTOP: Self = Self::all();
269
270    /// Whether pointer capture in either form is available.
271    #[inline]
272    #[must_use]
273    pub const fn has_pointer_capture(self) -> bool {
274        self.intersects(Self::POINTER_LOCK.union(Self::POINTER_CONFINE))
275    }
276
277    /// Whether a first-person camera can get trustworthy aim input: the pointer
278    /// can be locked *and* relative motion is delivered.
279    ///
280    /// Both halves are required, and this helper exists because forgetting the
281    /// second one produces a camera that works until the pointer reaches the
282    /// edge of the screen.
283    #[inline]
284    #[must_use]
285    pub const fn has_mouselook(self) -> bool {
286        self.contains(Self::POINTER_LOCK.union(Self::RAW_POINTER_MOTION))
287    }
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293
294    #[test]
295    fn mouselook_needs_both_halves() {
296        assert!(ShellCaps::DESKTOP.has_mouselook());
297        // Pointer lock alone is the trap: aim breaks at the screen edge.
298        assert!(!ShellCaps::POINTER_LOCK.has_mouselook());
299        assert!(!ShellCaps::RAW_POINTER_MOTION.has_mouselook());
300        assert!((ShellCaps::POINTER_LOCK | ShellCaps::RAW_POINTER_MOTION).has_mouselook());
301    }
302
303    #[test]
304    fn pointer_capture_is_either_form() {
305        assert!(ShellCaps::POINTER_LOCK.has_pointer_capture());
306        assert!(ShellCaps::POINTER_CONFINE.has_pointer_capture());
307        assert!(!ShellCaps::POINTER_WARP.has_pointer_capture());
308        assert!(!ShellCaps::empty().has_pointer_capture());
309    }
310
311    #[test]
312    fn a_wayland_shaped_cap_set_is_expressible() {
313        // The point of the type: the exact combination Wayland produces — hardware
314        // upscale yes, aspect hint no, pointer warp no — is a value, not a
315        // `#[cfg]`.
316        let wayland = ShellCaps::HW_UPSCALE
317            | ShellCaps::POINTER_LOCK
318            | ShellCaps::POINTER_CONFINE
319            | ShellCaps::RAW_POINTER_MOTION
320            | ShellCaps::TEXT_IME
321            | ShellCaps::CLIPBOARD
322            | ShellCaps::DRAG_DROP
323            | ShellCaps::MULTI_WINDOW
324            | ShellCaps::SERVER_DECORATIONS
325            | ShellCaps::FRACTIONAL_SCALE
326            | ShellCaps::EVENT_WAIT;
327        assert!(wayland.has_mouselook());
328        assert!(!wayland.contains(ShellCaps::POINTER_WARP));
329        assert!(!wayland.contains(ShellCaps::ASPECT_HINT_HONORED));
330        assert!(!wayland.contains(ShellCaps::WINDOW_POSITION));
331        // `wl_touch` exists and this backend does not bind it, which is the
332        // whole difference between a platform and a backend.
333        assert!(!wayland.contains(ShellCaps::TOUCH));
334        assert!(ShellCaps::DESKTOP.contains(wayland));
335        assert_eq!(ShellCaps::default(), ShellCaps::empty());
336    }
337}