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 /// The backend is wired to the platform's input method, the framework
129 /// CJK and other complex-script input runs through, end to end.
130 ///
131 /// For a window that named a field with
132 /// [`Shell::set_text_input`](crate::Shell::set_text_input), the
133 /// composition in progress arrives as
134 /// [`ShellEvent::TextPreedit`](crate::ShellEvent::TextPreedit), the
135 /// conversion the user picks as
136 /// [`ShellEvent::TextCommit`](crate::ShellEvent::TextCommit), and
137 /// [`Shell::set_text_input_area`](crate::Shell::set_text_input_area)
138 /// is passed on so the input method can place its candidate window.
139 /// Whether the user runs an input method is not the shell's to know;
140 /// the bit says one would reach the engine.
141 ///
142 /// Wayland sets it when the compositor offers `text-input-v3`, and
143 /// Win32 through `imm32`. Clear on X11, which has no XIM, IBus or
144 /// Fcitx client; on AppKit, which does not send the pre-edit yet; and
145 /// on the web. Dead keys and Compose sequences are
146 /// [`TEXT_COMPOSE`](Self::TEXT_COMPOSE), which a backend can have
147 /// without this.
148 const TEXT_IME = 1 << 6;
149
150 /// Clipboard get/set works. See
151 /// [`clipboard`](crate::clipboard).
152 ///
153 /// Explicitly a capability because the browser gates clipboard reads
154 /// behind a permission prompt and a user gesture, which
155 /// the windowing rules call out by name: the editor UI has to
156 /// degrade gracefully in-browser rather than offering a paste button
157 /// that cannot work.
158 const CLIPBOARD = 1 << 7;
159
160 /// Files dragged onto a window arrive as
161 /// [`ShellEvent::DroppedFile`](crate::ShellEvent::DroppedFile).
162 const DRAG_DROP = 1 << 8;
163
164 /// The shell can create more than one window.
165 ///
166 /// The MVP editor is single-window, and a canvas backend has exactly
167 /// one canvas, so this is not universal. A consumer that wants a
168 /// tear-off panel checks this rather than assuming.
169 const MULTI_WINDOW = 1 << 9;
170
171 /// Window position in desktop coordinates can be read and set.
172 ///
173 /// **Wayland cannot do either** — a client is not told where it is and
174 /// cannot ask to be moved. Anything that wants to restore a window's
175 /// position across sessions (the editor, topic 14's settings store)
176 /// must check this bit and degrade to "the compositor decides".
177 const WINDOW_POSITION = 1 << 10;
178
179 /// The window system draws the title bar and borders.
180 ///
181 /// Wayland with `xdg-decoration` and a compositor that opts in, and
182 /// every other desktop platform. Without it the UI layer has to draw
183 /// its own decorations, which is a layout decision, not a rendering
184 /// detail — so it belongs in caps rather than being discovered by
185 /// noticing the window looks wrong.
186 const SERVER_DECORATIONS = 1 << 11;
187
188 /// Scale factors other than whole integers are reported.
189 ///
190 /// Wayland `fractional-scale-v1` (in 1/120ths), Win32 per-monitor-v2,
191 /// browser `devicePixelRatio`. Without it the shell reports integer
192 /// scales only, and a 125% desktop shows up as 1.0 or 2.0 — which the
193 /// UI needs to know before it decides whether to snap its layout to a
194 /// pixel grid.
195 const FRACTIONAL_SCALE = 1 << 12;
196
197 /// [`Shell::wait_events`](crate::Shell::wait_events) genuinely blocks.
198 ///
199 /// An editor idling at zero frames per second on battery depends on
200 /// it; a game never calls it. Backends that cannot block — the browser
201 /// above all, where blocking the main thread is not a thing that
202 /// happens — leave this clear and their `wait_events` returns
203 /// immediately, which is always a correct implementation.
204 const EVENT_WAIT = 1 << 13;
205
206 /// Fingers arrive as [`ShellEvent::Touch`](crate::ShellEvent::Touch),
207 /// with a contact id and a phase, so more than one can be tracked at a
208 /// time.
209 ///
210 /// **Win32 is the one desktop backend that sets it** (`WM_POINTER*`),
211 /// beside the browser. Clear on the others, and that is a statement
212 /// about the backends rather than about the platforms: a Linux tablet
213 /// has a touchscreen, and X11 (XInput2 `XI_TouchBegin`), Wayland
214 /// (`wl_touch`) and AppKit (`NSTouch`) all have a way to deliver one.
215 /// None of those paths is written, so a game on them sees no contacts
216 /// at all — an input that is *absent*, which is a different thing from
217 /// one that silently fails.
218 ///
219 /// A backend that does set it owes the emulated pointer stream for the
220 /// primary contact as well; [`ShellEvent::Touch`](crate::ShellEvent::Touch)
221 /// says why, and that obligation is what stops a backend turning this on
222 /// from breaking every game that binds only the pointer.
223 const TOUCH = 1 << 14;
224
225 /// [`WindowRole::Panel`](crate::WindowRole::Panel) can be created:
226 /// desktop furniture held against a monitor's edges.
227 const PANEL = 1 << 15;
228
229 /// A panel's [`Reserve::OwnExtent`](crate::Reserve::OwnExtent) is
230 /// honoured: maximised windows stop at the panel.
231 ///
232 /// Separate from [`PANEL`](Self::PANEL) because a window system can
233 /// have panels and still give nothing but its own furniture reserved
234 /// space — macOS, where the panel is created and overlaps what is
235 /// behind it.
236 const PANEL_RESERVE = 1 << 16;
237
238 /// [`WindowRole::Popup`](crate::WindowRole::Popup) can be created:
239 /// a window anchored to another's rectangle.
240 const POPUP = 1 << 17;
241
242 /// [`WindowDesc::transparent`](crate::WindowDesc::transparent) is
243 /// honoured: where the frame's alpha is below one, the desktop shows
244 /// through.
245 ///
246 /// The window system's half. The frame's half is a swapchain that
247 /// carries alpha, premultiplied — which the HAL's surface caps say
248 /// whether the driver offers, and which `crcbl::engine::GpuContext`
249 /// asks for when the window's surface target says it is transparent
250 /// — and a renderer that clears to alpha zero. See
251 /// [`WindowDesc::transparent`](crate::WindowDesc::transparent) for the
252 /// whole recipe.
253 const TRANSPARENT = 1 << 18;
254
255 /// [`Shell::reposition_popup`](crate::Shell::reposition_popup) moves
256 /// and resizes a live popup.
257 ///
258 /// Separate from [`POPUP`](Self::POPUP) because Wayland's
259 /// `xdg_popup.reposition` arrived in `xdg_wm_base` 3, and a compositor
260 /// offering only 1 or 2 has popups that stay where they opened.
261 const POPUP_REPOSITION = 1 << 19;
262
263 /// `Shell::update_accessibility` reaches the platform's assistive
264 /// technologies, and the `Accessibility*` events are raised.
265 ///
266 /// Set only by a backend built with the `accesskit` feature, which is
267 /// where that method and those events are, and an adapter for its
268 /// platform.
269 const ACCESSIBILITY = 1 << 20;
270
271 /// Dead keys and Compose sequences compose: a dead accent and the next
272 /// key, or a Compose-key sequence, arrive as one
273 /// [`ShellEvent::TextCommit`](crate::ShellEvent::TextCommit) carrying
274 /// the composed text.
275 ///
276 /// libxkbcommon's compose module on Wayland and X11, with the user's
277 /// locale's table; `TranslateMessage` on Win32; `interpretKeyEvents:`
278 /// on AppKit. Without it a backend may still commit plain typing, but
279 /// an accent typed through a dead key never lands on its letter. It
280 /// says nothing about an input method, which is
281 /// [`TEXT_IME`](Self::TEXT_IME): X11 composes and has none.
282 const TEXT_COMPOSE = 1 << 21;
283
284 /// A panel with
285 /// [`PanelKeyboard::Exclusive`](crate::PanelKeyboard::Exclusive)
286 /// keeps the keyboard while it is mapped: the window system will not
287 /// give it to another window, whatever the user clicks.
288 ///
289 /// Wayland's layer-shell enforces it in the compositor, on the
290 /// [`Top`](crate::PanelLayer::Top) and
291 /// [`Overlay`](crate::PanelLayer::Overlay) layers; the protocol lets a
292 /// compositor use ordinary focus on the lower two. Clear on Win32 and
293 /// AppKit, where an exclusive panel takes the keyboard when it is
294 /// shown (or hears
295 /// [`FocusRefused`](crate::ShellEvent::FocusRefused)) and the user
296 /// can click it away, which arrives as
297 /// [`Focus`](crate::ShellEvent::Focus) with `focused: false`. A
298 /// launcher that should close when it loses the keyboard closes on
299 /// that event; a lock screen cannot be built without this bit.
300 const PANEL_EXCLUSIVE_KEYBOARD = 1 << 22;
301
302 /// [`Shell::set_cursor`](crate::Shell::set_cursor) with a shape
303 /// changes the cursor the user sees, to the platform's own themed
304 /// cursor for that [`CursorIcon`](crate::CursorIcon).
305 ///
306 /// Win32's stock `user32` cursors, AppKit's `NSCursor`, and the
307 /// canvas's CSS `cursor` on the web; on Wayland, `cursor-shape-v1`
308 /// where the compositor offers it, which hands the compositor the
309 /// shape's name and lets it draw the user's theme. Clear on X11, which
310 /// has no cursor theme loader yet. Without it, `set_cursor` still
311 /// accepts and records a shape — a UI calls it on every hover, and an
312 /// error there would be one every caller had to handle — and hiding
313 /// with `None` works everywhere; only the shape goes unseen.
314 const CURSOR_SHAPE = 1 << 23;
315 }
316}
317
318impl ShellCaps {
319 /// The set a full-featured desktop backend is expected to report.
320 ///
321 /// Not a promise about any particular platform — it is the reference point
322 /// tests and [`HeadlessShell`](crate::HeadlessShell) start from, and the
323 /// value a doc example can name without pretending to know what the machine
324 /// running it supports.
325 pub const DESKTOP: Self = Self::all();
326
327 /// Whether pointer capture in either form is available.
328 #[inline]
329 #[must_use]
330 pub const fn has_pointer_capture(self) -> bool {
331 self.intersects(Self::POINTER_LOCK.union(Self::POINTER_CONFINE))
332 }
333
334 /// Whether a first-person camera can get trustworthy aim input: the pointer
335 /// can be locked *and* relative motion is delivered.
336 ///
337 /// Both halves are required, and this helper exists because forgetting the
338 /// second one produces a camera that works until the pointer reaches the
339 /// edge of the screen.
340 #[inline]
341 #[must_use]
342 pub const fn has_mouselook(self) -> bool {
343 self.contains(Self::POINTER_LOCK.union(Self::RAW_POINTER_MOTION))
344 }
345}
346
347#[cfg(test)]
348mod tests {
349 use super::*;
350
351 #[test]
352 fn mouselook_needs_both_halves() {
353 assert!(ShellCaps::DESKTOP.has_mouselook());
354 // Pointer lock alone is the trap: aim breaks at the screen edge.
355 assert!(!ShellCaps::POINTER_LOCK.has_mouselook());
356 assert!(!ShellCaps::RAW_POINTER_MOTION.has_mouselook());
357 assert!((ShellCaps::POINTER_LOCK | ShellCaps::RAW_POINTER_MOTION).has_mouselook());
358 }
359
360 #[test]
361 fn pointer_capture_is_either_form() {
362 assert!(ShellCaps::POINTER_LOCK.has_pointer_capture());
363 assert!(ShellCaps::POINTER_CONFINE.has_pointer_capture());
364 assert!(!ShellCaps::POINTER_WARP.has_pointer_capture());
365 assert!(!ShellCaps::empty().has_pointer_capture());
366 }
367
368 #[test]
369 fn a_wayland_shaped_cap_set_is_expressible() {
370 // The point of the type: the exact combination Wayland produces — hardware
371 // upscale yes, aspect hint no, pointer warp no — is a value, not a
372 // `#[cfg]`.
373 let wayland = ShellCaps::HW_UPSCALE
374 | ShellCaps::POINTER_LOCK
375 | ShellCaps::POINTER_CONFINE
376 | ShellCaps::RAW_POINTER_MOTION
377 | ShellCaps::TEXT_IME
378 | ShellCaps::TEXT_COMPOSE
379 | ShellCaps::CLIPBOARD
380 | ShellCaps::DRAG_DROP
381 | ShellCaps::MULTI_WINDOW
382 | ShellCaps::SERVER_DECORATIONS
383 | ShellCaps::FRACTIONAL_SCALE
384 | ShellCaps::EVENT_WAIT
385 | ShellCaps::CURSOR_SHAPE;
386 assert!(wayland.has_mouselook());
387 assert!(!wayland.contains(ShellCaps::POINTER_WARP));
388 assert!(!wayland.contains(ShellCaps::ASPECT_HINT_HONORED));
389 assert!(!wayland.contains(ShellCaps::WINDOW_POSITION));
390 // `wl_touch` exists and this backend does not bind it, which is the
391 // whole difference between a platform and a backend.
392 assert!(!wayland.contains(ShellCaps::TOUCH));
393 assert!(ShellCaps::DESKTOP.contains(wayland));
394 assert_eq!(ShellCaps::default(), ShellCaps::empty());
395 }
396}