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