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 file was dropped on the window.
445 ///
446 /// One event per file: a multi-file drop produces several. Only delivered
447 /// when the window was created with
448 /// [`WindowDesc::accept_drops`](crate::WindowDesc::accept_drops) and
449 /// [`ShellCaps::DRAG_DROP`](crate::ShellCaps::DRAG_DROP) is set.
450 DroppedFile {
451 /// Which window.
452 window: WindowId,
453 /// When it happened.
454 time: EventTime,
455 /// The dropped path. Not guaranteed to exist or to be readable — it
456 /// comes from another process, and checking is the consumer's job.
457 path: PathBuf,
458 /// Where in the window it was dropped, if the backend said.
459 position: Option<PhysicalPoint>,
460 },
461
462 /// The answer to a [`clipboard_request`](crate::Shell::clipboard_request).
463 ///
464 /// **Exactly one of these arrives for every accepted request**, and it is
465 /// the only thing that ever answers one. It may be several frames late: a
466 /// backend holds a read until it can answer it rather than reporting an
467 /// empty clipboard it has not actually looked at. See
468 /// [`clipboard`](crate::clipboard) for why reads are asynchronous and why
469 /// there is no "ask again later" outcome.
470 ClipboardData {
471 /// Which window asked.
472 window: WindowId,
473 /// Which request this answers.
474 request: ClipboardRequestId,
475 /// The format that was delivered, spelled the way the *other*
476 /// application spelled it.
477 ///
478 /// A [`ReceivedMime`] rather than a
479 /// [`MimeType`](crate::MimeType) because the peer chose this string,
480 /// not us: asking for `text/plain;charset=utf-8` and being answered
481 /// with `text/plain` is normal and must round-trip verbatim. Compare
482 /// with [`ReceivedMime::matches`], never with string equality.
483 ///
484 /// For [`Empty`](ClipboardContent::Empty) and
485 /// [`Unavailable`](ClipboardContent::Unavailable) there is no peer
486 /// spelling to report, so this is the format that was *asked* for.
487 mime: ReceivedMime,
488 /// What the read produced — bytes, an empty clipboard, or a failure.
489 /// See [`ClipboardContent`], which exists because the three are not one
490 /// case.
491 content: ClipboardContent,
492 },
493
494 /// An assistive technology — a screen reader, a magnifier, voice control
495 /// — started reading `window`.
496 ///
497 /// From here until
498 /// [`AccessibilityDeactivated`](ShellEvent::AccessibilityDeactivated), the
499 /// program sends the window's accessibility tree with
500 /// [`update_accessibility`](crate::Shell::update_accessibility): a whole
501 /// tree first, then what changed. Before it nobody is reading, and building
502 /// a tree is wasted work.
503 #[cfg(feature = "accesskit")]
504 AccessibilityActivated {
505 /// The window being read.
506 window: WindowId,
507 },
508
509 /// An assistive technology asked for something done to a node of
510 /// `window`'s accessibility tree: focus it, click it, scroll it into view,
511 /// set its value.
512 ///
513 /// `request.target_node` is the node, by the
514 /// [`NodeId`](accesskit::NodeId) the program gave it. Act on it as the
515 /// matching input would have; the result shows in the next tree update,
516 /// and nothing else answers the request.
517 #[cfg(feature = "accesskit")]
518 AccessibilityAction {
519 /// The window the node is in.
520 window: WindowId,
521 /// What was asked, and of which node.
522 request: accesskit::ActionRequest,
523 },
524
525 /// The last assistive technology reading `window` stopped. Trees sent from
526 /// here on are dropped until the next
527 /// [`AccessibilityActivated`](ShellEvent::AccessibilityActivated), which
528 /// wants a whole tree again.
529 #[cfg(feature = "accesskit")]
530 AccessibilityDeactivated {
531 /// The window no longer read.
532 window: WindowId,
533 },
534}
535
536impl ShellEvent {
537 /// Which window this event concerns, if any.
538 ///
539 /// `None` only for [`MonitorsChanged`](ShellEvent::MonitorsChanged) and
540 /// [`MonitorRemoved`](ShellEvent::MonitorRemoved), which are properties of
541 /// the session rather than of a window. A multi-window consumer routes on
542 /// this.
543 #[must_use]
544 pub const fn window(&self) -> Option<WindowId> {
545 match self {
546 Self::Resized { window, .. }
547 | Self::ScaleFactorChanged { window, .. }
548 | Self::CloseRequested { window }
549 | Self::WindowDestroyed { window }
550 | Self::Focus { window, .. }
551 | Self::Key { window, .. }
552 | Self::PointerMotion { window, .. }
553 | Self::PointerFocus { window, .. }
554 | Self::Button { window, .. }
555 | Self::Wheel { window, .. }
556 | Self::Touch { window, .. }
557 | Self::TextCommit { window, .. }
558 | Self::TextPreedit { window, .. }
559 | Self::DroppedFile { window, .. }
560 | Self::FocusRefused { window }
561 | Self::FullScreenApp { window, .. }
562 | Self::ClipboardData { window, .. } => Some(*window),
563 #[cfg(feature = "accesskit")]
564 Self::AccessibilityActivated { window }
565 | Self::AccessibilityAction { window, .. }
566 | Self::AccessibilityDeactivated { window } => Some(*window),
567 Self::MonitorsChanged | Self::MonitorRemoved { .. } => None,
568 }
569 }
570
571 /// When this event happened, for the variants that are input samples.
572 ///
573 /// `None` for state transitions; see the [module docs](self) for why they
574 /// deliberately have no timestamp.
575 #[must_use]
576 pub const fn time(&self) -> Option<EventTime> {
577 match self {
578 Self::Key { time, .. }
579 | Self::PointerMotion { time, .. }
580 | Self::PointerFocus { time, .. }
581 | Self::Button { time, .. }
582 | Self::Wheel { time, .. }
583 | Self::Touch { time, .. }
584 | Self::TextCommit { time, .. }
585 | Self::TextPreedit { time, .. }
586 | Self::DroppedFile { time, .. } => Some(*time),
587 Self::Resized { .. }
588 | Self::ScaleFactorChanged { .. }
589 | Self::CloseRequested { .. }
590 | Self::WindowDestroyed { .. }
591 | Self::Focus { .. }
592 | Self::MonitorsChanged
593 | Self::MonitorRemoved { .. }
594 | Self::FocusRefused { .. }
595 | Self::FullScreenApp { .. }
596 | Self::ClipboardData { .. } => None,
597 #[cfg(feature = "accesskit")]
598 Self::AccessibilityActivated { .. }
599 | Self::AccessibilityAction { .. }
600 | Self::AccessibilityDeactivated { .. } => None,
601 }
602 }
603
604 /// Whether this event feeds the input pipeline rather than the window
605 /// lifecycle.
606 ///
607 /// The P2 action layer subscribes to exactly this subset.
608 #[inline]
609 #[must_use]
610 pub const fn is_input(&self) -> bool {
611 self.time().is_some()
612 }
613
614 /// A short, stable name for logs and test assertions.
615 ///
616 /// Stable because tests assert on sequences of these: a scripted
617 /// `HeadlessShell` session compares `["Resized", "Focus", "Key", …]`, which
618 /// stays readable in a failure message in a way that a `Debug` dump of the
619 /// full payloads does not.
620 #[must_use]
621 pub const fn name(&self) -> &'static str {
622 match self {
623 Self::Resized { .. } => "Resized",
624 Self::ScaleFactorChanged { .. } => "ScaleFactorChanged",
625 Self::CloseRequested { .. } => "CloseRequested",
626 Self::WindowDestroyed { .. } => "WindowDestroyed",
627 Self::Focus { .. } => "Focus",
628 Self::Key { .. } => "Key",
629 Self::PointerMotion { .. } => "PointerMotion",
630 Self::PointerFocus { .. } => "PointerFocus",
631 Self::Button { .. } => "Button",
632 Self::Wheel { .. } => "Wheel",
633 Self::Touch { .. } => "Touch",
634 Self::TextCommit { .. } => "TextCommit",
635 Self::TextPreedit { .. } => "TextPreedit",
636 Self::MonitorsChanged => "MonitorsChanged",
637 Self::MonitorRemoved { .. } => "MonitorRemoved",
638 Self::FocusRefused { .. } => "FocusRefused",
639 Self::FullScreenApp { .. } => "FullScreenApp",
640 Self::DroppedFile { .. } => "DroppedFile",
641 Self::ClipboardData { .. } => "ClipboardData",
642 #[cfg(feature = "accesskit")]
643 Self::AccessibilityActivated { .. } => "AccessibilityActivated",
644 #[cfg(feature = "accesskit")]
645 Self::AccessibilityAction { .. } => "AccessibilityAction",
646 #[cfg(feature = "accesskit")]
647 Self::AccessibilityDeactivated { .. } => "AccessibilityDeactivated",
648 }
649 }
650}
651
652#[cfg(test)]
653mod tests {
654 use super::*;
655 use core::time::Duration;
656 use crcbl_core::Pool;
657
658 fn window_id() -> WindowId {
659 let mut pool: Pool<u8> = Pool::new();
660 pool.insert(0).cast()
661 }
662
663 fn key_event(time: EventTime) -> ShellEvent {
664 ShellEvent::Key {
665 window: window_id(),
666 device: DeviceId(1),
667 time,
668 scancode: Scancode(57),
669 key_code: Some(KeyCode::Space),
670 keysym: Keysym::from_char(' '),
671 state: ButtonState::Pressed,
672 repeat: false,
673 modifiers: Modifiers::empty(),
674 }
675 }
676
677 #[test]
678 fn a_clipboard_answer_carries_the_peers_spelling() {
679 let event = ShellEvent::ClipboardData {
680 window: window_id(),
681 request: ClipboardRequestId(3),
682 mime: ReceivedMime::new("text/plain"),
683 content: ClipboardContent::Bytes(b"pasted".to_vec()),
684 };
685 let ShellEvent::ClipboardData { mime, content, .. } = &event else {
686 panic!("wrong variant");
687 };
688 assert_eq!(mime.as_str(), "text/plain");
689 assert!(mime.matches(crate::MimeType::TextUtf8));
690 assert_eq!(content.bytes(), Some(&b"pasted"[..]));
691 assert_eq!(content.text(), Some("pasted"));
692
693 // The three outcomes a caller must be able to tell apart. An empty
694 // *payload* is a successful read; an empty *clipboard* is not the same
695 // thing; and neither is a failure.
696 assert_eq!(ClipboardContent::Bytes(Vec::new()).bytes(), Some(&[][..]));
697 assert_ne!(ClipboardContent::Bytes(Vec::new()), ClipboardContent::Empty);
698 assert_eq!(ClipboardContent::Empty.bytes(), None);
699 assert_eq!(ClipboardContent::Unavailable.bytes(), None);
700 assert_ne!(ClipboardContent::Empty, ClipboardContent::Unavailable);
701 assert_eq!(ClipboardContent::Unavailable.name(), "Unavailable");
702 // Invalid UTF-8 is refused rather than lossily replaced.
703 assert_eq!(ClipboardContent::Bytes(vec![0xff]).text(), None);
704 assert_eq!(
705 event.time(),
706 None,
707 "a clipboard answer is not an input sample"
708 );
709 }
710
711 #[test]
712 fn input_events_carry_a_usable_timestamp_and_lifecycle_events_do_not() {
713 let pressed = key_event(EventTime::from_millis(1_000));
714 let released = key_event(EventTime::from_millis(1_180));
715
716 // This subtraction is the whole reason timestamps exist: 180 ms is a
717 // "tap", not a "hold", and no frame boundary got a vote.
718 let held = released
719 .time()
720 .expect("input")
721 .saturating_since(pressed.time().expect("input"));
722 assert_eq!(held, Duration::from_millis(180));
723
724 assert!(pressed.is_input());
725 assert!(!ShellEvent::MonitorsChanged.is_input());
726 assert_eq!(
727 ShellEvent::Resized {
728 window: window_id(),
729 size: PhysicalSize::new(1, 1),
730 scale_factor: 1.0,
731 }
732 .time(),
733 None
734 );
735 }
736
737 #[test]
738 fn every_variant_reports_its_window_and_a_stable_name() {
739 let window = window_id();
740 let events = [
741 ShellEvent::Resized {
742 window,
743 size: PhysicalSize::new(640, 360),
744 scale_factor: 1.0,
745 },
746 ShellEvent::ScaleFactorChanged {
747 window,
748 scale_factor: 2.0,
749 size: PhysicalSize::new(1280, 720),
750 },
751 ShellEvent::CloseRequested { window },
752 ShellEvent::WindowDestroyed { window },
753 ShellEvent::Focus {
754 window,
755 focused: true,
756 },
757 key_event(EventTime::ZERO),
758 ShellEvent::PointerMotion {
759 window,
760 device: DeviceId::UNKNOWN,
761 time: EventTime::ZERO,
762 abs: Some(PhysicalPoint::new(1.0, 2.0)),
763 raw_delta: Some((0.5, -0.5)),
764 },
765 ShellEvent::PointerFocus {
766 window,
767 device: DeviceId::UNKNOWN,
768 time: EventTime::ZERO,
769 entered: true,
770 position: None,
771 },
772 ShellEvent::Button {
773 window,
774 device: DeviceId::UNKNOWN,
775 time: EventTime::ZERO,
776 button: PointerButton::Left,
777 state: ButtonState::Pressed,
778 position: None,
779 modifiers: Modifiers::CTRL,
780 },
781 ShellEvent::Wheel {
782 window,
783 device: DeviceId::UNKNOWN,
784 time: EventTime::ZERO,
785 delta: ScrollDelta::Lines { x: 0.0, y: 1.0 },
786 position: None,
787 modifiers: Modifiers::empty(),
788 },
789 ShellEvent::Touch {
790 window,
791 device: DeviceId::UNKNOWN,
792 time: EventTime::ZERO,
793 contact: ContactId(1),
794 phase: TouchPhase::Began,
795 position: PhysicalPoint::new(4.0, 5.0),
796 },
797 ShellEvent::TextCommit {
798 window,
799 time: EventTime::ZERO,
800 text: "は".to_string(),
801 },
802 ShellEvent::DroppedFile {
803 window,
804 time: EventTime::ZERO,
805 path: PathBuf::from("/tmp/scene.ron"),
806 position: None,
807 },
808 ShellEvent::ClipboardData {
809 window,
810 request: ClipboardRequestId(1),
811 mime: ReceivedMime::from(crate::MimeType::TextUtf8),
812 content: ClipboardContent::Empty,
813 },
814 ShellEvent::MonitorsChanged,
815 ShellEvent::MonitorRemoved {
816 monitor: MonitorId(2),
817 },
818 ShellEvent::FocusRefused { window },
819 ShellEvent::FullScreenApp {
820 window,
821 active: true,
822 },
823 ];
824 #[cfg(feature = "accesskit")]
825 let events = {
826 let mut events = events.to_vec();
827 events.extend([
828 ShellEvent::AccessibilityActivated { window },
829 ShellEvent::AccessibilityAction {
830 window,
831 request: accesskit::ActionRequest {
832 action: accesskit::Action::Click,
833 target_tree: accesskit::TreeId::ROOT,
834 target_node: accesskit::NodeId(1),
835 data: None,
836 },
837 },
838 ShellEvent::AccessibilityDeactivated { window },
839 ]);
840 events
841 };
842
843 let mut names = Vec::new();
844 for event in &events {
845 names.push(event.name());
846 match event {
847 ShellEvent::MonitorsChanged | ShellEvent::MonitorRemoved { .. } => {
848 assert_eq!(event.window(), None);
849 }
850 _ => assert_eq!(event.window(), Some(window), "{}", event.name()),
851 }
852 }
853 let count = names.len();
854 names.sort_unstable();
855 names.dedup();
856 assert_eq!(names.len(), count, "event names must be unique");
857 }
858
859 /// Two fingers are two contacts, and the event says which is which.
860 ///
861 /// The shape claim in one test: a batch of touch events keyed by
862 /// [`ContactId`] can be reduced to a per-finger position, the two fingers do
863 /// not share an id, and moving one does not move the other. This is what the
864 /// seam is *for* — before it, a second finger had nowhere to go and the web
865 /// backend dropped it.
866 #[test]
867 fn a_batch_of_contacts_keeps_the_two_fingers_apart() {
868 let window = window_id();
869 let touch = |contact: u32, phase: TouchPhase, x: f64, y: f64| ShellEvent::Touch {
870 window,
871 device: DeviceId(3),
872 time: EventTime::from_millis(1),
873 contact: ContactId(contact),
874 phase,
875 position: PhysicalPoint::new(x, y),
876 };
877 let batch = [
878 touch(7, TouchPhase::Began, 10.0, 20.0),
879 touch(9, TouchPhase::Began, 300.0, 400.0),
880 touch(9, TouchPhase::Moved, 305.0, 410.0),
881 touch(7, TouchPhase::Ended, 10.0, 20.0),
882 ];
883
884 let mut live: Vec<(ContactId, TouchPhase, PhysicalPoint)> = Vec::new();
885 for event in &batch {
886 let ShellEvent::Touch {
887 contact,
888 phase,
889 position,
890 ..
891 } = event
892 else {
893 panic!("wrong variant");
894 };
895 live.retain(|(id, ..)| id != contact);
896 if !phase.ends_contact() {
897 live.push((*contact, *phase, *position));
898 }
899 }
900
901 // One finger left, at the place *its own* moves put it — not at the
902 // other's, and not at the average of the two.
903 assert_eq!(
904 live,
905 vec![(
906 ContactId(9),
907 TouchPhase::Moved,
908 PhysicalPoint::new(305.0, 410.0)
909 )]
910 );
911 assert!(TouchPhase::Ended.ends_contact());
912 assert!(TouchPhase::Cancelled.ends_contact());
913 assert!(!TouchPhase::Began.ends_contact());
914 assert!(!TouchPhase::Moved.ends_contact());
915 // A cancel is not an end: they agree that the contact is over and
916 // disagree about everything a consumer does next.
917 assert_ne!(TouchPhase::Ended, TouchPhase::Cancelled);
918 assert!(batch[0].is_input(), "a contact is an input sample");
919 assert_eq!(batch[0].time(), Some(EventTime::from_millis(1)));
920 }
921
922 #[test]
923 fn locked_pointer_motion_has_no_absolute_position() {
924 // The invariant `PointerMode::Locked` documents, expressed as a value.
925 let event = ShellEvent::PointerMotion {
926 window: window_id(),
927 device: DeviceId(2),
928 time: EventTime::from_micros(16_666),
929 abs: None,
930 raw_delta: Some((12.0, -3.0)),
931 };
932 let ShellEvent::PointerMotion { abs, raw_delta, .. } = event else {
933 panic!("wrong variant");
934 };
935 assert_eq!(abs, None);
936 assert_eq!(raw_delta, Some((12.0, -3.0)));
937 }
938}