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
278pub(crate) mod frame;
279pub(crate) mod keysym;
280
281#[cfg(any(target_os = "macos", target_os = "windows", test))]
282pub(crate) mod preedit;
283
284#[cfg(desktop_unix)]
285pub(crate) mod linux;
286
287#[cfg(desktop_unix)]
288pub(crate) mod wayland;
289
290#[cfg(desktop_unix)]
291pub(crate) mod x11;
292
293#[cfg(any(target_os = "windows", test))]
294pub(crate) mod win32;
295
296#[cfg(any(target_os = "macos", test))]
297pub(crate) mod appkit;
298
299#[cfg(any(target_arch = "wasm32", test))]
300pub(crate) mod web;
301
302/// Scaffolding for the nested-compositor end-to-end suite, behind the
303/// `wayland-e2e` feature.
304///
305/// Not part of the seam and not for consumers: it exists because a Wayland
306/// surface is only managed by the compositor once it has a *buffer*, and
307/// attaching one is the renderer's job — which does not exist until P1. See
308/// the module's docs for the full finding.
309#[cfg(all(desktop_unix, feature = "wayland-e2e"))]
310pub use wayland::e2e as wayland_test_support;
311
312/// Scaffolding for the Xvfb end-to-end suite, behind the `x11-e2e` feature.
313///
314/// Not part of the seam and not for consumers. Where the Wayland version exists
315/// because a surface needs a buffer, this one exists because on X11 the window
316/// manager, the input devices and the clipboard owner are all *other programs* —
317/// see the module's docs.
318#[cfg(all(desktop_unix, feature = "x11-e2e"))]
319pub use x11::e2e as x11_test_support;
320
321#[cfg(target_os = "macos")]
322pub use appkit::session_support;
323
324/// The accessibility vocabulary [`Shell::update_accessibility`] and the
325/// `Accessibility*` events speak, re-exported so a caller builds its tree with
326/// the version the shell was built against. Behind the `accesskit` feature.
327#[cfg(feature = "accesskit")]
328pub use accesskit;
329
330pub use backend::{BACKEND_ENV_VAR, ShellBackend, open, open_backend};
331pub use caps::ShellCaps;
332pub use clipboard::{
333    ClipboardContent, ClipboardOffer, ClipboardRequestId, MimeType, ReceivedMime, parse_uri_list,
334};
335pub use cursor::{CursorIcon, PointerMode};
336pub use error::ShellError;
337pub use event::ShellEvent;
338pub use geom::{
339    AspectRatio, LogicalPoint, LogicalRect, LogicalSize, PhysicalPoint, PhysicalRect, PhysicalSize,
340};
341pub use headless::HeadlessShell;
342pub use monitor::{MonitorId, MonitorInfo};
343pub use role::{
344    Margins, PanelAnchor, PanelDesc, PanelKeyboard, PanelLayer, PopupDesc, PopupInput,
345    PopupPlacement, Reserve, WindowRole,
346};
347pub use waker::ShellWaker;
348pub use window::{
349    CloseReply, DisplayMode, SizeConstraints, Window, WindowConfiguration, WindowDesc, WindowId,
350    WindowState,
351};
352
353/// Cross-seam vocabulary from `crcbl-core`: the input-event clock, the key
354/// names, and the one sanctioned platform leak.
355pub use crcbl_core::input::TextPurpose;
356/// Input vocabulary, defined in [`crcbl_core::input`] and re-exported so a
357/// consumer of the event stream needs one `use` rather than two.
358///
359/// See the [crate docs](self) for why these live in `crcbl-core`.
360pub use crcbl_core::input::{
361    ButtonState, ContactId, DeviceId, Keysym, Modifiers, PointerButton, Scancode, ScrollDelta,
362    TouchPhase,
363};
364pub use crcbl_core::{EventTime, KeyCode, SurfaceTarget};
365
366use core::time::Duration;
367
368/// The window system, as the engine sees it.
369///
370/// Object-safe by requirement; see the [crate docs](self) for why, and
371/// [`backend`] for how an implementation is selected at runtime.
372///
373/// # The loop is the caller's
374///
375/// There is no `run` that takes the program over: the caller loops on
376/// [`pump`](Self::pump) and [`wait_events`](Self::wait_events) itself, so
377/// ending the program is leaving that loop and dropping the shell. Each
378/// desktop backend's `Drop` destroys the windows it still holds, so nothing has
379/// to be torn down by hand first. Work that arrives
380/// on another thread reaches a sleeping loop through a [`ShellWaker`].
381///
382/// # Implementing this
383///
384/// Six obligations that are not visible in the signatures. The first three are
385/// P0.4's; the last three are P0.5c's, written down because a real compositor
386/// showed that leaving them unstated pushes the work onto every consumer.
387///
388/// 1. **Stale handles fail cleanly.** Every method taking a [`WindowId`] must
389///    return [`ShellError::InvalidWindow`] for a destroyed or foreign one, never
390///    act on whatever window took the slot.
391/// 2. **Timestamps are rebased.** Input events carry the window system's
392///    timestamp converted to the engine epoch — see [`EventTime`], which
393///    documents the conversion each platform needs.
394/// 3. **Capabilities are latched.** [`caps`](Self::caps) must return the same
395///    value for the shell's lifetime, so a consumer that branched on it at
396///    startup is never contradicted mid-session. See [`caps`] for the
397///    Wayland-binds-a-global-late edge this rules out.
398/// 4. **Every accepted clipboard read is answered exactly once, and within a
399///    bounded time.** [`clipboard_request`](Self::clipboard_request) that
400///    returns `Ok` promises exactly one
401///    [`ShellEvent::ClipboardData`] carrying that
402///    [`ClipboardRequestId`]. A backend that cannot complete the read answers
403///    [`ClipboardContent::Unavailable`] rather than dropping the request; a
404///    request with no answer is a UI stuck on "pasting…" forever, which no
405///    consumer can detect.
406/// 5. **A read that cannot be answered *yet* is held, never answered "empty".**
407///    If the backend does not yet know what is on the clipboard — Wayland's
408///    focus-gated, asynchronous `wl_data_device.selection` is the case this
409///    exists for — it holds the request until it does, and bounds that wait.
410///    Reporting [`Empty`](ClipboardContent::Empty) for "I have not looked yet"
411///    is indistinguishable from an empty clipboard, so it makes every consumer
412///    write a retry loop with a timeout it cannot choose correctly. Where the
413///    answer is always immediately available (X11 asks the server who owns the
414///    selection; a headless shell owns it), holding costs nothing and this
415///    obligation is discharged by answering.
416/// 6. **A refusal for want of user interaction is named.** Where the window
417///    system requires a recent input event to claim the clipboard — Wayland
418///    does, the browser does, X11 and Win32 do not —
419///    [`clipboard_offer`](Self::clipboard_offer) returns
420///    [`ShellError::NeedsUserInteraction`] and not a generic backend error, so
421///    a caller can distinguish "ask the user to press the key again" from "this
422///    is broken". A backend on a platform without the rule never returns it.
423pub trait Shell: core::fmt::Debug {
424    /// Which implementation this is. Logs and bug reports only — behaviour
425    /// branches on [`caps`](Self::caps).
426    fn backend(&self) -> ShellBackend;
427
428    /// What this backend can do. Fixed for the shell's lifetime.
429    fn caps(&self) -> ShellCaps;
430
431    /// Creates a window. **The window has no size yet.**
432    ///
433    /// `desc.size` is a request. The authoritative size arrives later, as the
434    /// first [`ShellEvent::Resized`], and until it does
435    /// [`WindowState::size`] is `None`. This is not a headless quirk: a Wayland
436    /// `xdg_surface` is unsized and may not be given a buffer until the
437    /// compositor answers with a `configure`, which is a round trip away.
438    ///
439    /// A swapchain needs an extent, so this is a hard ordering constraint:
440    ///
441    /// ```
442    /// # use crcbl_shell::{HeadlessShell, PhysicalSize, Shell, WindowDesc};
443    /// # let mut shell = HeadlessShell::new();
444    /// let window = shell.create_window(&WindowDesc::default())?;
445    /// let size: PhysicalSize = loop {
446    ///     shell.pump(&mut |_event| { /* … */ });
447    ///     if let Some(size) = shell.window_state(window)?.size() {
448    ///         break size;
449    ///     }
450    /// };
451    /// // Only now is there an extent to create a swapchain at.
452    /// assert_eq!(size, PhysicalSize::new(1280, 720));
453    /// # Ok::<(), crcbl_shell::ShellError>(())
454    /// ```
455    ///
456    /// [`HeadlessShell`] deliberately defers the first configure by at least one
457    /// `pump`, so a consumer that skips the loop fails in CI rather than at
458    /// P0.5.
459    ///
460    /// # Errors
461    ///
462    /// [`ShellError::WindowCreation`] if the window system refused, or
463    /// [`ShellError::Unsupported`] if this would be a second window on a
464    /// backend without [`ShellCaps::MULTI_WINDOW`].
465    fn create_window(&mut self, desc: &WindowDesc<'_>) -> Result<WindowId, ShellError>;
466
467    /// Destroys a window. A [`ShellEvent::WindowDestroyed`] follows.
468    ///
469    /// The [`SurfaceTarget`] previously returned for this window is dead
470    /// afterwards; the HAL surface built from it must be destroyed **first**.
471    ///
472    /// # Errors
473    ///
474    /// [`ShellError::InvalidWindow`] if the handle is stale.
475    fn destroy_window(&mut self, window: WindowId) -> Result<(), ShellError>;
476
477    /// A snapshot of the window's current state.
478    ///
479    /// For consumers that started late; not a substitute for handling events.
480    /// Note that [`WindowState::size`] is `None` until the window system has
481    /// configured the window, and that the *requested* mode and the *effective*
482    /// one are separate fields — see [`WindowState`].
483    ///
484    /// # Errors
485    ///
486    /// [`ShellError::InvalidWindow`] if the handle is stale.
487    fn window_state(&self, window: WindowId) -> Result<WindowState, ShellError>;
488
489    /// Sets the title bar text.
490    ///
491    /// # Errors
492    ///
493    /// [`ShellError::InvalidWindow`] if the handle is stale.
494    fn set_title(&mut self, window: WindowId, title: &str) -> Result<(), ShellError>;
495
496    /// Maps or unmaps the window.
497    ///
498    /// # Errors
499    ///
500    /// [`ShellError::InvalidWindow`] if the handle is stale.
501    fn set_visible(&mut self, window: WindowId, visible: bool) -> Result<(), ShellError>;
502
503    /// Asks for windowed or borderless.
504    ///
505    /// **A request, not a command.** It updates
506    /// [`WindowState::requested_mode`] immediately and nothing else; the mode
507    /// that is actually in effect appears in
508    /// [`WindowConfiguration::mode`] when the window system answers, which it
509    /// may do with something other than what was asked (a compositor can refuse
510    /// fullscreen, and a tiling window manager makes the question moot). Use
511    /// [`WindowState::mode_request_honoured`] rather than reading the request
512    /// back as fact.
513    ///
514    /// The answer usually arrives as a [`ShellEvent::Resized`], preceded by a
515    /// [`ShellEvent::ScaleFactorChanged`] when the target monitor has a
516    /// different scale. Never assume the new size — read the event.
517    ///
518    /// # Errors
519    ///
520    /// [`ShellError::InvalidWindow`] if the handle is stale, or
521    /// [`ShellError::NoSuchMonitor`] if the named monitor is gone.
522    fn set_mode(&mut self, window: WindowId, mode: DisplayMode) -> Result<(), ShellError>;
523
524    /// Asks for resize limits and an aspect lock.
525    ///
526    /// Hints, not guarantees, and a request rather than a command: it updates
527    /// [`WindowState::requested_constraints`] immediately, and the only
528    /// observable effect is whatever size the window system reports next. No
529    /// platform reports back "effective constraints", so neither does this
530    /// seam. See [`SizeConstraints`].
531    ///
532    /// # Errors
533    ///
534    /// [`ShellError::InvalidWindow`] if the handle is stale.
535    fn set_constraints(
536        &mut self,
537        window: WindowId,
538        constraints: SizeConstraints,
539    ) -> Result<(), ShellError>;
540
541    /// Moves a live popup against a new `anchor` in its parent and gives it
542    /// `size`, placed by the [`PopupPlacement`] it was created with: flipped
543    /// or slid to stay on screen, as when it opened.
544    ///
545    /// For a popup whose anchor moved — a bar's clock grew and its calendar
546    /// should follow — or whose content changed size. A request, like the
547    /// rest of a window's geometry: the new size arrives as the next
548    /// [`ShellEvent::Resized`], once the window system has placed it.
549    ///
550    /// Requires [`ShellCaps::POPUP_REPOSITION`]. Without it, close the popup
551    /// and open another.
552    ///
553    /// # Errors
554    ///
555    /// [`ShellError::Unsupported`] without the capability,
556    /// [`ShellError::InvalidWindow`] for a stale handle, and
557    /// [`ShellError::InvalidDescriptor`] for a window that is not a popup.
558    fn reposition_popup(
559        &mut self,
560        popup: WindowId,
561        anchor: LogicalRect,
562        size: LogicalSize,
563    ) -> Result<(), ShellError> {
564        let _ = (popup, anchor, size);
565        Err(ShellError::Unsupported {
566            backend: self.backend(),
567            what: "repositioning a popup",
568        })
569    }
570
571    /// Gives a live panel a new size and a new [`PanelDesc`]: its layer,
572    /// anchor, reserve, margins and keyboard change in place, with the same
573    /// surface and the same swapchain, where destroying it and creating
574    /// another would flicker.
575    ///
576    /// `size` means what [`WindowDesc::size`] means for a panel: ignored along
577    /// an axis anchored to both opposite edges. The new descriptor is checked
578    /// as [`create_window`](Self::create_window) checks one, so a reserving
579    /// panel must still name one edge. A request, like the rest of a window's
580    /// geometry: the size the panel gets arrives as the next
581    /// [`ShellEvent::Resized`], as its first one did, and none arrives when
582    /// the size did not change.
583    ///
584    /// **The namespace and the monitor cannot change.** `wlr-layer-shell`
585    /// fixes both when the surface is made, and every backend refuses a
586    /// change to either alike; close the panel and open another for that.
587    ///
588    /// A visible panel changed to [`PanelKeyboard::Exclusive`] takes the
589    /// keyboard at once on Wayland, where the compositor hands it over; on
590    /// Win32 and AppKit it takes it when it is next shown, as a new one does.
591    ///
592    /// A provided method answering [`ShellError::Unsupported`], as
593    /// [`create_window`](Self::create_window) answers a panel on a backend
594    /// without [`ShellCaps::PANEL`], once the handle has been checked; every
595    /// backend with panels implements it.
596    ///
597    /// # Errors
598    ///
599    /// [`ShellError::InvalidWindow`] for a stale handle,
600    /// [`ShellError::InvalidDescriptor`] for a window that is not a panel or a
601    /// descriptor that changes its namespace or its monitor, and whatever
602    /// [`create_window`](Self::create_window) refuses a panel with:
603    /// [`ShellError::Unsupported`] for what the backend cannot build, and
604    /// [`ShellError::NoSuchMonitor`] if the panel's monitor is gone.
605    fn set_panel(
606        &mut self,
607        window: WindowId,
608        size: LogicalSize,
609        panel: &PanelDesc<'_>,
610    ) -> Result<(), ShellError> {
611        let _ = (size, panel);
612        self.window_state(window)?;
613        Err(ShellError::Unsupported {
614            backend: self.backend(),
615            what: "panel windows",
616        })
617    }
618
619    /// Every connected monitor.
620    ///
621    /// Invalidated by [`ShellEvent::MonitorsChanged`]; call again rather than
622    /// caching across it.
623    fn monitors(&self) -> &[MonitorInfo];
624
625    /// One monitor by id, or `None` if it is not connected.
626    ///
627    /// A provided method rather than a required one: it is a lookup over
628    /// [`monitors`](Self::monitors), and every backend would write the same
629    /// three lines.
630    fn monitor(&self, id: MonitorId) -> Option<&MonitorInfo> {
631        self.monitors().iter().find(|monitor| monitor.id == id)
632    }
633
634    /// Drains everything that has arrived from the window system into `sink`.
635    ///
636    /// Non-blocking and finite: it delivers what is queued and returns. Call it
637    /// once at the top of every frame. See the [crate docs](self) for why there
638    /// is no `run()` and how a `requestAnimationFrame`-driven build uses this.
639    ///
640    /// The sink is `&mut dyn FnMut` rather than a generic parameter because the
641    /// trait must stay object-safe. That is not purely a cost: a closure passed
642    /// here can borrow the caller's state mutably, which an
643    /// `Iterator`-returning shape could not while the shell is also borrowed.
644    fn pump(&mut self, sink: &mut dyn FnMut(ShellEvent));
645
646    /// Lets the window system run, and delivers nothing.
647    ///
648    /// Everything [`pump`](Self::pump) does except hand events to a sink: the
649    /// platform's queue is drained, whatever it asks of the client is answered,
650    /// and what it produced is **kept** in this shell's queue, in order, for the
651    /// next `pump`. Every backend implements `pump` as this followed by the
652    /// delivery, so the two cannot drift apart.
653    ///
654    /// # What it is for: a long load on the thread that owns the window
655    ///
656    /// Desktops mark a client that stops draining its queue as hung. Windows
657    /// ghosts a window whose thread has not asked for a message for about five
658    /// seconds — `IsHungAppWindow`, a greyed "Not Responding" title, clicks
659    /// held — a Wayland compositor pings through `xdg_wm_base` and offers to
660    /// kill a client that does not answer (GNOME's "not responding" dialog),
661    /// and macOS puts the spinning cursor over an application whose main thread
662    /// has stopped taking events. A game that loads its assets between opening
663    /// its window and its first frame calls this every so often — a few times a
664    /// second is plenty — and stays responsive to all three.
665    ///
666    /// **Nothing is dropped**, which is why this is not `pump` with an empty
667    /// sink: a key pressed, a resize or a close request made during the load is
668    /// delivered by the first frame's `pump`, exactly as if the load had been
669    /// one long frame. So a close request stays unanswered until then — the
670    /// window stays open and the load finishes first — and a loader that must
671    /// stop for one has to pump and handle events itself.
672    ///
673    /// Work that can leave the loop thread should, instead: a loop that keeps
674    /// running frames keeps pumping on its own, and can show progress while it
675    /// does. This is for the load that cannot — work on the device the loop
676    /// owns, or on anything else tied to this thread.
677    ///
678    /// Non-blocking and finite, like `pump`, and with the same exception: on
679    /// Win32 and AppKit it does not return while the user is dragging the
680    /// window's border.
681    fn keep_alive(&mut self);
682
683    /// Blocks until an event arrives or `timeout` elapses.
684    ///
685    /// **Advisory.** Returning immediately is always correct, and backends
686    /// without [`ShellCaps::EVENT_WAIT`] — a browser above all — do exactly
687    /// that. A caller must treat this as "sleep if you can" and must not assume
688    /// an event is pending afterwards; [`pump`](Self::pump) is still what
689    /// delivers them.
690    ///
691    /// `timeout` of `None` means "until something happens", which on a backend
692    /// without the capability still means "immediately".
693    fn wait_events(&mut self, timeout: Option<Duration>) {
694        let _ = timeout;
695    }
696
697    /// A handle that wakes [`wait_events`](Self::wait_events) from another
698    /// thread — see [`ShellWaker`].
699    ///
700    /// Every call hands out a handle to the same doorbell, so a program can ask
701    /// once and clone, or ask wherever it needs one. `None` from a backend
702    /// whose wait never blocks, which is the browser: there, nothing sleeps and
703    /// there is nothing to wake.
704    fn waker(&mut self) -> Option<ShellWaker> {
705        None
706    }
707
708    /// Puts input timestamps on the engine's clock.
709    ///
710    /// Call this **once, at startup**, with the reading of the
711    /// [`TimeSource`](crcbl_core::time::TimeSource) that will drive
712    /// [`FrameClock::update`](crcbl_core::FrameClock::update).
713    ///
714    /// [`EventTime`]'s epoch is defined as "the same origin as" that source,
715    /// and no backend can know it: a shell is created some time *after* the
716    /// clock starts, and the window system's own clock has a third origin
717    /// again. Without this call, timestamps are measured from the shell's own
718    /// creation — internally consistent, so durations between two input events
719    /// are already correct, but offset from a
720    /// [`FrameClock`](crcbl_core::FrameClock) reading by however long startup
721    /// took. That offset is exactly what `docs/plan/26-prediction.md`'s input-to-photon
722    /// latency measurement is a subtraction across.
723    ///
724    /// A provided method with a no-op default, because it is only meaningful
725    /// for a backend whose event clock is not already the engine's — the
726    /// browser's `event.timeStamp` needs nothing done to it. The obligation it
727    /// discharges is the "Timestamps are rebased" one in this trait's
728    /// [implementor notes](Self), which previously had no way to be satisfied
729    /// from outside the crate.
730    ///
731    /// ```
732    /// # use core::time::Duration;
733    /// # use crcbl_shell::{HeadlessShell, Shell};
734    /// let mut shell = HeadlessShell::new();
735    /// // The engine clock has been running for 40 ms by the time the window
736    /// // system is up; input stamped "now" should read as 40 ms, not as zero.
737    /// shell.align_event_clock(Duration::from_millis(40));
738    /// ```
739    fn align_event_clock(&mut self, elapsed: Duration) {
740        let _ = elapsed;
741    }
742
743    /// The native handles a HAL backend needs to create a surface for this
744    /// window.
745    ///
746    /// Opaque to everyone except a HAL backend. Re-query it after a
747    /// [`set_mode`](Self::set_mode): some backends recreate the underlying
748    /// surface on a mode switch, and a cached target then names a dead object.
749    /// **A resize is not such an event** — see below.
750    ///
751    /// # Available before the window is configured, and unchanged by a resize
752    ///
753    /// The *handle* exists as soon as the window does — a `wl_surface` is
754    /// created up front and only its size is pending — so this succeeds
755    /// immediately and a HAL surface can be created from it right away. Only
756    /// the **swapchain** has to wait, because only the swapchain needs an
757    /// extent.
758    ///
759    /// **No variant carries a size**, so the value this returns does not change
760    /// when the window is resized, and a HAL surface created before the first
761    /// configure stays correct forever. That is what makes "re-query after a
762    /// mode change" a complete rule. [`SurfaceTarget::Offscreen`] used to carry
763    /// `width`/`height` and was the one exception; P0.7 removed it, because an
764    /// exception in this rule means a surface silently describing a size the
765    /// window no longer has. The extent reaches a backend through
766    /// [`WindowState::size`] and the swapchain descriptor, and only there —
767    /// `crcbl-hal`'s `swapchain` module states that precedence as a backend
768    /// obligation.
769    ///
770    /// # Errors
771    ///
772    /// [`ShellError::InvalidWindow`] if the handle is stale.
773    fn surface_target(&self, window: WindowId) -> Result<SurfaceTarget, ShellError>;
774
775    /// Frees, confines or locks the pointer.
776    ///
777    /// # Errors
778    ///
779    /// [`ShellError::Unsupported`] if [`caps`](Self::caps) lacks
780    /// [`PointerMode::required_cap`], or [`ShellError::InvalidWindow`] for a
781    /// stale handle.
782    fn set_pointer_mode(&mut self, window: WindowId, mode: PointerMode) -> Result<(), ShellError>;
783
784    /// Sets the cursor shape, or hides the cursor with `None`.
785    ///
786    /// Visibility and capture are separate axes; see [`cursor`].
787    ///
788    /// Hiding works on every backend. A shape is seen only where
789    /// [`ShellCaps::CURSOR_SHAPE`] is set; elsewhere it is accepted and
790    /// recorded rather than refused, because a UI calls this on every hover.
791    ///
792    /// # Errors
793    ///
794    /// [`ShellError::InvalidWindow`] if the handle is stale.
795    fn set_cursor(
796        &mut self,
797        window: WindowId,
798        cursor: Option<CursorIcon>,
799    ) -> Result<(), ShellError>;
800
801    /// Moves the pointer to a position in the window.
802    ///
803    /// Requires [`ShellCaps::POINTER_WARP`], which **Wayland does not have and
804    /// will not get**. Anything reaching for this to implement a camera should
805    /// use [`PointerMode::Locked`] instead; warping is for a UI that needs to
806    /// reposition a cursor (a slider snapping to a value), not for input.
807    ///
808    /// # Errors
809    ///
810    /// [`ShellError::Unsupported`] without the capability, or
811    /// [`ShellError::InvalidWindow`] for a stale handle.
812    fn warp_pointer(&mut self, window: WindowId, position: PhysicalPoint)
813    -> Result<(), ShellError>;
814
815    /// Answers a [`ShellEvent::CloseRequested`].
816    ///
817    /// Until this is called the window stays open and the request stays
818    /// outstanding. See [`CloseReply`].
819    ///
820    /// # Errors
821    ///
822    /// [`ShellError::NoPendingCloseRequest`] if nothing was asked, or
823    /// [`ShellError::InvalidWindow`] for a stale handle.
824    fn reply_close_request(
825        &mut self,
826        window: WindowId,
827        reply: CloseReply,
828    ) -> Result<(), ShellError>;
829
830    /// Publishes clipboard content in one or more formats.
831    ///
832    /// Synchronous: every platform's write is "claim the selection", and the
833    /// bytes transfer later, on demand. Offer both [`MimeType::TextUtf8`] and
834    /// [`MimeType::CrcblRon`] for engine data; see [`clipboard`].
835    ///
836    /// An empty `offers` slice releases the clipboard, where the platform can
837    /// express that.
838    ///
839    /// # Errors
840    ///
841    /// [`ShellError::Unsupported`] without [`ShellCaps::CLIPBOARD`],
842    /// [`ShellError::InvalidWindow`] for a stale handle, or
843    /// [`ShellError::NeedsUserInteraction`] where the window system requires a
844    /// recent input event to claim the clipboard and there has not been one —
845    /// implementor obligation 6 above, and **not** a failure a caller should
846    /// retry blindly.
847    fn clipboard_offer(
848        &mut self,
849        window: WindowId,
850        offers: &[ClipboardOffer<'_>],
851    ) -> Result<(), ShellError>;
852
853    /// Asks for the clipboard's content in `mime`.
854    ///
855    /// Asynchronous by necessity — the answer arrives as
856    /// [`ShellEvent::ClipboardData`] carrying the returned id, and **exactly one
857    /// answer arrives for every `Ok` return** (implementor obligations 4 and 5).
858    /// [`clipboard`] has the full argument; briefly, X11 `INCR` transfers,
859    /// Wayland file descriptors and the browser's Promise make the synchronous
860    /// shape unimplementable on three of five backends.
861    ///
862    /// The answer may be several frames away, and on a backend whose clipboard
863    /// is not readable at the moment of asking it is *held* until it is, rather
864    /// than being answered [`Empty`](ClipboardContent::Empty). A caller
865    /// therefore never needs to poll or retry: ask once, handle the event.
866    /// [`clipboard_readable`](Self::clipboard_readable) is the way to find out
867    /// in advance that the answer will not be immediate.
868    ///
869    /// # Errors
870    ///
871    /// [`ShellError::Unsupported`] without [`ShellCaps::CLIPBOARD`], or
872    /// [`ShellError::InvalidWindow`] for a stale handle. An empty clipboard is
873    /// **not** an error — it is an answer.
874    fn clipboard_request(
875        &mut self,
876        window: WindowId,
877        mime: MimeType,
878    ) -> Result<ClipboardRequestId, ShellError>;
879
880    /// Whether a [`clipboard_request`](Self::clipboard_request) issued for
881    /// `window` right now could be answered without waiting.
882    ///
883    /// What a "Paste" menu item greys out on, and the visible form of a
884    /// platform rule that is otherwise invisible: **on Wayland a client is told
885    /// what is on the clipboard only while one of its windows has keyboard
886    /// focus**, and only asynchronously, so a background window genuinely
887    /// cannot read the clipboard. `clipboard_request` still works there — it
888    /// holds the request — but it may take until focus arrives, and a UI that
889    /// would rather not offer the action than offer a slow one asks here first.
890    ///
891    /// `false` for a stale handle, and for a backend without
892    /// [`ShellCaps::CLIPBOARD`].
893    ///
894    /// # A provided method, because most platforms have nothing to say
895    ///
896    /// The default is "readable whenever the capability is present and the
897    /// handle is live", which is exactly right for X11 (any window may
898    /// `ConvertSelection` at any time, focus is not involved), for Win32, and
899    /// for [`HeadlessShell`] in its default configuration. Only a backend that
900    /// really has a gate overrides it — so this is a fact a consumer can rely
901    /// on, not ceremony every backend has to perform.
902    ///
903    /// The staleness half goes through
904    /// [`window_state`](Self::window_state) rather than being left to each
905    /// implementation. P0.6 found the earlier default — which ignored `window`
906    /// entirely — contradicting the "`false` for a stale handle" sentence
907    /// above: both backends that existed had *overridden* it and so had
908    /// covered for it, and the first backend to accept the default inherited
909    /// the bug. A default that cannot keep its own promise is worse than no
910    /// default.
911    fn clipboard_readable(&self, window: WindowId) -> bool {
912        self.caps().contains(ShellCaps::CLIPBOARD) && self.window_state(window).is_ok()
913    }
914
915    /// A token another program can raise its own window with, made from
916    /// `window` and the latest input this program received.
917    ///
918    /// What a notification daemon sends as the notification spec's
919    /// `ActivationToken` before `ActionInvoked`, and what a launcher puts in a
920    /// child's `XDG_ACTIVATION_TOKEN`: the receiver hands it back to its window
921    /// system, which raises the window if it accepts the token. Ask for it in
922    /// answer to the click that warrants it, since the window system judges a
923    /// token by the input it was made from.
924    ///
925    /// `Ok(None)` where the window system has no such thing: Wayland without
926    /// `xdg-activation-v1`, and every other backend, whose default this is.
927    /// Wayland waits for the compositor's answer, a round trip or more.
928    ///
929    /// # Errors
930    ///
931    /// [`ShellError::InvalidWindow`] for a stale handle, or
932    /// [`ShellError::Backend`] where the window system has the mechanism but
933    /// gave no token.
934    fn activation_token(&mut self, window: WindowId) -> Result<Option<String>, ShellError> {
935        self.window_state(window).map(|_| None)
936    }
937
938    /// Tells the input method where text is being entered, so it can put its
939    /// composition window and candidate list there instead of at a corner of the
940    /// screen.
941    ///
942    /// `area` is the text field's caret, or the line it sits on, in the
943    /// window's **client** device pixels; the candidate list opens beside it
944    /// without covering it. `None` hands placement back to the input method's
945    /// default. Call it when a field gains focus and whenever its caret moves.
946    /// A hint: the input method may place its windows elsewhere, and nothing
947    /// reports where they went.
948    ///
949    /// # A provided method, and a no-op where there is nothing to place
950    ///
951    /// Only a backend with an input method that draws its own windows has
952    /// anything to do here — Win32's IMM and TSF, a Wayland compositor's
953    /// `text-input-v3` cursor rectangle, AppKit's `firstRectForCharacterRange:`.
954    /// The default validates the handle and does nothing else, which is exactly
955    /// right for the rest. Win32, Wayland and AppKit override it. Wayland
956    /// sends the area only while [`set_text_input`](Self::set_text_input)
957    /// names a field, since `text-input-v3` has nowhere to put it otherwise;
958    /// AppKit answers `firstRectForCharacterRange:` with it whenever asked.
959    ///
960    /// # Errors
961    ///
962    /// [`ShellError::InvalidWindow`] if the handle is stale.
963    fn set_text_input_area(
964        &mut self,
965        window: WindowId,
966        area: Option<PhysicalRect>,
967    ) -> Result<(), ShellError> {
968        let _ = area;
969        self.window_state(window).map(|_| ())
970    }
971
972    /// Limits where `window` takes the pointer to a union of rectangles, so
973    /// the pointer anywhere else goes to whatever is behind the window.
974    ///
975    /// For a transparent window that draws a shape smaller than itself: a
976    /// launcher's rounded panel, whose transparent corners should let a click
977    /// through to the program beneath. A pixel of alpha zero is otherwise the
978    /// window's on every desktop backend; nothing hit-tests by alpha, because
979    /// that would read the frame back from the GPU on every pointer move.
980    ///
981    /// `region` is in the window's **client** device pixels, the units of
982    /// [`set_text_input_area`](Self::set_text_input_area). Empty rectangles
983    /// are ignored, and parts outside the window take nothing; an empty slice
984    /// leaves the window no pointer input at all. `None` gives the whole window
985    /// back, which is where every window starts. Keyboard focus is not
986    /// affected. The rectangles are the caller's layout, so send them again
987    /// after a [`ShellEvent::Resized`] or [`ShellEvent::ScaleFactorChanged`]
988    /// that moves the shape. [`PhysicalRect::rounded`] builds them for a
989    /// rounded rectangle.
990    ///
991    /// **Give the outer bound of what the window draws, antialiased edge
992    /// included.** On Win32 the region is a window region, which also clips
993    /// the window's drawing to it, so a region inside the edge's blend cuts
994    /// the edge off. Elsewhere a tighter region only loses the pointer over
995    /// the edge.
996    ///
997    /// A [`Passthrough`](PopupInput::Passthrough) popup stays passthrough: a
998    /// region given to it is validated and has no effect.
999    ///
1000    /// # A provided method
1001    ///
1002    /// The default validates the handle and does nothing else, which leaves
1003    /// the whole window taking the pointer. Wayland, X11 and Win32 override it,
1004    /// and [`ShellCaps::INPUT_REGION`] is set only where it is acted on; a
1005    /// caller that must have the click-through checks the bit rather than the
1006    /// platform.
1007    ///
1008    /// # Errors
1009    ///
1010    /// [`ShellError::InvalidWindow`] if the handle is stale.
1011    fn set_input_region(
1012        &mut self,
1013        window: WindowId,
1014        region: Option<&[PhysicalRect]>,
1015    ) -> Result<(), ShellError> {
1016        let _ = region;
1017        self.window_state(window).map(|_| ())
1018    }
1019
1020    /// Asks for a [`ShellEvent::FrameReady`] when `window` should present its
1021    /// next frame.
1022    ///
1023    /// For a loop that presents only when told to: a status bar on an output
1024    /// the compositor has turned off is never asked for a frame there, and a
1025    /// FIFO present to it can block the loop for as long as the output stays
1026    /// off. Ask **before** presenting the frame the answer paces, then present
1027    /// the next one once it comes. The first frame needs no answer.
1028    ///
1029    /// ```
1030    /// # use crcbl_shell::{HeadlessShell, Shell, ShellEvent, WindowDesc};
1031    /// # let mut shell = HeadlessShell::new();
1032    /// # let window = shell.create_window(&WindowDesc::default())?;
1033    /// let mut may_present = true;
1034    /// # let mut presented = 0;
1035    /// for _ in 0..3 {
1036    ///     shell.pump(&mut |event| {
1037    ///         if let ShellEvent::FrameReady { window: ready } = event {
1038    ///             may_present |= ready == window;
1039    ///         }
1040    ///     });
1041    ///     if may_present {
1042    ///         shell.request_frame(window)?;
1043    ///         // … record and present …
1044    /// #       presented += 1;
1045    ///         may_present = false;
1046    ///     }
1047    /// }
1048    /// // With no compositor to hold it back, each answer came at the next pump.
1049    /// assert_eq!(presented, 3);
1050    /// # Ok::<(), crcbl_shell::ShellError>(())
1051    /// ```
1052    ///
1053    /// Requests made before the answer comes share it: one `FrameReady`
1054    /// answers them all. A window destroyed with a request outstanding gets no
1055    /// answer.
1056    ///
1057    /// Where [`ShellCaps::FRAME_CALLBACK`] is set — Wayland, as
1058    /// `wl_surface.frame` — the compositor answers. The request is surface
1059    /// state that rides the next commit, which is the one the swapchain's
1060    /// present makes, and this call commits nothing itself, so a window that
1061    /// asks and then never presents may never be answered. Everywhere else
1062    /// the answer comes at the next [`pump`](Self::pump), and
1063    /// [`wait_events`](Self::wait_events) does not sleep while one is due.
1064    ///
1065    /// A required method, unlike its neighbours: a default could validate the
1066    /// handle but not keep the request, and a request nothing answers stalls
1067    /// the loop waiting for it.
1068    ///
1069    /// # Errors
1070    ///
1071    /// [`ShellError::InvalidWindow`] if the handle is stale.
1072    fn request_frame(&mut self, window: WindowId) -> Result<(), ShellError>;
1073
1074    /// Tells the input method what text field in `window` is taking typing:
1075    /// `Some(purpose)` as a field gains the keyboard focus, `None` as it loses
1076    /// it.
1077    ///
1078    /// While a field is taking typing, a platform input method composes what
1079    /// is typed in the window, reporting the composition as
1080    /// [`TextPreedit`](ShellEvent::TextPreedit) and the result as
1081    /// [`TextCommit`](ShellEvent::TextCommit). While none is, the input method
1082    /// keeps out of the way and keys reach the window as keys: one in its
1083    /// native mode would otherwise turn a game's WASD into a candidate list. A
1084    /// window starts with none.
1085    ///
1086    /// The [`TextPurpose`] says what the field is for. A password or a PIN is
1087    /// [sensitive](TextPurpose::is_sensitive): nothing typed into it may be
1088    /// learned, stored or suggested back.
1089    ///
1090    /// # A provided method
1091    ///
1092    /// The default validates the handle and does nothing else. Wayland acts on
1093    /// it with `text-input-v3`'s `enable`, `set_content_type` and `disable`;
1094    /// Win32 associates the window's input context only for a
1095    /// [`Normal`](TextPurpose::Normal) field, keeping it off for a password or
1096    /// a PIN as a Windows password box does. AppKit draws the same line by
1097    /// holding the view's input context to the keyboard layouts for no field
1098    /// and for a sensitive one, and also holds secure event input while a
1099    /// password or PIN field's window has the keyboard.
1100    /// [`ShellCaps::TEXT_IME`] is set only where this is acted on.
1101    ///
1102    /// # Errors
1103    ///
1104    /// [`ShellError::InvalidWindow`] if the handle is stale.
1105    fn set_text_input(
1106        &mut self,
1107        window: WindowId,
1108        field: Option<TextPurpose>,
1109    ) -> Result<(), ShellError> {
1110        let _ = field;
1111        self.window_state(window).map(|_| ())
1112    }
1113
1114    /// Hands `window`'s accessibility tree, or what changed in it, to the
1115    /// platform's assistive technologies.
1116    ///
1117    /// Send a whole tree (with [`TreeUpdate::tree`](accesskit::TreeUpdate::tree)
1118    /// set) after each
1119    /// [`AccessibilityActivated`](ShellEvent::AccessibilityActivated), then
1120    /// only what changed, each frame something did. An update sent while
1121    /// nobody is reading — before the activation, or after
1122    /// [`AccessibilityDeactivated`](ShellEvent::AccessibilityDeactivated) — is
1123    /// dropped, so a program may also send unconditionally and skip tracking
1124    /// the two events.
1125    ///
1126    /// # A provided method
1127    ///
1128    /// The default validates the handle and drops the update, which is right
1129    /// for a backend with no adapter: it never raises the activation either.
1130    /// [`ShellCaps::ACCESSIBILITY`] says whether the trees go anywhere.
1131    ///
1132    /// # Errors
1133    ///
1134    /// [`ShellError::InvalidWindow`] if the handle is stale.
1135    #[cfg(feature = "accesskit")]
1136    fn update_accessibility(
1137        &mut self,
1138        window: WindowId,
1139        update: accesskit::TreeUpdate,
1140    ) -> Result<(), ShellError> {
1141        let _ = update;
1142        self.window_state(window).map(|_| ())
1143    }
1144}