crcbl-shell 0.15.0

Crucible windowing shell: own Wayland, X11, Web/canvas and headless backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
//! What the window procedure records, and how a storm of it is collapsed.
//!
//! # Why the procedure records instead of acting
//!
//! A `WNDPROC` is called **by the system, re-entrantly, while the shell is
//! somewhere else**. `SetWindowPos`, `ShowWindow`, `SetWindowTextW` and
//! `DestroyWindow` all dispatch messages synchronously before they return, so
//! any of them called from a [`Shell`](crate::Shell) method runs the window
//! procedure *inside* that method — with `&mut self` already borrowed, and with
//! the shell's own invariants halfway through an update.
//!
//! So the procedure translates nothing and looks nothing up. It converts a
//! message into one of these, pushes it, and returns; [`pump`](crate::Shell::pump)
//! resolves the `HWND` against the window pool, updates state and produces the
//! [`ShellEvent`](crate::ShellEvent). The X11 backend has the same split for
//! the same reason and a milder version of the problem — there, events arrive
//! from a socket and re-entrancy is impossible; here it is the normal case.
//!
//! A window is named by its `HWND` as an `isize` rather than as a pointer, so
//! this type stays `Copy`, comparable and printable, and so nothing in the
//! queue is a handle that could be dereferenced after the window died.
//!
//! # The resize storm, and the modal loop behind it
//!
//! Dragging a window's edge produces a `WM_SIZE` per mouse movement — hundreds
//! per second — and, worse, produces them from inside a **modal message loop
//! the system runs itself** between `WM_ENTERSIZEMOVE` and `WM_EXITSIZEMOVE`.
//! `pump` does not return during a drag, so nothing drains the queue until the
//! user lets go. See the [module docs](super) for what that costs and why this
//! backend accepts it.
//!
//! [`enqueue`] is what keeps that from being a memory leak *and* an event
//! flood: a resize supersedes a pending resize for the same window, so a
//! three-second drag arrives as one [`Resized`](crate::ShellEvent::Resized)
//! carrying the size the window actually ended at. Coalescing is safe here in a
//! way it would not be for input, because a resize is a **state**, not an
//! event: the intermediate sizes are not information anyone can act on, since
//! no frame was rendered at any of them.

//! # Input is recorded raw, and interpreted with the shell in hand
//!
//! Every input variant below carries the numbers the message came with and
//! nothing derived from them — a scan code rather than a
//! [`KeyCode`](crcbl_core::KeyCode), a detent count rather than a
//! [`ScrollDelta`](crcbl_core::input::ScrollDelta), a `RAWMOUSE` flag word
//! rather than a delta. Two reasons, and both are about the window procedure
//! rather than about taste:
//!
//! * The interpretations that need *state* — a surrogate pair spanning two
//!   `WM_CHAR`s, an absolute raw report differenced against the previous one —
//!   have nowhere to keep it in a procedure that must not touch the shell.
//! * The interpretations that need a *system call* — the modifier snapshot, the
//!   layout's keysym — are two more calls in a callback the system runs inside
//!   our own `SetWindowPos`.
//!
//! So the procedure copies fields and the shell does the arithmetic, on the
//! pure functions in [`keys`](super::keys) and [`pointer`](super::pointer).
//!
//! Each of them also carries `millis`: `GetMessageTime` for the message being
//! processed, which [`TimeBase`](super::TimeBase) widens and rebases. It is read
//! in the procedure rather than at translation time because by then the value
//! belongs to a *later* message — the whole point of a timestamp is that it is
//! not the moment the queue was drained.

use crcbl_core::input::{ButtonState, Modifiers, PointerButton, TouchPhase};

use crate::PhysicalSize;

/// One thing the window procedure saw.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RawEvent {
    /// `WM_SIZE` with a real size — the client area changed.
    Resized {
        /// `HWND` as an integer.
        hwnd: isize,
        /// The new client area.
        size: PhysicalSize,
    },
    /// `WM_SIZE` with `SIZE_MINIMIZED`.
    ///
    /// Kept apart from [`Resized`](Self::Resized) because a minimized window
    /// reports a client area of 0×0, and publishing that as the swapchain's
    /// extent is a validation error rather than a fact. It is a visibility
    /// change; [`WindowState::visible`](crate::WindowState::visible) is defined
    /// as "mapped **and not minimized**".
    Minimized {
        /// `HWND` as an integer.
        hwnd: isize,
    },
    /// `WM_DPICHANGED` — the window moved to a monitor at another scale, or the
    /// user changed the scale of the one it is on.
    DpiChanged {
        /// `HWND` as an integer.
        hwnd: isize,
        /// The new DPI. 96 is 100%.
        dpi: u32,
    },
    /// `WM_SETFOCUS` or `WM_KILLFOCUS`.
    Focus {
        /// `HWND` as an integer.
        hwnd: isize,
        /// Whether the window now has the keyboard focus.
        focused: bool,
    },
    /// `WM_CLOSE`, which this backend intercepts rather than passing to
    /// `DefWindowProc` — that would destroy the window before anyone could ask
    /// about unsaved work.
    CloseRequested {
        /// `HWND` as an integer.
        hwnd: isize,
    },
    /// `WM_DESTROY` — the window is going away whether we asked or not.
    Destroyed {
        /// `HWND` as an integer.
        hwnd: isize,
    },
    /// `WM_KEYDOWN`, `WM_KEYUP` or either of their `WM_SYS*` twins.
    Key {
        /// `HWND` as an integer.
        hwnd: isize,
        /// The scan code out of `lParam`, with the `E0` prefix folded in — see
        /// [`keys::scancode`](super::keys::scancode).
        scancode: u32,
        /// The virtual key out of `wParam`, which is the only thing that can
        /// name the *symbol* the key produces in the current layout.
        virtual_key: u16,
        /// Down or up.
        state: ButtonState,
        /// Whether `lParam` said the key was already held — an auto-repeat.
        repeat: bool,
        /// The modifiers held when the window procedure handled the message,
        /// read there — see [`input::modifiers_now`](super::input::modifiers_now).
        modifiers: Modifiers,
        /// `GetMessageTime` milliseconds.
        millis: u32,
    },
    /// `WM_CHAR` — one **UTF-16 code unit** of committed text.
    ///
    /// Not a character: an astral codepoint arrives as two of these carrying a
    /// surrogate pair, which [`keys::Utf16`](super::keys::Utf16) reassembles.
    /// Deliberately separate from [`Key`](Self::Key), which is the relationship
    /// [`TextCommit`](crate::ShellEvent::TextCommit) documents as not being
    /// one-to-one.
    Char {
        /// `HWND` as an integer.
        hwnd: isize,
        /// The code unit out of `wParam`.
        unit: u16,
        /// `GetMessageTime` milliseconds.
        millis: u32,
    },
    /// `WM_MOUSEMOVE`, in client pixels.
    PointerMotion {
        /// `HWND` as an integer.
        hwnd: isize,
        /// Client x, **signed** — a captured pointer is legitimately outside.
        x: i32,
        /// Client y, likewise.
        y: i32,
        /// `GetMessageTime` milliseconds.
        millis: u32,
    },
    /// The pointer arrived or left.
    ///
    /// The arrival half has **no message of its own**: Windows sends
    /// `WM_MOUSELEAVE` and nothing for the entry, so the procedure derives it
    /// from the first motion after a leave. See [`proc`](super::proc).
    PointerFocus {
        /// `HWND` as an integer.
        hwnd: isize,
        /// Whether the pointer is now inside the client area.
        entered: bool,
        /// Client x where it entered. Meaningless on leave, which
        /// [`PointerFocus`](crate::ShellEvent::PointerFocus) reports as `None`.
        x: i32,
        /// Client y where it entered.
        y: i32,
        /// `GetMessageTime` milliseconds.
        millis: u32,
    },
    /// One of the five `WM_*BUTTON*` messages.
    Button {
        /// `HWND` as an integer.
        hwnd: isize,
        /// Which button, already told apart from the `WM_XBUTTON*` pair.
        button: PointerButton,
        /// Down or up.
        state: ButtonState,
        /// Client x.
        x: i32,
        /// Client y.
        y: i32,
        /// The modifiers held when the window procedure handled the message,
        /// read there — see [`input::modifiers_now`](super::input::modifiers_now).
        modifiers: Modifiers,
        /// `GetMessageTime` milliseconds.
        millis: u32,
    },
    /// `WM_MOUSEWHEEL` or `WM_MOUSEHWHEEL`.
    Wheel {
        /// `HWND` as an integer.
        hwnd: isize,
        /// Whether this is the tilt axis.
        horizontal: bool,
        /// The signed detent count, in `WHEEL_DELTA` units.
        ticks: i16,
        /// Client x — converted from the **screen** coordinates the wheel
        /// messages carry, which is the one place they differ from the rest.
        x: i32,
        /// Client y.
        y: i32,
        /// The modifiers held when the window procedure handled the message,
        /// read there — see [`input::modifiers_now`](super::input::modifiers_now).
        modifiers: Modifiers,
        /// `GetMessageTime` milliseconds.
        millis: u32,
    },
    /// A `WM_POINTER*` message for a **touch** contact, or a
    /// `WM_POINTERCAPTURECHANGED` for any pointer.
    ///
    /// Recorded only for touch: pen, touchpad and mouse pointers are left to
    /// the legacy mouse messages `DefWindowProc` synthesizes from them, which
    /// the arms above already record. A capture change is recorded whatever the
    /// pointer's kind, because by then the kind may no longer be answerable;
    /// the shell drops it unless the id is a contact it is tracking.
    Touch {
        /// `HWND` as an integer.
        hwnd: isize,
        /// The system's pointer id — distinct for contacts down at the same
        /// time, reused afterwards, which is exactly
        /// [`ContactId`](crcbl_core::input::ContactId)'s promise.
        pointer_id: u32,
        /// What the contact did.
        phase: TouchPhase,
        /// Client position, converted from the screen coordinates the pointer
        /// messages carry. `None` for a capture change, which carries no
        /// position; the shell reports the contact's last one.
        position: Option<(i32, i32)>,
        /// `GetMessageTime` milliseconds.
        millis: u32,
    },
    /// `WM_INPUT` carrying a `RAWMOUSE` report.
    ///
    /// The coordinates are a delta **or** a position depending on `flags`; see
    /// [`pointer::RawMotion`](super::pointer::RawMotion), which is where that is
    /// resolved and why it cannot be resolved here.
    RawMotion {
        /// `HWND` as an integer — raw input follows the keyboard focus, so this
        /// is whichever of our windows had it.
        hwnd: isize,
        /// `RAWINPUTHEADER::hDevice` as an integer, zero for injected input.
        device: isize,
        /// `RAWMOUSE::usFlags`.
        flags: u16,
        /// `RAWMOUSE::usButtonFlags`: the button and wheel edges this report
        /// carries, which say what device the matching messages came from.
        buttons: u16,
        /// `RAWMOUSE::lLastX`.
        x: i32,
        /// `RAWMOUSE::lLastY`.
        y: i32,
        /// `GetMessageTime` milliseconds.
        millis: u32,
    },
    /// `WM_INPUT` carrying a `RAWKEYBOARD` report. Produces no event of its
    /// own; it names the device of the key message that follows it. See
    /// [`devices`](super::devices).
    RawKey {
        /// `HWND` as an integer.
        hwnd: isize,
        /// `RAWINPUTHEADER::hDevice` as an integer, zero for injected input.
        device: isize,
        /// `RAWKEYBOARD::MakeCode`.
        make_code: u16,
        /// `RAWKEYBOARD::Flags`.
        flags: u16,
        /// `GetMessageTime` milliseconds.
        millis: u32,
    },
    /// `WM_INPUT_DEVICE_CHANGE` for a device that left. Its handle may be given
    /// to the next device that arrives, so the shell forgets it.
    DeviceRemoved {
        /// The raw input device handle as an integer.
        device: isize,
    },
    /// `WM_DROPFILES` — files were dropped on the window.
    ///
    /// **The paths are not here.** A drop carries a `Vec<PathBuf>`, which this
    /// enum cannot hold without giving up `Copy` — see the [module docs](self)
    /// — and the `HDROP` they come out of is live only for the length of the
    /// message, so the procedure reads them and puts them on
    /// [`Shared`](super::proc::Shared)'s own drop queue. This is the marker that
    /// keeps the drop in its place in the stream, so that a drop still follows
    /// the pointer motion which positioned it.
    FilesDropped {
        /// `HWND` as an integer. Also what the payload is matched by, so a
        /// drop on a window that dies before the pump is discarded with it
        /// rather than being handed to the next drop's marker.
        hwnd: isize,
        /// `GetMessageTime` milliseconds.
        millis: u32,
    },
    /// `WM_IME_COMPOSITION` with a new composition string, or
    /// `WM_IME_ENDCOMPOSITION`.
    ///
    /// **The string is not here**, for the reason [`FilesDropped`]'s paths are
    /// not: it lives on [`Shared`](super::proc::Shared)'s own queue and this is
    /// the marker that claims it, in its place in the stream.
    ///
    /// [`FilesDropped`]: Self::FilesDropped
    Preedit {
        /// `HWND` as an integer.
        hwnd: isize,
        /// `GetMessageTime` milliseconds.
        millis: u32,
    },
    /// `WM_DISPLAYCHANGE` — a monitor was plugged, unplugged or reconfigured
    /// — or `WM_SETTINGCHANGE` for a work area that moved.
    MonitorsChanged,
    /// An `ABN_*` notification to an appbar, in the callback message it was
    /// registered with.
    AppBar {
        /// `HWND` as an integer.
        hwnd: isize,
        /// The `ABN_*` code.
        notification: u32,
        /// The notification's `lParam`, which some codes carry a value in.
        param: isize,
    },
    /// The first `WM_GETOBJECT` a window's accessibility adapter answered: a
    /// reader started reading it. See [`access`](super::access).
    #[cfg(all(target_os = "windows", feature = "accesskit"))]
    AccessibilityActivated {
        /// `HWND` as an integer.
        hwnd: isize,
    },
}

impl RawEvent {
    /// The window this is about, or `None` for a desktop-wide event.
    #[must_use]
    pub const fn hwnd(self) -> Option<isize> {
        match self {
            Self::Resized { hwnd, .. }
            | Self::Minimized { hwnd }
            | Self::DpiChanged { hwnd, .. }
            | Self::Focus { hwnd, .. }
            | Self::CloseRequested { hwnd }
            | Self::Destroyed { hwnd }
            | Self::Key { hwnd, .. }
            | Self::Char { hwnd, .. }
            | Self::PointerMotion { hwnd, .. }
            | Self::PointerFocus { hwnd, .. }
            | Self::Button { hwnd, .. }
            | Self::Wheel { hwnd, .. }
            | Self::Touch { hwnd, .. }
            | Self::RawMotion { hwnd, .. }
            | Self::RawKey { hwnd, .. }
            | Self::Preedit { hwnd, .. }
            | Self::AppBar { hwnd, .. }
            | Self::FilesDropped { hwnd, .. } => Some(hwnd),
            #[cfg(all(target_os = "windows", feature = "accesskit"))]
            Self::AccessibilityActivated { hwnd } => Some(hwnd),
            Self::MonitorsChanged | Self::DeviceRemoved { .. } => None,
        }
    }
}

/// Appends `event`, letting it supersede a pending one where that is sound.
///
/// Exactly two kinds are collapsed, and neither loses information:
///
/// * A [`Resized`](RawEvent::Resized) replaces a pending resize **of the same
///   window**, in place, so the ordering against other events is unchanged and
///   the size that survives is the latest one. Two windows resizing never
///   collapse into each other.
/// * A [`MonitorsChanged`](RawEvent::MonitorsChanged) is dropped if one is
///   already queued: it carries nothing, the shell re-enumerates from scratch
///   when it sees one, and a single display reconfiguration sends several.
///
/// Everything else is kept, in order. A close request, a focus change and a
/// destruction are each a discrete thing that happened, and dropping the first
/// of two would lose a question the consumer has to answer.
///
/// **No input is collapsed**, deliberately. A resize is a *state* and its
/// intermediate values describe frames nobody rendered; a keystroke, a click and
/// a motion sample are *events*, and the durations between them are what
/// the action layer's patterns are defined over. Coalescing two
/// motion samples into their endpoints would erase the path a drag took, and
/// coalescing two key edges would turn a double-tap into a tap. Windows already
/// collapses `WM_MOUSEMOVE` in its own queue, which is the only place that
/// collapse is sound — the system knows which samples the application never saw.
pub fn enqueue(queue: &mut Vec<RawEvent>, event: RawEvent) {
    match event {
        RawEvent::Resized { hwnd, .. } => {
            if let Some(pending) = queue.iter_mut().find(
                |queued| matches!(queued, RawEvent::Resized { hwnd: queued, .. } if *queued == hwnd),
            ) {
                *pending = event;
                return;
            }
        }
        RawEvent::MonitorsChanged if queue.contains(&RawEvent::MonitorsChanged) => return,
        _ => {}
    }
    queue.push(event);
}

#[cfg(test)]
mod tests {
    use super::*;

    const A: isize = 0x1234;
    const B: isize = 0x5678;

    fn resize(hwnd: isize, width: u32) -> RawEvent {
        RawEvent::Resized {
            hwnd,
            size: PhysicalSize::new(width, 720),
        }
    }

    #[test]
    fn a_drag_resize_storm_collapses_to_the_size_the_window_ended_at() {
        // The modal-loop case: nothing drains the queue while the user drags,
        // so without this a three-second drag delivers a few hundred `Resized`
        // events in one pump, every one of them describing a size no frame was
        // ever rendered at.
        let mut queue = Vec::new();
        for width in [1280, 1281, 1290, 1400, 1401] {
            enqueue(&mut queue, resize(A, width));
        }
        assert_eq!(queue.len(), 1, "{queue:?}");
        assert_eq!(
            queue[0],
            RawEvent::Resized {
                hwnd: A,
                size: PhysicalSize::new(1401, 720)
            }
        );
    }

    #[test]
    fn two_windows_resizing_do_not_collapse_into_each_other() {
        let mut queue = Vec::new();
        enqueue(&mut queue, resize(A, 800));
        enqueue(&mut queue, resize(B, 1024));
        enqueue(&mut queue, resize(A, 900));
        assert_eq!(queue.len(), 2);
        // In place, so B is still second — the collapse must not reorder.
        assert_eq!(queue[0], resize(A, 900));
        assert_eq!(queue[1], resize(B, 1024));
    }

    #[test]
    fn everything_that_is_not_a_resize_keeps_every_occurrence_in_order() {
        // A close request asked twice is two questions, and dropping one leaves
        // the consumer's reply addressed to a request that no longer exists.
        let mut queue = Vec::new();
        let events = [
            RawEvent::Focus {
                hwnd: A,
                focused: true,
            },
            RawEvent::CloseRequested { hwnd: A },
            RawEvent::Focus {
                hwnd: A,
                focused: false,
            },
            RawEvent::CloseRequested { hwnd: A },
            RawEvent::DpiChanged { hwnd: A, dpi: 144 },
            RawEvent::DpiChanged { hwnd: A, dpi: 96 },
            // Two drops in one pump are two drops, and collapsing them would
            // leave the second one's paths on the shared queue with no marker
            // to claim them.
            RawEvent::FilesDropped {
                hwnd: A,
                millis: 1_000,
            },
            RawEvent::FilesDropped {
                hwnd: A,
                millis: 1_200,
            },
            RawEvent::Minimized { hwnd: A },
            RawEvent::Destroyed { hwnd: A },
            // A device that leaves twice in one pump — unplugged, then its
            // reappearance unplugged again — is two handles to forget.
            RawEvent::DeviceRemoved { device: 0x100 },
            RawEvent::DeviceRemoved { device: 0x200 },
            // Two compositions in one pump: each replaces the last, but the
            // consumer is owed both, in order.
            RawEvent::Preedit {
                hwnd: A,
                millis: 1_300,
            },
            RawEvent::Preedit {
                hwnd: A,
                millis: 1_301,
            },
        ];
        for event in events {
            enqueue(&mut queue, event);
        }
        assert_eq!(queue, events);
    }

    #[test]
    fn one_display_reconfiguration_is_one_monitors_changed() {
        // Windows sends `WM_DISPLAYCHANGE` to every top-level window, so a
        // two-window shell sees it twice for one cable.
        let mut queue = Vec::new();
        enqueue(&mut queue, RawEvent::MonitorsChanged);
        enqueue(&mut queue, resize(A, 1024));
        enqueue(&mut queue, RawEvent::MonitorsChanged);
        assert_eq!(queue, [RawEvent::MonitorsChanged, resize(A, 1024)]);
    }

    #[test]
    fn a_burst_of_input_keeps_every_sample_in_order() {
        // The counterpart to the resize collapse, and the reason `enqueue` is
        // not "coalesce anything repeated": a drag path, a double-click and an
        // auto-repeat run are all sequences whose *members* are the
        // information. Collapsing them turns a double-tap into a tap.
        let mut queue = Vec::new();
        let samples = [
            RawEvent::PointerMotion {
                hwnd: A,
                x: 10,
                y: 10,
                millis: 1_000,
            },
            RawEvent::PointerMotion {
                hwnd: A,
                x: 11,
                y: 12,
                millis: 1_004,
            },
            RawEvent::Button {
                hwnd: A,
                button: PointerButton::Left,
                state: ButtonState::Pressed,
                x: 11,
                y: 12,
                modifiers: Modifiers::empty(),
                millis: 1_008,
            },
            RawEvent::Button {
                hwnd: A,
                button: PointerButton::Left,
                state: ButtonState::Released,
                x: 11,
                y: 12,
                modifiers: Modifiers::empty(),
                millis: 1_060,
            },
            RawEvent::Button {
                hwnd: A,
                button: PointerButton::Left,
                state: ButtonState::Pressed,
                x: 11,
                y: 12,
                modifiers: Modifiers::empty(),
                millis: 1_140,
            },
            RawEvent::Key {
                hwnd: A,
                scancode: 0x0011,
                virtual_key: 0x57,
                state: ButtonState::Pressed,
                repeat: false,
                modifiers: Modifiers::empty(),
                millis: 1_200,
            },
            RawEvent::Key {
                hwnd: A,
                scancode: 0x0011,
                virtual_key: 0x57,
                state: ButtonState::Pressed,
                repeat: true,
                modifiers: Modifiers::empty(),
                millis: 1_500,
            },
            RawEvent::RawMotion {
                hwnd: A,
                device: 0,
                flags: 0,
                buttons: 0,
                x: 3,
                y: -2,
                millis: 1_501,
            },
            RawEvent::RawMotion {
                hwnd: A,
                device: 0,
                flags: 0,
                buttons: 0,
                x: 4,
                y: -1,
                millis: 1_502,
            },
            RawEvent::Char {
                hwnd: A,
                unit: 0xD83C,
                millis: 1_600,
            },
            RawEvent::Char {
                hwnd: A,
                unit: 0xDFAE,
                millis: 1_600,
            },
            // Two raw keyboard reports for one key, from two devices: each names
            // the device of its own key message, so neither may be dropped.
            RawEvent::RawKey {
                hwnd: A,
                device: 0x100,
                make_code: 0x1E,
                flags: 0,
                millis: 1_650,
            },
            RawEvent::RawKey {
                hwnd: A,
                device: 0x200,
                make_code: 0x1E,
                flags: 0,
                millis: 1_651,
            },
            // A tap that lands and lifts inside one pump: keeping only the
            // latest state per contact would report a finger that was never
            // down.
            RawEvent::Touch {
                hwnd: A,
                pointer_id: 5,
                phase: TouchPhase::Began,
                position: Some((20, 30)),
                millis: 1_700,
            },
            RawEvent::Touch {
                hwnd: A,
                pointer_id: 5,
                phase: TouchPhase::Moved,
                position: Some((21, 30)),
                millis: 1_708,
            },
            RawEvent::Touch {
                hwnd: A,
                pointer_id: 5,
                phase: TouchPhase::Ended,
                position: Some((21, 30)),
                millis: 1_716,
            },
        ];
        for sample in samples {
            enqueue(&mut queue, sample);
        }
        assert_eq!(queue, samples);
    }

    #[test]
    fn a_resize_still_collapses_past_the_input_that_arrived_with_it() {
        // The collapse is in-place, so it must not reorder a resize past the
        // input events queued after it — a click delivered before the resize
        // that produced the window it was aimed at is a click at the wrong
        // coordinates.
        let mut queue = Vec::new();
        let click = RawEvent::Button {
            hwnd: A,
            button: PointerButton::Right,
            state: ButtonState::Pressed,
            x: 4,
            y: 4,
            modifiers: Modifiers::empty(),
            millis: 9,
        };
        enqueue(&mut queue, resize(A, 800));
        enqueue(&mut queue, click);
        enqueue(&mut queue, resize(A, 900));
        assert_eq!(queue, [resize(A, 900), click]);
    }

    #[test]
    fn every_windowed_event_names_its_window_and_the_desktop_one_does_not() {
        // The routing predicate: an event with no `HWND` is not a stale-window
        // problem, it is a shell-wide fact.
        assert_eq!(resize(A, 640).hwnd(), Some(A));
        assert_eq!(RawEvent::Minimized { hwnd: B }.hwnd(), Some(B));
        assert_eq!(RawEvent::DpiChanged { hwnd: A, dpi: 96 }.hwnd(), Some(A));
        assert_eq!(
            RawEvent::Focus {
                hwnd: A,
                focused: true
            }
            .hwnd(),
            Some(A)
        );
        assert_eq!(RawEvent::CloseRequested { hwnd: A }.hwnd(), Some(A));
        assert_eq!(RawEvent::Destroyed { hwnd: A }.hwnd(), Some(A));
        assert_eq!(
            RawEvent::Key {
                hwnd: B,
                scancode: 1,
                virtual_key: 0x1B,
                state: ButtonState::Released,
                repeat: false,
                modifiers: Modifiers::empty(),
                millis: 0,
            }
            .hwnd(),
            Some(B)
        );
        assert_eq!(
            RawEvent::Char {
                hwnd: B,
                unit: 0x61,
                millis: 0
            }
            .hwnd(),
            Some(B)
        );
        assert_eq!(
            RawEvent::PointerMotion {
                hwnd: B,
                x: 0,
                y: 0,
                millis: 0
            }
            .hwnd(),
            Some(B)
        );
        assert_eq!(
            RawEvent::PointerFocus {
                hwnd: B,
                entered: false,
                x: 0,
                y: 0,
                millis: 0,
            }
            .hwnd(),
            Some(B)
        );
        assert_eq!(
            RawEvent::Button {
                hwnd: B,
                button: PointerButton::Middle,
                state: ButtonState::Pressed,
                x: 0,
                y: 0,
                modifiers: Modifiers::empty(),
                millis: 0,
            }
            .hwnd(),
            Some(B)
        );
        assert_eq!(
            RawEvent::Wheel {
                hwnd: B,
                horizontal: false,
                ticks: 120,
                x: 0,
                y: 0,
                modifiers: Modifiers::empty(),
                millis: 0,
            }
            .hwnd(),
            Some(B)
        );
        assert_eq!(
            RawEvent::RawMotion {
                hwnd: B,
                device: 0,
                flags: 0,
                buttons: 0,
                x: 1,
                y: 1,
                millis: 0
            }
            .hwnd(),
            Some(B)
        );
        assert_eq!(
            RawEvent::FilesDropped { hwnd: B, millis: 0 }.hwnd(),
            Some(B),
            "a drop's marker has to name its window, because that is what the \
             payload is matched by"
        );
        assert_eq!(
            RawEvent::AppBar {
                hwnd: B,
                notification: 1,
                param: 0,
            }
            .hwnd(),
            Some(B),
            "an appbar notification is placed against its own window"
        );
        assert_eq!(RawEvent::MonitorsChanged.hwnd(), None);
    }
}