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