tetanes 0.18.0

A cross-platform NES Emulator written in Rust using wgpu
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
use crate::nes::{
    action::{Action, Debug, DebugKind, DebugStep, Feature, Setting, Ui},
    config::{Config, InputConfig},
    renderer::{gui::Menu, shader::Shader},
};
use ahash::HashMap;
use serde::{Deserialize, Serialize};
use std::{
    collections::{BTreeMap, VecDeque},
    iter::Peekable,
    ops::{Deref, DerefMut},
};
use tetanes_core::{
    action::Action as DeckAction,
    apu::Channel,
    common::ResetKind,
    input::{JoypadBtn, Player},
    video::VideoFilter,
};
use tracing::warn;
use uuid::Uuid;
use winit::{
    event::{ElementState, MouseButton},
    keyboard::{KeyCode, ModifiersState},
};

macro_rules! action_binding {
    ($action:expr => $bindings:expr) => {{
        let action = $action.into();
        (action, ActionBindings::new(action, $bindings))
    }};
    ($action:expr => $modifiers:expr, $key:expr) => {
        action_binding!($action => [Some(Input::Key($key, $modifiers)), None, None])
    };
    ($action:expr => $modifiers1:expr, $key1:expr; $modifiers2:expr, $key2:expr) => {
        action_binding!(
            $action => [Some(Input::Key($key1, $modifiers1)), Some(Input::Key($key2, $modifiers2)), None]
        )
    };
}

#[allow(unused_macro_rules)]
macro_rules! shortcut_map {
    (@ $action:expr => $key:expr) => {
        action_binding!($action => ModifiersState::empty(), $key)
    };
    (@ $action:expr => $key1:expr; $key2:expr) => {
        action_binding!($action => ModifiersState::empty(), $key1; ModifiersState::empty(), $key2)
    };
    (@ $action:expr => :$modifiers:expr, $key:expr) => {
        action_binding!($action => $modifiers, $key)
    };
    (@ $action:expr => :$modifiers1:expr, $key1:expr; $key2:expr) => {
        action_binding!($action => $modifiers1, $key1; ModifiersState::empty(), $key2)
    };
    (@ $action:expr => :$modifiers1:expr, $key1:expr; :$modifiers2:expr, $key2:expr) => {
        action_binding!($action => $modifiers1, $key1; $modifiers2, $key2)
    };
    ($({ $action:expr => $(:$modifiers1:expr,) ?$key1:expr$(; $(:$modifiers2:expr,)? $key2:expr)? }),+$(,)?) => {
        vec![$(shortcut_map!(@ $action => $(:$modifiers1,)? $key1$(; $(:$modifiers2,)? $key2)?),)+]
    };
}

macro_rules! gamepad_map {
    (@ $action:expr => $player:expr; $button:expr) => {
        action_binding!($action => [Some(Input::Button($player, $button)), None, None])
    };
    (@ $action:expr => $player:expr; $button1:expr; ($button2:expr, $state:expr)) => {
        action_binding!($action => [Some(Input::Button($player, $button1)), Some(Input::Axis($player, $button2, $state)), None])
    };
    ($({ $action:expr => $player:expr; $button1:expr$(; ($button2:expr, $state:expr))? }),+$(,)?) => {
        vec![$(gamepad_map!(@ $action => $player; $button1$(; ($button2, $state))?),)+]
    };
}

macro_rules! mouse_map {
    (@ $action:expr => $button:expr) => {
        action_binding!($action => [Some(Input::Mouse($button)), None, None])
    };
    ($({ $action:expr => $button:expr }),+$(,)?) => {
        vec![$(mouse_map!(@ $action => $button),)+]
    };
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[must_use]
pub enum Input {
    Key(KeyCode, ModifiersState),
    Mouse(MouseButton),
    Button(Player, gilrs::Button),
    Axis(Player, gilrs::Axis, AxisDirection),
}

impl Input {
    pub fn fmt(input: Input) -> String {
        use winit::{
            event::MouseButton,
            keyboard::{KeyCode, ModifiersState},
        };

        match input {
            Input::Key(keycode, modifiers) => {
                let mut s = String::with_capacity(32);
                if modifiers.contains(ModifiersState::CONTROL) {
                    s += "Ctrl";
                }
                if modifiers.contains(ModifiersState::SHIFT) {
                    if !s.is_empty() {
                        s += "+";
                    }
                    s += "Shift";
                }
                if modifiers.contains(ModifiersState::ALT) {
                    if !s.is_empty() {
                        s += "+";
                    }
                    s += "Alt";
                }
                if modifiers.contains(ModifiersState::SUPER) {
                    if !s.is_empty() {
                        s += "+";
                    }
                    s += "Super";
                }
                let ch = match keycode {
                    KeyCode::Backquote => "`",
                    KeyCode::Backslash | KeyCode::IntlBackslash => "\\",
                    KeyCode::BracketLeft => "[",
                    KeyCode::BracketRight => "]",
                    KeyCode::Comma | KeyCode::NumpadComma => ",",
                    KeyCode::Digit0 => "0",
                    KeyCode::Digit1 => "1",
                    KeyCode::Digit2 => "2",
                    KeyCode::Digit3 => "3",
                    KeyCode::Digit4 => "4",
                    KeyCode::Digit5 => "5",
                    KeyCode::Digit6 => "6",
                    KeyCode::Digit7 => "7",
                    KeyCode::Digit8 => "8",
                    KeyCode::Digit9 => "9",
                    KeyCode::Equal => "=",
                    KeyCode::KeyA => "A",
                    KeyCode::KeyB => "B",
                    KeyCode::KeyC => "C",
                    KeyCode::KeyD => "D",
                    KeyCode::KeyE => "E",
                    KeyCode::KeyF => "F",
                    KeyCode::KeyG => "G",
                    KeyCode::KeyH => "H",
                    KeyCode::KeyI => "I",
                    KeyCode::KeyJ => "J",
                    KeyCode::KeyK => "K",
                    KeyCode::KeyL => "L",
                    KeyCode::KeyM => "M",
                    KeyCode::KeyN => "N",
                    KeyCode::KeyO => "O",
                    KeyCode::KeyP => "P",
                    KeyCode::KeyQ => "Q",
                    KeyCode::KeyR => "R",
                    KeyCode::KeyS => "S",
                    KeyCode::KeyT => "T",
                    KeyCode::KeyU => "U",
                    KeyCode::KeyV => "V",
                    KeyCode::KeyW => "W",
                    KeyCode::KeyX => "X",
                    KeyCode::KeyY => "Y",
                    KeyCode::KeyZ => "Z",
                    KeyCode::Minus | KeyCode::NumpadSubtract => "-",
                    KeyCode::Period | KeyCode::NumpadDecimal => ".",
                    KeyCode::Quote => "'",
                    KeyCode::Semicolon => ";",
                    KeyCode::Slash | KeyCode::NumpadDivide => "/",
                    KeyCode::Backspace | KeyCode::NumpadBackspace => "Backspace",
                    KeyCode::Enter | KeyCode::NumpadEnter => "Enter",
                    KeyCode::Space => "Space",
                    KeyCode::Tab => "Tab",
                    KeyCode::Delete => "Delete",
                    KeyCode::End => "End",
                    KeyCode::Help => "Help",
                    KeyCode::Home => "Home",
                    KeyCode::Insert => "Ins",
                    KeyCode::PageDown => "PageDown",
                    KeyCode::PageUp => "PageUp",
                    KeyCode::ArrowDown => "Down",
                    KeyCode::ArrowLeft => "Left",
                    KeyCode::ArrowRight => "Right",
                    KeyCode::ArrowUp => "Up",
                    KeyCode::Numpad0 => "Num0",
                    KeyCode::Numpad1 => "Num1",
                    KeyCode::Numpad2 => "Num2",
                    KeyCode::Numpad3 => "Num3",
                    KeyCode::Numpad4 => "Num4",
                    KeyCode::Numpad5 => "Num5",
                    KeyCode::Numpad6 => "Num6",
                    KeyCode::Numpad7 => "Num7",
                    KeyCode::Numpad8 => "Num8",
                    KeyCode::Numpad9 => "Num9",
                    KeyCode::NumpadAdd => "+",
                    KeyCode::NumpadEqual => "=",
                    KeyCode::NumpadHash => "#",
                    KeyCode::NumpadMultiply => "*",
                    KeyCode::NumpadParenLeft => "(",
                    KeyCode::NumpadParenRight => ")",
                    KeyCode::NumpadStar => "*",
                    KeyCode::Escape => "Escape",
                    KeyCode::Fn => "Fn",
                    KeyCode::F1 => "F1",
                    KeyCode::F2 => "F2",
                    KeyCode::F3 => "F3",
                    KeyCode::F4 => "F4",
                    KeyCode::F5 => "F5",
                    KeyCode::F6 => "F6",
                    KeyCode::F7 => "F7",
                    KeyCode::F8 => "F8",
                    KeyCode::F9 => "F9",
                    KeyCode::F10 => "F10",
                    KeyCode::F11 => "F11",
                    KeyCode::F12 => "F12",
                    KeyCode::F13 => "F13",
                    KeyCode::F14 => "F14",
                    KeyCode::F15 => "F15",
                    KeyCode::F16 => "F16",
                    KeyCode::F17 => "F17",
                    KeyCode::F18 => "F18",
                    KeyCode::F19 => "F19",
                    KeyCode::F20 => "F20",
                    KeyCode::F21 => "F21",
                    KeyCode::F22 => "F22",
                    KeyCode::F23 => "F23",
                    KeyCode::F24 => "F24",
                    KeyCode::F25 => "F25",
                    KeyCode::F26 => "F26",
                    KeyCode::F27 => "F27",
                    KeyCode::F28 => "F28",
                    KeyCode::F29 => "F29",
                    KeyCode::F30 => "F30",
                    KeyCode::F31 => "F31",
                    KeyCode::F32 => "F32",
                    KeyCode::F33 => "F33",
                    KeyCode::F34 => "F34",
                    KeyCode::F35 => "F35",
                    _ => "",
                };
                if !ch.is_empty() {
                    if !s.is_empty() {
                        s += "+";
                    }
                    s += ch;
                }
                s.shrink_to_fit();
                s
            }
            Input::Button(_, button) => format!("{button:#?}"),
            Input::Axis(_, axis, direction) => format!("{axis:#?} {direction:#?}"),
            Input::Mouse(button) => match button {
                MouseButton::Left => String::from("Left Click"),
                MouseButton::Right => String::from("Right Click"),
                MouseButton::Middle => String::from("Middle Click"),
                MouseButton::Back => String::from("Back Click"),
                MouseButton::Forward => String::from("Forward Click"),
                MouseButton::Other(id) => format!("Button {id} Click"),
            },
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum AxisDirection {
    Negative, // Left or Up
    Positive, // Right or Down
}

pub type Bindings = [Option<Input>; 3];

#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
#[must_use]
pub struct ActionBindings {
    pub action: Action,
    pub bindings: Bindings,
}

impl ActionBindings {
    pub const fn new(action: Action, bindings: Bindings) -> Self {
        Self { action, bindings }
    }

    pub fn empty(action: Action) -> Self {
        Self {
            action,
            bindings: Default::default(),
        }
    }
    pub fn default_shortcuts() -> BTreeMap<Action, ActionBindings> {
        use KeyCode::*;
        const SHIFT: ModifiersState = ModifiersState::SHIFT;
        const CONTROL: ModifiersState = ModifiersState::CONTROL;

        let mut bindings = Action::BINDABLE
            .into_iter()
            .filter(|action| !action.is_joypad())
            .map(|action| (action, ActionBindings::empty(action)))
            .collect::<BTreeMap<_, _>>();

        bindings.extend(shortcut_map!(
            { Debug::Step(DebugStep::Frame) => :SHIFT, KeyF },
            { Debug::Step(DebugStep::Into) => KeyC },
            { Debug::Step(DebugStep::Out) => :SHIFT, KeyO },
            { Debug::Step(DebugStep::Over) => KeyO },
            { Debug::Step(DebugStep::Scanline) => :SHIFT, KeyL },
            { Debug::Toggle(DebugKind::Apu) => :SHIFT, KeyA },
            { Debug::Toggle(DebugKind::Cpu) => :SHIFT, KeyD },
            { Debug::Toggle(DebugKind::Ppu) => :SHIFT, KeyP },
            { DeckAction::LoadState => :CONTROL, KeyL },
            { DeckAction::Reset(ResetKind::Hard) => :CONTROL, KeyH },
            { DeckAction::Reset(ResetKind::Soft) => :CONTROL, KeyR },
            { DeckAction::SaveState => :CONTROL, KeyS },
            { DeckAction::SetSaveSlot(1) => :CONTROL, Digit1 },
            { DeckAction::SetSaveSlot(2) => :CONTROL, Digit2 },
            { DeckAction::SetSaveSlot(3) => :CONTROL, Digit3 },
            { DeckAction::SetSaveSlot(4) => :CONTROL, Digit4 },
            { DeckAction::SetSaveSlot(5) => :CONTROL, Digit5 },
            { DeckAction::SetSaveSlot(6) => :CONTROL, Digit6 },
            { DeckAction::SetSaveSlot(7) => :CONTROL, Digit7 },
            { DeckAction::SetSaveSlot(8) => :CONTROL, Digit8 },
            { DeckAction::SetVideoFilter(VideoFilter::Ntsc) => :CONTROL, KeyN },
            { DeckAction::ToggleApuChannel(Channel::Dmc) => :SHIFT, Digit5 },
            { DeckAction::ToggleApuChannel(Channel::Mapper) => :SHIFT, Digit6 },
            { DeckAction::ToggleApuChannel(Channel::Noise) => :SHIFT, Digit4 },
            { DeckAction::ToggleApuChannel(Channel::Pulse1) => :SHIFT, Digit1 },
            { DeckAction::ToggleApuChannel(Channel::Pulse2) => :SHIFT, Digit2 },
            { DeckAction::ToggleApuChannel(Channel::Triangle) => :SHIFT, Digit3 },
            { Feature::TakeScreenshot => F10 },
            { Feature::ToggleAudioRecording => :SHIFT, KeyR },
            { Feature::ToggleReplayRecording => :SHIFT, KeyV },
            // Covers `Feature::InstantRewind` too — its handler rewinds instantly on a tap and
            // visually on a hold, so binding both actions to `R` would only make one of them win.
            { Feature::VisualRewind => KeyR },
            { Menu::About => F1 },
            { Menu::Keybinds => :CONTROL, KeyK },
            { Menu::Preferences => :CONTROL, KeyP; F2 },
            { Menu::PerfStats => :CONTROL, KeyF },
            { Setting::DecrementScale => :SHIFT, Minus },
            { Setting::DecrementSpeed => Minus },
            { Setting::FastForward => Space },
            { Setting::IncrementScale => :SHIFT, Equal },
            { Setting::IncrementSpeed => Equal },
            { Setting::ToggleAudio => :CONTROL, KeyM },
            { Setting::ToggleFullscreen => :CONTROL, Enter },
            { Setting::ToggleMenubar => :CONTROL, KeyE },
            { Setting::SetShader(Shader::CrtEasymode) => :CONTROL, KeyT },
            { Ui::LoadRom => :CONTROL, KeyO; F3 },
            { Ui::Quit => :CONTROL, KeyQ },
            { Ui::TogglePause => Escape },
        ));
        bindings.extend(mouse_map!(
            { DeckAction::ZapperTrigger => MouseButton::Left },
            { DeckAction::ZapperAimOffscreen => MouseButton::Right }
        ));

        bindings
    }

    pub fn default_player_bindings(player: Player) -> BTreeMap<Action, ActionBindings> {
        use KeyCode::*;
        use gilrs::{Axis, Button};

        let mut bindings = Action::BINDABLE
            .into_iter()
            .filter(|action| action.joypad_player(player))
            .map(|action| (action, ActionBindings::empty(action)))
            .collect::<BTreeMap<_, _>>();

        bindings.extend(gamepad_map!(
            { (player, JoypadBtn::A) => player; Button::East },
            { (player, JoypadBtn::TurboA) => player; Button::North },
            { (player, JoypadBtn::B) => player; Button::South },
            { (player, JoypadBtn::TurboB) => player; Button::West },
            { (player, JoypadBtn::Up) => player; Button::DPadUp; (Axis::LeftStickY, AxisDirection::Negative) },
            { (player, JoypadBtn::Down) => player; Button::DPadDown; (Axis::LeftStickY, AxisDirection::Positive) },
            { (player, JoypadBtn::Left) => player; Button::DPadLeft; (Axis::LeftStickX, AxisDirection::Negative) },
            { (player, JoypadBtn::Right) => player; Button::DPadRight; (Axis::LeftStickX, AxisDirection::Positive) },
            { (player, JoypadBtn::Select) => player; Button::Select },
            { (player, JoypadBtn::Start) => player; Button::Start },
        ));

        let additional_bindings = match player {
            Player::One => shortcut_map!(
                { (Player::One, JoypadBtn::A) => KeyZ },
                { (Player::One, JoypadBtn::TurboA) => KeyA },
                { (Player::One, JoypadBtn::B) => KeyX },
                { (Player::One, JoypadBtn::TurboB) => KeyS },
                { (Player::One, JoypadBtn::Up) => ArrowUp },
                { (Player::One, JoypadBtn::Down) => ArrowDown },
                { (Player::One, JoypadBtn::Left) => ArrowLeft },
                { (Player::One, JoypadBtn::Right) => ArrowRight },
                { (Player::One, JoypadBtn::Select) => KeyQ },
                { (Player::One, JoypadBtn::Select) => ShiftRight },
                { (Player::One, JoypadBtn::Start) => KeyW },
                { (Player::One, JoypadBtn::Start) => Enter },
            ),
            _ => Vec::new(),
        };

        for (action, addtl_binding) in additional_bindings {
            if let Some((_, existing_bindings)) = bindings
                .iter_mut()
                .find(|(existing_action, _)| **existing_action == action)
            {
                // The first free slot only, so the key never lands in two slots of one action.
                if let Some(binding) = existing_bindings
                    .bindings
                    .iter_mut()
                    .find(|binding| binding.is_none())
                {
                    *binding = addtl_binding.bindings[0];
                }
            } else {
                bindings.insert(action, addtl_binding);
            }
        }

        bindings
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InputBindings(HashMap<Input, Action>);

impl InputBindings {
    pub fn from_input_config(cfg: &InputConfig) -> Self {
        Self(
            cfg.action_bindings
                .iter()
                .flat_map(|bind| {
                    bind.bindings
                        .iter()
                        .flatten()
                        .map(|input| (*input, bind.action))
                })
                .collect(),
        )
    }
}

impl Deref for InputBindings {
    type Target = HashMap<Input, Action>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for InputBindings {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// Represents gamepad input state.
#[derive(Default, Debug)]
pub struct Gamepads {
    connected: HashMap<gilrs::GamepadId, Uuid>,
    inner: Option<gilrs::Gilrs>,
    events: VecDeque<gilrs::Event>,
}

impl Gamepads {
    pub fn new() -> Self {
        let mut connected = HashMap::default();
        let mut gilrs = gilrs::Gilrs::new();
        let mut events = VecDeque::new();
        match &mut gilrs {
            Ok(inputs) => {
                for (id, gamepad) in inputs.gamepads() {
                    let uuid = Self::create_uuid(&gamepad);
                    tracing::debug!("gamepad connected: {} ({uuid})", gamepad.name());
                    connected.insert(id, uuid);
                }
                events.reserve(256);
            }
            Err(err) => {
                warn!("failed to initialize inputs: {err:?}");
            }
        }

        Self {
            connected,
            inner: gilrs.ok(),
            events,
        }
    }

    /// Replaces the queue with everything gilrs has buffered since the last poll.
    ///
    /// The queue holds one poll's worth: the game path drains it every frame, and while the UI is
    /// consuming input nothing drains it, so without the clear it would grow for as long as a menu
    /// stays open and [`Gamepads::events`] would hand the keybind UI a backlog instead of what was
    /// just pressed.
    pub fn update_events(&mut self) {
        self.events.clear();
        if let Some(inner) = self.inner.as_mut() {
            while let Some(event) = inner.next_event() {
                self.events.push_back(event);
            }
        }
    }

    pub fn axis_state(value: f32) -> (Option<AxisDirection>, ElementState) {
        let direction = if value >= 0.6 {
            Some(AxisDirection::Positive)
        } else if value <= -0.6 {
            Some(AxisDirection::Negative)
        } else {
            None
        };
        let state = if direction.is_some() {
            ElementState::Pressed
        } else {
            ElementState::Released
        };
        (direction, state)
    }

    pub const fn has_events(&self) -> bool {
        !self.events.is_empty()
    }

    pub fn input_from_event(
        &self,
        event: &gilrs::Event,
        cfg: &Config,
    ) -> Option<(Input, ElementState)> {
        use gilrs::EventType;
        if let Some(player) = self
            .connected
            .get(&event.id)
            .and_then(|uuid| cfg.input.gamepad_assignment(uuid))
        {
            match event.event {
                EventType::ButtonPressed(button, _) => {
                    Some((Input::Button(player, button), ElementState::Pressed))
                }
                EventType::ButtonRepeated(button, _) => {
                    Some((Input::Button(player, button), ElementState::Pressed))
                }
                EventType::ButtonReleased(button, _) => {
                    Some((Input::Button(player, button), ElementState::Released))
                }
                EventType::AxisChanged(axis, value, _) => {
                    if let (Some(direction), state) = Gamepads::axis_state(value) {
                        Some((Input::Axis(player, axis, direction), state))
                    } else {
                        None
                    }
                }
                _ => None,
            }
        } else {
            None
        }
    }

    pub fn connected_gamepad(&self, id: gilrs::GamepadId) -> Option<gilrs::Gamepad<'_>> {
        self.inner
            .as_ref()
            .and_then(|inner| inner.connected_gamepad(id))
    }

    pub fn gamepad(&self, id: gilrs::GamepadId) -> Option<gilrs::Gamepad<'_>> {
        self.inner.as_ref().map(|inner| inner.gamepad(id))
    }

    pub fn gamepad_by_uuid(&self, uuid: &Uuid) -> Option<gilrs::Gamepad<'_>> {
        self.inner.as_ref().and_then(|inner| {
            self.connected
                .iter()
                .find(|(_, u)| *u == uuid)
                .and_then(|(id, _)| inner.connected_gamepad(*id))
        })
    }

    pub fn gamepad_name_by_uuid(&self, uuid: &Uuid) -> Option<String> {
        self.gamepad_by_uuid(uuid).map(|g| g.name().to_string())
    }

    pub fn gamepad_uuid(&self, id: gilrs::GamepadId) -> Option<Uuid> {
        self.connected_gamepad(id).map(|g| Self::create_uuid(&g))
    }

    pub fn is_connected(&self, uuid: &Uuid) -> bool {
        self.gamepad_by_uuid(uuid).is_some()
    }

    pub fn list(&self) -> Option<Peekable<gilrs::ConnectedGamepadsIterator<'_>>> {
        self.inner.as_ref().map(|inner| inner.gamepads().peekable())
    }

    pub fn connected_uuids(&self) -> impl Iterator<Item = &Uuid> {
        self.connected.values()
    }

    pub fn events(&self) -> impl Iterator<Item = &gilrs::Event> {
        self.events.iter()
    }

    // Front, not back: a press and its release can land in the same poll, and dispatching them in
    // reverse leaves the button stuck down.
    pub fn next_event(&mut self) -> Option<gilrs::Event> {
        self.events.pop_front()
    }

    pub fn connect(&mut self, gamepad_id: gilrs::GamepadId) {
        if let Some(gamepad) = self.connected_gamepad(gamepad_id) {
            let uuid = Self::create_uuid(&gamepad);
            tracing::debug!("gamepad connected: {} ({uuid})", gamepad.name());
            self.connected.insert(gamepad.id(), uuid);
        }
    }

    pub fn disconnect(&mut self, gamepad_id: gilrs::GamepadId) {
        if let Some(gamepad) = self.gamepad(gamepad_id) {
            let uuid = Self::create_uuid(&gamepad);
            tracing::debug!("gamepad disconnected: {} ({uuid})", gamepad.name());
        }
        self.connected.remove(&gamepad_id);
    }

    pub fn create_uuid(gamepad: &gilrs::Gamepad<'_>) -> Uuid {
        let uuid = Uuid::from_bytes(gamepad.uuid());
        if uuid != Uuid::nil() {
            return uuid;
        }

        // See: https://gitlab.com/gilrs-project/gilrs/-/issues/107

        // SDL always uses USB bus for UUID
        let bustype = u32::to_be(0x03);

        // Version is not available.
        let version = 0;
        let vendor_id = gamepad.vendor_id().unwrap_or(0);
        let product_id = gamepad.product_id().unwrap_or(0);

        if vendor_id == 0 && product_id == 0 {
            Uuid::new_v4()
        } else {
            Uuid::from_fields(
                bustype,
                vendor_id,
                0,
                &[
                    (product_id >> 8) as u8,
                    product_id as u8,
                    0,
                    0,
                    (version >> 8) as u8,
                    version as u8,
                    0,
                    0,
                ],
            )
        }
    }
}

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

    const JOYPAD_A: Action = Action::Deck(DeckAction::Joypad((Player::One, JoypadBtn::A)));

    #[test]
    fn default_bindings_have_no_duplicate_slots() {
        for bind in &InputConfig::default().action_bindings {
            let mut seen = Vec::new();
            for input in bind.bindings.iter().flatten() {
                assert!(
                    !seen.contains(input),
                    "{:?} is bound to {:?} in two slots",
                    bind.action,
                    input
                );
                seen.push(*input);
            }
        }
    }

    #[test]
    fn default_bindings_give_each_input_one_action() {
        // `InputBindings` is keyed by `Input`, so two actions sharing one means whichever is
        // collected last silently wins and the other never fires.
        let mut owner = HashMap::default();
        for bind in &InputConfig::default().action_bindings {
            for input in bind.bindings.iter().flatten() {
                if let Some(existing) = owner.insert(*input, bind.action) {
                    panic!(
                        "{input:?} is bound to both {:?} and {:?}",
                        existing, bind.action
                    );
                }
            }
        }
    }

    #[test]
    fn clear_binding_clears_every_slot() {
        let mut cfg = InputConfig::default();
        let input = Input::Key(KeyCode::KeyZ, ModifiersState::empty());

        // A config on disk can carry the same input in more than one of an action's slots.
        for bindings in [
            &mut cfg
                .action_bindings
                .iter_mut()
                .find(|bind| bind.action == JOYPAD_A)
                .expect("joypad A is bound by default")
                .bindings,
            &mut cfg.joypads[Player::One as usize]
                .get_mut(&JOYPAD_A)
                .expect("joypad A is bound by default")
                .bindings,
        ] {
            bindings.fill(Some(input));
        }

        cfg.clear_binding(input);

        let bind = cfg
            .action_bindings
            .iter()
            .find(|bind| bind.action == JOYPAD_A)
            .expect("joypad A is still present");
        assert!(
            bind.bindings.iter().all(Option::is_none),
            "left behind {:?}",
            bind.bindings
        );
        assert!(
            cfg.joypads[Player::One as usize][&JOYPAD_A]
                .bindings
                .iter()
                .all(Option::is_none),
            "the joypad mirror kept a stale slot"
        );
    }
}