Skip to main content

graphics/
event_queue.rs

1//! Fixed-capacity event ring owned by each window.
2//!
3//! The ring lives inline in the window object, so it never allocates, never
4//! grows and never fragments a heap, however many events a burst produces.
5//! Overflow is resolved by the policy documented on [`EventQueue`].
6
7use crate::{Event, EventKind, lvgl};
8use core::ptr;
9
10/// Regular event slots. A pending close request uses a separate slot.
11pub const WINDOW_EVENT_QUEUE_CAPACITY: usize = 16;
12
13// One extra slot belongs to the pending close request.
14const RING_CAPACITY: usize = WINDOW_EVENT_QUEUE_CAPACITY + 1;
15
16/// Slots kept for the rest of each accepted press. A short press ends with
17/// `Released`, `ShortClicked`, one of `SingleClicked`, `DoubleClicked` or
18/// `TripleClicked`, and `Clicked`; a long press sends `LongPressed`,
19/// `Released` and `Clicked`; a lost press ends with `PressLost`.
20const PRESS_END_RESERVATION: u8 = 4;
21
22/// Input devices whose current press, accepted or rejected, the queue
23/// follows at once.
24const PRESS_TRACKING_CAPACITY: usize = 4;
25
26/// Minimum time between two loss reports, in LVGL ticks (milliseconds).
27pub const LOSS_REPORT_INTERVAL: u32 = 1000;
28
29// Indices are stored as `u8`.
30const _: () = assert!(WINDOW_EVENT_QUEUE_CAPACITY > 0 && RING_CAPACITY <= u8::MAX as usize);
31// A pointer press and a keypad press fit with their whole ends, and room
32// remains for other events.
33const _: () = assert!(2 * (PRESS_END_RESERVATION as usize + 1) < WINDOW_EVENT_QUEUE_CAPACITY);
34
35/// The LVGL input device that sent an event, compared by address only. Null
36/// for events sent by code.
37pub type InputDevice = *const lvgl::lv_indev_t;
38
39/// What [`EventQueue::push`] did with an event.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum PushOutcome {
42    /// The event was appended.
43    Queued,
44    /// The event merged with a queued event.
45    Coalesced,
46    /// The event was appended after evicting the oldest evictable event.
47    EvictedOldest,
48    /// The event was rejected.
49    Dropped,
50}
51
52impl PushOutcome {
53    /// Whether an event was lost: evicted or rejected.
54    pub const fn lost_an_event(self) -> bool {
55        matches!(self, Self::EvictedOldest | Self::Dropped)
56    }
57}
58
59/// Events lost since the previous report.
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub struct LossReport {
62    /// Events lost since the previous report.
63    pub lost: u32,
64    /// Events lost since the queue was created.
65    pub total: u32,
66}
67
68/// How much an event may be sacrificed when the queue is full, from the
69/// least to the most important. An arrival only evicts events of its own tier
70/// or a less important one.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
72enum Tier {
73    /// Notifications no consumer depends on: evicted first.
74    Low,
75    /// Pointer moves and press repeats: coalescible, and soon superseded by
76    /// the next move or by the end of the press.
77    Transient,
78    /// State changes: coalescible, and the latest one per target must reach
79    /// the consumer, which reads the new state when it handles it.
80    State,
81    /// Input, focus and window lifecycle events: never evicted, never reordered.
82    Lifecycle,
83}
84
85impl Tier {
86    /// Whether a newer event replaces the queued one of the same kind and
87    /// target ("latest wins").
88    const fn coalesces(self) -> bool {
89        matches!(self, Self::Transient | Self::State)
90    }
91}
92
93const fn tier(kind: EventKind) -> Tier {
94    match kind {
95        EventKind::Scroll
96        | EventKind::ScrollBegin
97        | EventKind::ScrollThrowBegin
98        | EventKind::ScrollEnd
99        | EventKind::LayoutChanged
100        | EventKind::GetSelfSize
101        | EventKind::HoverOver
102        | EventKind::HoverLeave
103        | EventKind::HitTest
104        | EventKind::CoverCheck
105        | EventKind::RefreshExtDrawSize
106        | EventKind::DrawMainBegin
107        | EventKind::DrawMain
108        | EventKind::DrawMainEnd
109        | EventKind::DrawPostBegin
110        | EventKind::DrawPost
111        | EventKind::DrawPostEnd
112        | EventKind::DrawTaskAdded
113        | EventKind::InvalidateArea
114        | EventKind::Refresh
115        | EventKind::Create
116        | EventKind::Insert
117        | EventKind::Delete => Tier::Low,
118        EventKind::Pressing | EventKind::LongPressedRepeat => Tier::Transient,
119        EventKind::ValueChanged | EventKind::SizeChanged | EventKind::StyleChanged => Tier::State,
120        _ => Tier::Lifecycle,
121    }
122}
123
124/// Whether the window must tell which input device sent an event of `kind`:
125/// it takes part in a press, or it reports that a device was reset.
126pub const fn carries_input_device(kind: EventKind) -> bool {
127    press_role(kind).is_some() || matches!(kind, EventKind::InputDeviceReset)
128}
129
130/// The part an event plays in a press, from `Pressed` to its last click.
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132enum PressRole {
133    Start,
134    /// Movement and repeats: coalescible, so they need no reserved slot.
135    Progress,
136    LongPress,
137    Release,
138    Lost,
139    Click,
140    Final,
141}
142
143/// Whether `kind` starts or ends a press, or marks one of its steps: every
144/// press event except the coalescible moves and repeats.
145const fn is_press_boundary(kind: EventKind) -> bool {
146    !matches!(press_role(kind), None | Some(PressRole::Progress))
147}
148
149const fn press_role(kind: EventKind) -> Option<PressRole> {
150    match kind {
151        EventKind::Pressed => Some(PressRole::Start),
152        EventKind::Pressing | EventKind::LongPressedRepeat => Some(PressRole::Progress),
153        EventKind::LongPressed => Some(PressRole::LongPress),
154        EventKind::Released => Some(PressRole::Release),
155        EventKind::PressLost => Some(PressRole::Lost),
156        EventKind::ShortClicked
157        | EventKind::SingleClicked
158        | EventKind::DoubleClicked
159        | EventKind::TripleClicked => Some(PressRole::Click),
160        EventKind::Clicked => Some(PressRole::Final),
161        _ => None,
162    }
163}
164
165/// The current press of an input device, followed from its `Pressed` event
166/// to its end.
167#[derive(Debug, Clone, Copy)]
168struct PressGroup {
169    device: InputDevice,
170    /// The pressed widget. A keypad may end the press on another one: the
171    /// widget focused when the key is released.
172    target: *mut lvgl::lv_obj_t,
173    /// Whether `Pressed` was queued. The rest of a rejected press is dropped.
174    accepted: bool,
175    /// Whether `Released` arrived: only clicks can follow.
176    released: bool,
177    /// Slots still reserved for the end of an accepted press.
178    reserved: u8,
179}
180
181impl PressGroup {
182    const EMPTY: Self = Self {
183        device: ptr::null(),
184        target: ptr::null_mut(),
185        accepted: false,
186        released: false,
187        reserved: 0,
188    };
189}
190
191/// Bounded queue of window events in arrival order.
192///
193/// Regular events fall in four tiers, from the least to the most important:
194///
195/// - low: the scroll family, layout changes, hover, hit tests, drawing
196///   notifications, `Insert` and `Delete`;
197/// - transient: `Pressing` and `LongPressedRepeat`;
198/// - state: `ValueChanged`, `SizeChanged` and `StyleChanged`;
199/// - lifecycle: everything else, such as presses, releases, clicks, keys,
200///   focus changes, `Ready` and `Cancel`.
201///
202/// One slot is reserved for `CloseRequested`. It keeps its place in arrival
203/// order. Further close requests merge into the pending request until it is
204/// popped.
205///
206/// Transient and state events are "latest wins": a newer one replaces the
207/// queued event of the same kind and target and moves to the back, unless a
208/// lifecycle event for that target lies between them. The input device does
209/// not take part in the match: the moves and value changes that two devices
210/// make on one widget merge into the latest one. Consumers read the widget's
211/// current state, and events carry no device, which would cost a word per
212/// slot.
213///
214/// When the queue is full, an arrival evicts the oldest low event, or else the
215/// oldest transient event, or else the oldest state event, but never an event
216/// more important than itself. Lifecycle events are never evicted or
217/// reordered. An arrival that finds nothing to evict is rejected.
218///
219/// Presses are followed per input device (press events sent by code, without
220/// one, are queued by tier only). A `Pressed` event is accepted only
221/// with room for the rest of its press (`LongPressed`, `Released` or
222/// `PressLost`, then the clicks), which stays reserved until those events
223/// arrive, the device presses again, is reset, or the window learns that it
224/// was released or deleted ([`EventQueue::forget_ended_presses`]). Other
225/// lifecycle events cannot take that room. When a `Pressed` event is
226/// rejected, the rest of that press is dropped as well: the queue never drops
227/// a `Pressed` event while keeping the end of its press.
228///
229/// Every evicted or rejected event is counted, and
230/// [`EventQueue::take_loss_report`] summarizes the losses at most once per
231/// [`LOSS_REPORT_INTERVAL`].
232pub struct EventQueue {
233    slots: [Option<Event>; RING_CAPACITY],
234    head: u8,
235    length: u8,
236    close_requested: bool,
237    /// Number of valid entries at the start of `presses`, oldest first.
238    press_count: u8,
239    presses: [PressGroup; PRESS_TRACKING_CAPACITY],
240    dropped: u32,
241    unreported: u32,
242    last_report: Option<u32>,
243}
244
245impl EventQueue {
246    pub const fn new() -> Self {
247        Self {
248            slots: [const { None }; RING_CAPACITY],
249            head: 0,
250            length: 0,
251            close_requested: false,
252            press_count: 0,
253            presses: [PressGroup::EMPTY; PRESS_TRACKING_CAPACITY],
254            dropped: 0,
255            unreported: 0,
256            last_report: None,
257        }
258    }
259
260    pub const fn len(&self) -> usize {
261        self.length as usize
262    }
263
264    pub const fn is_empty(&self) -> bool {
265        self.length == 0
266    }
267
268    fn is_full(&self) -> bool {
269        self.len() - usize::from(self.close_requested) == WINDOW_EVENT_QUEUE_CAPACITY
270    }
271
272    pub const fn has_close_request(&self) -> bool {
273        self.close_requested
274    }
275
276    /// Whether a press is followed: its target must be forgotten when it dies.
277    pub const fn follows_presses(&self) -> bool {
278        self.press_count > 0
279    }
280
281    /// Number of events lost to overflow since creation, including rejections
282    /// and evictions.
283    pub const fn dropped(&self) -> u32 {
284        self.dropped
285    }
286
287    /// Whether losses happened since the last report.
288    pub const fn has_unreported_losses(&self) -> bool {
289        self.unreported > 0
290    }
291
292    /// Summarize the losses since the last report, unless there were none or
293    /// the last report is less than [`LOSS_REPORT_INTERVAL`] ticks old. `now`
294    /// is the current LVGL tick.
295    pub fn take_loss_report(&mut self, now: u32) -> Option<LossReport> {
296        if self.unreported == 0 {
297            return None;
298        }
299        if let Some(last) = self.last_report
300            && now.wrapping_sub(last) < LOSS_REPORT_INTERVAL
301        {
302            return None;
303        }
304        self.last_report = Some(now);
305        Some(LossReport {
306            lost: core::mem::take(&mut self.unreported),
307            total: self.dropped,
308        })
309    }
310
311    /// Append an event that `device` sent, according to the queue's overflow
312    /// policy. `device` only matters for press events and device resets (see
313    /// [`carries_input_device`]). Press events sent by code, without a device,
314    /// are queued by tier only: nothing ends such a press reliably.
315    pub fn push(&mut self, event: Event, device: InputDevice) -> PushOutcome {
316        if event.code == EventKind::CloseRequested {
317            if self.close_requested {
318                return PushOutcome::Coalesced;
319            }
320            self.append(event);
321            self.close_requested = true;
322            return PushOutcome::Queued;
323        }
324        if event.code == EventKind::InputDeviceReset && !device.is_null() {
325            // LVGL forgot the widget the device pressed: it never ends that
326            // press, and a new press starts if the device is still held.
327            self.forget_presses(|group| group.device == device);
328        }
329        let Some(role) = press_role(event.code).filter(|_| !device.is_null()) else {
330            return self.insert(event, false);
331        };
332        if role == PressRole::Start {
333            return self.push_press(event, device);
334        }
335        // LVGL sends the rest of a press from the same device, possibly to
336        // another widget: a keypad releases on the focused widget.
337        let Some(index) = self.press_index(device) else {
338            return self.insert(event, false);
339        };
340
341        let group = &mut self.presses[index];
342        let accepted = group.accepted;
343        let uses_reservation = accepted && role != PressRole::Progress && group.reserved > 0;
344        if uses_reservation {
345            group.reserved -= 1;
346        }
347        match role {
348            PressRole::Release => group.released = true,
349            PressRole::Lost | PressRole::Final => self.forget_press(index),
350            _ => {}
351        }
352
353        if accepted {
354            self.insert(event, uses_reservation)
355        } else {
356            self.lose()
357        }
358    }
359
360    fn push_press(&mut self, event: Event, device: InputDevice) -> PushOutcome {
361        // A device presses one widget at a time, so a new press ends its
362        // previous one, even one LVGL never ended (an encoder long press that
363        // leaves edit mode, or a widget disabled while pressed). LVGL also
364        // sends a release and its clicks back to back, so a new press means
365        // every released press has ended.
366        self.forget_presses(|group| group.released || group.device == device);
367
368        let accepted =
369            self.lifecycle_count() + 1 + self.reserved() + PRESS_END_RESERVATION as usize
370                <= WINDOW_EVENT_QUEUE_CAPACITY;
371        self.follow_press(PressGroup {
372            device,
373            target: event.target,
374            accepted,
375            released: false,
376            reserved: if accepted { PRESS_END_RESERVATION } else { 0 },
377        });
378        if accepted {
379            self.insert(event, false)
380        } else {
381            self.lose()
382        }
383    }
384
385    /// Queue `event` by its tier. `uses_reservation` means a slot reserved
386    /// for the end of its press was just released for it.
387    fn insert(&mut self, event: Event, uses_reservation: bool) -> PushOutcome {
388        let tier = tier(event.code);
389        if tier.coalesces()
390            && let Some(index) = self.superseded_by(&event)
391        {
392            self.remove(index);
393            self.append(event);
394            return PushOutcome::Coalesced;
395        }
396        // Lifecycle events never take the room reserved for press ends.
397        if tier == Tier::Lifecycle
398            && !uses_reservation
399            && self.lifecycle_count() + self.reserved() >= WINDOW_EVENT_QUEUE_CAPACITY
400        {
401            return self.lose();
402        }
403        if !self.is_full() {
404            self.append(event);
405            return PushOutcome::Queued;
406        }
407
408        let victim = [Tier::Low, Tier::Transient, Tier::State]
409            .into_iter()
410            .take_while(|candidate| *candidate <= tier)
411            .find_map(|candidate| self.oldest(candidate));
412        match victim {
413            Some(index) => {
414                self.remove(index);
415                self.append(event);
416                self.lose();
417                PushOutcome::EvictedOldest
418            }
419            None => self.lose(),
420        }
421    }
422
423    pub fn front(&self) -> Option<&Event> {
424        self.get(0)
425    }
426
427    pub fn pop_front(&mut self) -> Option<Event> {
428        if self.is_empty() {
429            return None;
430        }
431        let event = self.slots[self.head as usize].take();
432        self.head = self.physical(1) as u8;
433        self.length -= 1;
434        if event
435            .as_ref()
436            .is_some_and(|event| event.code == EventKind::CloseRequested)
437        {
438            self.close_requested = false;
439        }
440        event
441    }
442
443    /// Forget the press of every input device that `may_continue` rejects:
444    /// LVGL will send nothing more for that press. The window rejects a device
445    /// that is released or deleted, unless LVGL is reading it right now.
446    /// Forgetting an accepted press gives its reservation back, and
447    /// forgetting a rejected one is safe because its end was already sent.
448    /// `may_continue` must only compare the address: the device may already
449    /// be deleted.
450    pub fn forget_ended_presses(&mut self, mut may_continue: impl FnMut(InputDevice) -> bool) {
451        self.forget_presses(|group| !may_continue(group.device));
452    }
453
454    /// Remove every event aimed at `target`, preserving the order of the rest,
455    /// and give up the reservation of an accepted press of `target`. Press
456    /// boundaries and close requests keep a null target. This preserves the
457    /// close request and keeps the start and end of a press paired when a
458    /// keypad ends its press on another widget. This method only compares
459    /// addresses.
460    pub fn discard_target(&mut self, target: *mut lvgl::lv_obj_t) {
461        let mut kept = 0;
462        for index in 0..self.len() {
463            let source = self.physical(index);
464            let Some(mut event) = self.slots[source].take() else {
465                continue;
466            };
467            let discarded = event.target == target;
468            if discarded {
469                event.target = ptr::null_mut();
470            }
471            if !discarded
472                || is_press_boundary(event.code)
473                || event.code == EventKind::CloseRequested
474            {
475                let destination = self.physical(kept);
476                self.slots[destination] = Some(event);
477                kept += 1;
478            }
479        }
480        self.length = kept as u8;
481        self.forget_accepted_presses(|pressed| pressed == target);
482    }
483
484    /// Keep every event but null the ones aimed at `target`, and give up the
485    /// reservation of an accepted press of `target`.
486    /// Only compares addresses; never dereferences `target`.
487    pub fn clear_target(&mut self, target: *mut lvgl::lv_obj_t) {
488        for event in self.slots.iter_mut().flatten() {
489            if event.target == target {
490                event.target = ptr::null_mut();
491            }
492        }
493        self.forget_accepted_presses(|pressed| pressed == target);
494    }
495
496    /// Null the target of every event whose target `is_live` rejects, keep
497    /// the events, and give up the reservations of accepted presses of
498    /// rejected targets. `is_live` is called once per distinct run of targets
499    /// and once per accepted press, and must only compare the address; the
500    /// targets may already be deleted.
501    pub fn clear_dead_targets(&mut self, mut is_live: impl FnMut(*mut lvgl::lv_obj_t) -> bool) {
502        let mut last = (ptr::null_mut(), true);
503        for event in self.slots.iter_mut().flatten() {
504            if event.target.is_null() {
505                continue;
506            }
507            if last.0 != event.target {
508                last = (event.target, is_live(event.target));
509            }
510            if !last.1 {
511                event.target = ptr::null_mut();
512            }
513        }
514        self.forget_accepted_presses(|pressed| !is_live(pressed));
515    }
516
517    /// Forget the accepted presses whose widget `is_gone`. Forgetting one
518    /// only gives up its reservation. A rejected press is kept: its device
519    /// may still end it on another widget, and that end must be dropped.
520    fn forget_accepted_presses(&mut self, mut is_gone: impl FnMut(*mut lvgl::lv_obj_t) -> bool) {
521        self.forget_presses(|group| group.accepted && is_gone(group.target));
522    }
523
524    fn lose(&mut self) -> PushOutcome {
525        self.dropped = self.dropped.saturating_add(1);
526        self.unreported = self.unreported.saturating_add(1);
527        PushOutcome::Dropped
528    }
529
530    /// The queued event that `event` supersedes: the newest one of the same
531    /// kind and target, unless a lifecycle event for that target follows it.
532    fn superseded_by(&self, event: &Event) -> Option<usize> {
533        for index in (0..self.len()).rev() {
534            let queued = self.get(index)?;
535            if queued.target != event.target {
536                continue;
537            }
538            if queued.code == event.code {
539                return Some(index);
540            }
541            if tier(queued.code) == Tier::Lifecycle {
542                return None;
543            }
544        }
545        None
546    }
547
548    fn oldest(&self, wanted: Tier) -> Option<usize> {
549        (0..self.len()).find(|&index| {
550            self.get(index)
551                .is_some_and(|event| tier(event.code) == wanted)
552        })
553    }
554
555    fn lifecycle_count(&self) -> usize {
556        (0..self.len())
557            .filter(|&index| {
558                self.get(index).is_some_and(|event| {
559                    event.code != EventKind::CloseRequested && tier(event.code) == Tier::Lifecycle
560                })
561            })
562            .count()
563    }
564
565    fn reserved(&self) -> usize {
566        self.followed_presses()
567            .iter()
568            .map(|group| group.reserved as usize)
569            .sum()
570    }
571
572    fn followed_presses(&self) -> &[PressGroup] {
573        &self.presses[..self.press_count as usize]
574    }
575
576    fn press_index(&self, device: InputDevice) -> Option<usize> {
577        self.followed_presses()
578            .iter()
579            .position(|group| group.device == device)
580    }
581
582    /// Start following a press. With more than [`PRESS_TRACKING_CAPACITY`]
583    /// input devices pressing at once, this makes room by forgetting the
584    /// oldest accepted press, or else the oldest press; only the latter can
585    /// let the end of a rejected press through.
586    fn follow_press(&mut self, group: PressGroup) {
587        if self.press_count as usize == PRESS_TRACKING_CAPACITY {
588            let index = self
589                .followed_presses()
590                .iter()
591                .position(|group| group.accepted)
592                .unwrap_or(0);
593            self.forget_press(index);
594        }
595        self.presses[self.press_count as usize] = group;
596        self.press_count += 1;
597    }
598
599    fn forget_press(&mut self, index: usize) {
600        let count = self.press_count as usize;
601        self.presses.copy_within(index + 1..count, index);
602        self.presses[count - 1] = PressGroup::EMPTY;
603        self.press_count -= 1;
604    }
605
606    fn forget_presses(&mut self, mut forget: impl FnMut(&PressGroup) -> bool) {
607        let mut index = 0;
608        while index < self.press_count as usize {
609            if forget(&self.presses[index]) {
610                self.forget_press(index);
611            } else {
612                index += 1;
613            }
614        }
615    }
616
617    fn physical(&self, index: usize) -> usize {
618        (self.head as usize + index) % RING_CAPACITY
619    }
620
621    fn get(&self, index: usize) -> Option<&Event> {
622        if index < self.len() {
623            self.slots[self.physical(index)].as_ref()
624        } else {
625            None
626        }
627    }
628
629    /// Append to the ring. The caller checks whether the event has room.
630    fn append(&mut self, event: Event) {
631        let slot = self.physical(self.len());
632        self.slots[slot] = Some(event);
633        self.length += 1;
634    }
635
636    /// Remove the event at logical `index`, shifting later events forward.
637    fn remove(&mut self, index: usize) {
638        if index == 0 {
639            self.pop_front();
640            return;
641        }
642        for position in index..self.len() - 1 {
643            let (from, to) = (self.physical(position + 1), self.physical(position));
644            self.slots[to] = self.slots[from].take();
645        }
646        let last = self.physical(self.len() - 1);
647        self.slots[last] = None;
648        self.length -= 1;
649    }
650}
651
652impl Default for EventQueue {
653    fn default() -> Self {
654        Self::new()
655    }
656}
657
658#[cfg(test)]
659mod tests {
660    use super::*;
661    use crate::Key;
662    use alloc::vec::Vec;
663
664    impl EventQueue {
665        /// Push an event from the pointer.
666        fn send(&mut self, event: Event) -> PushOutcome {
667            self.push(event, device(1))
668        }
669
670        /// Push an event sent by code, without an input device.
671        fn send_by_code(&mut self, event: Event) -> PushOutcome {
672            self.push(event, ptr::null())
673        }
674    }
675
676    fn device(address: usize) -> InputDevice {
677        address as InputDevice
678    }
679
680    fn object(address: usize) -> *mut lvgl::lv_obj_t {
681        address as *mut lvgl::lv_obj_t
682    }
683
684    fn event(code: EventKind, address: usize) -> Event {
685        Event::new(code, object(address), None)
686    }
687
688    fn pointer_move(address: usize, x: i32) -> Event {
689        let mut moved = event(EventKind::Pressing, address);
690        moved.pointer = Some([x, 0, 100, 100]);
691        moved
692    }
693
694    fn drain(queue: &mut EventQueue) -> Vec<(EventKind, usize)> {
695        core::iter::from_fn(|| queue.pop_front())
696            .map(|event| (event.code, event.target as usize))
697            .collect()
698    }
699
700    fn only(drained: &[(EventKind, usize)], target: usize) -> Vec<EventKind> {
701        drained
702            .iter()
703            .filter(|(_, address)| *address == target)
704            .map(|(code, _)| *code)
705            .collect()
706    }
707
708    /// Fill the queue with lifecycle events for `target` until one is rejected.
709    fn flood(queue: &mut EventQueue, code: EventKind, target: usize) -> usize {
710        let mut queued = 0;
711        while queue.send(event(code, target)) != PushOutcome::Dropped {
712            queued += 1;
713        }
714        queued
715    }
716
717    const SHORT_PRESS_END: [EventKind; 4] = [
718        EventKind::Released,
719        EventKind::ShortClicked,
720        EventKind::SingleClicked,
721        EventKind::Clicked,
722    ];
723
724    #[test]
725    fn pops_in_push_order_across_wraparound() {
726        let mut queue = EventQueue::new();
727        for round in 0..5 {
728            for index in 0..10 {
729                assert_eq!(
730                    queue.send(event(EventKind::Clicked, round * 100 + index + 1)),
731                    PushOutcome::Queued
732                );
733            }
734            let expected: Vec<_> = (0..10)
735                .map(|index| (EventKind::Clicked, round * 100 + index + 1))
736                .collect();
737            assert_eq!(drain(&mut queue), expected);
738            assert!(queue.is_empty());
739        }
740        assert_eq!(queue.dropped(), 0);
741    }
742
743    #[test]
744    fn peek_front_does_not_consume() {
745        let mut queue = EventQueue::new();
746        assert!(queue.front().is_none());
747        queue.send(event(EventKind::Pressed, 1));
748        queue.send(event(EventKind::Released, 1));
749        assert_eq!(queue.front().unwrap().code, EventKind::Pressed);
750        assert_eq!(queue.len(), 2);
751        assert_eq!(queue.pop_front().unwrap().code, EventKind::Pressed);
752        assert_eq!(queue.front().unwrap().code, EventKind::Released);
753    }
754
755    #[test]
756    fn pointer_moves_for_one_target_keep_the_latest() {
757        let mut queue = EventQueue::new();
758        queue.send(event(EventKind::Pressed, 1));
759        assert_eq!(queue.send(pointer_move(1, 10)), PushOutcome::Queued);
760        for x in 11..200 {
761            assert_eq!(queue.send(pointer_move(1, x)), PushOutcome::Coalesced);
762        }
763        assert_eq!(queue.len(), 2);
764        queue.pop_front();
765        assert_eq!(queue.pop_front().unwrap().pointer, Some([199, 0, 100, 100]));
766        assert_eq!(queue.dropped(), 0);
767    }
768
769    #[test]
770    fn coalescing_moves_the_latest_event_to_the_back_even_when_not_at_the_tail() {
771        let mut queue = EventQueue::new();
772        queue.send(event(EventKind::Pressed, 1));
773        queue.send(pointer_move(1, 1));
774        queue.send(event(EventKind::ValueChanged, 1));
775        queue.send(event(EventKind::Scroll, 1));
776        queue.send(pointer_move(2, 5));
777        assert_eq!(queue.send(pointer_move(1, 2)), PushOutcome::Coalesced);
778        assert_eq!(
779            queue.send(event(EventKind::ValueChanged, 1)),
780            PushOutcome::Coalesced
781        );
782        assert_eq!(
783            queue.send(event(EventKind::LongPressedRepeat, 1)),
784            PushOutcome::Queued
785        );
786        assert_eq!(
787            queue.send(event(EventKind::LongPressedRepeat, 1)),
788            PushOutcome::Coalesced
789        );
790        let mut positions = Vec::new();
791        while let Some(event) = queue.pop_front() {
792            positions.push((event.code, event.target as usize, event.pointer));
793        }
794        assert_eq!(
795            positions,
796            [
797                (EventKind::Pressed, 1, None),
798                (EventKind::Scroll, 1, None),
799                (EventKind::Pressing, 2, Some([5, 0, 100, 100])),
800                (EventKind::Pressing, 1, Some([2, 0, 100, 100])),
801                (EventKind::ValueChanged, 1, None),
802                (EventKind::LongPressedRepeat, 1, None),
803            ]
804        );
805        assert_eq!(queue.dropped(), 0);
806    }
807
808    #[test]
809    fn coalescing_never_crosses_a_lifecycle_event_of_the_same_target() {
810        let mut queue = EventQueue::new();
811        queue.send(pointer_move(1, 1));
812        queue.send(event(EventKind::Key, 1));
813        assert_eq!(queue.send(pointer_move(1, 2)), PushOutcome::Queued);
814        queue.send(event(EventKind::ValueChanged, 2));
815        queue.send(event(EventKind::Clicked, 3));
816        assert_eq!(
817            queue.send(event(EventKind::ValueChanged, 2)),
818            PushOutcome::Coalesced
819        );
820        assert_eq!(
821            drain(&mut queue),
822            [
823                (EventKind::Pressing, 1),
824                (EventKind::Key, 1),
825                (EventKind::Pressing, 1),
826                (EventKind::Clicked, 3),
827                (EventKind::ValueChanged, 2),
828            ]
829        );
830    }
831
832    #[test]
833    fn full_queue_never_evicts_a_more_important_event() {
834        let mut queue = EventQueue::new();
835        for address in 1..=5 {
836            queue.send(event(EventKind::ValueChanged, address));
837            queue.send(pointer_move(address, 0));
838            queue.send(event(EventKind::ScrollEnd, address));
839        }
840        queue.send(event(EventKind::Focused, 99));
841        assert!(queue.is_full());
842        let expect = |queue: &mut EventQueue, code, address, outcome| {
843            assert_eq!(queue.send(event(code, address)), outcome, "{code:?}");
844        };
845        use PushOutcome::{Dropped, EvictedOldest};
846
847        // Low and transient arrivals evict low events first.
848        expect(&mut queue, EventKind::ScrollBegin, 50, EvictedOldest);
849        expect(&mut queue, EventKind::Pressing, 60, EvictedOldest);
850        for address in 10..=13 {
851            expect(&mut queue, EventKind::Focused, address, EvictedOldest);
852        }
853        // No low event is left: a low arrival is rejected, the others evict
854        // the oldest transient event.
855        expect(&mut queue, EventKind::ScrollBegin, 51, Dropped);
856        expect(&mut queue, EventKind::Pressing, 61, EvictedOldest);
857        for address in 14..=19 {
858            expect(&mut queue, EventKind::Focused, address, EvictedOldest);
859        }
860        // Only state and lifecycle events are left: a transient arrival is
861        // rejected, a state or lifecycle arrival evicts the oldest state event.
862        expect(&mut queue, EventKind::Pressing, 62, Dropped);
863        expect(&mut queue, EventKind::SizeChanged, 70, EvictedOldest);
864        expect(&mut queue, EventKind::Focused, 20, EvictedOldest);
865
866        let mut expected: Vec<_> = (3..=5)
867            .map(|address| (EventKind::ValueChanged, address))
868            .collect();
869        expected.push((EventKind::Focused, 99));
870        expected.extend((10..=19).map(|address| (EventKind::Focused, address)));
871        expected.push((EventKind::SizeChanged, 70));
872        expected.push((EventKind::Focused, 20));
873        assert_eq!(drain(&mut queue), expected);
874        assert_eq!(queue.dropped(), 17);
875    }
876
877    /// The window is resized while a list inside it is flung, and the consumer
878    /// is busy: the scroll burst must not push out the resize.
879    #[test]
880    fn a_scroll_burst_keeps_the_latest_resize() {
881        let mut queue = EventQueue::new();
882        let (window, list) = (1, 2);
883        queue.send(event(EventKind::SizeChanged, window));
884        queue.send(event(EventKind::StyleChanged, window));
885        for step in 0..500 {
886            queue.send(event(EventKind::Scroll, list));
887            if step == 250 {
888                assert_eq!(
889                    queue.send(event(EventKind::SizeChanged, window)),
890                    PushOutcome::Coalesced
891                );
892            }
893            if step % 50 == 0 {
894                queue.send(event(EventKind::ScrollBegin, list));
895                queue.send(event(EventKind::ScrollEnd, list));
896            }
897        }
898        let drained = drain(&mut queue);
899        assert_eq!(
900            only(&drained, window),
901            [EventKind::StyleChanged, EventKind::SizeChanged]
902        );
903        assert_eq!(drained.len(), WINDOW_EVENT_QUEUE_CAPACITY);
904    }
905
906    #[test]
907    fn lifecycle_events_are_never_evicted() {
908        let mut queue = EventQueue::new();
909        for address in 1..=WINDOW_EVENT_QUEUE_CAPACITY {
910            queue.send(event(EventKind::Clicked, address));
911        }
912        for code in [
913            EventKind::Clicked,
914            EventKind::Pressing,
915            EventKind::ValueChanged,
916            EventKind::Scroll,
917        ] {
918            assert_eq!(queue.send(event(code, 99)), PushOutcome::Dropped);
919        }
920        assert_eq!(
921            drain(&mut queue),
922            (1..=WINDOW_EVENT_QUEUE_CAPACITY)
923                .map(|address| (EventKind::Clicked, address))
924                .collect::<Vec<_>>()
925        );
926        assert_eq!(queue.dropped(), 4);
927    }
928
929    #[test]
930    fn events_are_sorted_in_tiers() {
931        for code in [EventKind::Pressing, EventKind::LongPressedRepeat] {
932            assert_eq!(tier(code), Tier::Transient, "{code:?}");
933        }
934        for code in [
935            EventKind::ValueChanged,
936            EventKind::SizeChanged,
937            EventKind::StyleChanged,
938        ] {
939            assert_eq!(tier(code), Tier::State, "{code:?}");
940        }
941        for code in [
942            EventKind::Scroll,
943            EventKind::ScrollBegin,
944            EventKind::ScrollThrowBegin,
945            EventKind::ScrollEnd,
946            EventKind::LayoutChanged,
947            EventKind::HoverOver,
948            EventKind::HoverLeave,
949            EventKind::DrawMain,
950            EventKind::Refresh,
951            EventKind::InvalidateArea,
952            EventKind::HitTest,
953            EventKind::Create,
954            EventKind::Insert,
955            EventKind::Delete,
956        ] {
957            assert_eq!(tier(code), Tier::Low, "{code:?}");
958        }
959        for code in [
960            EventKind::Pressed,
961            EventKind::Released,
962            EventKind::PressLost,
963            EventKind::Clicked,
964            EventKind::ShortClicked,
965            EventKind::LongPressed,
966            EventKind::Key,
967            EventKind::Focused,
968            EventKind::Defocused,
969            EventKind::CloseRequested,
970            EventKind::Ready,
971            EventKind::Cancel,
972            EventKind::Custom1,
973            EventKind::Custom2,
974        ] {
975            assert_eq!(tier(code), Tier::Lifecycle, "{code:?}");
976        }
977    }
978
979    /// A slider drag inside one LVGL poll: `Pressing` and `ValueChanged`
980    /// alternate hundreds of times while unrelated input fills the queue.
981    #[test]
982    fn slider_drag_burst_keeps_the_press_whole() {
983        let mut queue = EventQueue::new();
984        assert_eq!(
985            queue.send(event(EventKind::Pressed, 1)),
986            PushOutcome::Queued
987        );
988        for step in 0..512 {
989            queue.send(pointer_move(1, step));
990            queue.send(event(EventKind::ValueChanged, 1));
991            queue.send(event(EventKind::Scroll, 3));
992            queue.send_by_code(event(EventKind::Clicked, 2));
993        }
994        for code in SHORT_PRESS_END {
995            assert_ne!(queue.send(event(code, 1)), PushOutcome::Dropped, "{code:?}");
996        }
997        assert!(queue.dropped() > 0);
998
999        let drained = drain(&mut queue);
1000        assert_eq!(
1001            only(&drained, 1),
1002            [
1003                EventKind::Pressed,
1004                EventKind::Released,
1005                EventKind::ShortClicked,
1006                EventKind::SingleClicked,
1007                EventKind::Clicked,
1008            ],
1009            "drag moves are evicted for the unrelated clicks, the press is kept whole"
1010        );
1011        assert!(only(&drained, 2).len() >= WINDOW_EVENT_QUEUE_CAPACITY / 2);
1012    }
1013
1014    /// A held button: `LongPressed`, then `Pressing` and `LongPressedRepeat`
1015    /// alternate while the user types into another widget.
1016    #[test]
1017    fn held_button_while_typing_keeps_the_press_whole() {
1018        let mut queue = EventQueue::new();
1019        queue.send(event(EventKind::Pressed, 1));
1020        queue.send(event(EventKind::Focused, 2));
1021        for step in 0..300 {
1022            if step == 3 {
1023                assert_eq!(
1024                    queue.send(event(EventKind::LongPressed, 1)),
1025                    PushOutcome::Queued
1026                );
1027            }
1028            queue.send(pointer_move(1, step));
1029            queue.send(event(EventKind::LongPressedRepeat, 1));
1030            queue.send(Event::new(
1031                EventKind::Key,
1032                object(2),
1033                Some(Key::Character(b'a')),
1034            ));
1035            queue.send(event(EventKind::ValueChanged, 2));
1036        }
1037        for code in [EventKind::Released, EventKind::Clicked] {
1038            assert_ne!(queue.send(event(code, 1)), PushOutcome::Dropped, "{code:?}");
1039        }
1040        assert!(queue.dropped() > 0, "keys beyond the free room are lost");
1041
1042        let drained = drain(&mut queue);
1043        assert_eq!(
1044            only(&drained, 1)
1045                .into_iter()
1046                .filter(|code| tier(*code) == Tier::Lifecycle)
1047                .collect::<Vec<_>>(),
1048            [
1049                EventKind::Pressed,
1050                EventKind::LongPressed,
1051                EventKind::Released,
1052                EventKind::Clicked,
1053            ]
1054        );
1055        let first_key = drained
1056            .iter()
1057            .position(|(code, _)| *code == EventKind::Key)
1058            .unwrap();
1059        assert_eq!(drained[1], (EventKind::Focused, 2));
1060        assert!(first_key > 1);
1061    }
1062
1063    #[test]
1064    fn a_rejected_press_drops_the_rest_of_its_press() {
1065        let mut queue = EventQueue::new();
1066        let room = flood(&mut queue, EventKind::Key, 9);
1067        assert_eq!(room, WINDOW_EVENT_QUEUE_CAPACITY);
1068        queue.pop_front();
1069        queue.pop_front();
1070        // Two free slots: not enough for the press and its end.
1071        assert_eq!(
1072            queue.send(event(EventKind::Pressed, 1)),
1073            PushOutcome::Dropped
1074        );
1075        for code in [
1076            EventKind::Pressing,
1077            EventKind::LongPressed,
1078            EventKind::LongPressedRepeat,
1079            EventKind::Released,
1080            EventKind::ShortClicked,
1081            EventKind::DoubleClicked,
1082            EventKind::Clicked,
1083        ] {
1084            assert_eq!(queue.send(event(code, 1)), PushOutcome::Dropped, "{code:?}");
1085        }
1086        // A press lost to a slide onto another widget is dropped too.
1087        assert_eq!(
1088            queue.send(event(EventKind::Pressed, 2)),
1089            PushOutcome::Dropped
1090        );
1091        assert_eq!(
1092            queue.send(event(EventKind::PressLost, 2)),
1093            PushOutcome::Dropped
1094        );
1095        let drained = drain(&mut queue);
1096        assert!(only(&drained, 1).is_empty());
1097        assert!(only(&drained, 2).is_empty());
1098        assert_eq!(queue.dropped(), 1 + 1 + 7 + 2);
1099
1100        // The next press of the same target is accepted again.
1101        assert_eq!(
1102            queue.send(event(EventKind::Pressed, 1)),
1103            PushOutcome::Queued
1104        );
1105        assert_eq!(
1106            queue.send(event(EventKind::Released, 1)),
1107            PushOutcome::Queued
1108        );
1109        assert_eq!(
1110            drain(&mut queue),
1111            [(EventKind::Pressed, 1), (EventKind::Released, 1)]
1112        );
1113    }
1114
1115    #[test]
1116    fn an_accepted_press_reserves_room_for_its_end() {
1117        let mut queue = EventQueue::new();
1118        queue.send(event(EventKind::Pressed, 1));
1119        assert_eq!(
1120            queue.send_by_code(event(EventKind::CloseRequested, 2)),
1121            PushOutcome::Queued
1122        );
1123        let room = flood(&mut queue, EventKind::Key, 9);
1124        assert_eq!(
1125            room,
1126            WINDOW_EVENT_QUEUE_CAPACITY - 1 - PRESS_END_RESERVATION as usize
1127        );
1128        for code in SHORT_PRESS_END {
1129            assert_eq!(queue.send(event(code, 1)), PushOutcome::Queued, "{code:?}");
1130        }
1131        assert!(queue.is_full());
1132        assert!(!queue.follows_presses(), "the click ends the press");
1133        let drained = drain(&mut queue);
1134        assert_eq!(drained[0], (EventKind::Pressed, 1));
1135        assert_eq!(drained[1], (EventKind::CloseRequested, 2));
1136        assert_eq!(only(&drained, 1)[1..], SHORT_PRESS_END);
1137    }
1138
1139    #[test]
1140    fn a_full_queue_of_moves_still_takes_the_end_of_the_press() {
1141        let mut queue = EventQueue::new();
1142        queue.send(event(EventKind::Pressed, 1));
1143        for address in 2..=WINDOW_EVENT_QUEUE_CAPACITY {
1144            queue.send(pointer_move(address, 0));
1145        }
1146        assert!(queue.is_full());
1147        for code in SHORT_PRESS_END {
1148            assert_eq!(
1149                queue.send(event(code, 1)),
1150                PushOutcome::EvictedOldest,
1151                "{code:?}"
1152            );
1153        }
1154        let drained = drain(&mut queue);
1155        assert_eq!(drained[0], (EventKind::Pressed, 1));
1156        assert_eq!(only(&drained, 1)[1..], SHORT_PRESS_END);
1157    }
1158
1159    #[test]
1160    fn press_lost_and_clicks_give_back_the_reservation() {
1161        let mut queue = EventQueue::new();
1162        queue.send(event(EventKind::Pressed, 1));
1163        queue.send(event(EventKind::PressLost, 1));
1164        assert!(!queue.follows_presses());
1165        queue.send(event(EventKind::Pressed, 2));
1166        queue.send(event(EventKind::LongPressed, 2));
1167        queue.send(event(EventKind::Released, 2));
1168        queue.send(event(EventKind::Clicked, 2));
1169        assert!(!queue.follows_presses());
1170        assert_eq!(
1171            flood(&mut queue, EventKind::Key, 9),
1172            WINDOW_EVENT_QUEUE_CAPACITY - 6
1173        );
1174    }
1175
1176    #[test]
1177    fn a_release_without_click_keeps_its_reservation_until_the_next_press() {
1178        let mut queue = EventQueue::new();
1179        // A scroll ends the press with a release and no click.
1180        queue.send(event(EventKind::Pressed, 1));
1181        queue.send(event(EventKind::Released, 1));
1182        assert_eq!(drain(&mut queue).len(), 2);
1183        assert_eq!(
1184            flood(&mut queue, EventKind::Key, 9),
1185            WINDOW_EVENT_QUEUE_CAPACITY - 3
1186        );
1187        drain(&mut queue);
1188        queue.send(event(EventKind::Pressed, 2));
1189        queue.send(event(EventKind::PressLost, 2));
1190        assert!(!queue.follows_presses());
1191        drain(&mut queue);
1192        assert_eq!(
1193            flood(&mut queue, EventKind::Key, 9),
1194            WINDOW_EVENT_QUEUE_CAPACITY
1195        );
1196    }
1197
1198    #[test]
1199    fn a_press_without_end_holds_one_reservation_until_its_device_presses_again() {
1200        let mut queue = EventQueue::new();
1201        let encoder = device(3);
1202        // An encoder long press that leaves edit mode sends nothing after
1203        // `Pressed`, twice.
1204        for target in [1, 2] {
1205            assert_eq!(
1206                queue.push(event(EventKind::Pressed, target), encoder),
1207                PushOutcome::Queued
1208            );
1209        }
1210        assert_eq!(queue.followed_presses().len(), 1);
1211        assert_eq!(
1212            flood(&mut queue, EventKind::Key, 9),
1213            WINDOW_EVENT_QUEUE_CAPACITY - 2 - PRESS_END_RESERVATION as usize
1214        );
1215        drain(&mut queue);
1216        // The next press of the encoder ends and reserves for itself only.
1217        queue.push(event(EventKind::Pressed, 3), encoder);
1218        queue.push(event(EventKind::Released, 3), encoder);
1219        queue.push(event(EventKind::Clicked, 3), encoder);
1220        assert!(!queue.follows_presses());
1221        drain(&mut queue);
1222        assert_eq!(
1223            flood(&mut queue, EventKind::Key, 9),
1224            WINDOW_EVENT_QUEUE_CAPACITY
1225        );
1226    }
1227
1228    #[test]
1229    fn a_pointer_press_stays_whole_while_the_encoder_presses_twice() {
1230        let mut queue = EventQueue::new();
1231        let (pointer, encoder) = (device(1), device(3));
1232        queue.push(event(EventKind::Pressed, 1), pointer);
1233        queue.push(event(EventKind::Pressed, 7), encoder);
1234        queue.push(pointer_move(1, 4), pointer);
1235        queue.push(event(EventKind::Pressed, 8), encoder);
1236        queue.push(event(EventKind::Released, 8), encoder);
1237        queue.push(event(EventKind::Clicked, 8), encoder);
1238        assert_eq!(
1239            flood(&mut queue, EventKind::Key, 9),
1240            WINDOW_EVENT_QUEUE_CAPACITY - 5 - PRESS_END_RESERVATION as usize,
1241            "only the pointer press still holds a reservation"
1242        );
1243        for code in SHORT_PRESS_END {
1244            assert_ne!(
1245                queue.push(event(code, 1), pointer),
1246                PushOutcome::Dropped,
1247                "{code:?}"
1248            );
1249        }
1250        let drained = drain(&mut queue);
1251        assert_eq!(
1252            only(&drained, 1)
1253                .into_iter()
1254                .filter(|code| tier(*code) == Tier::Lifecycle)
1255                .collect::<Vec<_>>(),
1256            [
1257                EventKind::Pressed,
1258                EventKind::Released,
1259                EventKind::ShortClicked,
1260                EventKind::SingleClicked,
1261                EventKind::Clicked,
1262            ]
1263        );
1264        assert_eq!(
1265            only(&drained, 8),
1266            [EventKind::Pressed, EventKind::Released, EventKind::Clicked]
1267        );
1268    }
1269
1270    #[test]
1271    fn a_keypad_press_ends_on_the_focused_widget() {
1272        let mut queue = EventQueue::new();
1273        let keypad = device(2);
1274        queue.push(event(EventKind::Pressed, 1), keypad);
1275        flood(&mut queue, EventKind::Key, 9);
1276        // The focus moved to widget 2 before the key was released.
1277        for code in SHORT_PRESS_END {
1278            assert_eq!(
1279                queue.push(event(code, 2), keypad),
1280                PushOutcome::Queued,
1281                "{code:?}"
1282            );
1283        }
1284        let drained = drain(&mut queue);
1285        assert_eq!(only(&drained, 1), [EventKind::Pressed]);
1286        assert_eq!(only(&drained, 2), SHORT_PRESS_END);
1287
1288        // The end of a rejected keypad press is dropped on any widget.
1289        flood(&mut queue, EventKind::Key, 9);
1290        assert_eq!(
1291            queue.push(event(EventKind::Pressed, 1), keypad),
1292            PushOutcome::Dropped
1293        );
1294        drain(&mut queue);
1295        for code in SHORT_PRESS_END {
1296            assert_eq!(
1297                queue.push(event(code, 2), keypad),
1298                PushOutcome::Dropped,
1299                "{code:?}"
1300            );
1301        }
1302        assert!(queue.is_empty());
1303    }
1304
1305    #[test]
1306    fn two_devices_pressing_one_widget_keep_separate_presses() {
1307        let mut queue = EventQueue::new();
1308        let (pointer, keypad) = (device(1), device(2));
1309        queue.push(event(EventKind::Pressed, 1), pointer);
1310        queue.push(event(EventKind::Pressed, 1), keypad);
1311        assert_eq!(queue.followed_presses().len(), 2);
1312        assert_eq!(
1313            flood(&mut queue, EventKind::Key, 9),
1314            WINDOW_EVENT_QUEUE_CAPACITY - 2 - 2 * PRESS_END_RESERVATION as usize
1315        );
1316        for code in SHORT_PRESS_END {
1317            assert_eq!(queue.push(event(code, 1), pointer), PushOutcome::Queued);
1318        }
1319        assert_eq!(queue.followed_presses().len(), 1);
1320        assert_eq!(queue.followed_presses()[0].device, keypad);
1321        for code in [
1322            EventKind::LongPressed,
1323            EventKind::Released,
1324            EventKind::Clicked,
1325        ] {
1326            assert_eq!(queue.push(event(code, 1), keypad), PushOutcome::Queued);
1327        }
1328        assert!(!queue.follows_presses());
1329    }
1330
1331    #[test]
1332    fn presses_sent_by_code_are_queued_by_tier_only() {
1333        let mut queue = EventQueue::new();
1334        flood(&mut queue, EventKind::Key, 9);
1335        assert_eq!(
1336            queue.send_by_code(event(EventKind::Pressed, 1)),
1337            PushOutcome::Dropped
1338        );
1339        assert!(!queue.follows_presses());
1340        drain(&mut queue);
1341        // A rejected press sent by code never blocks later clicks sent by code.
1342        for code in [EventKind::Released, EventKind::Clicked] {
1343            assert_eq!(
1344                queue.send_by_code(event(code, 2)),
1345                PushOutcome::Queued,
1346                "{code:?}"
1347            );
1348        }
1349        // And a press sent by code reserves nothing.
1350        queue.send_by_code(event(EventKind::Pressed, 3));
1351        assert!(!queue.follows_presses());
1352        assert_eq!(
1353            flood(&mut queue, EventKind::Key, 9),
1354            WINDOW_EVENT_QUEUE_CAPACITY - 3
1355        );
1356    }
1357
1358    /// LVGL never ends these presses: an encoder long press that leaves edit
1359    /// mode, and a keypad whose focus moved to another window. Once the window
1360    /// sees the devices released, it gives their reservations back.
1361    #[test]
1362    fn presses_of_released_devices_give_their_reservations_back() {
1363        let mut queue = EventQueue::new();
1364        let (pointer, keypad, encoder) = (device(1), device(2), device(3));
1365        queue.push(event(EventKind::Pressed, 1), encoder);
1366        queue.push(event(EventKind::Pressed, 2), keypad);
1367        queue.push(event(EventKind::Pressed, 3), pointer);
1368        // Only four slots are left, and two reservations are stale: a press of
1369        // a fourth device would be rejected.
1370        let reserved = 3 * PRESS_END_RESERVATION as usize;
1371        assert_eq!(
1372            flood(&mut queue, EventKind::Key, 9),
1373            WINDOW_EVENT_QUEUE_CAPACITY - 3 - reserved
1374        );
1375        assert_eq!(
1376            queue.push(event(EventKind::Pressed, 4), device(4)),
1377            PushOutcome::Dropped
1378        );
1379        drain(&mut queue);
1380        assert_eq!(queue.followed_presses().len(), 4);
1381
1382        // The pointer is still pressed.
1383        queue.forget_ended_presses(|source| source == pointer);
1384        assert_eq!(queue.followed_presses().len(), 1);
1385        assert_eq!(queue.followed_presses()[0].device, pointer);
1386        assert_eq!(
1387            flood(&mut queue, EventKind::Key, 9),
1388            WINDOW_EVENT_QUEUE_CAPACITY - PRESS_END_RESERVATION as usize
1389        );
1390        for code in SHORT_PRESS_END {
1391            assert_ne!(
1392                queue.push(event(code, 3), pointer),
1393                PushOutcome::Dropped,
1394                "{code:?}"
1395            );
1396        }
1397        assert!(!queue.follows_presses());
1398    }
1399
1400    /// A released device has already sent the end of its press, so forgetting
1401    /// a rejected press never lets its end through.
1402    #[test]
1403    fn forgetting_ended_presses_keeps_live_rejected_ones() {
1404        let mut queue = EventQueue::new();
1405        let keypad = device(2);
1406        flood(&mut queue, EventKind::Key, 9);
1407        assert_eq!(
1408            queue.push(event(EventKind::Pressed, 1), keypad),
1409            PushOutcome::Dropped
1410        );
1411        drain(&mut queue);
1412        // Still held: the rejected press stays followed.
1413        queue.forget_ended_presses(|source| source == keypad);
1414        for code in SHORT_PRESS_END {
1415            assert_eq!(
1416                queue.push(event(code, 2), keypad),
1417                PushOutcome::Dropped,
1418                "{code:?}"
1419            );
1420        }
1421        assert!(!queue.follows_presses());
1422
1423        // Released without an end for this window, then forgotten.
1424        flood(&mut queue, EventKind::Key, 9);
1425        queue.push(event(EventKind::Pressed, 1), keypad);
1426        drain(&mut queue);
1427        queue.forget_ended_presses(|_| false);
1428        assert!(!queue.follows_presses());
1429    }
1430
1431    #[test]
1432    fn a_device_reset_forgets_its_press() {
1433        let mut queue = EventQueue::new();
1434        let (pointer, keypad) = (device(1), device(2));
1435        queue.push(event(EventKind::Pressed, 1), pointer);
1436        queue.push(event(EventKind::Pressed, 2), keypad);
1437        assert_eq!(
1438            queue.push(event(EventKind::InputDeviceReset, 1), pointer),
1439            PushOutcome::Queued
1440        );
1441        assert_eq!(queue.followed_presses().len(), 1);
1442        assert_eq!(queue.followed_presses()[0].device, keypad);
1443        // A reset sent by code forgets nothing.
1444        queue.push(event(EventKind::InputDeviceReset, 2), ptr::null());
1445        assert_eq!(queue.followed_presses().len(), 1);
1446        assert_eq!(
1447            drain(&mut queue),
1448            [
1449                (EventKind::Pressed, 1),
1450                (EventKind::Pressed, 2),
1451                (EventKind::InputDeviceReset, 1),
1452                (EventKind::InputDeviceReset, 2),
1453            ]
1454        );
1455        assert_eq!(
1456            flood(&mut queue, EventKind::Key, 9),
1457            WINDOW_EVENT_QUEUE_CAPACITY - PRESS_END_RESERVATION as usize
1458        );
1459    }
1460
1461    /// The consumer discards a widget while its keypad press is queued, and
1462    /// the keypad then releases on another widget: the end must not arrive
1463    /// without its `Pressed`.
1464    #[test]
1465    fn discarding_a_target_keeps_its_press_events() {
1466        let mut queue = EventQueue::new();
1467        let keypad = device(2);
1468        queue.push(event(EventKind::Pressed, 1), keypad);
1469        queue.push(pointer_move(1, 3), keypad);
1470        queue.push(event(EventKind::ValueChanged, 1), keypad);
1471        queue.push(event(EventKind::Focused, 1), ptr::null());
1472        queue.push(event(EventKind::Clicked, 3), ptr::null());
1473        queue.discard_target(object(1));
1474        assert!(!queue.follows_presses(), "the reservation is given back");
1475        for code in SHORT_PRESS_END {
1476            assert_eq!(
1477                queue.push(event(code, 2), keypad),
1478                PushOutcome::Queued,
1479                "{code:?}"
1480            );
1481        }
1482        let mut expected = Vec::from([(EventKind::Pressed, 0), (EventKind::Clicked, 3)]);
1483        expected.extend(SHORT_PRESS_END.map(|code| (code, 2)));
1484        assert_eq!(drain(&mut queue), expected);
1485
1486        // The ends of a press on the discarded widget are kept as well.
1487        queue.push(event(EventKind::Pressed, 1), keypad);
1488        queue.push(event(EventKind::LongPressed, 1), keypad);
1489        queue.push(event(EventKind::Released, 1), keypad);
1490        queue.push(event(EventKind::LongPressedRepeat, 1), keypad);
1491        queue.discard_target(object(1));
1492        assert_eq!(
1493            drain(&mut queue),
1494            [
1495                (EventKind::Pressed, 0),
1496                (EventKind::LongPressed, 0),
1497                (EventKind::Released, 0),
1498            ]
1499        );
1500    }
1501
1502    /// Latest wins is matched by kind and target only: two devices moving on
1503    /// one widget, or changing its value, merge into the latest event.
1504    #[test]
1505    fn two_devices_on_one_widget_share_the_latest_move_and_value() {
1506        let mut queue = EventQueue::new();
1507        let (pointer, keypad) = (device(1), device(2));
1508        queue.push(event(EventKind::Pressed, 1), pointer);
1509        queue.push(event(EventKind::Pressed, 1), keypad);
1510        queue.push(pointer_move(1, 4), pointer);
1511        assert_eq!(
1512            queue.push(pointer_move(1, 8), keypad),
1513            PushOutcome::Coalesced
1514        );
1515        queue.push(event(EventKind::ValueChanged, 1), pointer);
1516        assert_eq!(
1517            queue.push(event(EventKind::ValueChanged, 1), keypad),
1518            PushOutcome::Coalesced
1519        );
1520        queue.push(event(EventKind::LongPressedRepeat, 1), pointer);
1521        assert_eq!(
1522            queue.push(event(EventKind::LongPressedRepeat, 1), keypad),
1523            PushOutcome::Coalesced
1524        );
1525        let drained: Vec<_> = core::iter::from_fn(|| queue.pop_front())
1526            .map(|event| (event.code, event.pointer))
1527            .collect();
1528        assert_eq!(
1529            drained,
1530            [
1531                (EventKind::Pressed, None),
1532                (EventKind::Pressed, None),
1533                (EventKind::Pressing, Some([8, 0, 100, 100])),
1534                (EventKind::ValueChanged, None),
1535                (EventKind::LongPressedRepeat, None),
1536            ]
1537        );
1538    }
1539
1540    #[test]
1541    fn forgetting_a_target_forgets_its_accepted_press() {
1542        let mut queue = EventQueue::new();
1543        queue.push(event(EventKind::Pressed, 1), device(1));
1544        queue.discard_target(object(1));
1545        assert!(!queue.follows_presses());
1546
1547        queue.push(event(EventKind::Pressed, 2), device(1));
1548        queue.clear_target(object(2));
1549        assert!(!queue.follows_presses());
1550
1551        queue.push(event(EventKind::Pressed, 3), device(1));
1552        queue.push(event(EventKind::Pressed, 4), device(2));
1553        queue.clear_dead_targets(|target| target == object(4));
1554        assert_eq!(queue.followed_presses().len(), 1);
1555        assert_eq!(queue.followed_presses()[0].target, object(4));
1556        drain(&mut queue);
1557
1558        // A rejected press is kept: its device may end it on another widget.
1559        flood(&mut queue, EventKind::Key, 9);
1560        assert_eq!(
1561            queue.push(event(EventKind::Pressed, 5), device(3)),
1562            PushOutcome::Dropped
1563        );
1564        drain(&mut queue);
1565        queue.discard_target(object(5));
1566        queue.clear_dead_targets(|target| target != object(5));
1567        assert_eq!(
1568            queue.push(event(EventKind::Released, 6), device(3)),
1569            PushOutcome::Dropped
1570        );
1571    }
1572
1573    #[test]
1574    fn losses_are_reported_at_most_once_per_interval() {
1575        let mut queue = EventQueue::new();
1576        assert_eq!(queue.take_loss_report(0), None);
1577        flood(&mut queue, EventKind::Key, 1);
1578        queue.send(event(EventKind::Key, 1));
1579        assert!(queue.has_unreported_losses());
1580        assert_eq!(
1581            queue.take_loss_report(5_000),
1582            Some(LossReport { lost: 2, total: 2 })
1583        );
1584        assert!(!queue.has_unreported_losses());
1585
1586        // The consumer never drains the queue: losses keep being reported.
1587        for now in [5_100, 5_900] {
1588            queue.send(event(EventKind::Key, 1));
1589            assert_eq!(queue.take_loss_report(now), None);
1590        }
1591        queue.send(event(EventKind::Key, 1));
1592        assert_eq!(
1593            queue.take_loss_report(6_000),
1594            Some(LossReport { lost: 3, total: 5 })
1595        );
1596        assert_eq!(queue.take_loss_report(60_000), None, "nothing new lost");
1597
1598        // Ticks wrap around.
1599        let mut queue = EventQueue::new();
1600        flood(&mut queue, EventKind::Key, 1);
1601        assert!(queue.take_loss_report(u32::MAX - 10).is_some());
1602        queue.send(event(EventKind::Key, 1));
1603        assert_eq!(queue.take_loss_report(100), None);
1604        assert_eq!(
1605            queue.take_loss_report(LOSS_REPORT_INTERVAL - 11),
1606            Some(LossReport { lost: 1, total: 2 })
1607        );
1608        assert_eq!(queue.dropped(), 2);
1609    }
1610
1611    /// Deterministic pseudo-random numbers (xorshift64*).
1612    struct Random(u64);
1613
1614    impl Random {
1615        fn below(&mut self, bound: usize) -> usize {
1616            self.0 ^= self.0 >> 12;
1617            self.0 ^= self.0 << 25;
1618            self.0 ^= self.0 >> 27;
1619            (self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 33) as usize % bound
1620        }
1621    }
1622
1623    /// One input device and its current press: target, press number and
1624    /// whether `LongPressed` was sent.
1625    struct Device {
1626        identifier: usize,
1627        first_target: usize,
1628        targets: usize,
1629        /// Whether it may release on another widget, like a keypad.
1630        releases_elsewhere: bool,
1631        press: Option<(usize, usize, bool)>,
1632        abandoned: bool,
1633    }
1634
1635    /// A queue fed by the randomized test, which checks every push against
1636    /// its outcome. Each event carries its sequence number and its press
1637    /// number (0 outside a device press) in `pointer`.
1638    struct Stream {
1639        queue: EventQueue,
1640        sequence: i32,
1641        /// Per sequence number: whether the event is lifecycle and queued, so
1642        /// the consumer must receive it.
1643        must_arrive: Vec<bool>,
1644    }
1645
1646    impl Stream {
1647        fn tier_count(&self, wanted: Tier) -> usize {
1648            (0..self.queue.len())
1649                .filter(|&index| {
1650                    self.queue
1651                        .get(index)
1652                        .is_some_and(|event| tier(event.code) == wanted)
1653                })
1654                .count()
1655        }
1656
1657        fn sequences(&self) -> Vec<i32> {
1658            (0..self.queue.len())
1659                .filter_map(|index| self.queue.get(index))
1660                .map(|event| event.pointer.unwrap()[0])
1661                .collect()
1662        }
1663
1664        fn push(&mut self, code: EventKind, target: usize, press: usize, source: usize) {
1665            self.sequence += 1;
1666            let mut queued = event(code, target);
1667            queued.pointer = Some([self.sequence, press as i32, 0, 0]);
1668            let (length, dropped) = (self.queue.len(), self.queue.dropped());
1669            let state = self.tier_count(Tier::State);
1670            let outcome = self.queue.push(queued, device(source));
1671
1672            let back = self
1673                .queue
1674                .len()
1675                .checked_sub(1)
1676                .and_then(|index| self.queue.get(index).map(|event| event.pointer.unwrap()[0]));
1677            let (expected_length, expected_dropped) = match outcome {
1678                PushOutcome::Queued => (length + 1, dropped),
1679                PushOutcome::Coalesced => (length, dropped),
1680                PushOutcome::EvictedOldest => {
1681                    assert_eq!(length, WINDOW_EVENT_QUEUE_CAPACITY, "evicted from room");
1682                    (length, dropped + 1)
1683                }
1684                PushOutcome::Dropped => (length, dropped + 1),
1685            };
1686            assert_eq!(self.queue.len(), expected_length, "{code:?} {outcome:?}");
1687            assert_eq!(
1688                self.queue.dropped(),
1689                expected_dropped,
1690                "{code:?} {outcome:?}"
1691            );
1692            assert_eq!(
1693                back == Some(self.sequence),
1694                outcome != PushOutcome::Dropped,
1695                "{code:?} {outcome:?}"
1696            );
1697            if outcome == PushOutcome::Coalesced {
1698                assert!(tier(code).coalesces(), "{code:?} coalesced");
1699            }
1700            if tier(code) < Tier::State {
1701                assert!(
1702                    self.tier_count(Tier::State) >= state,
1703                    "{code:?} pushed out a state event"
1704                );
1705            }
1706            self.must_arrive
1707                .push(tier(code) == Tier::Lifecycle && outcome != PushOutcome::Dropped);
1708        }
1709
1710        /// Whether the queue still follows a press of the input device
1711        /// `source`, and so may hold slots for it.
1712        fn follows_press_of(&self, source: usize) -> bool {
1713            self.queue.press_index(device(source)).is_some()
1714        }
1715
1716        /// The widget `target` is deleted: the window forgets it in one of
1717        /// the three ways it can.
1718        fn delete(&mut self, target: usize, way: usize) {
1719            let before = self.sequences();
1720            match way {
1721                0 => self.queue.discard_target(object(target)),
1722                1 => self.queue.clear_target(object(target)),
1723                _ => self
1724                    .queue
1725                    .clear_dead_targets(|candidate| candidate != object(target)),
1726            }
1727            let after = self.sequences();
1728            for sequence in before {
1729                if !after.contains(&sequence) {
1730                    self.must_arrive[sequence as usize - 1] = false;
1731                }
1732            }
1733        }
1734    }
1735
1736    /// Random LVGL-like streams from a pointer, a keypad and an encoder,
1737    /// with random consumer pauses. Presses may be left without an end, two
1738    /// devices press the same widgets, the keypad may release on another
1739    /// widget, widgets are deleted and devices reset, code sends press events
1740    /// without a device, and the window forgets the presses of released
1741    /// devices. The consumer never receives the end of a press whose
1742    /// `Pressed` was dropped, events keep their order, value changes stay
1743    /// inside their press, an accepted press arrives whole unless its widget
1744    /// was deleted, every queued lifecycle event arrives, every push reports
1745    /// what it did, and no reset or released device keeps its press.
1746    #[test]
1747    fn random_bursts_keep_presses_whole_and_in_order() {
1748        let mut random = Random(0x9E37_79B9_7F4A_7C15);
1749        let mut stream = Stream {
1750            queue: EventQueue::new(),
1751            sequence: 0,
1752            must_arrive: Vec::new(),
1753        };
1754        let mut devices = [(1, 1, 4, false), (2, 3, 4, true), (3, 5, 3, false)].map(
1755            |(identifier, first_target, targets, releases_elsewhere)| Device {
1756                identifier,
1757                first_target,
1758                targets,
1759                releases_elsewhere,
1760                press: None,
1761                abandoned: false,
1762            },
1763        );
1764        let mut delivered = Vec::new();
1765        // Per press: its device, then the events that hold a reservation,
1766        // pushed and delivered, and whether its widget was deleted during it.
1767        let mut presses: Vec<(usize, usize, usize, bool)> = Vec::new();
1768        let mut replacements = 0;
1769        let mut deletions = 0;
1770
1771        for _ in 0..300_000 {
1772            match random.below(20) {
1773                0..=9 => {
1774                    let device = &mut devices[random.below(3)];
1775                    let source = device.identifier;
1776                    match device.press {
1777                        None => {
1778                            let target = device.first_target + random.below(device.targets);
1779                            presses.push((source, 0, 0, false));
1780                            let press = presses.len();
1781                            replacements += usize::from(core::mem::take(&mut device.abandoned));
1782                            device.press = Some((target, press, false));
1783                            stream.push(EventKind::Pressed, target, press, source);
1784                        }
1785                        Some((target, press, long)) => match random.below(15) {
1786                            0..=5 => stream.push(EventKind::Pressing, target, press, source),
1787                            6 => stream.push(EventKind::ValueChanged, target, press, source),
1788                            7 if !long => {
1789                                stream.push(EventKind::LongPressed, target, press, source);
1790                                presses[press - 1].1 += 1;
1791                                device.press = Some((target, press, true));
1792                            }
1793                            7 => stream.push(EventKind::LongPressedRepeat, target, press, source),
1794                            8 => {
1795                                stream.push(EventKind::PressLost, target, press, source);
1796                                presses[press - 1].1 += 1;
1797                                device.press = None;
1798                            }
1799                            9 => {
1800                                // Released after a scroll: no click.
1801                                stream.push(EventKind::Released, target, press, source);
1802                                presses[press - 1].1 += 1;
1803                                device.press = None;
1804                            }
1805                            10 => {
1806                                // No end at all: an encoder long press that
1807                                // leaves edit mode.
1808                                device.press = None;
1809                                device.abandoned = true;
1810                            }
1811                            11 if !device.releases_elsewhere => {
1812                                // LVGL forgets the pressed widget: the press
1813                                // never ends.
1814                                stream.push(EventKind::InputDeviceReset, target, 0, source);
1815                                assert!(
1816                                    !stream.follows_press_of(source),
1817                                    "a reset device keeps its press"
1818                                );
1819                                device.press = None;
1820                                device.abandoned = true;
1821                            }
1822                            _ => {
1823                                let target = if device.releases_elsewhere && random.below(2) == 0 {
1824                                    device.first_target + random.below(device.targets)
1825                                } else {
1826                                    target
1827                                };
1828                                // LVGL sends a release and its clicks back to back.
1829                                let mut codes = Vec::from([EventKind::Released]);
1830                                if !long {
1831                                    codes.push(EventKind::ShortClicked);
1832                                    codes.push(
1833                                        [
1834                                            EventKind::SingleClicked,
1835                                            EventKind::DoubleClicked,
1836                                            EventKind::TripleClicked,
1837                                        ][random.below(3)],
1838                                    );
1839                                }
1840                                codes.push(EventKind::Clicked);
1841                                for code in codes {
1842                                    stream.push(code, target, press, source);
1843                                    presses[press - 1].1 += 1;
1844                                }
1845                                device.press = None;
1846                            }
1847                        },
1848                    }
1849                }
1850                10 | 11 => stream.push(
1851                    [EventKind::Key, EventKind::Focused, EventKind::Custom1][random.below(3)],
1852                    10 + random.below(3),
1853                    0,
1854                    0,
1855                ),
1856                12 | 13 => stream.push(
1857                    [
1858                        EventKind::Scroll,
1859                        EventKind::ScrollEnd,
1860                        EventKind::ScrollBegin,
1861                    ][random.below(3)],
1862                    1 + random.below(12),
1863                    0,
1864                    0,
1865                ),
1866                14 | 15 => stream.push(
1867                    [EventKind::ValueChanged, EventKind::SizeChanged][random.below(2)],
1868                    20 + random.below(2),
1869                    0,
1870                    0,
1871                ),
1872                16 => {
1873                    // Press events sent by code, without a device.
1874                    let code = [
1875                        EventKind::Pressed,
1876                        EventKind::Pressing,
1877                        EventKind::Released,
1878                        EventKind::Clicked,
1879                        EventKind::PressLost,
1880                    ][random.below(5)];
1881                    stream.push(code, 1 + random.below(7), 0, 0);
1882                }
1883                17 if random.below(20) == 0 => {
1884                    // A widget is deleted, and a new one may take its
1885                    // address. LVGL forgets a press of that widget, except a
1886                    // keypad, which may end it on the next focused widget.
1887                    let target = 1 + random.below(21);
1888                    for device in &mut devices {
1889                        let Some((pressed, press, long)) = device.press else {
1890                            continue;
1891                        };
1892                        if pressed != target {
1893                            continue;
1894                        }
1895                        presses[press - 1].3 = true;
1896                        if device.releases_elsewhere && random.below(2) == 0 {
1897                            let next = device.first_target + random.below(device.targets);
1898                            device.press = Some((next, press, long));
1899                        } else {
1900                            device.press = None;
1901                            device.abandoned = true;
1902                        }
1903                    }
1904                    stream.delete(target, random.below(3));
1905                    deletions += 1;
1906                }
1907                _ => {
1908                    if random.below(4) != 0 {
1909                        // The window forgets the presses of released devices
1910                        // when the consumer pops.
1911                        if random.below(2) == 0 {
1912                            stream.queue.forget_ended_presses(|source| {
1913                                devices.iter().any(|device| {
1914                                    device.press.is_some() && source == device_of(device)
1915                                })
1916                            });
1917                            for device in &devices {
1918                                assert!(
1919                                    device.press.is_some()
1920                                        || !stream.follows_press_of(device.identifier),
1921                                    "a released device keeps its press"
1922                                );
1923                            }
1924                        }
1925                        delivered.extend(stream.queue.pop_front());
1926                    }
1927                }
1928            }
1929        }
1930        delivered.extend(core::iter::from_fn(|| stream.queue.pop_front()));
1931        assert!(stream.queue.dropped() > 10_000, "the stream must overflow");
1932        assert!(
1933            replacements > 1_000,
1934            "presses without an end must be replaced"
1935        );
1936        assert!(deletions > 100, "widgets must be deleted");
1937
1938        // Per device: the press being delivered and whether it was released.
1939        let mut state = [None::<(usize, bool)>; 4];
1940        let mut ended = alloc::vec![false; presses.len() + 1];
1941        let mut arrived = alloc::vec![false; stream.must_arrive.len()];
1942        let mut last_sequence = 0;
1943        let mut accepted = 0;
1944        for event in &delivered {
1945            let [sequence, press, _, _] = event.pointer.unwrap();
1946            let press = press as usize;
1947            assert!(sequence > last_sequence, "events were reordered");
1948            last_sequence = sequence;
1949            arrived[sequence as usize - 1] = true;
1950            if press == 0 {
1951                continue;
1952            }
1953            let source = presses[press - 1].0;
1954            let Some(role) = press_role(event.code) else {
1955                assert_eq!(event.code, EventKind::ValueChanged);
1956                assert!(!ended[press], "a value change crossed the end of its press");
1957                continue;
1958            };
1959            let current = state[source];
1960            match role {
1961                PressRole::Start => {
1962                    accepted += 1;
1963                    state[source] = Some((press, false));
1964                }
1965                PressRole::Progress | PressRole::LongPress | PressRole::Lost => {
1966                    assert_eq!(
1967                        current,
1968                        Some((press, false)),
1969                        "{:?} without its press",
1970                        event.code
1971                    );
1972                }
1973                PressRole::Release => {
1974                    assert_eq!(current, Some((press, false)), "release without its press");
1975                    state[source] = Some((press, true));
1976                }
1977                PressRole::Click | PressRole::Final => {
1978                    assert_eq!(
1979                        current,
1980                        Some((press, true)),
1981                        "{:?} without its release",
1982                        event.code
1983                    );
1984                }
1985            }
1986            if matches!(
1987                role,
1988                PressRole::Lost | PressRole::Release | PressRole::Final
1989            ) {
1990                ended[press] = true;
1991            }
1992            if matches!(role, PressRole::Lost | PressRole::Final) {
1993                state[source] = None;
1994            }
1995            if role != PressRole::Start && role != PressRole::Progress {
1996                presses[press - 1].2 += 1;
1997            }
1998        }
1999        assert!(accepted > 1_000, "presses must get through");
2000        for event in &delivered {
2001            let press = event.pointer.unwrap()[1] as usize;
2002            if event.code == EventKind::Pressed && press > 0 {
2003                let (_, pushed, received, deleted) = presses[press - 1];
2004                if !deleted {
2005                    assert_eq!(pushed, received, "press {press} arrived incomplete");
2006                }
2007            }
2008        }
2009        for (index, must_arrive) in stream.must_arrive.iter().enumerate() {
2010            assert!(
2011                !must_arrive || arrived[index],
2012                "queued lifecycle event {} was lost",
2013                index + 1
2014            );
2015        }
2016    }
2017
2018    fn device_of(model: &Device) -> InputDevice {
2019        device(model.identifier)
2020    }
2021
2022    #[test]
2023    fn key_information_is_captured_with_the_event() {
2024        let mut queue = EventQueue::new();
2025        queue.send(Event::new(EventKind::Key, object(1), Some(Key::Escape)));
2026        assert_eq!(queue.pop_front().unwrap().key, Some(Key::Escape));
2027    }
2028
2029    #[test]
2030    fn discarding_a_target_preserves_the_order_of_the_others() {
2031        let mut queue = EventQueue::new();
2032        // Wrap the ring so the compaction crosses the end of the array.
2033        for _ in 0..12 {
2034            queue.send(event(EventKind::Clicked, 7));
2035        }
2036        for _ in 0..12 {
2037            queue.pop_front();
2038        }
2039        for (index, target) in [1, 2, 1, 3, 2, 1, 3, 3].into_iter().enumerate() {
2040            queue.send(event(
2041                if index % 2 == 0 {
2042                    EventKind::Focused
2043                } else {
2044                    EventKind::Defocused
2045                },
2046                target,
2047            ));
2048        }
2049        queue.discard_target(object(1));
2050        assert_eq!(
2051            drain(&mut queue),
2052            [
2053                (EventKind::Defocused, 2),
2054                (EventKind::Defocused, 3),
2055                (EventKind::Focused, 2),
2056                (EventKind::Focused, 3),
2057                (EventKind::Defocused, 3),
2058            ]
2059        );
2060        assert!(queue.is_empty());
2061        // The ring is fully usable afterwards.
2062        for index in 0..WINDOW_EVENT_QUEUE_CAPACITY {
2063            queue.send(event(EventKind::Clicked, index + 1));
2064        }
2065        assert!(queue.is_full());
2066    }
2067
2068    #[test]
2069    fn clearing_a_target_keeps_events_but_nulls_the_target() {
2070        let mut queue = EventQueue::new();
2071        queue.send(event(EventKind::Pressed, 1));
2072        queue.send(event(EventKind::Clicked, 2));
2073        queue.send(event(EventKind::Released, 1));
2074        queue.clear_target(object(1));
2075        assert_eq!(
2076            drain(&mut queue),
2077            [
2078                (EventKind::Pressed, 0),
2079                (EventKind::Clicked, 2),
2080                (EventKind::Released, 0),
2081            ]
2082        );
2083    }
2084
2085    #[test]
2086    fn dead_targets_are_cleared_and_live_ones_kept() {
2087        let mut queue = EventQueue::new();
2088        for target in [1, 1, 2, 3, 2, 1] {
2089            queue.send(event(EventKind::Clicked, target));
2090        }
2091        let mut calls = 0;
2092        queue.clear_dead_targets(|target| {
2093            calls += 1;
2094            target == object(2)
2095        });
2096        // One call per run of equal targets, not per event.
2097        assert_eq!(calls, 5);
2098        assert_eq!(
2099            drain(&mut queue),
2100            [
2101                (EventKind::Clicked, 0),
2102                (EventKind::Clicked, 0),
2103                (EventKind::Clicked, 2),
2104                (EventKind::Clicked, 0),
2105                (EventKind::Clicked, 2),
2106                (EventKind::Clicked, 0),
2107            ]
2108        );
2109    }
2110
2111    #[test]
2112    fn queue_storage_is_fixed_and_fits_the_window_class() {
2113        extern crate std;
2114        use alloc::collections::VecDeque;
2115        std::println!(
2116            "Event={} Option<Event>={} PressGroup={} old queue={}+{} new queue={} Window={}",
2117            size_of::<Event>(),
2118            size_of::<Option<Event>>(),
2119            size_of::<PressGroup>(),
2120            size_of::<VecDeque<Event>>(),
2121            10 * size_of::<Event>(),
2122            size_of::<EventQueue>(),
2123            size_of::<crate::Window>()
2124        );
2125        assert!(size_of::<crate::Window>() < 65536);
2126        assert!(
2127            size_of::<EventQueue>()
2128                <= RING_CAPACITY * size_of::<Option<Event>>()
2129                    + PRESS_TRACKING_CAPACITY * size_of::<PressGroup>()
2130                    + 24
2131        );
2132    }
2133
2134    #[test]
2135    fn a_burst_never_grows_the_ring() {
2136        // Constructible in a constant: there is no allocation to perform.
2137        const EMPTY: EventQueue = EventQueue::new();
2138        let mut queue = EMPTY;
2139        let size = size_of::<EventQueue>();
2140        for index in 0..10_000usize {
2141            let code = match index % 5 {
2142                0 => EventKind::Pressed,
2143                1 | 2 => EventKind::Pressing,
2144                3 => EventKind::Key,
2145                _ => EventKind::Released,
2146            };
2147            queue.send(event(code, index % 3 + 1));
2148            assert!(queue.len() <= WINDOW_EVENT_QUEUE_CAPACITY);
2149            assert!(queue.followed_presses().len() <= PRESS_TRACKING_CAPACITY);
2150            if index % 7 == 0 {
2151                queue.pop_front();
2152            }
2153        }
2154        assert_eq!(size_of::<EventQueue>(), size);
2155        assert!(queue.dropped() > 0);
2156    }
2157}