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