Skip to main content

crcbl_shell/
lib.rs

1//! The Crucible windowing seam: one trait, engine-typed vocabulary, and a
2//! complete headless implementation.
3//!
4//! Everything above this crate — the engine loop, the renderer, the samples,
5//! the editor — talks to the window system exclusively through [`Shell`].
6//! Everything below it (the Wayland and X11 backends at P0.5/P0.6, Win32 at
7//! P5C, AppKit next to it, the canvas at P5) implements it. **No platform
8//! type ever appears in a signature here, and a `#[cfg(target_os = …)]` in a
9//! consumer is a regression** — the same discipline `crcbl-hal` applies to the
10//! GPU, applied to the window.
11//!
12//! The one sanctioned leak is [`SurfaceTarget`], produced by
13//! [`Shell::surface_target`] and destructured only by HAL backends. It lives in
14//! `crcbl-core` because this crate and `crcbl-hal` must not depend on each
15//! other; see [`crcbl_core::surface`] for the argument. The dependency
16//! direction across the two seams is:
17//!
18//! ```text
19//! crcbl-shell ──▶ crcbl-core ◀── crcbl-hal ◀── crcbl-vk / crcbl-webgpu / …
20//! ```
21//!
22//! # What is in this crate
23//!
24//! P0.4 added the seam and [`HeadlessShell`]. P0.5a added the **Wayland
25//! backend**'s window lifecycle — connection, registry, `xdg-shell`,
26//! configure/ack, modes, monitors. P0.5b added everything downstream of
27//! `wl_seat`: keyboard and pointer input with XKB keymaps, pointer lock and
28//! confinement, raw relative motion, fractional scale, `xdg_output` monitor
29//! geometry and `xdg-decoration`. P0.5c added `data-device`: the clipboard in
30//! both directions and drag-and-drop *reception*, with the payload transfers
31//! run across pipes without ever blocking the frame loop.
32//!
33//! P0.6 added the **X11 backend**: libxcb through `dlopen`, the window
34//! lifecycle with ICCCM and EWMH properties, RandR monitor enumeration, XKB
35//! keymaps read from the server, XInput 2 raw motion, pointer grabs, and the
36//! selection protocol with `TARGETS` negotiation and `INCR` transfers in both
37//! directions. Drag and drop (XDND) is deliberately *not* in it and
38//! [`ShellCaps::DRAG_DROP`] says so. Both backends are compiled only on Linux,
39//! reached only through [`open`], and built on hand-written `extern "C"`
40//! declarations — for libwayland-client, libxcb and libxkbcommon — with the
41//! Wayland protocol marshalling generated at build time from vendored XML by
42//! `crcbl-wl-scanner`. There is no `wayland-client`, no `x11rb` and no `winit`.
43//!
44//! P5C added the **Win32 backend**: the window class and its procedure,
45//! create/destroy, title, visibility, windowed ↔ borderless on a named monitor,
46//! `WM_GETMINMAXINFO` and `WM_SIZING` size constraints, monitor enumeration with
47//! per-monitor-v2 DPI, the message pump and a blocking `wait_events` — then
48//! keyboard, text, pointer, wheel, raw relative motion, pointer lock and
49//! confinement, cursors and warping. The clipboard and drag-and-drop are the
50//! slice after it, and [`ShellCaps`] is clear on every bit they would set. It is
51//! hand-written `extern "system"` FFI to `user32`, `gdi32`, `shcore` and
52//! `kernel32` — **linked rather than `dlopen`ed**, which is the one place the
53//! native backends deliberately disagree: a Linux box can genuinely lack
54//! libwayland, and a Windows cannot lack `user32.dll`. There is no
55//! `windows-rs`.
56//!
57//! P5C also added the **AppKit backend**: the Objective-C runtime FFI, the
58//! `NSApplication` bootstrap, `NSWindow` and a layer-hosting `NSView` carrying
59//! the `CAMetalLayer` that *is* [`SurfaceTarget::AppKit`], the event pump and a
60//! blocking `wait_events`, windowed ↔ borderless on a named display, `NSScreen`
61//! enumeration with scale and refresh, size constraints and close-request
62//! interception — then keyboard, text through a real `NSTextInputClient`,
63//! pointer, both scroll units, relative motion, pointer lock, cursors and
64//! warping. The pasteboard and drag-and-drop are the slice after it, and
65//! [`ShellCaps`] is clear on every bit they would set. It is hand-written
66//! `objc_msgSend` FFI — **linked rather than `dlopen`ed**, for the same reason
67//! the Win32 backend gives — with no `objc2` and no framework.
68//!
69//! Four macOS facts are worth knowing at this level rather than at that one.
70//! **AppKit is main-thread-only and enforces it by raising an Objective-C
71//! exception**, which is the concrete reason [`Shell`] is not `Send` and is a
72//! stronger rule than Win32's thread affinity — there, any thread may own a
73//! window as long as it is the one pumping. **The Y axis points up**, and macOS
74//! is the only one of the five platforms whose coordinate system disagrees with
75//! this seam's about that. **`backingScaleFactor` is 1.0 or 2.0 and nothing
76//! between**, so [`ShellCaps::FRACTIONAL_SCALE`] is clear on the one desktop
77//! backend a reader would expect it to be set on. And **macOS cannot confine a
78//! pointer at all** — there is no `ClipCursor` and no `confine_to`, only warping
79//! it back after it has already left — so [`ShellCaps::POINTER_CONFINE`] is
80//! clear while [`ShellCaps::POINTER_LOCK`] is set, which is a split no other
81//! desktop backend has.
82//!
83//! Two Win32 facts the other backends do not have are worth knowing at this
84//! level rather than at that one. A window's contents freeze while the user
85//! drags its edge, because Windows runs a **modal message loop** of its own
86//! there and [`pump`](Shell::pump) does not return until the mouse is released.
87//! And a window belongs to the thread that created it, which is the concrete
88//! reason [`Shell`] is not `Send`.
89//!
90//! Two properties of the Wayland clipboard shaped the seam rather than being
91//! worked around in the backend, because they are properties of the *platform*:
92//! a client may only read the selection while one of its windows has keyboard
93//! focus, and may only *claim* it while holding a serial from real user input.
94//! So [`Shell::clipboard_readable`] says whether a read would answer now,
95//! [`Shell::clipboard_request`] **holds** a read it cannot yet answer instead of
96//! reporting an empty clipboard, [`ClipboardContent`] separates "empty" from
97//! "could not be read", and [`ShellError::NeedsUserInteraction`] names the
98//! refusal. [`HeadlessShell`] can simulate all three, so a consumer is tested
99//! against them with no compositor in the room.
100//!
101//! P0.6 checked that prediction against the other platform, and it held with
102//! one correction worth recording: X11 needs none of the *holding* (its
103//! `GetSelectionOwner` answers synchronously and there is no focus gate) and
104//! never returns [`ShellError::NeedsUserInteraction`] (there is no such rule),
105//! but it does **not** get "answered within a bounded time" for free. A stalled
106//! `INCR` transfer has no descriptor to poll and no protocol event for "the
107//! owner gave up", so the X11 backend carries its own deadline. The seam did
108//! not move; one backend obligation turned out to cost more than predicted, and
109//! that is written down where it is paid.
110//!
111//! `HeadlessShell` is not a stub standing in for the real thing: per the
112//! windowing rules in `docs/notes/backends.md` it is a first-class implementation that CI,
113//! `crcbl screenshot` and `crcbl sim` run the *identical* engine loop through.
114//! Where the real compositor turned out to differ from what it models, the
115//! difference is documented in the Wayland backend rather than smoothed over —
116//! the first configure carrying no size at all is the one to know about.
117//!
118//! # Decision: `dyn`-primary, like the HAL
119//!
120//! [`Shell`] is object-safe and [`open`] returns `Box<dyn Shell>`. This is
121//! forced rather than chosen: the windowing rules require Wayland and
122//! X11 to be compiled in together and selected *at runtime*, so the backend
123//! cannot be a type parameter. The consequences are the ones `crcbl-hal`
124//! documents — no generic methods, no `impl Trait` returns, no cross-crate
125//! inlining — and they cost less here: a frame makes a handful of shell calls,
126//! not one per draw. Generic use still works (`fn f<S: Shell + ?Sized>(s: &S)`)
127//! and monomorphises normally.
128//!
129//! The trait requires [`Debug`](core::fmt::Debug) and deliberately **not**
130//! `Send`/`Sync`. Shells are thread-affine and cannot promise otherwise: a
131//! Win32 `HWND` belongs to the thread pumping its message queue, and AppKit is
132//! main-thread-only. [`SurfaceTarget`] reached the same conclusion for the same
133//! reason. Create the shell on the thread that will pump it.
134//!
135//! # Decision: `pump` is a drain, never a loop
136//!
137//! ```text
138//! loop {                                  // native: the outer loop is yours
139//!     shell.pump(&mut |event| …);         // ← drain what arrived
140//!     clock.update(time.elapsed());
141//!     while clock.consume_tick() { tick(clock.tick_dt()); }
142//!     render(clock.alpha());
143//! }
144//! ```
145//!
146//! There is no `Shell::run(closure)` and there never will be, because
147//! the browser requires the engine loop to be "a `fn tick(dt)`
148//! driven by an outer loop, not a `loop {}` that owns the thread" — in a
149//! browser the outer loop is `requestAnimationFrame`, which *calls* the engine
150//! and cannot be called by it. A framework-shaped `run()` would compile on wasm
151//! and then deadlock on the first frame, which is the worst possible failure
152//! schedule. The rAF build is the same body with the `loop {` line deleted:
153//!
154//! ```text
155//! // wasm: the outer loop is the browser's
156//! extern "C" fn crcbl_frame(now_ms: f64) {   // called from rAF by the JS shim
157//!     shell.pump(&mut |event| …);
158//!     clock.update(Duration::from_secs_f64(now_ms / 1000.0));
159//!     while clock.consume_tick() { tick(clock.tick_dt()); }
160//!     render(clock.alpha());
161//! }
162//! ```
163//!
164//! [`Shell::wait_events`] exists for the editor, which idles at zero frames per
165//! second on battery. It is *advisory*: returning immediately is always a
166//! correct implementation, which is what makes it portable to a browser that
167//! cannot block at all.
168//!
169//! # Decision: where the input vocabulary lives
170//!
171//! The shell-boundary rule in `docs/notes/backends.md` puts input normalization in
172//! `crcbl-core::input`, and [`ShellEvent`] is naturally a `crcbl-shell` type.
173//! Both are true, and the split is:
174//!
175//! | Lives in | What | Why |
176//! | --- | --- | --- |
177//! | [`crcbl_core::input`] | [`KeyCode`], [`Keysym`], [`PointerButton`], [`Modifiers`], [`ScrollDelta`], [`DeviceId`] | the P2 action layer, the profile store, the ECS and the UI all need to *name* a key; none of them should link a windowing library to spell `Space` |
178//! | `crcbl-shell` | [`ShellEvent`] | it names [`WindowId`], and only a shell backend ever produces one |
179//!
180//! Dependency direction: `crcbl-shell → crcbl-core`, never the reverse, and
181//! `crcbl-input` (P2) will depend on `crcbl-core` for vocabulary plus
182//! `crcbl-shell` for the event stream. The vocabulary types are re-exported
183//! here so an event consumer needs one `use`, not two.
184//!
185//! # Decision: raw events only
186//!
187//! This crate produces *normalized raw* events. Actions, bindings, contexts and
188//! patterns are `crcbl-input`'s action layer. What
189//! this slice owes that layer is the information it cannot reconstruct later —
190//! per-device ids, and timestamps that are the window system's rather than the
191//! frame's. Both are on every input event; see [`event`].
192//!
193//! # Decision: a window has no size until the window system says so
194//!
195//! [`Shell::create_window`] returns a [`WindowId`] and *nothing else*.
196//! [`WindowState::size`] is `None` until the first
197//! [`ShellEvent::Resized`] arrives, and a swapchain — which needs an extent —
198//! cannot be created before then.
199//!
200//! This is the shape Wayland forces: an `xdg_surface` is unsized and may not be
201//! given a buffer until the compositor answers with a `configure`, a round trip
202//! away. Modelling it in the type rather than in prose is the difference
203//! between every consumer written before P0.5 being correct and all of them
204//! breaking on the same day. [`HeadlessShell`] deliberately defers the first
205//! configure by at least one [`pump`](Shell::pump) — same reasoning as
206//! `crcbl-hal`'s injected readback latency — so the create-then-wait loop is
207//! *exercised* in CI rather than merely documented.
208//!
209//! The same distinction runs through [`WindowState`]: what was **requested**
210//! ([`requested_mode`](WindowState::requested_mode),
211//! [`requested_constraints`](WindowState::requested_constraints)) is always
212//! known because we said it, while what is **effective**
213//! ([`WindowConfiguration`]) only exists once the window system has answered
214//! and may disagree forever. A compositor can refuse a fullscreen request; a
215//! tiling window manager ignores every size hint there is.
216//!
217//! # Stability
218//!
219//! Provisional, like the HAL seam, and with a specific reason to be: it has no
220//! real backend behind it yet. The places most likely to move are stated rather
221//! than glossed — [`HeadlessShell`]'s event ordering is a *model* of a
222//! compositor's, not a recording of one, and its configure delay is a fixed
223//! number of pumps where a compositor's is a round trip.
224//!
225//! # Example
226//!
227//! A complete, deterministic window session with no window system anywhere:
228//!
229//! ```
230//! use crcbl_shell::{CloseReply, HeadlessShell, PhysicalSize, Shell, WindowDesc};
231//!
232//! let mut shell = HeadlessShell::new();
233//! let window = shell.create_window(&WindowDesc {
234//!     title: "sandbox",
235//!     ..WindowDesc::default()
236//! })?;
237//!
238//! // The window has no size yet, so there is no swapchain to create.
239//! assert_eq!(shell.window_state(window)?.size(), None);
240//!
241//! // Wait for the window system to configure it. This loop is mandatory, not
242//! // defensive: on Wayland the answer is a round trip away.
243//! let size = loop {
244//!     shell.pump(&mut |_event| {});
245//!     if let Some(size) = shell.window_state(window)?.size() {
246//!         break size;
247//!     }
248//! };
249//! assert_eq!(size, PhysicalSize::new(1280, 720));
250//!
251//! // Script what a compositor would do next.
252//! shell.resize(window, PhysicalSize::new(1920, 1080))?;
253//! shell.request_close(window)?;
254//!
255//! let mut names = Vec::new();
256//! shell.pump(&mut |event| names.push(event.name()));
257//! assert_eq!(names, ["Resized", "CloseRequested"]);
258//!
259//! // The close request is a question, not a notification.
260//! shell.reply_close_request(window, CloseReply::Keep)?;
261//! assert!(shell.window_state(window).is_ok(), "still open");
262//! # Ok::<(), crcbl_shell::ShellError>(())
263//! ```
264
265pub mod backend;
266pub mod caps;
267pub mod clipboard;
268pub mod cursor;
269pub mod error;
270pub mod event;
271pub mod geom;
272pub mod headless;
273pub mod monitor;
274pub mod role;
275pub mod waker;
276pub mod window;
277
278#[cfg(any(target_os = "macos", target_os = "windows", test))]
279pub(crate) mod keysym;
280
281#[cfg(desktop_unix)]
282pub(crate) mod linux;
283
284#[cfg(desktop_unix)]
285pub(crate) mod wayland;
286
287#[cfg(desktop_unix)]
288pub(crate) mod x11;
289
290#[cfg(any(target_os = "windows", test))]
291pub(crate) mod win32;
292
293#[cfg(any(target_os = "macos", test))]
294pub(crate) mod appkit;
295
296#[cfg(any(target_arch = "wasm32", test))]
297pub(crate) mod web;
298
299/// Scaffolding for the nested-compositor end-to-end suite, behind the
300/// `wayland-e2e` feature.
301///
302/// Not part of the seam and not for consumers: it exists because a Wayland
303/// surface is only managed by the compositor once it has a *buffer*, and
304/// attaching one is the renderer's job — which does not exist until P1. See
305/// the module's docs for the full finding.
306#[cfg(all(desktop_unix, feature = "wayland-e2e"))]
307pub use wayland::e2e as wayland_test_support;
308
309/// Scaffolding for the Xvfb end-to-end suite, behind the `x11-e2e` feature.
310///
311/// Not part of the seam and not for consumers. Where the Wayland version exists
312/// because a surface needs a buffer, this one exists because on X11 the window
313/// manager, the input devices and the clipboard owner are all *other programs* —
314/// see the module's docs.
315#[cfg(all(desktop_unix, feature = "x11-e2e"))]
316pub use x11::e2e as x11_test_support;
317
318#[cfg(target_os = "macos")]
319pub use appkit::session_support;
320
321/// The accessibility vocabulary [`Shell::update_accessibility`] and the
322/// `Accessibility*` events speak, re-exported so a caller builds its tree with
323/// the version the shell was built against. Behind the `accesskit` feature.
324#[cfg(feature = "accesskit")]
325pub use accesskit;
326
327pub use backend::{BACKEND_ENV_VAR, ShellBackend, open, open_backend};
328pub use caps::ShellCaps;
329pub use clipboard::{
330    ClipboardContent, ClipboardOffer, ClipboardRequestId, MimeType, ReceivedMime, parse_uri_list,
331};
332pub use cursor::{CursorIcon, PointerMode};
333pub use error::ShellError;
334pub use event::ShellEvent;
335pub use geom::{
336    AspectRatio, LogicalPoint, LogicalRect, LogicalSize, PhysicalPoint, PhysicalRect, PhysicalSize,
337};
338pub use headless::HeadlessShell;
339pub use monitor::{MonitorId, MonitorInfo};
340pub use role::{
341    Margins, PanelAnchor, PanelDesc, PanelKeyboard, PanelLayer, PopupDesc, PopupInput,
342    PopupPlacement, Reserve, WindowRole,
343};
344pub use waker::ShellWaker;
345pub use window::{
346    CloseReply, DisplayMode, SizeConstraints, Window, WindowConfiguration, WindowDesc, WindowId,
347    WindowState,
348};
349
350/// Cross-seam vocabulary from `crcbl-core`: the input-event clock, the key
351/// names, and the one sanctioned platform leak.
352pub use crcbl_core::input::TextPurpose;
353/// Input vocabulary, defined in [`crcbl_core::input`] and re-exported so a
354/// consumer of the event stream needs one `use` rather than two.
355///
356/// See the [crate docs](self) for why these live in `crcbl-core`.
357pub use crcbl_core::input::{
358    ButtonState, ContactId, DeviceId, Keysym, Modifiers, PointerButton, Scancode, ScrollDelta,
359    TouchPhase,
360};
361pub use crcbl_core::{EventTime, KeyCode, SurfaceTarget};
362
363use core::time::Duration;
364
365/// The window system, as the engine sees it.
366///
367/// Object-safe by requirement; see the [crate docs](self) for why, and
368/// [`backend`] for how an implementation is selected at runtime.
369///
370/// # The loop is the caller's
371///
372/// There is no `run` that takes the program over: the caller loops on
373/// [`pump`](Self::pump) and [`wait_events`](Self::wait_events) itself, so
374/// ending the program is leaving that loop and dropping the shell. Each
375/// desktop backend's `Drop` destroys the windows it still holds, so nothing has
376/// to be torn down by hand first. Work that arrives
377/// on another thread reaches a sleeping loop through a [`ShellWaker`].
378///
379/// # Implementing this
380///
381/// Six obligations that are not visible in the signatures. The first three are
382/// P0.4's; the last three are P0.5c's, written down because a real compositor
383/// showed that leaving them unstated pushes the work onto every consumer.
384///
385/// 1. **Stale handles fail cleanly.** Every method taking a [`WindowId`] must
386///    return [`ShellError::InvalidWindow`] for a destroyed or foreign one, never
387///    act on whatever window took the slot.
388/// 2. **Timestamps are rebased.** Input events carry the window system's
389///    timestamp converted to the engine epoch — see [`EventTime`], which
390///    documents the conversion each platform needs.
391/// 3. **Capabilities are latched.** [`caps`](Self::caps) must return the same
392///    value for the shell's lifetime, so a consumer that branched on it at
393///    startup is never contradicted mid-session. See [`caps`] for the
394///    Wayland-binds-a-global-late edge this rules out.
395/// 4. **Every accepted clipboard read is answered exactly once, and within a
396///    bounded time.** [`clipboard_request`](Self::clipboard_request) that
397///    returns `Ok` promises exactly one
398///    [`ShellEvent::ClipboardData`] carrying that
399///    [`ClipboardRequestId`]. A backend that cannot complete the read answers
400///    [`ClipboardContent::Unavailable`] rather than dropping the request; a
401///    request with no answer is a UI stuck on "pasting…" forever, which no
402///    consumer can detect.
403/// 5. **A read that cannot be answered *yet* is held, never answered "empty".**
404///    If the backend does not yet know what is on the clipboard — Wayland's
405///    focus-gated, asynchronous `wl_data_device.selection` is the case this
406///    exists for — it holds the request until it does, and bounds that wait.
407///    Reporting [`Empty`](ClipboardContent::Empty) for "I have not looked yet"
408///    is indistinguishable from an empty clipboard, so it makes every consumer
409///    write a retry loop with a timeout it cannot choose correctly. Where the
410///    answer is always immediately available (X11 asks the server who owns the
411///    selection; a headless shell owns it), holding costs nothing and this
412///    obligation is discharged by answering.
413/// 6. **A refusal for want of user interaction is named.** Where the window
414///    system requires a recent input event to claim the clipboard — Wayland
415///    does, the browser does, X11 and Win32 do not —
416///    [`clipboard_offer`](Self::clipboard_offer) returns
417///    [`ShellError::NeedsUserInteraction`] and not a generic backend error, so
418///    a caller can distinguish "ask the user to press the key again" from "this
419///    is broken". A backend on a platform without the rule never returns it.
420pub trait Shell: core::fmt::Debug {
421    /// Which implementation this is. Logs and bug reports only — behaviour
422    /// branches on [`caps`](Self::caps).
423    fn backend(&self) -> ShellBackend;
424
425    /// What this backend can do. Fixed for the shell's lifetime.
426    fn caps(&self) -> ShellCaps;
427
428    /// Creates a window. **The window has no size yet.**
429    ///
430    /// `desc.size` is a request. The authoritative size arrives later, as the
431    /// first [`ShellEvent::Resized`], and until it does
432    /// [`WindowState::size`] is `None`. This is not a headless quirk: a Wayland
433    /// `xdg_surface` is unsized and may not be given a buffer until the
434    /// compositor answers with a `configure`, which is a round trip away.
435    ///
436    /// A swapchain needs an extent, so this is a hard ordering constraint:
437    ///
438    /// ```
439    /// # use crcbl_shell::{HeadlessShell, PhysicalSize, Shell, WindowDesc};
440    /// # let mut shell = HeadlessShell::new();
441    /// let window = shell.create_window(&WindowDesc::default())?;
442    /// let size: PhysicalSize = loop {
443    ///     shell.pump(&mut |_event| { /* … */ });
444    ///     if let Some(size) = shell.window_state(window)?.size() {
445    ///         break size;
446    ///     }
447    /// };
448    /// // Only now is there an extent to create a swapchain at.
449    /// assert_eq!(size, PhysicalSize::new(1280, 720));
450    /// # Ok::<(), crcbl_shell::ShellError>(())
451    /// ```
452    ///
453    /// [`HeadlessShell`] deliberately defers the first configure by at least one
454    /// `pump`, so a consumer that skips the loop fails in CI rather than at
455    /// P0.5.
456    ///
457    /// # Errors
458    ///
459    /// [`ShellError::WindowCreation`] if the window system refused, or
460    /// [`ShellError::Unsupported`] if this would be a second window on a
461    /// backend without [`ShellCaps::MULTI_WINDOW`].
462    fn create_window(&mut self, desc: &WindowDesc<'_>) -> Result<WindowId, ShellError>;
463
464    /// Destroys a window. A [`ShellEvent::WindowDestroyed`] follows.
465    ///
466    /// The [`SurfaceTarget`] previously returned for this window is dead
467    /// afterwards; the HAL surface built from it must be destroyed **first**.
468    ///
469    /// # Errors
470    ///
471    /// [`ShellError::InvalidWindow`] if the handle is stale.
472    fn destroy_window(&mut self, window: WindowId) -> Result<(), ShellError>;
473
474    /// A snapshot of the window's current state.
475    ///
476    /// For consumers that started late; not a substitute for handling events.
477    /// Note that [`WindowState::size`] is `None` until the window system has
478    /// configured the window, and that the *requested* mode and the *effective*
479    /// one are separate fields — see [`WindowState`].
480    ///
481    /// # Errors
482    ///
483    /// [`ShellError::InvalidWindow`] if the handle is stale.
484    fn window_state(&self, window: WindowId) -> Result<WindowState, ShellError>;
485
486    /// Sets the title bar text.
487    ///
488    /// # Errors
489    ///
490    /// [`ShellError::InvalidWindow`] if the handle is stale.
491    fn set_title(&mut self, window: WindowId, title: &str) -> Result<(), ShellError>;
492
493    /// Maps or unmaps the window.
494    ///
495    /// # Errors
496    ///
497    /// [`ShellError::InvalidWindow`] if the handle is stale.
498    fn set_visible(&mut self, window: WindowId, visible: bool) -> Result<(), ShellError>;
499
500    /// Asks for windowed or borderless.
501    ///
502    /// **A request, not a command.** It updates
503    /// [`WindowState::requested_mode`] immediately and nothing else; the mode
504    /// that is actually in effect appears in
505    /// [`WindowConfiguration::mode`] when the window system answers, which it
506    /// may do with something other than what was asked (a compositor can refuse
507    /// fullscreen, and a tiling window manager makes the question moot). Use
508    /// [`WindowState::mode_request_honoured`] rather than reading the request
509    /// back as fact.
510    ///
511    /// The answer usually arrives as a [`ShellEvent::Resized`], preceded by a
512    /// [`ShellEvent::ScaleFactorChanged`] when the target monitor has a
513    /// different scale. Never assume the new size — read the event.
514    ///
515    /// # Errors
516    ///
517    /// [`ShellError::InvalidWindow`] if the handle is stale, or
518    /// [`ShellError::NoSuchMonitor`] if the named monitor is gone.
519    fn set_mode(&mut self, window: WindowId, mode: DisplayMode) -> Result<(), ShellError>;
520
521    /// Asks for resize limits and an aspect lock.
522    ///
523    /// Hints, not guarantees, and a request rather than a command: it updates
524    /// [`WindowState::requested_constraints`] immediately, and the only
525    /// observable effect is whatever size the window system reports next. No
526    /// platform reports back "effective constraints", so neither does this
527    /// seam. See [`SizeConstraints`].
528    ///
529    /// # Errors
530    ///
531    /// [`ShellError::InvalidWindow`] if the handle is stale.
532    fn set_constraints(
533        &mut self,
534        window: WindowId,
535        constraints: SizeConstraints,
536    ) -> Result<(), ShellError>;
537
538    /// Moves a live popup against a new `anchor` in its parent and gives it
539    /// `size`, placed by the [`PopupPlacement`] it was created with: flipped
540    /// or slid to stay on screen, as when it opened.
541    ///
542    /// For a popup whose anchor moved — a bar's clock grew and its calendar
543    /// should follow — or whose content changed size. A request, like the
544    /// rest of a window's geometry: the new size arrives as the next
545    /// [`ShellEvent::Resized`], once the window system has placed it.
546    ///
547    /// Requires [`ShellCaps::POPUP_REPOSITION`]. Without it, close the popup
548    /// and open another.
549    ///
550    /// # Errors
551    ///
552    /// [`ShellError::Unsupported`] without the capability,
553    /// [`ShellError::InvalidWindow`] for a stale handle, and
554    /// [`ShellError::InvalidDescriptor`] for a window that is not a popup.
555    fn reposition_popup(
556        &mut self,
557        popup: WindowId,
558        anchor: LogicalRect,
559        size: LogicalSize,
560    ) -> Result<(), ShellError> {
561        let _ = (popup, anchor, size);
562        Err(ShellError::Unsupported {
563            backend: self.backend(),
564            what: "repositioning a popup",
565        })
566    }
567
568    /// Every connected monitor.
569    ///
570    /// Invalidated by [`ShellEvent::MonitorsChanged`]; call again rather than
571    /// caching across it.
572    fn monitors(&self) -> &[MonitorInfo];
573
574    /// One monitor by id, or `None` if it is not connected.
575    ///
576    /// A provided method rather than a required one: it is a lookup over
577    /// [`monitors`](Self::monitors), and every backend would write the same
578    /// three lines.
579    fn monitor(&self, id: MonitorId) -> Option<&MonitorInfo> {
580        self.monitors().iter().find(|monitor| monitor.id == id)
581    }
582
583    /// Drains everything that has arrived from the window system into `sink`.
584    ///
585    /// Non-blocking and finite: it delivers what is queued and returns. Call it
586    /// once at the top of every frame. See the [crate docs](self) for why there
587    /// is no `run()` and how a `requestAnimationFrame`-driven build uses this.
588    ///
589    /// The sink is `&mut dyn FnMut` rather than a generic parameter because the
590    /// trait must stay object-safe. That is not purely a cost: a closure passed
591    /// here can borrow the caller's state mutably, which an
592    /// `Iterator`-returning shape could not while the shell is also borrowed.
593    fn pump(&mut self, sink: &mut dyn FnMut(ShellEvent));
594
595    /// Lets the window system run, and delivers nothing.
596    ///
597    /// Everything [`pump`](Self::pump) does except hand events to a sink: the
598    /// platform's queue is drained, whatever it asks of the client is answered,
599    /// and what it produced is **kept** in this shell's queue, in order, for the
600    /// next `pump`. Every backend implements `pump` as this followed by the
601    /// delivery, so the two cannot drift apart.
602    ///
603    /// # What it is for: a long load on the thread that owns the window
604    ///
605    /// Desktops mark a client that stops draining its queue as hung. Windows
606    /// ghosts a window whose thread has not asked for a message for about five
607    /// seconds — `IsHungAppWindow`, a greyed "Not Responding" title, clicks
608    /// held — a Wayland compositor pings through `xdg_wm_base` and offers to
609    /// kill a client that does not answer (GNOME's "not responding" dialog),
610    /// and macOS puts the spinning cursor over an application whose main thread
611    /// has stopped taking events. A game that loads its assets between opening
612    /// its window and its first frame calls this every so often — a few times a
613    /// second is plenty — and stays responsive to all three.
614    ///
615    /// **Nothing is dropped**, which is why this is not `pump` with an empty
616    /// sink: a key pressed, a resize or a close request made during the load is
617    /// delivered by the first frame's `pump`, exactly as if the load had been
618    /// one long frame. So a close request stays unanswered until then — the
619    /// window stays open and the load finishes first — and a loader that must
620    /// stop for one has to pump and handle events itself.
621    ///
622    /// Work that can leave the loop thread should, instead: a loop that keeps
623    /// running frames keeps pumping on its own, and can show progress while it
624    /// does. This is for the load that cannot — work on the device the loop
625    /// owns, or on anything else tied to this thread.
626    ///
627    /// Non-blocking and finite, like `pump`, and with the same exception: on
628    /// Win32 and AppKit it does not return while the user is dragging the
629    /// window's border.
630    fn keep_alive(&mut self);
631
632    /// Blocks until an event arrives or `timeout` elapses.
633    ///
634    /// **Advisory.** Returning immediately is always correct, and backends
635    /// without [`ShellCaps::EVENT_WAIT`] — a browser above all — do exactly
636    /// that. A caller must treat this as "sleep if you can" and must not assume
637    /// an event is pending afterwards; [`pump`](Self::pump) is still what
638    /// delivers them.
639    ///
640    /// `timeout` of `None` means "until something happens", which on a backend
641    /// without the capability still means "immediately".
642    fn wait_events(&mut self, timeout: Option<Duration>) {
643        let _ = timeout;
644    }
645
646    /// A handle that wakes [`wait_events`](Self::wait_events) from another
647    /// thread — see [`ShellWaker`].
648    ///
649    /// Every call hands out a handle to the same doorbell, so a program can ask
650    /// once and clone, or ask wherever it needs one. `None` from a backend
651    /// whose wait never blocks, which is the browser: there, nothing sleeps and
652    /// there is nothing to wake.
653    fn waker(&mut self) -> Option<ShellWaker> {
654        None
655    }
656
657    /// Puts input timestamps on the engine's clock.
658    ///
659    /// Call this **once, at startup**, with the reading of the
660    /// [`TimeSource`](crcbl_core::time::TimeSource) that will drive
661    /// [`FrameClock::update`](crcbl_core::FrameClock::update).
662    ///
663    /// [`EventTime`]'s epoch is defined as "the same origin as" that source,
664    /// and no backend can know it: a shell is created some time *after* the
665    /// clock starts, and the window system's own clock has a third origin
666    /// again. Without this call, timestamps are measured from the shell's own
667    /// creation — internally consistent, so durations between two input events
668    /// are already correct, but offset from a
669    /// [`FrameClock`](crcbl_core::FrameClock) reading by however long startup
670    /// took. That offset is exactly what `docs/plan/26-prediction.md`'s input-to-photon
671    /// latency measurement is a subtraction across.
672    ///
673    /// A provided method with a no-op default, because it is only meaningful
674    /// for a backend whose event clock is not already the engine's — the
675    /// browser's `event.timeStamp` needs nothing done to it. The obligation it
676    /// discharges is the "Timestamps are rebased" one in this trait's
677    /// [implementor notes](Self), which previously had no way to be satisfied
678    /// from outside the crate.
679    ///
680    /// ```
681    /// # use core::time::Duration;
682    /// # use crcbl_shell::{HeadlessShell, Shell};
683    /// let mut shell = HeadlessShell::new();
684    /// // The engine clock has been running for 40 ms by the time the window
685    /// // system is up; input stamped "now" should read as 40 ms, not as zero.
686    /// shell.align_event_clock(Duration::from_millis(40));
687    /// ```
688    fn align_event_clock(&mut self, elapsed: Duration) {
689        let _ = elapsed;
690    }
691
692    /// The native handles a HAL backend needs to create a surface for this
693    /// window.
694    ///
695    /// Opaque to everyone except a HAL backend. Re-query it after a
696    /// [`set_mode`](Self::set_mode): some backends recreate the underlying
697    /// surface on a mode switch, and a cached target then names a dead object.
698    /// **A resize is not such an event** — see below.
699    ///
700    /// # Available before the window is configured, and unchanged by a resize
701    ///
702    /// The *handle* exists as soon as the window does — a `wl_surface` is
703    /// created up front and only its size is pending — so this succeeds
704    /// immediately and a HAL surface can be created from it right away. Only
705    /// the **swapchain** has to wait, because only the swapchain needs an
706    /// extent.
707    ///
708    /// **No variant carries a size**, so the value this returns does not change
709    /// when the window is resized, and a HAL surface created before the first
710    /// configure stays correct forever. That is what makes "re-query after a
711    /// mode change" a complete rule. [`SurfaceTarget::Offscreen`] used to carry
712    /// `width`/`height` and was the one exception; P0.7 removed it, because an
713    /// exception in this rule means a surface silently describing a size the
714    /// window no longer has. The extent reaches a backend through
715    /// [`WindowState::size`] and the swapchain descriptor, and only there —
716    /// `crcbl-hal`'s `swapchain` module states that precedence as a backend
717    /// obligation.
718    ///
719    /// # Errors
720    ///
721    /// [`ShellError::InvalidWindow`] if the handle is stale.
722    fn surface_target(&self, window: WindowId) -> Result<SurfaceTarget, ShellError>;
723
724    /// Frees, confines or locks the pointer.
725    ///
726    /// # Errors
727    ///
728    /// [`ShellError::Unsupported`] if [`caps`](Self::caps) lacks
729    /// [`PointerMode::required_cap`], or [`ShellError::InvalidWindow`] for a
730    /// stale handle.
731    fn set_pointer_mode(&mut self, window: WindowId, mode: PointerMode) -> Result<(), ShellError>;
732
733    /// Sets the cursor shape, or hides the cursor with `None`.
734    ///
735    /// Visibility and capture are separate axes; see [`cursor`].
736    ///
737    /// # Errors
738    ///
739    /// [`ShellError::InvalidWindow`] if the handle is stale.
740    fn set_cursor(
741        &mut self,
742        window: WindowId,
743        cursor: Option<CursorIcon>,
744    ) -> Result<(), ShellError>;
745
746    /// Moves the pointer to a position in the window.
747    ///
748    /// Requires [`ShellCaps::POINTER_WARP`], which **Wayland does not have and
749    /// will not get**. Anything reaching for this to implement a camera should
750    /// use [`PointerMode::Locked`] instead; warping is for a UI that needs to
751    /// reposition a cursor (a slider snapping to a value), not for input.
752    ///
753    /// # Errors
754    ///
755    /// [`ShellError::Unsupported`] without the capability, or
756    /// [`ShellError::InvalidWindow`] for a stale handle.
757    fn warp_pointer(&mut self, window: WindowId, position: PhysicalPoint)
758    -> Result<(), ShellError>;
759
760    /// Answers a [`ShellEvent::CloseRequested`].
761    ///
762    /// Until this is called the window stays open and the request stays
763    /// outstanding. See [`CloseReply`].
764    ///
765    /// # Errors
766    ///
767    /// [`ShellError::NoPendingCloseRequest`] if nothing was asked, or
768    /// [`ShellError::InvalidWindow`] for a stale handle.
769    fn reply_close_request(
770        &mut self,
771        window: WindowId,
772        reply: CloseReply,
773    ) -> Result<(), ShellError>;
774
775    /// Publishes clipboard content in one or more formats.
776    ///
777    /// Synchronous: every platform's write is "claim the selection", and the
778    /// bytes transfer later, on demand. Offer both [`MimeType::TextUtf8`] and
779    /// [`MimeType::CrcblRon`] for engine data; see [`clipboard`].
780    ///
781    /// An empty `offers` slice releases the clipboard, where the platform can
782    /// express that.
783    ///
784    /// # Errors
785    ///
786    /// [`ShellError::Unsupported`] without [`ShellCaps::CLIPBOARD`],
787    /// [`ShellError::InvalidWindow`] for a stale handle, or
788    /// [`ShellError::NeedsUserInteraction`] where the window system requires a
789    /// recent input event to claim the clipboard and there has not been one —
790    /// implementor obligation 6 above, and **not** a failure a caller should
791    /// retry blindly.
792    fn clipboard_offer(
793        &mut self,
794        window: WindowId,
795        offers: &[ClipboardOffer<'_>],
796    ) -> Result<(), ShellError>;
797
798    /// Asks for the clipboard's content in `mime`.
799    ///
800    /// Asynchronous by necessity — the answer arrives as
801    /// [`ShellEvent::ClipboardData`] carrying the returned id, and **exactly one
802    /// answer arrives for every `Ok` return** (implementor obligations 4 and 5).
803    /// [`clipboard`] has the full argument; briefly, X11 `INCR` transfers,
804    /// Wayland file descriptors and the browser's Promise make the synchronous
805    /// shape unimplementable on three of five backends.
806    ///
807    /// The answer may be several frames away, and on a backend whose clipboard
808    /// is not readable at the moment of asking it is *held* until it is, rather
809    /// than being answered [`Empty`](ClipboardContent::Empty). A caller
810    /// therefore never needs to poll or retry: ask once, handle the event.
811    /// [`clipboard_readable`](Self::clipboard_readable) is the way to find out
812    /// in advance that the answer will not be immediate.
813    ///
814    /// # Errors
815    ///
816    /// [`ShellError::Unsupported`] without [`ShellCaps::CLIPBOARD`], or
817    /// [`ShellError::InvalidWindow`] for a stale handle. An empty clipboard is
818    /// **not** an error — it is an answer.
819    fn clipboard_request(
820        &mut self,
821        window: WindowId,
822        mime: MimeType,
823    ) -> Result<ClipboardRequestId, ShellError>;
824
825    /// Whether a [`clipboard_request`](Self::clipboard_request) issued for
826    /// `window` right now could be answered without waiting.
827    ///
828    /// What a "Paste" menu item greys out on, and the visible form of a
829    /// platform rule that is otherwise invisible: **on Wayland a client is told
830    /// what is on the clipboard only while one of its windows has keyboard
831    /// focus**, and only asynchronously, so a background window genuinely
832    /// cannot read the clipboard. `clipboard_request` still works there — it
833    /// holds the request — but it may take until focus arrives, and a UI that
834    /// would rather not offer the action than offer a slow one asks here first.
835    ///
836    /// `false` for a stale handle, and for a backend without
837    /// [`ShellCaps::CLIPBOARD`].
838    ///
839    /// # A provided method, because most platforms have nothing to say
840    ///
841    /// The default is "readable whenever the capability is present and the
842    /// handle is live", which is exactly right for X11 (any window may
843    /// `ConvertSelection` at any time, focus is not involved), for Win32, and
844    /// for [`HeadlessShell`] in its default configuration. Only a backend that
845    /// really has a gate overrides it — so this is a fact a consumer can rely
846    /// on, not ceremony every backend has to perform.
847    ///
848    /// The staleness half goes through
849    /// [`window_state`](Self::window_state) rather than being left to each
850    /// implementation. P0.6 found the earlier default — which ignored `window`
851    /// entirely — contradicting the "`false` for a stale handle" sentence
852    /// above: both backends that existed had *overridden* it and so had
853    /// covered for it, and the first backend to accept the default inherited
854    /// the bug. A default that cannot keep its own promise is worse than no
855    /// default.
856    fn clipboard_readable(&self, window: WindowId) -> bool {
857        self.caps().contains(ShellCaps::CLIPBOARD) && self.window_state(window).is_ok()
858    }
859
860    /// Tells the input method where text is being entered, so it can put its
861    /// composition window and candidate list there instead of at a corner of the
862    /// screen.
863    ///
864    /// `area` is the text field's caret, or the line it sits on, in the
865    /// window's **client** device pixels; the candidate list opens beside it
866    /// without covering it. `None` hands placement back to the input method's
867    /// default. Call it when a field gains focus and whenever its caret moves.
868    /// A hint: the input method may place its windows elsewhere, and nothing
869    /// reports where they went.
870    ///
871    /// # A provided method, and a no-op where there is nothing to place
872    ///
873    /// Only a backend with an input method that draws its own windows has
874    /// anything to do here — Win32's IMM and TSF, a Wayland compositor's
875    /// `text-input-v3` cursor rectangle, AppKit's `firstRectForCharacterRange:`.
876    /// The default validates the handle and does nothing else, which is exactly
877    /// right for the rest. Win32 and Wayland override it; AppKit takes the
878    /// default and leaves its input method to place itself. Wayland sends the
879    /// area only while [`set_text_input`](Self::set_text_input) names a field,
880    /// since `text-input-v3` has nowhere to put it otherwise.
881    ///
882    /// # Errors
883    ///
884    /// [`ShellError::InvalidWindow`] if the handle is stale.
885    fn set_text_input_area(
886        &mut self,
887        window: WindowId,
888        area: Option<PhysicalRect>,
889    ) -> Result<(), ShellError> {
890        let _ = area;
891        self.window_state(window).map(|_| ())
892    }
893
894    /// Tells the input method what text field in `window` is taking typing:
895    /// `Some(purpose)` as a field gains the keyboard focus, `None` as it loses
896    /// it.
897    ///
898    /// While a field is taking typing, a platform input method composes what
899    /// is typed in the window, reporting the composition as
900    /// [`TextPreedit`](ShellEvent::TextPreedit) and the result as
901    /// [`TextCommit`](ShellEvent::TextCommit). While none is, the input method
902    /// keeps out of the way and keys reach the window as keys: one in its
903    /// native mode would otherwise turn a game's WASD into a candidate list. A
904    /// window starts with none.
905    ///
906    /// The [`TextPurpose`] says what the field is for. A password or a PIN is
907    /// [sensitive](TextPurpose::is_sensitive): nothing typed into it may be
908    /// learned, stored or suggested back.
909    ///
910    /// # A provided method
911    ///
912    /// The default validates the handle and does nothing else. Wayland acts on
913    /// it with `text-input-v3`'s `enable`, `set_content_type` and `disable`;
914    /// Win32 associates the window's input context only for a
915    /// [`Normal`](TextPurpose::Normal) field, keeping it off for a password or
916    /// a PIN as a Windows password box does. AppKit takes the default, and its
917    /// input methods compose in every window whatever this says.
918    ///
919    /// # Errors
920    ///
921    /// [`ShellError::InvalidWindow`] if the handle is stale.
922    fn set_text_input(
923        &mut self,
924        window: WindowId,
925        field: Option<TextPurpose>,
926    ) -> Result<(), ShellError> {
927        let _ = field;
928        self.window_state(window).map(|_| ())
929    }
930
931    /// Hands `window`'s accessibility tree, or what changed in it, to the
932    /// platform's assistive technologies.
933    ///
934    /// Send a whole tree (with [`TreeUpdate::tree`](accesskit::TreeUpdate::tree)
935    /// set) after each
936    /// [`AccessibilityActivated`](ShellEvent::AccessibilityActivated), then
937    /// only what changed, each frame something did. An update sent while
938    /// nobody is reading — before the activation, or after
939    /// [`AccessibilityDeactivated`](ShellEvent::AccessibilityDeactivated) — is
940    /// dropped, so a program may also send unconditionally and skip tracking
941    /// the two events.
942    ///
943    /// # A provided method
944    ///
945    /// The default validates the handle and drops the update, which is right
946    /// for a backend with no adapter: it never raises the activation either.
947    /// [`ShellCaps::ACCESSIBILITY`] says whether the trees go anywhere.
948    ///
949    /// # Errors
950    ///
951    /// [`ShellError::InvalidWindow`] if the handle is stale.
952    #[cfg(feature = "accesskit")]
953    fn update_accessibility(
954        &mut self,
955        window: WindowId,
956        update: accesskit::TreeUpdate,
957    ) -> Result<(), ShellError> {
958        let _ = update;
959        self.window_state(window).map(|_| ())
960    }
961}