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