1
//! Gamepad manager — cross-platform state for the controller surface
2
//! (`SUPER_PLAN_2` §1 feature 6 + research/03).
3
//!
4
//! Poll + push-driven, like the sensors:
5
//!
6
//! - The **platform backend** (`dll/src/desktop/extra/gamepad/<plat>.rs`) polls `gilrs` / iOS
7
//!   `GCController` / Android `InputDevice` and calls [`push_gamepad_state`] whenever a pad's state
8
//!   changes.
9
//! - The dll **layout pass** drains the channel via [`drain_gamepad_states`] and folds each into
10
//!   the manager through [`GamepadManager::set_state`].
11
//! - **Callbacks** read [`GamepadManager::state`] / [`GamepadManager::primary`] synchronously (via
12
//!   `CallbackInfo::get_gamepad_state`) to drive movement / menu UI.
13
//!
14
//! Unlike the sensors' fixed three slots, the set of pads is dynamic: one
15
//! [`GamepadState`] slot per [`GamepadId`] seen this session, kept across
16
//! frames so a disconnect stays observable (`connected = false`). No
17
//! platform deps (`SUPER_PLAN_2` §0.5); the channel mirrors `sensors.rs`.
18

            
19
use alloc::vec::Vec;
20

            
21
pub use azul_core::gamepad::{GamepadAxis, GamepadButton, GamepadId, GamepadState};
22
use azul_core::{
23
    dom::DomNodeId,
24
    events::{EventData, EventProvider, EventSource as CoreEventSource, EventType, SyntheticEvent},
25
    task::Instant,
26
};
27

            
28
/// Cross-platform gamepad state. One per `App` — the OS exposes a single
29
/// per-process controller subscription, not per-window.
30
#[derive(Debug, Clone, PartialEq, Default)]
31
pub struct GamepadManager {
32
    /// One slot per pad seen this session; `connected` flips to `false` on
33
    /// unplug (the slot is retained so a callback can observe it).
34
    pads: Vec<GamepadState>,
35
    /// `true` when a pad's state advanced since the last event-pass drain.
36
    /// Set by [`set_state`](Self::set_state); cleared by the dll after dispatch.
37
    pending_event: bool,
38
    /// `true` while any node in the current layout registers a
39
    /// `GamepadInput` callback (Hover or Window filter). Recomputed on every
40
    /// relayout by the DOM walk in `shell2::common::layout`; the capability
41
    /// pump polls gilrs/GCController only while this is set (MWA-A1 arming
42
    /// signal — no listeners, no polling, no ~16ms timer).
43
    has_listeners: bool,
44
    /// Connect/disconnect transitions seen since the last drain — `true` for
45
    /// an arrival, `false` for a departure. Drained by
46
    /// [`take_pending_hotplug`](Self::take_pending_hotplug) into
47
    /// `EventType::DeviceConnected` / `DeviceDisconnected`.
48
    pending_hotplug: Vec<bool>,
49
    /// Buttons that went from released to pressed since the last drain, OR-ed
50
    /// across every pad.
51
    ///
52
    /// An EDGE, not a level: holding the D-pad must move focus once, not once
53
    /// per poll at ~60 Hz. The manager is the only place that sees both the
54
    /// old and the new bitset, so it is the only place the edge can be
55
    /// computed — a consumer reading `buttons` sees a level and cannot tell a
56
    /// fresh press from a held one.
57
    pending_pressed: u32,
58
}
59

            
60
impl GamepadManager {
61
    #[must_use]
62
7662
    pub fn new() -> Self {
63
7662
        Self::default()
64
7662
    }
65

            
66
    /// Latest state for `id`, or `None` if that pad was never seen.
67
    #[must_use]
68
148
    pub fn state(&self, id: GamepadId) -> Option<GamepadState> {
69
220
        self.pads.iter().find(|p| p.id == id).copied()
70
148
    }
71

            
72
    /// The first currently-connected pad — the common single-controller
73
    /// case, so a callback doesn't have to track ids.
74
    #[must_use]
75
29
    pub fn primary(&self) -> Option<GamepadState> {
76
29
        self.pads.iter().find(|p| p.connected).copied()
77
29
    }
78

            
79
    /// Every pad slot seen this session (connected or not).
80
    #[must_use]
81
31
    pub fn gamepads(&self) -> &[GamepadState] {
82
31
        &self.pads
83
31
    }
84

            
85
    /// Apply a state the backend delivered (upsert by id). Returns `true`
86
    /// if it advanced (bit-pattern different from the previous slot), so an
87
    /// idle controller doesn't make every frame look "changed".
88
1307
    pub fn set_state(&mut self, state: GamepadState) -> bool {
89
1316
        let changed = if let Some(slot) = self.pads.iter_mut().find(|p| p.id == state.id) {
90
1206
            let changed = !state_bitwise_eq(slot, &state);
91
            // Hotplug is a TRANSITION of `connected`, not its value: the slot
92
            // is retained after an unplug so a callback can still observe it,
93
            // so `connected == false` is the steady state of every pad ever
94
            // seen this session and says nothing about whether one just left.
95
1206
            if slot.connected != state.connected {
96
6
                self.pending_hotplug.push(state.connected);
97
1200
            }
98
1206
            self.pending_pressed |= state.buttons & !slot.buttons;
99
1206
            *slot = state;
100
1206
            changed
101
        } else {
102
            // First sighting of a pad. A pad that arrives already disconnected
103
            // is not an arrival — the backends enumerate known-but-absent pads
104
            // on some platforms — so only a live one announces itself.
105
101
            if state.connected {
106
96
                self.pending_hotplug.push(true);
107
96
            }
108
            // Every button already held on the first sighting is an edge: we
109
            // have no earlier bitset to have seen it go down against.
110
101
            self.pending_pressed |= state.buttons;
111
101
            self.pads.push(state);
112
101
            true
113
        };
114
1307
        if changed {
115
1284
            self.pending_event = true;
116
1284
        }
117
1307
        changed
118
1307
    }
119

            
120
    /// Drain the hotplug transitions recorded since the last call.
121
    ///
122
    /// `true` = a pad arrived, `false` = a pad left. Kept separate from
123
    /// `pending_event` because that one coalesces: a pad can connect and have
124
    /// its sticks move in the same pass, and the arrival must not be lost
125
    /// behind the state change.
126
    pub fn take_pending_hotplug(&mut self) -> Vec<bool> {
127
        core::mem::take(&mut self.pending_hotplug)
128
    }
129

            
130
    /// Clear the pending-event flag. The dll calls this after the event pass
131
    /// has collected the `GamepadInput` event.
132
150
    pub const fn clear_pending_event(&mut self) {
133
150
        self.pending_event = false;
134
150
    }
135

            
136
    /// Drain the buttons that went down since the last call.
137
    ///
138
    /// Kept separate from `pending_event`, which coalesces: a pad can press a
139
    /// button and move a stick in the same pass, and the press must not be
140
    /// lost behind the state change — the same reason `pending_hotplug` is
141
    /// separate.
142
10
    pub const fn take_pending_pressed(&mut self) -> u32 {
143
10
        let out = self.pending_pressed;
144
10
        self.pending_pressed = 0;
145
10
        out
146
10
    }
147

            
148
    /// Relayout walk reports whether any node listens for `GamepadInput`.
149
12
    pub const fn set_has_listeners(&mut self, has: bool) {
150
12
        self.has_listeners = has;
151
12
    }
152

            
153
    /// `true` while the capability pump should poll the controller backend.
154
    #[must_use]
155
21
    pub const fn has_listeners(&self) -> bool {
156
21
        self.has_listeners
157
21
    }
158
}
159

            
160
impl EventProvider for GamepadManager {
161
    /// Yield a window-level `GamepadInput` event when a pad's state advanced
162
    /// since the last drain (target = root; read it via
163
    /// `CallbackInfo::get_primary_gamepad` / `get_gamepad_state`).
164
163
    fn get_pending_events(&self, timestamp: Instant) -> Vec<SyntheticEvent> {
165
163
        let mut events = Vec::new();
166

            
167
        // Hotplug first: an app that reacts to a pad arriving wants to see the
168
        // arrival before the first stick sample from that pad, not after.
169
179
        for connected in &self.pending_hotplug {
170
16
            events.push(SyntheticEvent::new(
171
16
                if *connected {
172
16
                    EventType::DeviceConnected
173
                } else {
174
                    EventType::DeviceDisconnected
175
                },
176
16
                CoreEventSource::User,
177
                DomNodeId::ROOT,
178
16
                timestamp.clone(),
179
16
                EventData::None,
180
            ));
181
        }
182

            
183
163
        if self.pending_event {
184
14
            events.push(SyntheticEvent::new(
185
14
                EventType::GamepadInput,
186
14
                CoreEventSource::User,
187
14
                DomNodeId::ROOT,
188
14
                timestamp,
189
14
                EventData::None,
190
14
            ));
191
159
        }
192
163
        events
193
163
    }
194
}
195

            
196
1258
fn state_bitwise_eq(a: &GamepadState, b: &GamepadState) -> bool {
197
1258
    a.id == b.id
198
1256
        && a.connected == b.connected
199
1248
        && a.buttons == b.buttons
200
216
        && a.left_stick_x.to_bits() == b.left_stick_x.to_bits()
201
187
        && a.left_stick_y.to_bits() == b.left_stick_y.to_bits()
202
159
        && a.right_stick_x.to_bits() == b.right_stick_x.to_bits()
203
132
        && a.right_stick_y.to_bits() == b.right_stick_y.to_bits()
204
105
        && a.left_z.to_bits() == b.left_z.to_bits()
205
77
        && a.right_z.to_bits() == b.right_z.to_bits()
206
        // THE FIELDS 8f ADDED, and leaving them out was a real gap: a pad
207
        // whose only change is an IMU sample, a finger on the touchpad or a
208
        // battery step reported "unchanged" and fired no `GamepadInput` - so
209
        // the producers 8f-i and 8f-i-a filled had nothing downstream reading
210
        // them. A gyro-aiming game needs the per-frame event this now emits.
211
52
        && a.battery.to_bits() == b.battery.to_bits()
212
51
        && a.touchpad_x.to_bits() == b.touchpad_x.to_bits()
213
50
        && a.touchpad_y.to_bits() == b.touchpad_y.to_bits()
214
49
        && a.touchpad_active == b.touchpad_active
215
48
        && a.touchpad2_x.to_bits() == b.touchpad2_x.to_bits()
216
47
        && a.touchpad2_y.to_bits() == b.touchpad2_y.to_bits()
217
46
        && a.touchpad2_active == b.touchpad2_active
218
45
        && a.gyro_x.to_bits() == b.gyro_x.to_bits()
219
44
        && a.gyro_y.to_bits() == b.gyro_y.to_bits()
220
43
        && a.gyro_z.to_bits() == b.gyro_z.to_bits()
221
42
        && a.accel_x.to_bits() == b.accel_x.to_bits()
222
41
        && a.accel_y.to_bits() == b.accel_y.to_bits()
223
40
        && a.accel_z.to_bits() == b.accel_z.to_bits()
224
1258
}
225

            
226
// ────────── Async update channel (platform backend → manager) ──────────
227
//
228
// gilrs / GCController / InputDevice deliver on the backend's poll thread
229
// with no handle to the live `GamepadManager` (inside the window's
230
// `LayoutWindow`). The backend parks each changed state here; the layout
231
// pass drains it and applies the latest per id. Pure Rust — no platform
232
// dependency (SUPER_PLAN_2 §0.5). Mirrors the sensor reading channel.
233

            
234
static PENDING_STATES: std::sync::Mutex<Vec<GamepadState>> = std::sync::Mutex::new(Vec::new());
235

            
236
/// Park a gamepad state delivered by a platform backend (in the dll).
237
/// Thread-safe; poison-recovering.
238
13
pub fn push_gamepad_state(state: GamepadState) {
239
13
    let mut q = PENDING_STATES
240
13
        .lock()
241
13
        .unwrap_or_else(std::sync::PoisonError::into_inner);
242
13
    q.push(state);
243
13
}
244

            
245
/// Drain every state parked by [`push_gamepad_state`], in arrival order.
246
/// Called once per layout pass; the caller applies them through
247
/// [`GamepadManager::set_state`] (the last per id wins).
248
23
pub fn drain_gamepad_states() -> Vec<GamepadState> {
249
23
    let mut q = PENDING_STATES
250
23
        .lock()
251
23
        .unwrap_or_else(std::sync::PoisonError::into_inner);
252
23
    core::mem::take(&mut *q)
253
23
}
254

            
255
#[cfg(test)]
256
mod tests {
257
    use super::*;
258

            
259
    /// THE FIELDS 8f ADDED MUST BE VISIBLE TO THE CHANGE DETECTOR. They were
260
    /// not, so a pad whose only change was an IMU sample, a finger on the
261
    /// touchpad or a battery step reported "unchanged" and fired no event -
262
    /// leaving 8f-i and 8f-i-a's producers writing into a value nothing read.
263
    #[test]
264
1
    fn every_gamepad_field_is_part_of_the_change_detection() {
265
1
        let base = GamepadState {
266
1
            id: GamepadId { id: 3 },
267
1
            connected: true,
268
1
            ..Default::default()
269
1
        };
270

            
271
1
        let mut cases: Vec<(&str, GamepadState)> = Vec::new();
272
1
        let mut c = base;
273
1
        c.buttons = 1;
274
1
        cases.push(("buttons", c));
275
1
        let mut c = base;
276
1
        c.left_stick_x = 0.5;
277
1
        cases.push(("left_stick_x", c));
278
1
        let mut c = base;
279
1
        c.left_stick_y = 0.5;
280
1
        cases.push(("left_stick_y", c));
281
1
        let mut c = base;
282
1
        c.right_stick_x = 0.5;
283
1
        cases.push(("right_stick_x", c));
284
1
        let mut c = base;
285
1
        c.right_stick_y = 0.5;
286
1
        cases.push(("right_stick_y", c));
287
1
        let mut c = base;
288
1
        c.left_z = 0.5;
289
1
        cases.push(("left_z", c));
290
1
        let mut c = base;
291
1
        c.right_z = 0.5;
292
1
        cases.push(("right_z", c));
293
1
        let mut c = base;
294
1
        c.battery = 0.5;
295
1
        cases.push(("battery", c));
296
1
        let mut c = base;
297
1
        c.touchpad_x = 0.5;
298
1
        cases.push(("touchpad_x", c));
299
1
        let mut c = base;
300
1
        c.touchpad_y = 0.5;
301
1
        cases.push(("touchpad_y", c));
302
1
        let mut c = base;
303
1
        c.touchpad_active = true;
304
1
        cases.push(("touchpad_active", c));
305
1
        let mut c = base;
306
1
        c.touchpad2_x = 0.5;
307
1
        cases.push(("touchpad2_x", c));
308
1
        let mut c = base;
309
1
        c.touchpad2_y = 0.5;
310
1
        cases.push(("touchpad2_y", c));
311
1
        let mut c = base;
312
1
        c.touchpad2_active = true;
313
1
        cases.push(("touchpad2_active", c));
314
1
        let mut c = base;
315
1
        c.gyro_x = 0.5;
316
1
        cases.push(("gyro_x", c));
317
1
        let mut c = base;
318
1
        c.gyro_y = 0.5;
319
1
        cases.push(("gyro_y", c));
320
1
        let mut c = base;
321
1
        c.gyro_z = 0.5;
322
1
        cases.push(("gyro_z", c));
323
1
        let mut c = base;
324
1
        c.accel_x = 0.5;
325
1
        cases.push(("accel_x", c));
326
1
        let mut c = base;
327
1
        c.accel_y = 0.5;
328
1
        cases.push(("accel_y", c));
329
1
        let mut c = base;
330
1
        c.accel_z = 0.5;
331
1
        cases.push(("accel_z", c));
332
1
        let mut c = base;
333
1
        c.connected = false;
334
1
        cases.push(("connected", c));
335

            
336
22
        for (field, changed) in cases {
337
21
            let mut mgr = GamepadManager::new();
338
21
            mgr.set_state(base);
339
21
            assert!(
340
21
                mgr.set_state(changed),
341
                "changing `{field}` did not register as a change"
342
            );
343
        }
344

            
345
        // ...and the other half: an IDENTICAL state must NOT, or an idle pad
346
        // would make every frame look changed.
347
1
        let mut mgr = GamepadManager::new();
348
1
        mgr.set_state(base);
349
1
        assert!(!mgr.set_state(base), "an unchanged pad reported a change");
350
1
    }
351

            
352
10
    fn st(id: u32, connected: bool, buttons: u32) -> GamepadState {
353
10
        let mut s = GamepadState::empty(GamepadId { id });
354
10
        s.connected = connected;
355
10
        s.buttons = buttons;
356
10
        s
357
        // Fields this site does not set. Growing GamepadState must not
358
        // break every construction of it.
359
10
    }
360

            
361
    #[test]
362
1
    fn manager_upserts_by_id_and_flags_change() {
363
1
        let mut mgr = GamepadManager::new();
364
1
        assert_eq!(mgr.state(GamepadId { id: 0 }), None);
365
        // First state for an id is a change + adds a slot.
366
1
        assert!(mgr.set_state(st(0, true, 0b1)));
367
1
        assert!(mgr.state(GamepadId { id: 0 }).is_some());
368
        // Same state again — no change.
369
1
        assert!(!mgr.set_state(st(0, true, 0b1)));
370
        // Different buttons — change, same slot (not a new pad).
371
1
        assert!(mgr.set_state(st(0, true, 0b11)));
372
1
        assert_eq!(mgr.gamepads().len(), 1);
373
        // A second pad adds a slot.
374
1
        assert!(mgr.set_state(st(1, true, 0)));
375
1
        assert_eq!(mgr.gamepads().len(), 2);
376
1
    }
377

            
378
    #[test]
379
1
    fn primary_is_first_connected() {
380
1
        let mut mgr = GamepadManager::new();
381
1
        mgr.set_state(st(0, false, 0)); // disconnected
382
1
        mgr.set_state(st(1, true, 0));
383
1
        assert_eq!(mgr.primary().map(|p| p.id.id), Some(1));
384
1
    }
385

            
386
    #[test]
387
1
    fn is_pressed_decodes_the_bitset() {
388
1
        let s = st(
389
            0,
390
            true,
391
1
            GamepadButton::South.bit() | GamepadButton::Start.bit(),
392
        );
393
1
        assert!(s.is_pressed(GamepadButton::South));
394
1
        assert!(s.is_pressed(GamepadButton::Start));
395
1
        assert!(!s.is_pressed(GamepadButton::East));
396
1
    }
397

            
398
    #[test]
399
1
    fn listener_flag_gates_polling_decision() {
400
1
        let mut mgr = GamepadManager::new();
401
1
        assert!(
402
1
            !mgr.has_listeners(),
403
            "no listeners until the relayout walk reports some"
404
        );
405
1
        mgr.set_has_listeners(true);
406
1
        assert!(mgr.has_listeners());
407
1
        mgr.set_has_listeners(false);
408
1
        assert!(!mgr.has_listeners());
409
1
    }
410

            
411
    #[test]
412
1
    fn states_round_trip_through_the_channel() {
413
1
        drop(drain_gamepad_states());
414
1
        push_gamepad_state(st(0, true, 0b1));
415
1
        push_gamepad_state(st(0, true, 0b10)); // last per id wins
416
1
        push_gamepad_state(st(1, true, 0));
417
1
        let drained = drain_gamepad_states();
418
1
        assert_eq!(drained.len(), 3);
419

            
420
1
        let mut mgr = GamepadManager::new();
421
4
        for s in &drained {
422
3
            mgr.set_state(*s);
423
3
        }
424
1
        assert_eq!(
425
1
            mgr.state(GamepadId { id: 0 }).map(|p| p.buttons),
426
            Some(0b10)
427
        );
428
1
        assert_eq!(mgr.gamepads().len(), 2);
429
1
        assert!(drain_gamepad_states().is_empty());
430
1
    }
431
}
432

            
433
#[cfg(test)]
434
mod autotest_generated {
435
    use azul_core::task::SystemTick;
436

            
437
    use super::*;
438

            
439
    // NOTE on coverage: `push_gamepad_state` / `drain_gamepad_states` are
440
    // deliberately NOT tested here. They share one process-global
441
    // `PENDING_STATES` mutex, and `tests::states_round_trip_through_the_channel`
442
    // above already asserts an *exact* drained length on it. Since the test
443
    // harness runs both modules on parallel threads in the same binary, a push
444
    // or drain from here could interleave with that test's push/drain window and
445
    // make it fail spuriously. The round-trip is already covered there.
446

            
447
    /// Every axis field, paired with a setter, so a test can walk all six
448
    /// without depending on `GamepadState::axis` (a bug there must not mask a
449
    /// bug here).
450
    type AxisSetter = (&'static str, fn(&mut GamepadState, f32));
451
    const AXIS_SETTERS: [AxisSetter; 6] = [
452
        ("left_stick_x", |s, v| s.left_stick_x = v),
453
        ("left_stick_y", |s, v| s.left_stick_y = v),
454
        ("right_stick_x", |s, v| s.right_stick_x = v),
455
        ("right_stick_y", |s, v| s.right_stick_y = v),
456
        ("left_z", |s, v| s.left_z = v),
457
        ("right_z", |s, v| s.right_z = v),
458
    ];
459

            
460
    /// Floats a real backend can hand us that break naive `==` comparison.
461
    const NASTY_FLOATS: [f32; 10] = [
462
        f32::NAN,
463
        f32::INFINITY,
464
        f32::NEG_INFINITY,
465
        0.0,
466
        -0.0,
467
        -1.0,
468
        1.0,
469
        f32::MIN,
470
        f32::MAX,
471
        f32::MIN_POSITIVE,
472
    ];
473

            
474
    fn pad(id: u32) -> GamepadState {
475
        GamepadState::empty(GamepadId { id })
476
        // Fields this site does not set. Growing GamepadState must not
477
        // break every construction of it.
478
    }
479

            
480
    fn connected(id: u32) -> GamepadState {
481
        let mut s = pad(id);
482
        s.connected = true;
483
        s
484
        // Fields this site does not set. Growing GamepadState must not
485
        // break every construction of it.
486
    }
487

            
488
    fn ts(tick: u64) -> Instant {
489
        Instant::Tick(SystemTick::new(tick))
490
    }
491

            
492
    /// Field-by-field bit comparison, written independently of
493
    /// `state_bitwise_eq` so it can be used to check that function.
494
    fn same_bits(a: &GamepadState, b: &GamepadState) -> bool {
495
        a.id == b.id
496
            && a.connected == b.connected
497
            && a.buttons == b.buttons
498
            && [
499
                (a.left_stick_x, b.left_stick_x),
500
                (a.left_stick_y, b.left_stick_y),
501
                (a.right_stick_x, b.right_stick_x),
502
                (a.right_stick_y, b.right_stick_y),
503
                (a.left_z, b.left_z),
504
                (a.right_z, b.right_z),
505
            ]
506
            .iter()
507
            .all(|(x, y)| x.to_bits() == y.to_bits())
508
    }
509

            
510
    // ------------------------------------------------------------------
511
    // GamepadManager::new  (constructor)
512
    // ------------------------------------------------------------------
513

            
514
    /// no_panic + invariants_hold: a fresh manager is the documented zero —
515
    /// no slots, nothing pending, no listeners — and is indistinguishable from
516
    /// `Default` (the dll builds one per `App` either way).
517
    #[test]
518
    fn new_is_default_and_starts_completely_empty() {
519
        let mgr = GamepadManager::new();
520

            
521
        assert_eq!(mgr, GamepadManager::default());
522
        assert!(mgr.gamepads().is_empty());
523
        assert_eq!(mgr.gamepads().len(), 0);
524
        assert_eq!(mgr.primary(), None);
525
        assert!(
526
            !mgr.has_listeners(),
527
            "polling must be disarmed until a relayout arms it"
528
        );
529
        assert!(
530
            !mgr.pending_event,
531
            "a manager nobody touched cannot have a pending event"
532
        );
533
        assert!(
534
            mgr.get_pending_events(ts(0)).is_empty(),
535
            "a fresh manager must not synthesise a GamepadInput event"
536
        );
537
    }
538

            
539
    // ------------------------------------------------------------------
540
    // GamepadManager::state  (other)
541
    // ------------------------------------------------------------------
542

            
543
    /// no_panic_smoke + boundary ids: an id that was never seen is `None`, on
544
    /// an empty manager *and* on a populated one. `u32::MAX` / `0` are the
545
    /// interesting ones — the backend normalises platform device ids into a
546
    /// `u32`, so both ends of the range are reachable.
547
    #[test]
548
    fn state_returns_none_for_ids_never_seen() {
549
        let mut mgr = GamepadManager::new();
550
        for id in [0, 1, u32::MAX / 2, u32::MAX - 1, u32::MAX] {
551
            assert_eq!(
552
                mgr.state(GamepadId { id }),
553
                None,
554
                "id {id} on an empty manager"
555
            );
556
        }
557

            
558
        mgr.set_state(connected(7));
559
        assert!(mgr.state(GamepadId { id: 7 }).is_some());
560
        for id in [0, 6, 8, u32::MAX] {
561
            assert_eq!(
562
                mgr.state(GamepadId { id }),
563
                None,
564
                "id {id} was never pushed"
565
            );
566
        }
567
    }
568

            
569
    /// The lookup must key on the *whole* id, not a truncated / masked one:
570
    /// pads whose ids differ only in the low or high bits must not alias.
571
    #[test]
572
    fn state_does_not_alias_neighbouring_or_truncated_ids() {
573
        let mut mgr = GamepadManager::new();
574
        // (id, fingerprint) — ids that differ only in the low or the high half.
575
        let pads = [
576
            (0u32, 0x0000_0001u32),
577
            (1, 0x0000_0002),
578
            (0xFFFF, 0x0000_0004),
579
            (0x1_0000, 0x0000_0008),
580
            (u32::MAX - 1, 0x0000_0010),
581
            (u32::MAX, 0x0000_0020),
582
        ];
583
        for (id, fingerprint) in pads {
584
            let mut s = connected(id);
585
            s.buttons = fingerprint;
586
            mgr.set_state(s);
587
        }
588
        assert_eq!(
589
            mgr.gamepads().len(),
590
            pads.len(),
591
            "distinct ids must not collapse into one slot"
592
        );
593
        for (id, fingerprint) in pads {
594
            let got = mgr.state(GamepadId { id }).expect("pad was pushed");
595
            assert_eq!(got.id.id, id);
596
            assert_eq!(
597
                got.buttons, fingerprint,
598
                "id {id} returned another pad's snapshot"
599
            );
600
        }
601
    }
602

            
603
    /// round-trip / encode == decode: whatever the backend delivered comes back
604
    /// out of `state()` bit-for-bit, including the floats `==` would mangle
605
    /// (NaN, ±inf, −0.0) and a fully-set button bitset.
606
    #[test]
607
    fn state_returns_the_pushed_snapshot_bit_exactly() {
608
        let mut mgr = GamepadManager::new();
609

            
610
        let mut s = connected(u32::MAX);
611
        s.buttons = u32::MAX;
612
        s.left_stick_x = f32::NAN;
613
        s.left_stick_y = -0.0;
614
        s.right_stick_x = f32::INFINITY;
615
        s.right_stick_y = f32::NEG_INFINITY;
616
        s.left_z = f32::MIN;
617
        s.right_z = f32::MAX;
618
        mgr.set_state(s);
619

            
620
        let got = mgr
621
            .state(GamepadId { id: u32::MAX })
622
            .expect("pad u32::MAX was pushed");
623
        assert!(
624
            same_bits(&got, &s),
625
            "state() did not return the pushed snapshot bit-exactly: {got:?} vs {s:?}"
626
        );
627
        // …and the NaN axis really is a NaN, i.e. nothing sanitised it on the way.
628
        assert!(got.left_stick_x.is_nan());
629
        assert_eq!(
630
            got.left_stick_y.to_bits(),
631
            (-0.0f32).to_bits(),
632
            "−0.0 collapsed to +0.0"
633
        );
634
    }
635

            
636
    /// `state()` is a read-only view: calling it (even for a missing id) leaves
637
    /// the manager — slots, pending flag, listener flag — untouched.
638
    #[test]
639
    fn state_does_not_mutate_the_manager() {
640
        let mut mgr = GamepadManager::new();
641
        mgr.set_state(connected(0));
642
        mgr.clear_pending_event();
643
        let before = mgr.clone();
644

            
645
        for id in [0, 1, u32::MAX] {
646
            let _ = mgr.state(GamepadId { id });
647
        }
648
        assert_eq!(mgr, before);
649
        assert!(
650
            !mgr.pending_event,
651
            "a read must not raise the pending-event flag"
652
        );
653
    }
654

            
655
    // ------------------------------------------------------------------
656
    // GamepadManager::primary  (getter)
657
    // ------------------------------------------------------------------
658

            
659
    /// edge_access: `None` on a default manager, and still `None` once pads
660
    /// exist but every one of them is disconnected (the slots are retained, so
661
    /// "has slots" must not be confused with "has a pad").
662
    #[test]
663
    fn primary_is_none_when_empty_or_when_nothing_is_connected() {
664
        let mut mgr = GamepadManager::new();
665
        assert_eq!(mgr.primary(), None);
666
        assert_eq!(GamepadManager::default().primary(), None);
667

            
668
        mgr.set_state(pad(0)); // connected = false
669
        mgr.set_state(pad(1));
670
        assert_eq!(
671
            mgr.gamepads().len(),
672
            2,
673
            "disconnected pads still occupy slots"
674
        );
675
        assert_eq!(
676
            mgr.primary(),
677
            None,
678
            "a disconnected slot is not a primary pad"
679
        );
680
    }
681

            
682
    /// basic_access, pinned against the plausible misreading: "first" means
683
    /// *first connected slot in arrival order*, NOT lowest id. Pad 9 arrives
684
    /// before pad 1, so pad 9 is primary — a callback that assumed
685
    /// `min(id)` would drive the wrong controller.
686
    #[test]
687
    fn primary_is_the_first_connected_in_arrival_order_not_the_lowest_id() {
688
        let mut mgr = GamepadManager::new();
689
        mgr.set_state(pad(3)); // seen, but disconnected — must be skipped
690
        mgr.set_state(connected(9));
691
        mgr.set_state(connected(1));
692

            
693
        assert_eq!(mgr.primary().map(|p| p.id.id), Some(9));
694
        assert_eq!(
695
            mgr.gamepads().first().map(|p| p.id.id),
696
            Some(3),
697
            "arrival order kept"
698
        );
699
    }
700

            
701
    /// A disconnect must hand primacy to the next connected pad, and the last
702
    /// disconnect must take it back to `None` — without ever dropping a slot.
703
    #[test]
704
    fn primary_follows_disconnects_while_slots_are_retained() {
705
        let mut mgr = GamepadManager::new();
706
        mgr.set_state(connected(0));
707
        mgr.set_state(connected(1));
708
        assert_eq!(mgr.primary().map(|p| p.id.id), Some(0));
709

            
710
        mgr.set_state(pad(0)); // unplug pad 0
711
        assert_eq!(
712
            mgr.primary().map(|p| p.id.id),
713
            Some(1),
714
            "primacy must fall through to pad 1"
715
        );
716
        assert_eq!(
717
            mgr.gamepads().len(),
718
            2,
719
            "the unplugged slot must be retained"
720
        );
721
        assert_eq!(
722
            mgr.state(GamepadId { id: 0 }).map(|p| p.connected),
723
            Some(false),
724
            "the disconnect must stay observable"
725
        );
726

            
727
        mgr.set_state(pad(1)); // unplug the last one
728
        assert_eq!(mgr.primary(), None);
729
        assert_eq!(mgr.gamepads().len(), 2);
730

            
731
        mgr.set_state(connected(0)); // re-plug: the same slot comes back, no new one
732
        assert_eq!(mgr.primary().map(|p| p.id.id), Some(0));
733
        assert_eq!(
734
            mgr.gamepads().len(),
735
            2,
736
            "a re-plug must reuse the id's slot"
737
        );
738
    }
739

            
740
    // ------------------------------------------------------------------
741
    // GamepadManager::gamepads  (getter)
742
    // ------------------------------------------------------------------
743

            
744
    /// basic_access + invariant: one slot per *unique* id, in arrival order,
745
    /// no matter how many updates each pad delivers. A slot leak here would
746
    /// grow unboundedly at ~60 Hz for the lifetime of the process.
747
    #[test]
748
    fn gamepads_keeps_one_slot_per_id_in_arrival_order() {
749
        let mut mgr = GamepadManager::new();
750
        // (id, buttons) — 3 unique ids, each pushed more than once. The button
751
        // value differs on every push, so each one is a genuine change.
752
        let arrival = [(5u32, 1u32), (0, 2), (u32::MAX, 3), (5, 4), (0, 5), (5, 6)];
753

            
754
        for (id, buttons) in arrival {
755
            let mut s = connected(id);
756
            s.buttons = buttons;
757
            mgr.set_state(s);
758
        }
759

            
760
        let ids: Vec<u32> = mgr.gamepads().iter().map(|p| p.id.id).collect();
761
        assert_eq!(
762
            ids,
763
            alloc::vec![5, 0, u32::MAX],
764
            "arrival order / dedup by id broken"
765
        );
766
        assert_eq!(mgr.gamepads().len(), 3);
767

            
768
        // 1000 further updates to a known id must not add a single slot.
769
        for i in 0..1000u32 {
770
            let mut s = connected(5);
771
            s.buttons = i;
772
            mgr.set_state(s);
773
        }
774
        assert_eq!(mgr.gamepads().len(), 3, "repeated updates leaked slots");
775
    }
776

            
777
    /// The slice `gamepads()` hands out must agree with `state()` /
778
    /// `primary()` — they are three views of the same `pads` vec, so a caller
779
    /// iterating the slice must never see something the id lookup denies.
780
    #[test]
781
    fn gamepads_slice_agrees_with_state_and_primary() {
782
        let mut mgr = GamepadManager::new();
783
        mgr.set_state(pad(2));
784
        mgr.set_state(connected(4));
785
        mgr.set_state(connected(8));
786

            
787
        for p in mgr.gamepads() {
788
            assert_eq!(
789
                mgr.state(p.id).as_ref(),
790
                Some(p),
791
                "slice and state() disagree for {p:?}"
792
            );
793
        }
794
        assert_eq!(
795
            mgr.primary().as_ref(),
796
            mgr.gamepads().iter().find(|p| p.connected),
797
            "primary() must be the first connected element of the slice"
798
        );
799
    }
800

            
801
    // ------------------------------------------------------------------
802
    // GamepadManager::set_state  (other)
803
    // ------------------------------------------------------------------
804

            
805
    /// The core contract: `true` iff the bit pattern advanced. An idle
806
    /// controller re-reporting the same snapshot every frame must return
807
    /// `false`, or the dll would relayout at the poll rate forever.
808
    #[test]
809
    fn set_state_reports_change_only_when_the_bits_advance() {
810
        let mut mgr = GamepadManager::new();
811
        let mut s = connected(0);
812

            
813
        assert!(mgr.set_state(s), "a never-seen id is always a change");
814
        assert!(
815
            !mgr.set_state(s),
816
            "an idle controller must not look changed"
817
        );
818
        assert!(!mgr.set_state(s), "…and must keep not looking changed");
819

            
820
        s.buttons = GamepadButton::South.bit();
821
        assert!(mgr.set_state(s), "a button press is a change");
822
        assert!(!mgr.set_state(s), "a held button is not a new change");
823

            
824
        s.connected = false;
825
        assert!(mgr.set_state(s), "a disconnect is a change");
826
        assert!(!mgr.set_state(s));
827

            
828
        s.left_stick_x = 0.5;
829
        assert!(mgr.set_state(s), "an axis move is a change");
830
        assert!(!mgr.set_state(s));
831

            
832
        assert_eq!(mgr.gamepads().len(), 1, "all of that was one pad");
833
    }
834

            
835
    /// Adversarial float #1 — NaN. A stick that reports NaN (a real gilrs /
836
    /// driver failure mode) would make a derived-`PartialEq` comparison say
837
    /// "changed" on *every* frame forever, because NaN != NaN. `set_state`
838
    /// compares `to_bits()`, so an unchanging NaN correctly reads as idle.
839
    /// This test pins that: the derived `==` disagrees, and `set_state` is right.
840
    #[test]
841
    fn set_state_treats_an_unchanging_nan_axis_as_idle() {
842
        let mut mgr = GamepadManager::new();
843
        let mut s = connected(0);
844
        s.left_stick_x = f32::NAN;
845

            
846
        // Sanity: the derived PartialEq really is non-reflexive here, so a
847
        // `!=`-based implementation would spin.
848
        let bit_identical_copy = s;
849
        assert_ne!(
850
            s, bit_identical_copy,
851
            "precondition: a NaN axis makes derived PartialEq non-reflexive"
852
        );
853

            
854
        assert!(mgr.set_state(s), "first sighting of the pad is a change");
855
        assert!(
856
            !mgr.set_state(s),
857
            "a stuck NaN axis must NOT look like a change every frame"
858
        );
859
        assert!(!mgr.set_state(s));
860

            
861
        // A *different* NaN payload is a different bit pattern → a change.
862
        let mut other = s;
863
        other.left_stick_x = f32::from_bits(f32::NAN.to_bits() | 0x1);
864
        assert!(other.left_stick_x.is_nan());
865
        assert!(
866
            mgr.set_state(other),
867
            "a different NaN bit pattern is a bitwise change"
868
        );
869
        assert!(!mgr.set_state(other));
870
    }
871

            
872
    /// Adversarial float #2 — signed zero. `-0.0 == 0.0` is *true* in IEEE, so
873
    /// a value-comparing implementation would miss a stick crossing centre from
874
    /// the negative side. `to_bits()` catches it: the flip is reported.
875
    #[test]
876
    fn set_state_reports_a_positive_to_negative_zero_flip() {
877
        let mut mgr = GamepadManager::new();
878
        let mut s = connected(0);
879
        s.left_stick_y = 0.0;
880
        assert!(mgr.set_state(s));
881

            
882
        s.left_stick_y = -0.0;
883
        // Precondition: the two zeroes compare *equal* under `==` (IEEE) yet
884
        // differ in their bits — which is exactly what set_state must key on.
885
        assert_ne!((0.0f32).to_bits(), (-0.0f32).to_bits());
886
        assert!(
887
            mgr.set_state(s),
888
            "a +0.0 → −0.0 sign flip is a bitwise change"
889
        );
890
        assert!(!mgr.set_state(s));
891
        assert_eq!(
892
            mgr.state(GamepadId { id: 0 })
893
                .map(|p| p.left_stick_y.to_bits()),
894
            Some((-0.0f32).to_bits())
895
        );
896
    }
897

            
898
    /// Every field independently drives the change decision — a change in any
899
    /// one of `connected`, `buttons` or the six axes must be reported. A
900
    /// forgotten field in the comparison would silently swallow that input.
901
    #[test]
902
    fn set_state_notices_a_change_in_every_single_field() {
903
        // `connected`
904
        let mut mgr = GamepadManager::new();
905
        let base = connected(0);
906
        assert!(mgr.set_state(base));
907
        let mut flipped = base;
908
        flipped.connected = false;
909
        assert!(
910
            mgr.set_state(flipped),
911
            "a change in `connected` went unnoticed"
912
        );
913

            
914
        // `buttons` — every defined bit, one at a time.
915
        for bit in 0..17u32 {
916
            let mut mgr = GamepadManager::new();
917
            assert!(mgr.set_state(base));
918
            let mut s = base;
919
            s.buttons = 1 << bit;
920
            assert!(
921
                mgr.set_state(s),
922
                "a change in button bit {bit} went unnoticed"
923
            );
924
        }
925

            
926
        // the six axes.
927
        for (name, set) in AXIS_SETTERS {
928
            let mut mgr = GamepadManager::new();
929
            assert!(mgr.set_state(base));
930
            let mut s = base;
931
            set(&mut s, 1.0);
932
            assert!(mgr.set_state(s), "a change in axis `{name}` went unnoticed");
933
            assert!(
934
                !mgr.set_state(s),
935
                "…and re-reporting `{name}` is not a second change"
936
            );
937
        }
938
    }
939

            
940
    /// no_panic_smoke over extremes: saturated ids / bitsets and every nasty
941
    /// float in every axis. Nothing panics, the slot count stays at one per id,
942
    /// and the stored snapshot is always exactly what was pushed.
943
    #[test]
944
    fn set_state_survives_extreme_ids_bitsets_and_floats() {
945
        let mut mgr = GamepadManager::new();
946

            
947
        for id in [0u32, u32::MAX] {
948
            for (_, set) in AXIS_SETTERS {
949
                for v in NASTY_FLOATS {
950
                    let mut s = connected(id);
951
                    s.buttons = u32::MAX;
952
                    set(&mut s, v);
953
                    mgr.set_state(s);
954
                    let got = mgr.state(GamepadId { id }).expect("just pushed");
955
                    assert!(
956
                        same_bits(&got, &s),
957
                        "pushing {v:?} into pad {id} did not round-trip"
958
                    );
959
                }
960
            }
961
        }
962
        assert_eq!(
963
            mgr.gamepads().len(),
964
            2,
965
            "two ids must occupy exactly two slots"
966
        );
967
    }
968

            
969
    /// Upserting one pad must not touch any other slot — the `find` walks by
970
    /// id, so an index/id mix-up would corrupt a neighbour.
971
    #[test]
972
    fn set_state_upsert_leaves_the_other_slots_untouched() {
973
        let mut mgr = GamepadManager::new();
974
        for (id, z) in [(0u32, 0.0f32), (1, 0.25), (2, 0.5), (3, 0.75)] {
975
            let mut s = connected(id);
976
            s.buttons = 1 << id;
977
            s.left_z = z;
978
            mgr.set_state(s);
979
        }
980
        let before: Vec<GamepadState> = mgr.gamepads().to_vec();
981

            
982
        let mut updated = connected(2);
983
        updated.buttons = u32::MAX;
984
        updated.left_z = -1.0;
985
        assert!(mgr.set_state(updated));
986

            
987
        assert_eq!(mgr.gamepads().len(), 4);
988
        for (i, p) in mgr.gamepads().iter().enumerate() {
989
            if i == 2 {
990
                assert!(same_bits(p, &updated), "the targeted slot was not updated");
991
            } else {
992
                assert!(
993
                    same_bits(p, &before[i]),
994
                    "slot {i} was corrupted by an upsert of pad 2"
995
                );
996
            }
997
        }
998
    }
999

            
    /// The pending flag is set **only** by a real change, and is sticky until
    /// the dll drains it — several changes between two drains must coalesce
    /// into one flag (and one event), not queue up.
    #[test]
    fn set_state_raises_pending_only_on_a_real_change_and_coalesces() {
        let mut mgr = GamepadManager::new();
        assert!(!mgr.pending_event);
        let mut s = connected(0);
        assert!(mgr.set_state(s));
        assert!(mgr.pending_event, "a new pad must raise the pending flag");
        mgr.clear_pending_event();
        assert!(!mgr.set_state(s), "idle re-report");
        assert!(
            !mgr.pending_event,
            "an idle re-report must NOT raise the pending flag"
        );
        // Three changes, one flag.
        s.buttons = 1;
        assert!(mgr.set_state(s));
        s.buttons = 2;
        assert!(mgr.set_state(s));
        s.left_z = 1.0;
        assert!(mgr.set_state(s));
        assert!(mgr.pending_event);
        assert_eq!(
            input_event_count(&mgr, ts(0)),
            1,
            "changes must coalesce into one event"
        );
    }
    // ------------------------------------------------------------------
    // GamepadManager::clear_pending_event  (other)
    // ------------------------------------------------------------------
    /// no_panic_smoke: clearing is safe on an empty manager, is idempotent, and
    /// touches *only* the flag — not the pads, not the listener arming.
    #[test]
    fn clear_pending_event_is_idempotent_and_touches_nothing_else() {
        let mut mgr = GamepadManager::new();
        mgr.clear_pending_event(); // nothing pending, no pads at all
        mgr.clear_pending_event();
        assert!(!mgr.pending_event);
        mgr.set_has_listeners(true);
        mgr.set_state(connected(1));
        assert!(mgr.pending_event);
        mgr.clear_pending_event();
        assert!(!mgr.pending_event);
        mgr.clear_pending_event();
        assert!(
            !mgr.pending_event,
            "a second clear must not resurrect the flag"
        );
        assert_eq!(mgr.gamepads().len(), 1, "clearing must not drop pad slots");
        assert!(
            mgr.has_listeners(),
            "clearing must not disarm the listener flag"
        );
        assert_eq!(
            input_event_count(&mgr, ts(1)),
            0,
            "no input event after a clear"
        );
        // …and a fresh change re-arms it, so the flag is not one-shot.
        let mut s = connected(1);
        s.buttons = 1;
        assert!(mgr.set_state(s));
        assert!(
            mgr.pending_event,
            "the flag must be re-raisable after a clear"
        );
    }
    // ------------------------------------------------------------------
    // set_has_listeners / has_listeners  (other + predicate)
    // ------------------------------------------------------------------
    /// basic_true_false + edge_inputs: the arming flag round-trips, is
    /// idempotent in both directions, and is completely independent of the pad
    /// slots and the pending flag (the relayout walk owns it alone).
    #[test]
    fn has_listeners_roundtrips_and_is_independent_of_pad_state() {
        let mut mgr = GamepadManager::new();
        assert!(
            !mgr.has_listeners(),
            "default must be disarmed — no listeners, no polling"
        );
        for _ in 0..3 {
            mgr.set_has_listeners(true);
            assert!(mgr.has_listeners());
        }
        for _ in 0..3 {
            mgr.set_has_listeners(false);
            assert!(!mgr.has_listeners());
        }
        // Pads arriving must not arm polling by themselves…
        mgr.set_state(connected(0));
        assert!(
            !mgr.has_listeners(),
            "a connected pad must not arm the pump on its own"
        );
        // …and arming must not fabricate pads or events.
        let mut fresh = GamepadManager::new();
        fresh.set_has_listeners(true);
        assert!(fresh.gamepads().is_empty());
        assert!(!fresh.pending_event);
        assert!(fresh.get_pending_events(ts(0)).is_empty());
    }
    // ------------------------------------------------------------------
    // state_bitwise_eq  (private)
    // ------------------------------------------------------------------
    /// The whole reason this function exists: unlike the derived `PartialEq`,
    /// it is **reflexive over NaN**. A snapshot with a NaN in every axis must
    /// equal itself — otherwise an idle broken stick would look "changed"
    /// forever.
    #[test]
    fn state_bitwise_eq_is_reflexive_even_for_nan_axes() {
        let mut s = connected(u32::MAX);
        s.buttons = u32::MAX;
        for (_, set) in AXIS_SETTERS {
            set(&mut s, f32::NAN);
        }
        let copy = s;
        assert_ne!(
            s, copy,
            "precondition: derived PartialEq is non-reflexive over NaN"
        );
        assert!(state_bitwise_eq(&s, &s), "bitwise eq must be reflexive");
        assert!(
            state_bitwise_eq(&s, &copy),
            "a bit-identical copy must compare equal"
        );
        assert!(state_bitwise_eq(&copy, &s), "…symmetrically");
    }
    /// no_panic_smoke + exhaustive field coverage: flipping any ONE of the nine
    /// fields must make the comparison false, and the relation must stay
    /// symmetric. A field missing from the `&&` chain would show up here.
    #[test]
    fn state_bitwise_eq_detects_a_difference_in_every_field() {
        let base = {
            let mut s = connected(1);
            s.buttons = 0b1010;
            s.left_stick_x = 0.25;
            s.left_stick_y = -0.25;
            s.right_stick_x = 0.5;
            s.right_stick_y = -0.5;
            s.left_z = 0.75;
            s.right_z = 1.0;
            s
        };
        assert!(state_bitwise_eq(&base, &base));
        let mut mutations: Vec<(&str, GamepadState)> = Vec::new();
        let mut m = base;
        m.id = GamepadId { id: 2 };
        mutations.push(("id", m));
        let mut m = base;
        m.connected = false;
        mutations.push(("connected", m));
        let mut m = base;
        m.buttons = 0b1011;
        mutations.push(("buttons", m));
        for (name, set) in AXIS_SETTERS {
            let mut m = base;
            set(&mut m, -12.5); // a value no axis holds in `base`
            mutations.push((name, m));
        }
        assert_eq!(mutations.len(), 9, "all nine fields must be exercised");
        for (name, m) in mutations {
            assert!(
                !state_bitwise_eq(&base, &m),
                "a change in `{name}` was not detected"
            );
            assert!(
                !state_bitwise_eq(&m, &base),
                "…and the relation must be symmetric (`{name}`)"
            );
        }
    }
    /// The two IEEE traps in one place: `-0.0` vs `+0.0` (equal by `==`, must
    /// be *unequal* here) and NaN vs NaN with the same payload (unequal by
    /// `==`, must be *equal* here). Checked on every axis, so no arm of the
    /// comparison chain gets it right by accident.
    #[test]
    fn state_bitwise_eq_splits_signed_zero_and_joins_identical_nan() {
        for (name, set) in AXIS_SETTERS {
            let base = connected(0);
            let mut pos = base;
            set(&mut pos, 0.0);
            let mut neg = base;
            set(&mut neg, -0.0);
            assert_eq!(
                pos, neg,
                "precondition: ±0.0 compare equal via derived PartialEq"
            );
            assert!(
                !state_bitwise_eq(&pos, &neg),
                "axis `{name}`: +0.0 and −0.0 must differ bitwise"
            );
            let mut nan_a = base;
            set(&mut nan_a, f32::NAN);
            let nan_b = nan_a;
            assert!(
                state_bitwise_eq(&nan_a, &nan_b),
                "axis `{name}`: identical NaN bit patterns must compare equal"
            );
            // Different NaN payloads are different bit patterns → not equal.
            let mut nan_c = base;
            set(&mut nan_c, f32::from_bits(f32::NAN.to_bits() | 0x7));
            assert!(
                !state_bitwise_eq(&nan_a, &nan_c),
                "axis `{name}`: distinct NaN payloads must not compare equal"
            );
        }
    }
    /// Infinities are ordinary bit patterns here — `inf == inf` must hold and
    /// `+inf != -inf`, with no arithmetic (which could produce a NaN) involved.
    #[test]
    fn state_bitwise_eq_handles_infinities_without_arithmetic() {
        for (name, set) in AXIS_SETTERS {
            let mut a = connected(0);
            set(&mut a, f32::INFINITY);
            let b = a;
            assert!(
                state_bitwise_eq(&a, &b),
                "axis `{name}`: +inf must equal +inf"
            );
            let mut c = connected(0);
            set(&mut c, f32::NEG_INFINITY);
            assert!(
                !state_bitwise_eq(&a, &c),
                "axis `{name}`: +inf must not equal −inf"
            );
        }
    }
    // ------------------------------------------------------------------
    // EventProvider::get_pending_events  (the manager's only output edge)
    // ------------------------------------------------------------------
    /// How many `GamepadInput` events this drain would yield.
    ///
    /// Not the total: `get_pending_events` ALSO reports hotplug, and a pad's
    /// first `set_state` is by definition an arrival, so a bare length check
    /// counts the `DeviceConnected` that legitimately accompanies it. These
    /// tests are about the input event, so they select it.
    fn input_event_count(mgr: &GamepadManager, t: Instant) -> usize {
        mgr.get_pending_events(t)
            .iter()
            .filter(|e| e.event_type == EventType::GamepadInput)
            .count()
    }
    /// A pending change yields exactly one window-level `GamepadInput` event
    /// aimed at the root, carrying the timestamp it was given — and yields it
    /// *repeatedly* until the dll clears the flag (the event pass may run
    /// twice before the drain).
    #[test]
    fn pending_change_yields_one_root_gamepad_input_event() {
        let mut mgr = GamepadManager::new();
        assert!(mgr.get_pending_events(ts(0)).is_empty());
        mgr.set_state(connected(0));
        let evs: Vec<_> = mgr
            .get_pending_events(ts(42))
            .into_iter()
            .filter(|e| e.event_type == EventType::GamepadInput)
            .collect();
        assert_eq!(evs.len(), 1);
        let ev = &evs[0];
        assert_eq!(ev.event_type, EventType::GamepadInput);
        assert_eq!(ev.source, CoreEventSource::User);
        assert_eq!(
            ev.target,
            DomNodeId::ROOT,
            "the gamepad event is window-level"
        );
        assert_eq!(
            ev.timestamp,
            ts(42),
            "the caller's timestamp must be carried through"
        );
        assert_eq!(
            ev.data,
            EventData::None,
            "the payload is read via CallbackInfo, not the event"
        );
        // Still pending until it is explicitly cleared. (The arrival is still
        // pending too — `clear_pending_event` does not drain hotplug, which
        // has its own `take_pending_hotplug` — so both assertions select the
        // input event rather than counting the drain.)
        assert_eq!(input_event_count(&mgr, ts(43)), 1);
        mgr.clear_pending_event();
        assert_eq!(
            input_event_count(&mgr, ts(44)),
            0,
            "cleared -> no more input events"
        );
    }
    /// The listener flag arms the *pump*, not the event stream: it must not, by
    /// itself, make the manager emit (or suppress) an event. Only a real state
    /// change does.
    #[test]
    fn listener_flag_does_not_fabricate_or_suppress_events() {
        let mut mgr = GamepadManager::new();
        mgr.set_has_listeners(true);
        assert!(
            mgr.get_pending_events(ts(0)).is_empty(),
            "arming alone must not emit an event"
        );
        mgr.set_state(connected(0));
        mgr.set_has_listeners(false);
        assert_eq!(
            input_event_count(&mgr, ts(0)),
            1,
            "disarming must not swallow an already-pending event"
        );
    }
    /// `take_pending_pressed` reports an EDGE, not a level.
    ///
    /// The distinction is the whole reason it lives in the manager: a pad is
    /// polled at ~60 Hz and reports a HELD button in every snapshot, so a
    /// consumer reading `buttons` cannot tell a fresh press from a held one
    /// and spatial focus would run away across the UI while the D-pad is down.
    #[test]
    fn pending_pressed_is_an_edge_and_a_held_button_does_not_repeat() {
        use azul_core::gamepad::GamepadButton;
        let mut m = GamepadManager::new();
        let mut st = GamepadState {
            connected: true,
            ..Default::default()
        };
        // First sighting with the button already held counts as an edge:
        // there is no earlier bitset it could have gone down against.
        st.buttons = GamepadButton::DPadUp.bit();
        m.set_state(st);
        assert_eq!(m.take_pending_pressed(), GamepadButton::DPadUp.bit());
        // Drained.
        assert_eq!(m.take_pending_pressed(), 0);
        // Still held over several polls -> no further edges.
        for _ in 0..5 {
            m.set_state(st);
            assert_eq!(
                m.take_pending_pressed(),
                0,
                "a held button must not re-fire"
            );
        }
        // Release is not a press.
        st.buttons = 0;
        m.set_state(st);
        assert_eq!(m.take_pending_pressed(), 0);
        // Pressed again -> one new edge.
        st.buttons = GamepadButton::DPadUp.bit();
        m.set_state(st);
        assert_eq!(m.take_pending_pressed(), GamepadButton::DPadUp.bit());
    }
    /// Edges accumulate across pads and across polls until they are drained —
    /// a press must not be lost because another pad reported in the same pass.
    #[test]
    fn pending_pressed_accumulates_until_drained() {
        use azul_core::gamepad::GamepadButton;
        let mut m = GamepadManager::new();
        let a = GamepadState {
            id: GamepadId { id: 0 },
            connected: true,
            buttons: GamepadButton::DPadLeft.bit(),
            ..Default::default()
        };
        let b = GamepadState {
            id: GamepadId { id: 1 },
            connected: true,
            buttons: GamepadButton::DPadRight.bit(),
            ..Default::default()
        };
        m.set_state(a);
        m.set_state(b);
        assert_eq!(
            m.take_pending_pressed(),
            GamepadButton::DPadLeft.bit() | GamepadButton::DPadRight.bit(),
        );
    }
}