crcbl_shell/backend.rs
1//! Choosing a backend at runtime.
2//!
3//! # The decision: runtime selection, one registry, `Box<dyn Shell>`
4//!
5//! The windowing rules in `docs/notes/backends.md` require it in one sentence —
6//! "backend selection
7//! at runtime, not compile time, on Linux: try Wayland socket → fall back to
8//! X11 (both compiled in; `CRCBL_SHELL=x11` override)" — and that sentence has
9//! consequences the API has to absorb *now*, because retrofitting them costs a
10//! rewrite of every consumer:
11//!
12//! 1. **[`Shell`] must be object-safe.** A generic `Shell` would make the
13//! backend a compile-time parameter, and "try Wayland, fall back to X11"
14//! would then have to monomorphise every consumer twice and pick between the
15//! two instantiations with an `enum` wrapper — which is a hand-written
16//! vtable with extra steps. `crcbl-hal` reached the same conclusion for the
17//! same reason and states the costs; they apply here in a milder form, since
18//! the shell is called a handful of times per frame rather than per draw.
19//! 2. **The entry point cannot be a constructor.** `WaylandShell::new()` puts
20//! the platform name in the caller's source, which is the regression the
21//! whole seam exists to prevent. So the entry point is [`open`], and the
22//! only concrete shell type a consumer ever names is
23//! [`HeadlessShell`] — deliberately, because a test
24//! asking for determinism is asking for a *specific* implementation.
25//!
26//! # What is registered today
27//!
28//! Wayland then X11 on Linux, Win32 on Windows, AppKit on macOS, and
29//! [`HeadlessShell`] everywhere — the last only when asked for by name. **P0.6
30//! confirmed the property this module was shaped to have and P5C confirmed it
31//! twice more**: adding a whole X11 backend touched [`REGISTRY`](self) and these
32//! tests, and no other file outside `src/x11/` (plus `src/linux/`, which is the
33//! evdev table and libxkbcommon moving up one level to be shared rather than
34//! copied); adding the Win32 backend touched this file, `src/lib.rs` and
35//! `src/win32/`, and adding the AppKit one touched this file, `src/lib.rs` and
36//! `src/appkit/`. No consumer changed, no trait method was added, and no
37//! `#[cfg]` appeared anywhere above this crate.
38//!
39//! **Every variant of [`ShellBackend`] is now registered somewhere**, which
40//! changes how the "a backend this build does not have" property is tested. It
41//! used to be asserted against whichever variant had not landed yet — X11 until
42//! P0.6, Win32 until P5C, AppKit until this slice — and there is no fourth
43//! candidate. The tests below now derive the absent set from the table itself
44//! and assert the property per platform, which is what was actually meant all
45//! along: *asking for a backend this build lacks is an honest
46//! [`UnknownBackend`](ShellError::UnknownBackend)*. It also cannot go stale
47//! again — a future backend is covered the day it is added, on the platforms
48//! that do not have it.
49//!
50//! Headless is registered with `auto: false`, so [`open`] never selects it
51//! implicitly. A game that silently ran headless because a compositor was
52//! missing would look like a hang; failing with
53//! [`ShellError::NoBackend`] names the actual problem.
54//!
55//! # Why both Linux entries are `dlopen`-backed, and the Windows one is not
56//!
57//! The registry is a fall-through list, so every entry has to be able to *fail*
58//! at runtime. A backend linked against `libwayland-client.so.0` — or
59//! `libxcb.so.1` — with `DT_NEEDED` cannot: the process dies in `ld.so` before
60//! `main`, on any machine without the library, and this list never runs.
61//! `crates/crcbl-wayland/src/ffi.rs` has the full argument and
62//! `crates/crcbl-x11/src/ffi.rs` sharpens it,
63//! since X11 is the *fallback* and is reached only after Wayland has already
64//! failed.
65//!
66//! The Win32 and AppKit entries link their libraries instead, and the
67//! difference is this list's shape rather than a change of mind: each of those
68//! platforms has one backend, so nothing falls through to anything, and neither
69//! `user32.dll` nor AppKit can be missing from a system that is running a
70//! process at all. `src/win32/ffi.rs` states it in full and `src/appkit/ffi.rs`
71//! repeats it for the frameworks.
72
73use crate::{HeadlessShell, Shell, ShellError};
74
75/// Which implementation is behind the [`Shell`] trait.
76///
77/// For logs, error messages and bug reports. Shell *behaviour* must key off
78/// [`ShellCaps`](crate::ShellCaps), never off this — that is the difference
79/// between a capability system and platform sniffing, and it is the same rule
80/// `crcbl-hal`'s `BackendKind` carries.
81#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
82pub enum ShellBackend {
83 /// Wayland, through libwayland-client and our own protocol layer (P0.5).
84 Wayland,
85 /// X11, through libxcb and our own request/event layer (P0.6).
86 X11,
87 /// Win32, through hand-written `extern "system"` declarations (P5C).
88 Win32,
89 /// AppKit (P5C).
90 AppKit,
91 /// A browser canvas, through the hand-rolled JS shim (P5).
92 Web,
93 /// [`HeadlessShell`] — no window system at all.
94 Headless,
95}
96
97impl ShellBackend {
98 /// The lowercase name used in `CRCBL_SHELL` and in log lines.
99 #[must_use]
100 pub const fn as_str(self) -> &'static str {
101 match self {
102 Self::Wayland => "wayland",
103 Self::X11 => "x11",
104 Self::Win32 => "win32",
105 Self::AppKit => "appkit",
106 Self::Web => "web",
107 Self::Headless => "headless",
108 }
109 }
110
111 /// Parses a `CRCBL_SHELL` value.
112 ///
113 /// Accepts `x11` and its common misspelling `xcb`, because the backend is
114 /// built on libxcb and someone will type it.
115 #[must_use]
116 pub fn from_name(name: &str) -> Option<Self> {
117 match name.trim().to_ascii_lowercase().as_str() {
118 "wayland" | "wl" => Some(Self::Wayland),
119 "x11" | "xcb" => Some(Self::X11),
120 "win32" | "windows" => Some(Self::Win32),
121 "appkit" | "macos" | "cocoa" => Some(Self::AppKit),
122 "web" | "canvas" => Some(Self::Web),
123 "headless" | "null" => Some(Self::Headless),
124 _ => None,
125 }
126 }
127}
128
129impl core::fmt::Display for ShellBackend {
130 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
131 f.write_str(self.as_str())
132 }
133}
134
135/// The environment variable that overrides automatic backend selection.
136pub const BACKEND_ENV_VAR: &str = "CRCBL_SHELL";
137
138/// One entry in the backend table.
139struct Registration {
140 backend: ShellBackend,
141 /// Whether [`open`] may select this entry without being asked for it by
142 /// name. See the [module docs](self) for why headless is `false`.
143 auto: bool,
144 open: fn() -> Result<Box<dyn Shell>, ShellError>,
145}
146
147/// Every backend compiled into this build, in the order [`open`] tries them.
148///
149/// The order is the windowing rules' preference order: Wayland
150/// first, X11 as the fallback. On a session running both — which is every
151/// XWayland-capable compositor — Wayland wins, and `CRCBL_SHELL=x11` is how a
152/// developer reproduces an X11 bug without logging out.
153static REGISTRY: &[Registration] = &[
154 // `#[cfg]` on the element, not on the whole table: on macOS and Windows
155 // the entry simply is not there, so nothing else in this file mentions a
156 // platform and `open_auto` needs no conditional compilation of its own.
157 #[cfg(desktop_unix)]
158 Registration {
159 backend: ShellBackend::Wayland,
160 auto: true,
161 open: || Ok(Box::new(crate::wayland::WaylandShell::open()?)),
162 },
163 #[cfg(desktop_unix)]
164 Registration {
165 backend: ShellBackend::X11,
166 auto: true,
167 open: || Ok(Box::new(crate::x11::X11Shell::open()?)),
168 },
169 // Windows has exactly one backend, so nothing here falls through to
170 // anything — which is what lets `src/win32/ffi.rs` link its libraries
171 // instead of `dlopen`ing them. See that module for the asymmetry.
172 #[cfg(target_os = "windows")]
173 Registration {
174 backend: ShellBackend::Win32,
175 auto: true,
176 open: || Ok(Box::new(crate::win32::Win32Shell::open()?)),
177 },
178 // macOS likewise has exactly one backend, so `src/appkit/ffi.rs` links its
179 // frameworks for the same reason `src/win32/ffi.rs` links its DLLs.
180 #[cfg(target_os = "macos")]
181 Registration {
182 backend: ShellBackend::AppKit,
183 auto: true,
184 open: || Ok(Box::new(crate::appkit::AppKitShell::open()?)),
185 },
186 Registration {
187 backend: ShellBackend::Headless,
188 auto: false,
189 open: || Ok(Box::new(HeadlessShell::new())),
190 },
191 Registration {
192 backend: ShellBackend::Web,
193 auto: false,
194 open: web_open,
195 },
196];
197
198fn registry_names(entries: impl Iterator<Item = ShellBackend>) -> String {
199 let names: Vec<&str> = entries.map(ShellBackend::as_str).collect();
200 if names.is_empty() {
201 "none".to_string()
202 } else {
203 names.join(", ")
204 }
205}
206
207/// Opens the best available shell for this process.
208///
209/// Reads [`BACKEND_ENV_VAR`]: when it names a backend, that backend is opened
210/// and a failure is *not* fallen back from — someone who set the variable meant
211/// it, and quietly running on a different backend turns a debugging session
212/// into a wild goose chase. Otherwise the compiled-in backends are tried in
213/// preference order and the first one that connects wins.
214///
215/// # Errors
216///
217/// * [`ShellError::UnknownBackend`] if `CRCBL_SHELL` names something this build
218/// does not have.
219/// * The backend's own error if a named backend fails to open.
220/// * [`ShellError::NoBackend`] if nothing connected.
221///
222/// # Today
223///
224/// On Linux, Wayland is tried and then X11; `CRCBL_SHELL=wayland` or
225/// `CRCBL_SHELL=x11` forces one of them. On Windows and on macOS there is one
226/// backend each and it is selected automatically — although the AppKit one
227/// requires the process's **main thread** and returns
228/// [`ShellError::Backend`] naming that rule anywhere else, which is a failure
229/// this list falls through rather than one it hides. Every other target has
230/// only [`HeadlessShell`], which is not auto-selected, so this returns
231/// [`ShellError::NoBackend`] there unless `CRCBL_SHELL=headless` is set — the
232/// honest answer for a build with no window-system backend in it.
233pub fn open() -> Result<Box<dyn Shell>, ShellError> {
234 match std::env::var(BACKEND_ENV_VAR) {
235 Ok(value) if !value.trim().is_empty() => {
236 let Some(requested) = ShellBackend::from_name(&value) else {
237 return Err(ShellError::UnknownBackend {
238 requested: value,
239 available: registry_names(REGISTRY.iter().map(|entry| entry.backend)),
240 });
241 };
242 open_backend(requested)
243 }
244 _ => open_auto(),
245 }
246}
247
248/// Opens a specific backend, ignoring [`BACKEND_ENV_VAR`].
249///
250/// For `crcbl` CLI subcommands that must be headless whatever the environment
251/// says, and for tests.
252///
253/// # Errors
254///
255/// [`ShellError::UnknownBackend`] if this build has no such backend, or the
256/// backend's own error if it fails to open.
257pub fn open_backend(backend: ShellBackend) -> Result<Box<dyn Shell>, ShellError> {
258 match REGISTRY.iter().find(|entry| entry.backend == backend) {
259 Some(entry) => (entry.open)(),
260 None => Err(ShellError::UnknownBackend {
261 requested: backend.as_str().to_string(),
262 available: registry_names(REGISTRY.iter().map(|entry| entry.backend)),
263 }),
264 }
265}
266
267/// Opens the web backend, which exists only inside a browser.
268///
269/// Registered on every target — unlike the two Linux entries, which are
270/// `#[cfg]`ed out where they cannot work — because the failure it has to produce
271/// off wasm is a *diagnostic*. `CRCBL_SHELL=web` on a desktop used to hand back
272/// a shell that could never receive an event, so the application hung in its
273/// configure loop with nothing in the log; `UnknownBackend` would have been
274/// almost as bad, since "web is not in this build" is not what is wrong. The
275/// error names the actual problem instead. This is the same argument the module
276/// docs make for why headless is `auto: false`.
277///
278/// The canvas id comes from the shim's `__crcbl_web_canvas`, not from an
279/// environment variable: `std::env::var` on `wasm32-unknown-unknown` always
280/// answers `NotPresent`, so a `CRCBL_CANVAS_ID` lookup silently always produced
281/// the fallback.
282fn web_open() -> Result<Box<dyn Shell>, ShellError> {
283 #[cfg(target_arch = "wasm32")]
284 {
285 Ok(Box::new(crate::web::open(crate::web::canvas_id())?))
286 }
287 #[cfg(not(target_arch = "wasm32"))]
288 {
289 Err(ShellError::Unsupported {
290 backend: ShellBackend::Web,
291 what: "the web backend outside a browser — build for wasm32-unknown-unknown",
292 })
293 }
294}
295
296/// Tries every auto-selectable backend in preference order.
297fn open_auto() -> Result<Box<dyn Shell>, ShellError> {
298 let mut tried = Vec::new();
299 for entry in REGISTRY.iter().filter(|entry| entry.auto) {
300 tried.push(entry.backend);
301 match (entry.open)() {
302 Ok(shell) => {
303 crcbl_core::log::info!("opened the {} shell backend", entry.backend);
304 return Ok(shell);
305 }
306 // A backend that is compiled in but cannot connect is the normal
307 // case on a Wayland-only or X11-only session, so it is a debug line
308 // rather than a warning — but it is never silent, because "why did
309 // it pick X11?" is a question someone will ask.
310 Err(error) => {
311 crcbl_core::log::debug!("{} shell backend unavailable: {error}", entry.backend)
312 }
313 }
314 }
315 Err(ShellError::NoBackend {
316 tried: registry_names(tried.into_iter()),
317 })
318}
319
320#[cfg(test)]
321mod tests {
322 use super::*;
323
324 #[test]
325 fn backend_names_round_trip() {
326 let backends = [
327 ShellBackend::Wayland,
328 ShellBackend::X11,
329 ShellBackend::Win32,
330 ShellBackend::AppKit,
331 ShellBackend::Web,
332 ShellBackend::Headless,
333 ];
334 for backend in backends {
335 assert_eq!(ShellBackend::from_name(backend.as_str()), Some(backend));
336 assert_eq!(backend.to_string(), backend.as_str());
337 }
338 // Aliases someone will actually type.
339 assert_eq!(ShellBackend::from_name("XCB"), Some(ShellBackend::X11));
340 assert_eq!(
341 ShellBackend::from_name(" WaYlAnD "),
342 Some(ShellBackend::Wayland)
343 );
344 assert_eq!(ShellBackend::from_name("mir"), None);
345 }
346
347 #[test]
348 fn the_table_matches_the_platform_and_headless_is_never_automatic() {
349 // The tripwire for every backend slice: adding a registration must be a
350 // deliberate edit here too.
351 let backends: Vec<ShellBackend> = REGISTRY.iter().map(|entry| entry.backend).collect();
352 if cfg!(desktop_unix) {
353 assert_eq!(
354 backends,
355 [
356 ShellBackend::Wayland,
357 ShellBackend::X11,
358 ShellBackend::Headless,
359 ShellBackend::Web,
360 ]
361 );
362 } else if cfg!(target_os = "windows") {
363 assert_eq!(
364 backends,
365 [
366 ShellBackend::Win32,
367 ShellBackend::Headless,
368 ShellBackend::Web,
369 ]
370 );
371 } else if cfg!(target_os = "macos") {
372 assert_eq!(
373 backends,
374 [
375 ShellBackend::AppKit,
376 ShellBackend::Headless,
377 ShellBackend::Web,
378 ]
379 );
380 } else {
381 assert_eq!(backends, [ShellBackend::Headless, ShellBackend::Web]);
382 }
383 let headless = REGISTRY
384 .iter()
385 .find(|entry| entry.backend == ShellBackend::Headless)
386 .expect("headless is always compiled in");
387 assert!(!headless.auto, "a game must never silently run headless");
388 assert!(
389 REGISTRY
390 .iter()
391 .filter(|entry| entry.auto)
392 .all(|entry| entry.backend != ShellBackend::Headless)
393 );
394 }
395
396 #[test]
397 fn opening_by_name_works_and_unknown_backends_are_rejected() {
398 let shell = open_backend(ShellBackend::Headless).expect("headless is registered");
399 assert_eq!(shell.backend(), ShellBackend::Headless);
400
401 // Registered everywhere, but it only *works* in a browser — and off
402 // wasm it says so rather than handing back a shell that can never
403 // produce an event.
404 if !cfg!(target_arch = "wasm32") {
405 let error = open_backend(ShellBackend::Web).expect_err("no browser here");
406 let ShellError::Unsupported { backend, what } = error else {
407 panic!("wrong variant");
408 };
409 assert_eq!(backend, ShellBackend::Web);
410 assert!(what.contains("wasm32"), "{what}");
411 }
412
413 // **Every backend this build does not have**, derived from the table
414 // rather than named. X11 was the example until P0.6 registered it,
415 // Win32 until P5C did, and AppKit until the slice after that — at which
416 // point every variant is registered *somewhere* and there is no fourth
417 // candidate to promote. The property being asserted was never about a
418 // particular backend: it is that asking for one this build lacks is an
419 // honest `UnknownBackend` rather than a silent fallback onto something
420 // else. Reading the absent set out of `REGISTRY` says exactly that, and
421 // covers a future backend on the day it is added.
422 let registered: Vec<ShellBackend> = REGISTRY.iter().map(|entry| entry.backend).collect();
423 let absent: Vec<ShellBackend> = [
424 ShellBackend::Wayland,
425 ShellBackend::X11,
426 ShellBackend::Win32,
427 ShellBackend::AppKit,
428 ShellBackend::Web,
429 ShellBackend::Headless,
430 ]
431 .into_iter()
432 .filter(|backend| !registered.contains(backend))
433 .collect();
434 // A loop over an empty set asserts nothing, and this one would be empty
435 // if the `#[cfg]`s ever compiled every entry in at once.
436 assert!(
437 !absent.is_empty(),
438 "every backend is registered on this platform, so nothing here checks the \
439 UnknownBackend path: {registered:?}"
440 );
441 for backend in absent {
442 let error = open_backend(backend).expect_err("not in this build");
443 let ShellError::UnknownBackend {
444 requested,
445 available,
446 } = error
447 else {
448 panic!("{backend} is not registered here, so it must answer UnknownBackend");
449 };
450 assert_eq!(requested, backend.as_str());
451 assert!(available.contains("headless"), "{available}");
452 }
453
454 // And the other half, which is what makes the first half meaningful:
455 // this platform's own backend **is** registered, so asking for it by
456 // name gets a real shell or its own failure — never `UnknownBackend`.
457 #[cfg(target_os = "windows")]
458 {
459 let shell = open_backend(ShellBackend::Win32).expect("registered on Windows");
460 assert_eq!(shell.backend(), ShellBackend::Win32);
461 }
462 #[cfg(target_os = "macos")]
463 {
464 // Not `expect`: AppKit requires the process's main thread, and a
465 // test body never is one — see `appkit::app`. The point here is the
466 // *variant*, and the failure that is legal is the backend's own.
467 match open_backend(ShellBackend::AppKit) {
468 Ok(shell) => assert_eq!(shell.backend(), ShellBackend::AppKit),
469 Err(error) => assert!(
470 !matches!(error, ShellError::UnknownBackend { .. }),
471 "AppKit is registered on macOS, so this must be its own failure: {error}"
472 ),
473 }
474 }
475 }
476
477 #[test]
478 fn automatic_selection_reports_what_it_tried() {
479 // On a machine with a compositor this genuinely connects, which is the
480 // correct behaviour and not something to assert against; the point of
481 // the test is the failure path's message.
482 match open_auto() {
483 Ok(shell) => assert!(
484 matches!(
485 shell.backend(),
486 ShellBackend::Wayland
487 | ShellBackend::X11
488 | ShellBackend::Win32
489 | ShellBackend::AppKit
490 ),
491 "the auto-selectable backends are the two Linux ones — Wayland \
492 first — and the single Windows and macOS ones: {}",
493 shell.backend()
494 ),
495 Err(ShellError::NoBackend { tried }) => {
496 let expected = if cfg!(desktop_unix) {
497 "wayland, x11"
498 } else if cfg!(target_os = "windows") {
499 "win32"
500 } else if cfg!(target_os = "macos") {
501 // Reached on every macOS test run, because a test body is
502 // never the main thread and `AppKitShell::open` refuses
503 // there — so this branch is the *normal* path on that
504 // platform rather than the degraded one, and it is still
505 // asserting the same thing: the failure names what it tried.
506 "appkit"
507 } else {
508 "none"
509 };
510 assert_eq!(tried, expected, "every attempt is named, in order");
511 }
512 Err(error) => panic!("unexpected error: {error}"),
513 }
514 }
515}