Skip to main content

crcbl_shell/
event.rs

1//! [`ShellEvent`] — everything the window system tells the engine, in engine
2//! types.
3//!
4//! # Timestamps, and the clock they are on
5//!
6//! Every input-bearing variant carries an [`EventTime`]. This is not
7//! decoration: the input design makes the pattern evaluator a pure function
8//! over timestamped edges (`docs/notes/simulation.md`) — tap versus hold versus
9//! double-tap are *defined* by inter-event durations — and topic 26's client
10//! prediction needs input-to-photon latency, which is a subtraction between an
11//! event timestamp and a present timestamp. Neither works if the timestamp is
12//! the moment the engine got around to draining the queue: a 20 ms frame
13//! quantizes every duration to 20 ms and makes a fast double-tap
14//! indistinguishable from a slow one.
15//!
16//! So the timestamp is the **window system's**, rebased onto the engine's
17//! monotonic clock. [`EventTime`]'s own documentation states the epoch and
18//! spells out the per-platform rebasing each backend owes; the short version is
19//! that an `EventTime` and [`FrameClock`](crcbl_core::FrameClock) readings live
20//! on one timeline, so they can be subtracted.
21//!
22//! Non-input variants ([`Resized`](ShellEvent::Resized),
23//! [`MonitorsChanged`](ShellEvent::MonitorsChanged)) carry no timestamp. They
24//! are state transitions, not samples; nothing computes a duration between two
25//! resizes, and a field that exists only to be ignored invites someone to use
26//! it for something it is not.
27//!
28//! # Modifiers are stamped onto every event, not delivered separately
29//!
30//! Wayland sends `wl_keyboard.modifiers` as its own message, X11 puts a
31//! modifier mask on each event, and Win32 makes you call `GetKeyState`. The
32//! seam picks the X11 shape: the backend tracks modifier state and stamps the
33//! current value onto each event.
34//!
35//! The reason is that the alternative loses information the consumer cannot
36//! recover. If modifiers arrive as a separate event, a consumer that batches a
37//! frame's events — which every consumer does — sees "Ctrl went down" and "S
38//! went down" as two facts in a list and has to replay them in order to know
39//! whether it was `Ctrl+S`. That replay is exactly the state machine each
40//! backend has to write anyway, so it is written once, in the backend, where
41//! the ordering is authoritative.
42//!
43//! # Non-exhaustive, unlike [`SurfaceTarget`](crcbl_core::SurfaceTarget)
44//!
45//! `SurfaceTarget` is deliberately exhaustive so a new platform breaks every
46//! HAL backend loudly. `ShellEvent` is the opposite: a consumer that ignores an
47//! event it has never heard of degrades gracefully (touch input does nothing,
48//! rather than doing something wrong), and
49//! [`TextPreedit`](ShellEvent::TextPreedit) arrived that way after it. Breaking
50//! every `match` in the engine for each new event is not a useful forcing
51//! function, it is churn. (Gamepads are not window events and do not come
52//! through here: their backends emit `crcbl_input::GamepadEvent`s from a poll
53//! of their own.)
54//!
55//! [`Touch`](ShellEvent::Touch) is what that promise looked like when it was
56//! collected: it landed without touching a single `match` outside the shell,
57//! and a game that never heard of it kept playing with one finger because the
58//! primary contact is reported through the pointer variants as well.
59
60use std::path::PathBuf;
61
62use crcbl_core::EventTime;
63use crcbl_core::input::{
64    ButtonState, ContactId, DeviceId, Keysym, Modifiers, PointerButton, Scancode, ScrollDelta,
65    TouchPhase,
66};
67
68use crate::{
69    ClipboardContent, ClipboardRequestId, KeyCode, MonitorId, PhysicalPoint, PhysicalSize,
70    ReceivedMime, WindowId,
71};
72
73/// Something the window system reported.
74///
75/// Delivered by [`Shell::pump`](crate::Shell::pump). See the [module
76/// docs](self) for the timestamp and modifier conventions.
77#[derive(Clone, Debug, PartialEq)]
78#[non_exhaustive]
79pub enum ShellEvent {
80    /// The client area changed size.
81    ///
82    /// The authoritative size for the swapchain — never the size that was
83    /// asked for in [`WindowDesc`](crate::WindowDesc). Carries the scale factor
84    /// too, because a resize and a scale change can arrive together (dragging a
85    /// window between monitors of different DPI does exactly that) and a
86    /// consumer that reads size from one event and scale from another will
87    /// briefly hold a mismatched pair.
88    Resized {
89        /// Which window.
90        window: WindowId,
91        /// New client area in device pixels.
92        size: PhysicalSize,
93        /// Device pixels per logical unit, at the same instant.
94        scale_factor: f64,
95    },
96
97    /// The window's scale factor changed — it moved to a different monitor, or
98    /// the user changed the display scale.
99    ///
100    /// Carries the *new* physical size as well: on Wayland a scale change is a
101    /// `configure` that also restates the size, and on Win32 `WM_DPICHANGED`
102    /// hands over a suggested rectangle. A consumer must treat this as a resize
103    /// too. The windowing rules (`docs/notes/backends.md`) call out "scale-factor changes
104    /// mid-session must not leak wrong-size swapchains" as a required test, and
105    /// putting both facts in one event is what makes that testable rather than
106    /// order-dependent.
107    ScaleFactorChanged {
108        /// Which window.
109        window: WindowId,
110        /// New device pixels per logical unit.
111        scale_factor: f64,
112        /// Client area in device pixels after the change.
113        size: PhysicalSize,
114    },
115
116    /// The user asked to close the window — title-bar button, Alt-F4, session
117    /// logout.
118    ///
119    /// The window is **still open**. Answer with
120    /// [`reply_close_request`](crate::Shell::reply_close_request); until you
121    /// do, the shell holds the request. See
122    /// [`CloseReply`](crate::CloseReply).
123    CloseRequested {
124        /// Which window.
125        window: WindowId,
126    },
127
128    /// The window was destroyed and its [`WindowId`] is now stale.
129    ///
130    /// Follows a [`CloseReply::Close`](crate::CloseReply::Close), an explicit
131    /// [`destroy_window`](crate::Shell::destroy_window), or the compositor
132    /// taking the window away — every window at once when the connection to
133    /// the window system is lost.
134    WindowDestroyed {
135        /// The window that is gone.
136        window: WindowId,
137    },
138
139    /// Keyboard focus entered or left the window.
140    ///
141    /// A consumer **must** treat focus loss as "every key is now up": no
142    /// platform delivers releases for keys held when focus leaves, and a game
143    /// that does not clear its key state walks into a wall until the player
144    /// taps the key again. The action layer (P2) does this centrally; raw
145    /// consumers do it themselves.
146    Focus {
147        /// Which window.
148        window: WindowId,
149        /// Whether the window now has focus.
150        focused: bool,
151    },
152
153    /// A key went down or came up.
154    ///
155    /// Three views of the same keystroke — see
156    /// [`crcbl_core::input`] for why they are all here and what each is for.
157    ///
158    /// **A key the input method consumes while composing is not reported as
159    /// a `Key`** — neither its press nor its release. The Backspace that
160    /// deletes a kana from a [`TextPreedit`](ShellEvent::TextPreedit) and the
161    /// Enter that commits the conversion are the input method's, and a text
162    /// field that also saw them as editing keys would delete a character or
163    /// submit the form. This is what a Wayland compositor already does by not
164    /// sending the key at all; the Win32 backend recognizes the keystrokes its
165    /// input method marks as taken. The AppKit backend cannot yet tell such a
166    /// keystroke apart, and still reports it.
167    Key {
168        /// Which window had focus.
169        window: WindowId,
170        /// Which keyboard.
171        device: DeviceId,
172        /// When it happened; see the [module docs](self).
173        time: EventTime,
174        /// The platform's raw code, for keys the engine has no name for.
175        scancode: Scancode,
176        /// The physical key, layout-independent. `None` when the scancode maps
177        /// to no key this engine names — the key is still bindable through
178        /// `scancode`. Right for game bindings (WASD stays where the fingers
179        /// are), wrong for menus and shortcuts: an xkb remap such as
180        /// `caps:escape` or a virtual keyboard's own keymap does not change it
181        /// (`wtype`'s Down arrives on evdev 1, which is Escape).
182        key_code: Option<KeyCode>,
183        /// The symbol this key produces in the current layout, for menus,
184        /// shortcuts, rebind menus and shortcut labels. The keys no layout
185        /// moves have named constants, [`Keysym::ESCAPE`], [`Keysym::DOWN`]
186        /// and the rest.
187        keysym: Keysym,
188        /// The symbol this key produces with Caps Lock (xkb's `Lock`
189        /// modifier) not applied: what a shortcut or a menu accelerator should
190        /// match, so `Ctrl+R` with Caps Lock on still reads as `Ctrl+r`. Equal
191        /// to `keysym` whenever Caps Lock is off.
192        ///
193        /// Shift is still applied wherever `keysym` applies it — `Ctrl+Shift+R`
194        /// is its own shortcut. Per backend:
195        ///
196        /// * **Wayland, X11** — read from a second xkb state that tracks the
197        ///   first with Lock removed, so the layout decides what Lock would
198        ///   have changed (AZERTY's `caps:digits_row` moves the digit row too;
199        ///   some layouts leave keys alone). A Shift Lock (`caps:shiftlock`) is
200        ///   a locked Shift, not Lock, so it stays applied here and in
201        ///   `modifiers`. [`Keysym::NONE`] without libxkbcommon, as `keysym`
202        ///   is.
203        /// * **Win32** — `keysym`, which `MAPVK_VK_TO_CHAR` answers without
204        ///   reading any modifier state, Caps Lock and Shift included.
205        /// * **AppKit** — `keysym`, read from `charactersIgnoringModifiers`,
206        ///   which ignores every modifier but Shift, Caps Lock included.
207        ///   Letters are lowercased; Shift still applies to the rest, so
208        ///   Shift+1 is `!`.
209        /// * **Headless** — `keysym`; the synthetic keyboard has no Caps Lock.
210        /// * **Web** — `keysym`, *with* Caps Lock applied: the browser's
211        ///   `KeyboardEvent.key` arrives with it, and nothing in the event says
212        ///   what the key would have produced without it.
213        shortcut_keysym: Keysym,
214        /// Down or up.
215        state: ButtonState,
216        /// Whether this is an auto-repeat, not a fresh press.
217        ///
218        /// Text fields want repeats; a jump button must not. Filtering them at
219        /// the source would break the first, keeping them silently breaks the
220        /// second, so the fact is carried and the consumer decides.
221        repeat: bool,
222        /// Modifiers held at the time; see the [module docs](self).
223        modifiers: Modifiers,
224    },
225
226    /// The pointer moved.
227    ///
228    /// Both fields are optional, and which are present is the difference
229    /// between a UI event and a camera event:
230    ///
231    /// * `abs` is where the pointer is, in window pixels. `None` under
232    ///   [`PointerMode::Locked`](crate::PointerMode::Locked), where there is no
233    ///   meaningful position.
234    /// * `raw_delta` is unaccelerated, unclipped motion. `None` when the
235    ///   backend has no relative-motion source — see
236    ///   [`ShellCaps::RAW_POINTER_MOTION`](crate::ShellCaps::RAW_POINTER_MOTION).
237    ///
238    /// A camera must use `raw_delta` and must not difference successive `abs`
239    /// values: the latter is clamped at the screen edge and has pointer
240    /// acceleration already applied, which is why aim in games that get this
241    /// wrong stops working when the cursor reaches the edge of the display.
242    PointerMotion {
243        /// Which window.
244        window: WindowId,
245        /// Which pointing device.
246        device: DeviceId,
247        /// When it happened.
248        time: EventTime,
249        /// Position in the window, in device pixels.
250        abs: Option<PhysicalPoint>,
251        /// Unaccelerated relative motion in device pixels, `(dx, dy)`.
252        raw_delta: Option<(f64, f64)>,
253    },
254
255    /// The pointer entered or left the window.
256    ///
257    /// Not in the windowing rules' event set, and added anyway: every backend
258    /// delivers enter/leave natively (`wl_pointer.enter`, X11
259    /// `EnterNotify`, `WM_MOUSELEAVE`), the UI layer needs it for hover state,
260    /// and the alternative — inferring it from motion events that stop
261    /// arriving — cannot distinguish "the pointer left" from "the pointer
262    /// stopped moving".
263    PointerFocus {
264        /// Which window.
265        window: WindowId,
266        /// Which pointing device.
267        device: DeviceId,
268        /// When it happened.
269        time: EventTime,
270        /// Whether the pointer is now inside the window.
271        entered: bool,
272        /// Where it entered, if the backend said. Always `None` on leave.
273        position: Option<PhysicalPoint>,
274    },
275
276    /// A pointer button went down or came up.
277    Button {
278        /// Which window.
279        window: WindowId,
280        /// Which pointing device.
281        device: DeviceId,
282        /// When it happened.
283        time: EventTime,
284        /// Which button.
285        button: PointerButton,
286        /// Down or up.
287        state: ButtonState,
288        /// Where the pointer was, if known. `None` under
289        /// [`PointerMode::Locked`](crate::PointerMode::Locked).
290        position: Option<PhysicalPoint>,
291        /// Modifiers held at the time.
292        modifiers: Modifiers,
293    },
294
295    /// A scroll wheel or touchpad scrolled.
296    Wheel {
297        /// Which window.
298        window: WindowId,
299        /// Which pointing device.
300        device: DeviceId,
301        /// When it happened.
302        time: EventTime,
303        /// How far, in the units the device reported — see
304        /// [`ScrollDelta`], which does not collapse detents into pixels.
305        delta: ScrollDelta,
306        /// Where the pointer was, if known.
307        position: Option<PhysicalPoint>,
308        /// Modifiers held at the time. Ctrl+wheel is zoom nearly everywhere,
309        /// so this is load-bearing rather than informational.
310        modifiers: Modifiers,
311    },
312
313    /// A finger landed, moved, lifted, or had its gesture taken away.
314    ///
315    /// **One event per contact**, so two fingers moving at once are two events
316    /// and not one averaged pointer. [`ContactId`] carries the identity and
317    /// [`TouchPhase`] the lifecycle; between them a consumer can hold per-finger
318    /// state, which is the whole reason this variant exists and the reason a
319    /// second finger used to be dropped at the backend.
320    ///
321    /// # A touchscreen also produces pointer events, and that is deliberate
322    ///
323    /// The **primary** contact — the first finger of a gesture, and the only one
324    /// while there is only one — is *also* reported as
325    /// [`PointerMotion`](ShellEvent::PointerMotion) and
326    /// [`Button`](ShellEvent::Button), exactly as a browser emulates mouse
327    /// events for touch and Windows synthesizes them from `WM_POINTER`. So a
328    /// game bound to `Binding::MouseButton` is playable with one finger without
329    /// knowing this variant exists, and a game that wants two fingers reads
330    /// `Touch` and ignores the emulation.
331    ///
332    /// That is an obligation on a backend that sets
333    /// [`ShellCaps::TOUCH`](crate::ShellCaps::TOUCH), not an accident of one
334    /// platform: a backend whose window system does not emulate must do it
335    /// itself, or every existing pointer binding stops working the day it
336    /// reports its first contact. Contacts that are not primary have no pointer
337    /// events at all — a second finger is not the first one teleporting.
338    ///
339    /// # No modifiers, and a position that is never absent
340    ///
341    /// A finger carries no `modifiers`: no platform reports keyboard state on a
342    /// touch event, and a field the backends would have to invent is a field a
343    /// consumer would believe. And `position` is a [`PhysicalPoint`] rather than
344    /// an `Option` — a contact is *defined* by where it touches, including on
345    /// the release, and there is no [`PointerMode::Locked`](crate::PointerMode)
346    /// equivalent that could take the position away.
347    Touch {
348        /// Which window.
349        window: WindowId,
350        /// Which touchscreen. Every contact on one screen shares this — see
351        /// [`ContactId`], which is the one that tells fingers apart.
352        device: DeviceId,
353        /// When it happened.
354        time: EventTime,
355        /// Which finger.
356        contact: ContactId,
357        /// What it just did.
358        phase: TouchPhase,
359        /// Where it is, in device pixels. On
360        /// [`Cancelled`](TouchPhase::Cancelled) this is the last place the
361        /// platform knew about rather than a place the user chose.
362        position: PhysicalPoint,
363    },
364
365    /// Text was committed — by typing, by an input method, or by a paste the
366    /// window system routed as text input.
367    ///
368    /// Separate from [`Key`](ShellEvent::Key) because the relationship is not
369    /// one-to-one: an IME commits several characters from one keystroke, or one
370    /// character from five, and a dead key commits nothing at all. A text field
371    /// that reconstructs its content from key events is a text field that
372    /// cannot type in Japanese.
373    TextCommit {
374        /// Which window.
375        window: WindowId,
376        /// When it happened.
377        time: EventTime,
378        /// The committed text. Never empty.
379        text: String,
380    },
381
382    /// An input method's composition in progress: the pre-edit a text field
383    /// draws at its caret, underlined, until it is committed or abandoned.
384    ///
385    /// **Each one replaces the last**, and an empty `text` means there is no
386    /// pre-edit any more: the composition was committed, cancelled, or deleted
387    /// back to nothing. The committed text itself arrives separately, as
388    /// [`TextCommit`](ShellEvent::TextCommit), and a consumer must not
389    /// synthesize it from the last pre-edit: an input method commits the
390    /// conversion the user chose, which is usually not the reading they typed.
391    /// The two streams are independent — a field inserts each commit at its
392    /// caret and draws the latest pre-edit after it — so their relative order
393    /// within one pump carries no meaning.
394    ///
395    /// The keystrokes that edit a composition are the input method's: a key
396    /// it consumes while composing is not reported as a
397    /// [`Key`](ShellEvent::Key).
398    ///
399    /// Sent where [`ShellCaps::TEXT_IME`](crate::ShellCaps::TEXT_IME) is set.
400    /// A backend without it never sends this.
401    /// [`Shell::set_text_input_area`](crate::Shell::set_text_input_area) is how a
402    /// field tells the input method where to put that window and its
403    /// candidate list.
404    TextPreedit {
405        /// Which window.
406        window: WindowId,
407        /// When it happened.
408        time: EventTime,
409        /// The composition so far. Empty when the pre-edit ended.
410        text: String,
411        /// Where the input method's cursor sits in `text`, as a byte offset on
412        /// a `char` boundary, if it said. `None` for an empty `text`.
413        cursor: Option<usize>,
414    },
415
416    /// The set of monitors changed — hotplug, resolution change, or a layout
417    /// rearrangement.
418    ///
419    /// Carries no payload: [`Shell::monitors`](crate::Shell::monitors) is the
420    /// authority, and duplicating the list into the event would let a consumer
421    /// hold a stale copy that looks authoritative. A window's *own* scale
422    /// change arrives separately as
423    /// [`ScaleFactorChanged`](ShellEvent::ScaleFactorChanged).
424    MonitorsChanged,
425
426    /// A monitor was disconnected.
427    ///
428    /// Arrives before the [`MonitorsChanged`](ShellEvent::MonitorsChanged)
429    /// after which [`Shell::monitors`](crate::Shell::monitors) no longer lists
430    /// it, so a consumer can act on the id while it still knows what the id
431    /// named. After that the id names nothing, and it is never reused.
432    ///
433    /// By the time that `MonitorsChanged` arrives, every
434    /// [panel](crate::WindowRole::Panel) created for this monitor has been sent
435    /// a [`CloseRequested`](ShellEvent::CloseRequested): a bar on an unplugged
436    /// display has nowhere to be. A window system that closes the panel itself
437    /// may send that request before this event. Other windows stay wherever
438    /// the window system moves them.
439    MonitorRemoved {
440        /// The monitor that went.
441        monitor: MonitorId,
442    },
443
444    /// The window asked for the keyboard and the window system refused it.
445    ///
446    /// A [panel](crate::WindowRole::Panel) that takes the keyboard outright
447    /// ([`PanelKeyboard::Exclusive`](crate::PanelKeyboard::Exclusive)) asks
448    /// when it is shown. Win32 refuses the foreground to a process the user is
449    /// not working in, and AppKit can decline to make the panel the key
450    /// window; then no [`Focus`](ShellEvent::Focus) follows: keys keep going
451    /// to the window the user was in. This is how a program finds
452    /// out, without guessing a timeout — to retry, to say so, or to draw the
453    /// user's attention another way.
454    FocusRefused {
455        /// The window that asked.
456        window: WindowId,
457    },
458
459    /// A full-screen window opened on this panel's monitor, or the last one
460    /// closed: `active` says which.
461    ///
462    /// For a bar that should step aside while a game or a video is full
463    /// screen. Raised on Win32, for a [panel](crate::WindowRole::Panel) that
464    /// reserves its edge ([`Reserve::OwnExtent`](crate::Reserve::OwnExtent)),
465    /// from the shell's `ABN_FULLSCREENAPP`. Wayland and AppKit do not need
466    /// it: their compositors already draw a full-screen window over a bar, or
467    /// in a space of its own. X11 does not raise it either, so a bar there
468    /// that cares watches `_NET_WM_STATE_FULLSCREEN` itself.
469    FullScreenApp {
470        /// The panel told.
471        window: WindowId,
472        /// Whether a full-screen window is now open on its monitor.
473        active: bool,
474    },
475
476    /// A good time to present the window's next frame: the answer to a
477    /// [`request_frame`](crate::Shell::request_frame).
478    ///
479    /// **One per request**, however many requests were made before it came,
480    /// and none for a window destroyed first. Where
481    /// [`ShellCaps::FRAME_CALLBACK`](crate::ShellCaps::FRAME_CALLBACK) is set
482    /// the compositor sends it, and may hold it back for as long as nothing of
483    /// the window is visible — an output it has turned off, a hidden window —
484    /// which is when presenting would block or be wasted. Elsewhere it arrives
485    /// at the next [`pump`](crate::Shell::pump) after the request.
486    FrameReady {
487        /// The window that may present.
488        window: WindowId,
489    },
490
491    /// A file was dropped on the window.
492    ///
493    /// One event per file: a multi-file drop produces several. Only delivered
494    /// when the window was created with
495    /// [`WindowDesc::accept_drops`](crate::WindowDesc::accept_drops) and
496    /// [`ShellCaps::DRAG_DROP`](crate::ShellCaps::DRAG_DROP) is set.
497    DroppedFile {
498        /// Which window.
499        window: WindowId,
500        /// When it happened.
501        time: EventTime,
502        /// The dropped path. Not guaranteed to exist or to be readable — it
503        /// comes from another process, and checking is the consumer's job.
504        path: PathBuf,
505        /// Where in the window it was dropped, if the backend said.
506        position: Option<PhysicalPoint>,
507    },
508
509    /// The answer to a [`clipboard_request`](crate::Shell::clipboard_request).
510    ///
511    /// **Exactly one of these arrives for every accepted request**, and it is
512    /// the only thing that ever answers one. It may be several frames late: a
513    /// backend holds a read until it can answer it rather than reporting an
514    /// empty clipboard it has not actually looked at. See
515    /// [`clipboard`](crate::clipboard) for why reads are asynchronous and why
516    /// there is no "ask again later" outcome.
517    ClipboardData {
518        /// Which window asked.
519        window: WindowId,
520        /// Which request this answers.
521        request: ClipboardRequestId,
522        /// The format that was delivered, spelled the way the *other*
523        /// application spelled it.
524        ///
525        /// A [`ReceivedMime`] rather than a
526        /// [`MimeType`](crate::MimeType) because the peer chose this string,
527        /// not us: asking for `text/plain;charset=utf-8` and being answered
528        /// with `text/plain` is normal and must round-trip verbatim. Compare
529        /// with [`ReceivedMime::matches`], never with string equality.
530        ///
531        /// For [`Empty`](ClipboardContent::Empty) and
532        /// [`Unavailable`](ClipboardContent::Unavailable) there is no peer
533        /// spelling to report, so this is the format that was *asked* for.
534        mime: ReceivedMime,
535        /// What the read produced — bytes, an empty clipboard, or a failure.
536        /// See [`ClipboardContent`], which exists because the three are not one
537        /// case.
538        content: ClipboardContent,
539    },
540
541    /// An assistive technology — a screen reader, a magnifier, voice control
542    /// — started reading `window`.
543    ///
544    /// From here until
545    /// [`AccessibilityDeactivated`](ShellEvent::AccessibilityDeactivated), the
546    /// program sends the window's accessibility tree with
547    /// [`update_accessibility`](crate::Shell::update_accessibility): a whole
548    /// tree first, then what changed. Before it nobody is reading, and building
549    /// a tree is wasted work.
550    #[cfg(feature = "accesskit")]
551    AccessibilityActivated {
552        /// The window being read.
553        window: WindowId,
554    },
555
556    /// An assistive technology asked for something done to a node of
557    /// `window`'s accessibility tree: focus it, click it, scroll it into view,
558    /// set its value.
559    ///
560    /// `request.target_node` is the node, by the
561    /// [`NodeId`](accesskit::NodeId) the program gave it. Act on it as the
562    /// matching input would have; the result shows in the next tree update,
563    /// and nothing else answers the request.
564    #[cfg(feature = "accesskit")]
565    AccessibilityAction {
566        /// The window the node is in.
567        window: WindowId,
568        /// What was asked, and of which node.
569        request: accesskit::ActionRequest,
570    },
571
572    /// The last assistive technology reading `window` stopped. Trees sent from
573    /// here on are dropped until the next
574    /// [`AccessibilityActivated`](ShellEvent::AccessibilityActivated), which
575    /// wants a whole tree again.
576    #[cfg(feature = "accesskit")]
577    AccessibilityDeactivated {
578        /// The window no longer read.
579        window: WindowId,
580    },
581}
582
583impl ShellEvent {
584    /// Which window this event concerns, if any.
585    ///
586    /// `None` only for [`MonitorsChanged`](ShellEvent::MonitorsChanged) and
587    /// [`MonitorRemoved`](ShellEvent::MonitorRemoved), which are properties of
588    /// the session rather than of a window. A multi-window consumer routes on
589    /// this.
590    #[must_use]
591    pub const fn window(&self) -> Option<WindowId> {
592        match self {
593            Self::Resized { window, .. }
594            | Self::ScaleFactorChanged { window, .. }
595            | Self::CloseRequested { window }
596            | Self::WindowDestroyed { window }
597            | Self::Focus { window, .. }
598            | Self::Key { window, .. }
599            | Self::PointerMotion { window, .. }
600            | Self::PointerFocus { window, .. }
601            | Self::Button { window, .. }
602            | Self::Wheel { window, .. }
603            | Self::Touch { window, .. }
604            | Self::TextCommit { window, .. }
605            | Self::TextPreedit { window, .. }
606            | Self::DroppedFile { window, .. }
607            | Self::FocusRefused { window }
608            | Self::FullScreenApp { window, .. }
609            | Self::FrameReady { window }
610            | Self::ClipboardData { window, .. } => Some(*window),
611            #[cfg(feature = "accesskit")]
612            Self::AccessibilityActivated { window }
613            | Self::AccessibilityAction { window, .. }
614            | Self::AccessibilityDeactivated { window } => Some(*window),
615            Self::MonitorsChanged | Self::MonitorRemoved { .. } => None,
616        }
617    }
618
619    /// When this event happened, for the variants that are input samples.
620    ///
621    /// `None` for state transitions; see the [module docs](self) for why they
622    /// deliberately have no timestamp.
623    #[must_use]
624    pub const fn time(&self) -> Option<EventTime> {
625        match self {
626            Self::Key { time, .. }
627            | Self::PointerMotion { time, .. }
628            | Self::PointerFocus { time, .. }
629            | Self::Button { time, .. }
630            | Self::Wheel { time, .. }
631            | Self::Touch { time, .. }
632            | Self::TextCommit { time, .. }
633            | Self::TextPreedit { time, .. }
634            | Self::DroppedFile { time, .. } => Some(*time),
635            Self::Resized { .. }
636            | Self::ScaleFactorChanged { .. }
637            | Self::CloseRequested { .. }
638            | Self::WindowDestroyed { .. }
639            | Self::Focus { .. }
640            | Self::MonitorsChanged
641            | Self::MonitorRemoved { .. }
642            | Self::FocusRefused { .. }
643            | Self::FullScreenApp { .. }
644            | Self::FrameReady { .. }
645            | Self::ClipboardData { .. } => None,
646            #[cfg(feature = "accesskit")]
647            Self::AccessibilityActivated { .. }
648            | Self::AccessibilityAction { .. }
649            | Self::AccessibilityDeactivated { .. } => None,
650        }
651    }
652
653    /// Whether this event feeds the input pipeline rather than the window
654    /// lifecycle.
655    ///
656    /// The P2 action layer subscribes to exactly this subset.
657    #[inline]
658    #[must_use]
659    pub const fn is_input(&self) -> bool {
660        self.time().is_some()
661    }
662
663    /// A short, stable name for logs and test assertions.
664    ///
665    /// Stable because tests assert on sequences of these: a scripted
666    /// `HeadlessShell` session compares `["Resized", "Focus", "Key", …]`, which
667    /// stays readable in a failure message in a way that a `Debug` dump of the
668    /// full payloads does not.
669    #[must_use]
670    pub const fn name(&self) -> &'static str {
671        match self {
672            Self::Resized { .. } => "Resized",
673            Self::ScaleFactorChanged { .. } => "ScaleFactorChanged",
674            Self::CloseRequested { .. } => "CloseRequested",
675            Self::WindowDestroyed { .. } => "WindowDestroyed",
676            Self::Focus { .. } => "Focus",
677            Self::Key { .. } => "Key",
678            Self::PointerMotion { .. } => "PointerMotion",
679            Self::PointerFocus { .. } => "PointerFocus",
680            Self::Button { .. } => "Button",
681            Self::Wheel { .. } => "Wheel",
682            Self::Touch { .. } => "Touch",
683            Self::TextCommit { .. } => "TextCommit",
684            Self::TextPreedit { .. } => "TextPreedit",
685            Self::MonitorsChanged => "MonitorsChanged",
686            Self::MonitorRemoved { .. } => "MonitorRemoved",
687            Self::FocusRefused { .. } => "FocusRefused",
688            Self::FullScreenApp { .. } => "FullScreenApp",
689            Self::FrameReady { .. } => "FrameReady",
690            Self::DroppedFile { .. } => "DroppedFile",
691            Self::ClipboardData { .. } => "ClipboardData",
692            #[cfg(feature = "accesskit")]
693            Self::AccessibilityActivated { .. } => "AccessibilityActivated",
694            #[cfg(feature = "accesskit")]
695            Self::AccessibilityAction { .. } => "AccessibilityAction",
696            #[cfg(feature = "accesskit")]
697            Self::AccessibilityDeactivated { .. } => "AccessibilityDeactivated",
698        }
699    }
700}
701
702#[cfg(test)]
703mod tests {
704    use super::*;
705    use core::time::Duration;
706    use crcbl_core::Pool;
707
708    fn window_id() -> WindowId {
709        let mut pool: Pool<u8> = Pool::new();
710        pool.insert(0).cast()
711    }
712
713    fn key_event(time: EventTime) -> ShellEvent {
714        ShellEvent::Key {
715            window: window_id(),
716            device: DeviceId(1),
717            time,
718            scancode: Scancode(57),
719            key_code: Some(KeyCode::Space),
720            keysym: Keysym::from_char(' '),
721            shortcut_keysym: Keysym::from_char(' '),
722            state: ButtonState::Pressed,
723            repeat: false,
724            modifiers: Modifiers::empty(),
725        }
726    }
727
728    #[test]
729    fn a_clipboard_answer_carries_the_peers_spelling() {
730        let event = ShellEvent::ClipboardData {
731            window: window_id(),
732            request: ClipboardRequestId(3),
733            mime: ReceivedMime::new("text/plain"),
734            content: ClipboardContent::Bytes(b"pasted".to_vec()),
735        };
736        let ShellEvent::ClipboardData { mime, content, .. } = &event else {
737            panic!("wrong variant");
738        };
739        assert_eq!(mime.as_str(), "text/plain");
740        assert!(mime.matches(crate::MimeType::TextUtf8));
741        assert_eq!(content.bytes(), Some(&b"pasted"[..]));
742        assert_eq!(content.text(), Some("pasted"));
743
744        // The three outcomes a caller must be able to tell apart. An empty
745        // *payload* is a successful read; an empty *clipboard* is not the same
746        // thing; and neither is a failure.
747        assert_eq!(ClipboardContent::Bytes(Vec::new()).bytes(), Some(&[][..]));
748        assert_ne!(ClipboardContent::Bytes(Vec::new()), ClipboardContent::Empty);
749        assert_eq!(ClipboardContent::Empty.bytes(), None);
750        assert_eq!(ClipboardContent::Unavailable.bytes(), None);
751        assert_ne!(ClipboardContent::Empty, ClipboardContent::Unavailable);
752        assert_eq!(ClipboardContent::Unavailable.name(), "Unavailable");
753        // Invalid UTF-8 is refused rather than lossily replaced.
754        assert_eq!(ClipboardContent::Bytes(vec![0xff]).text(), None);
755        assert_eq!(
756            event.time(),
757            None,
758            "a clipboard answer is not an input sample"
759        );
760    }
761
762    #[test]
763    fn input_events_carry_a_usable_timestamp_and_lifecycle_events_do_not() {
764        let pressed = key_event(EventTime::from_millis(1_000));
765        let released = key_event(EventTime::from_millis(1_180));
766
767        // This subtraction is the whole reason timestamps exist: 180 ms is a
768        // "tap", not a "hold", and no frame boundary got a vote.
769        let held = released
770            .time()
771            .expect("input")
772            .saturating_since(pressed.time().expect("input"));
773        assert_eq!(held, Duration::from_millis(180));
774
775        assert!(pressed.is_input());
776        assert!(!ShellEvent::MonitorsChanged.is_input());
777        assert_eq!(
778            ShellEvent::Resized {
779                window: window_id(),
780                size: PhysicalSize::new(1, 1),
781                scale_factor: 1.0,
782            }
783            .time(),
784            None
785        );
786    }
787
788    #[test]
789    fn every_variant_reports_its_window_and_a_stable_name() {
790        let window = window_id();
791        let events = [
792            ShellEvent::Resized {
793                window,
794                size: PhysicalSize::new(640, 360),
795                scale_factor: 1.0,
796            },
797            ShellEvent::ScaleFactorChanged {
798                window,
799                scale_factor: 2.0,
800                size: PhysicalSize::new(1280, 720),
801            },
802            ShellEvent::CloseRequested { window },
803            ShellEvent::WindowDestroyed { window },
804            ShellEvent::Focus {
805                window,
806                focused: true,
807            },
808            key_event(EventTime::ZERO),
809            ShellEvent::PointerMotion {
810                window,
811                device: DeviceId::UNKNOWN,
812                time: EventTime::ZERO,
813                abs: Some(PhysicalPoint::new(1.0, 2.0)),
814                raw_delta: Some((0.5, -0.5)),
815            },
816            ShellEvent::PointerFocus {
817                window,
818                device: DeviceId::UNKNOWN,
819                time: EventTime::ZERO,
820                entered: true,
821                position: None,
822            },
823            ShellEvent::Button {
824                window,
825                device: DeviceId::UNKNOWN,
826                time: EventTime::ZERO,
827                button: PointerButton::Left,
828                state: ButtonState::Pressed,
829                position: None,
830                modifiers: Modifiers::CTRL,
831            },
832            ShellEvent::Wheel {
833                window,
834                device: DeviceId::UNKNOWN,
835                time: EventTime::ZERO,
836                delta: ScrollDelta::Lines { x: 0.0, y: 1.0 },
837                position: None,
838                modifiers: Modifiers::empty(),
839            },
840            ShellEvent::Touch {
841                window,
842                device: DeviceId::UNKNOWN,
843                time: EventTime::ZERO,
844                contact: ContactId(1),
845                phase: TouchPhase::Began,
846                position: PhysicalPoint::new(4.0, 5.0),
847            },
848            ShellEvent::TextCommit {
849                window,
850                time: EventTime::ZERO,
851                text: "は".to_string(),
852            },
853            ShellEvent::DroppedFile {
854                window,
855                time: EventTime::ZERO,
856                path: PathBuf::from("/tmp/scene.ron"),
857                position: None,
858            },
859            ShellEvent::ClipboardData {
860                window,
861                request: ClipboardRequestId(1),
862                mime: ReceivedMime::from(crate::MimeType::TextUtf8),
863                content: ClipboardContent::Empty,
864            },
865            ShellEvent::MonitorsChanged,
866            ShellEvent::MonitorRemoved {
867                monitor: MonitorId(2),
868            },
869            ShellEvent::FocusRefused { window },
870            ShellEvent::FullScreenApp {
871                window,
872                active: true,
873            },
874            ShellEvent::FrameReady { window },
875        ];
876        #[cfg(feature = "accesskit")]
877        let events = {
878            let mut events = events.to_vec();
879            events.extend([
880                ShellEvent::AccessibilityActivated { window },
881                ShellEvent::AccessibilityAction {
882                    window,
883                    request: accesskit::ActionRequest {
884                        action: accesskit::Action::Click,
885                        target_tree: accesskit::TreeId::ROOT,
886                        target_node: accesskit::NodeId(1),
887                        data: None,
888                    },
889                },
890                ShellEvent::AccessibilityDeactivated { window },
891            ]);
892            events
893        };
894
895        let mut names = Vec::new();
896        for event in &events {
897            names.push(event.name());
898            match event {
899                ShellEvent::MonitorsChanged | ShellEvent::MonitorRemoved { .. } => {
900                    assert_eq!(event.window(), None);
901                }
902                _ => assert_eq!(event.window(), Some(window), "{}", event.name()),
903            }
904        }
905        let count = names.len();
906        names.sort_unstable();
907        names.dedup();
908        assert_eq!(names.len(), count, "event names must be unique");
909    }
910
911    /// Two fingers are two contacts, and the event says which is which.
912    ///
913    /// The shape claim in one test: a batch of touch events keyed by
914    /// [`ContactId`] can be reduced to a per-finger position, the two fingers do
915    /// not share an id, and moving one does not move the other. This is what the
916    /// seam is *for* — before it, a second finger had nowhere to go and the web
917    /// backend dropped it.
918    #[test]
919    fn a_batch_of_contacts_keeps_the_two_fingers_apart() {
920        let window = window_id();
921        let touch = |contact: u32, phase: TouchPhase, x: f64, y: f64| ShellEvent::Touch {
922            window,
923            device: DeviceId(3),
924            time: EventTime::from_millis(1),
925            contact: ContactId(contact),
926            phase,
927            position: PhysicalPoint::new(x, y),
928        };
929        let batch = [
930            touch(7, TouchPhase::Began, 10.0, 20.0),
931            touch(9, TouchPhase::Began, 300.0, 400.0),
932            touch(9, TouchPhase::Moved, 305.0, 410.0),
933            touch(7, TouchPhase::Ended, 10.0, 20.0),
934        ];
935
936        let mut live: Vec<(ContactId, TouchPhase, PhysicalPoint)> = Vec::new();
937        for event in &batch {
938            let ShellEvent::Touch {
939                contact,
940                phase,
941                position,
942                ..
943            } = event
944            else {
945                panic!("wrong variant");
946            };
947            live.retain(|(id, ..)| id != contact);
948            if !phase.ends_contact() {
949                live.push((*contact, *phase, *position));
950            }
951        }
952
953        // One finger left, at the place *its own* moves put it — not at the
954        // other's, and not at the average of the two.
955        assert_eq!(
956            live,
957            vec![(
958                ContactId(9),
959                TouchPhase::Moved,
960                PhysicalPoint::new(305.0, 410.0)
961            )]
962        );
963        assert!(TouchPhase::Ended.ends_contact());
964        assert!(TouchPhase::Cancelled.ends_contact());
965        assert!(!TouchPhase::Began.ends_contact());
966        assert!(!TouchPhase::Moved.ends_contact());
967        // A cancel is not an end: they agree that the contact is over and
968        // disagree about everything a consumer does next.
969        assert_ne!(TouchPhase::Ended, TouchPhase::Cancelled);
970        assert!(batch[0].is_input(), "a contact is an input sample");
971        assert_eq!(batch[0].time(), Some(EventTime::from_millis(1)));
972    }
973
974    #[test]
975    fn locked_pointer_motion_has_no_absolute_position() {
976        // The invariant `PointerMode::Locked` documents, expressed as a value.
977        let event = ShellEvent::PointerMotion {
978            window: window_id(),
979            device: DeviceId(2),
980            time: EventTime::from_micros(16_666),
981            abs: None,
982            raw_delta: Some((12.0, -3.0)),
983        };
984        let ShellEvent::PointerMotion { abs, raw_delta, .. } = event else {
985            panic!("wrong variant");
986        };
987        assert_eq!(abs, None);
988        assert_eq!(raw_delta, Some((12.0, -3.0)));
989    }
990}