bevy_ratatui 0.6.4

A Bevy plugin for building terminal user interfaces with Ratatui
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
//! Input forwarding for the keyboard

use std::{
    collections::HashSet,
    hash::{Hash, Hasher},
    time::Duration,
};

use bevy::{
    input::{keyboard::KeyboardInput, ButtonState},
    prelude::*,
};
use crossterm::event::KeyModifiers;

use crate::event::{InputSet, KeyEvent};

bitflags::bitflags! {
    /// Crudely defines some capabilities of terminal. Useful for representing
    /// both detection ([Detect]) and emulation ([EmulationPolicy]).
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
    pub struct Capability: u8 {
        /// Represents a terminal that emits its own key release events.
        const KEY_RELEASE = 0b0000_0001;
        /// Represents a terminal that emits its own modifier key press and
        /// release events independently from other keys.
        const MODIFIER = 0b0000_0010;
        const ALL = Self::KEY_RELEASE.bits() | Self::MODIFIER.bits();
    }
}

/// Keyboard emulation policy
///
/// - The [Automatic][EmulationPolicy::Automatic] policy will emulate key release or modifiers if
///   they have not been detected.
///
/// - The [Manual][EmulationPolicy::Manual] policy defines whether modifiers or key releases will be
///   emulated.
///
/// Note: If key releases are emulated and key releases are provided by the
/// terminal, dupliate events may be sent.
#[derive(Debug, Default, Resource, Clone, Copy)]
pub enum EmulationPolicy {
    /// Emulate everything that has not been detected.
    #[default]
    Automatic,
    /// Define what will be emulated.
    Manual(Capability),
}

impl EmulationPolicy {
    /// Return what capabilities to emulate.
    pub fn emulate_capabilities(&self, detected: &Detected) -> Capability {
        match self {
            EmulationPolicy::Automatic => !detected.0,
            EmulationPolicy::Manual(capabilitiy) => *capabilitiy,
        }
    }
}

/// This represents the currently detected capabilities of the terminal.
///
/// When the program starts, will be empty and this will return true:
/// `detected.is_empty()`. When a key is pressed and released, if a key release
/// was emitted, then `detected` will contain [Capability::KEY_RELEASE].
///
/// Likewise for a modifier key, if any modifier events are detected, then
/// `detected` will contain [Capability::MODIFIER].
///
/// Once those flags are set, they are never unset.
#[derive(Debug, Resource, Default, Deref)]
pub struct Detected(pub Capability);

/// Pass crossterm key events through to the bevy input system. See
/// [input_forwarding][crate::input_forwarding] for more details.
pub struct KeyboardPlugin;

impl Plugin for KeyboardPlugin {
    fn build(&self, app: &mut App) {
        if !app.is_plugin_added::<bevy::input::InputPlugin>() {
            // We need this plugin to submit our events.
            app.add_plugins(bevy::input::InputPlugin);
        }
        if !app.is_plugin_added::<bevy::time::TimePlugin>() {
            // We need this plugin for the delay timer.
            app.add_plugins(bevy::time::TimePlugin);
        }
        app.init_resource::<ReleaseKey>()
            .init_resource::<Detected>()
            .init_resource::<EmulationPolicy>()
            .init_resource::<Emulate>()
            .add_systems(Startup, setup_window)
            .add_systems(
                PreUpdate,
                reset_emulation_check
                    .run_if(resource_changed::<EmulationPolicy>)
                    .in_set(InputSet::Pre),
            )
            .add_systems(
                PreUpdate,
                (detect_capabilities, check_for_emulation)
                    .chain()
                    .run_if(resource_exists::<Emulate>)
                    .in_set(InputSet::CheckEmulation),
            )
            .add_systems(
                PreUpdate,
                (
                    send_key_events_with_emulation.run_if(resource_exists::<Emulate>),
                    send_key_events_no_emulation.run_if(not(resource_exists::<Emulate>)),
                )
                    .in_set(InputSet::EmitBevy),
            );
    }
}

/// A new type so we can implement Default and use with `Local`.
#[derive(Debug, Deref, DerefMut)]
struct Modifiers(KeyModifiers);

impl Default for Modifiers {
    fn default() -> Self {
        Self(KeyModifiers::empty())
    }
}

// I wish KeyboardInput had the Hash derive.
//
// TODO: Drop this if KeyboardInput gets a Hash impl.
// [PR](https://github.com/bevyengine/bevy/pull/14263)
#[derive(Deref, DerefMut, PartialEq, Eq)]
struct KeyInput(KeyboardInput);

impl Hash for KeyInput {
    fn hash<H>(&self, state: &mut H)
    where
        H: Hasher,
    {
        self.key_code.hash(state);
        self.logical_key.hash(state);
        self.state.hash(state);
        self.window.hash(state);
    }
}

/// This is a double-buffer for the last keys pressed.
///
/// - `.0` is current frame's last keys pressed.
/// - `.1` is the next frame's last keys pressed.
///
/// During processing we read from `.0` and write to `.1`.
#[derive(Default)]
struct LastPress(HashSet<KeyInput>, HashSet<KeyInput>);

impl LastPress {
    fn swap(&mut self) {
        std::mem::swap(&mut self.0, &mut self.1);
    }
}

/// If the terminal does not support sending key release events, this plugin will
/// emulate them. A crossterm event stream might look like this:
///
/// `Press A, Press B`
///
/// which will result in bevy events, i.e., a key release will be emitted on the
/// next press key event.
///
/// `Press A, Release A, Press B`
///
/// `A` is released when `B` is pressed, but how does one deal with releasing
/// `B`? If another key is pressed, that will release `B`. [ReleaseKey] concerns
/// itself with how to handle the last pressed key assuming it will be a while
/// before another key press comes.
///
/// This plugin will emit events like so depending on the variant:
///
/// - Duration
///
///   `Press A, Release A, Press B, (timer finishes) Release B`
///
///   The default is a one second duration before emitting a release on the last
///   pressed key
///
/// - FrameCount
///
///   `Press A, Release A, Press B, (frame count reached) Release B`
///
/// - Immediate
///
///   `Press A, Release A, Press B, (next frame) Release B`
///
/// - OnNextKey
///
///   `Press A, Release A, Press B`
///
///   The `Release B` event won't come until another key is pressed. This will
///   make it look like the last key pressed is being held down according to the
///   bevy API.
#[derive(Resource, Debug)]
pub enum ReleaseKey {
    /// Release key after a short duration.
    Duration(Duration),
    /// Release key after a number of frames.
    FrameCount(u32),
    /// Release key next frame.
    Immediate,
    /// Do not emit a key release until someone presses another key.
    OnNextKey,
}

impl Default for ReleaseKey {
    /// Set the release key timer for 1 second by default.
    fn default() -> Self {
        ReleaseKey::Duration(Duration::from_secs(1))
    }
}

#[derive(Default)]
enum ReleaseKeyState {
    #[default]
    None,
    Count(u32),
    Timer(Timer),
}

impl ReleaseKey {
    fn tick(&self, state: &mut ReleaseKeyState, delta: Duration) {
        use ReleaseKey::*;
        match self {
            FrameCount(_) | Immediate => {
                if let ReleaseKeyState::Count(ref mut c) = state {
                    *c = c.saturating_add(1);
                } else {
                    *state = ReleaseKeyState::Count(0);
                }
            }
            Duration(d) => {
                if let ReleaseKeyState::Timer(ref mut timer) = state {
                    timer.tick(delta);
                } else {
                    *state = ReleaseKeyState::Timer(Timer::new(*d, TimerMode::Once));
                }
            }
            _ => (),
        }
    }

    fn finished(&self, state: &ReleaseKeyState) -> bool {
        use ReleaseKey::*;
        match self {
            OnNextKey => false,
            FrameCount(target) => {
                let ReleaseKeyState::Count(ref count) = state else {
                    return false;
                };
                count >= target
            }
            Duration(_) => {
                let ReleaseKeyState::Timer(ref timer) = state else {
                    return false;
                };
                timer.finished()
            }
            Immediate => true,
        }
    }

    fn reset(&self, state: &mut ReleaseKeyState) {
        use ReleaseKey::*;
        match self {
            FrameCount(_) | Immediate => *state = ReleaseKeyState::Count(0),
            Duration(d) => {
                if let ReleaseKeyState::Timer(ref mut timer) = state {
                    timer.reset();
                } else {
                    *state = ReleaseKeyState::Timer(Timer::new(*d, TimerMode::Once));
                }
            }
            _ => (),
        }
    }
}

#[allow(clippy::too_many_arguments)]
fn detect_capabilities(mut keys: EventReader<KeyEvent>, mut detected: ResMut<Detected>) {
    for key_event in keys.read() {
        if matches!(key_event.code, crossterm::event::KeyCode::Modifier(_)) {
            detected.0 |= Capability::MODIFIER;
        }
        if matches!(key_event.kind, crossterm::event::KeyEventKind::Release) {
            detected.0 |= Capability::KEY_RELEASE;
        }
    }
}

/// Marker resource used to determine whether this plugin will emulate any
/// terminal capabilities. If it is not present, that's the best case because
/// the terminal doesn't require this plugin to emulate any capabilities. It's a
/// simpler and faster code path.
#[derive(Debug, Resource, Default)]
pub struct Emulate;

fn check_for_emulation(
    detected: Res<Detected>,
    policy: Res<EmulationPolicy>,
    mut commands: Commands,
) {
    if policy.emulate_capabilities(&detected).is_empty() {
        // We don't need to emulate anything, so don't.
        commands.remove_resource::<Emulate>();
    }
}

fn reset_emulation_check(mut commands: Commands) {
    commands.insert_resource(Emulate);
}

#[allow(clippy::too_many_arguments)]
fn send_key_events_with_emulation(
    mut keys: EventReader<KeyEvent>,
    window: Query<Entity, With<DummyWindow>>,
    mut modifiers: Local<Modifiers>,
    mut last_pressed: Local<LastPress>,
    mut keyboard_input: EventWriter<KeyboardInput>,
    release_key: Res<ReleaseKey>,
    mut release_key_state: Local<ReleaseKeyState>,
    time: Res<Time>,
    detected: Res<Detected>,
    policy: Res<EmulationPolicy>,
) {
    release_key.tick(&mut release_key_state, time.delta());
    if keys.is_empty() && !release_key.finished(&release_key_state) {
        return;
    }

    let bevy_window = window.single();
    for key_event in keys.read() {
        if let Some((bevy_event, mods, repeated)) = key_event_to_bevy(key_event, bevy_window) {
            let emulation = policy.emulate_capabilities(&detected);
            if emulation.contains(Capability::MODIFIER) && mods != **modifiers {
                let delta = mods.symmetric_difference(**modifiers);
                for flag in delta {
                    let state = if mods.contains(flag) {
                        // This flag has been added.
                        ButtonState::Pressed
                    } else {
                        // This flag has been removed.
                        ButtonState::Released
                    };
                    let modifier_event =
                        modifier_to_bevy(crossterm_modifier_to_bevy_key(flag), state, bevy_window);
                    keyboard_input.send(modifier_event);
                }
                **modifiers = mods;
            }

            if repeated {
                // Repeated key events are converted to key release events by
                // `key_event_to_bevy()`. But are queued up to emit a key press
                // on the next frame.
                last_pressed.1.insert(KeyInput(bevy_event.clone()));
            }
            if emulation.contains(Capability::KEY_RELEASE) {
                // Must send the release events ourselves.
                let wrapped = KeyInput(bevy_event.clone());
                if let Some(last_press) = last_pressed.0.take(&wrapped) {
                    // It's being held down. Pass to the next frame.
                    last_pressed.1.insert(last_press);
                } else {
                    last_pressed.1.insert(wrapped);
                    keyboard_input.send(bevy_event);
                }
            } else {
                keyboard_input.send(bevy_event);
            }
        }
    }
    for e in last_pressed.0.drain() {
        // In general this is where we emit key released events. However,
        // we also emit key pressed events for repeated keys.
        let reciprocal_event = KeyboardInput {
            state: match e.0.state {
                ButtonState::Pressed => ButtonState::Released,
                ButtonState::Released => ButtonState::Pressed,
            },
            ..e.0
        };
        keyboard_input.send(reciprocal_event);
    }

    if release_key.finished(&release_key_state)
        && policy
            .emulate_capabilities(&detected)
            .contains(Capability::MODIFIER)
    {
        // Release the modifiers too if we've timed out.
        for flag in **modifiers {
            let state = ButtonState::Released;
            let modifier_event =
                modifier_to_bevy(crossterm_modifier_to_bevy_key(flag), state, bevy_window);
            keyboard_input.send(modifier_event);
        }
        **modifiers = KeyModifiers::empty();
    }
    last_pressed.swap();
    release_key.reset(&mut release_key_state);
}

/// Send bevy events without any emulation. This merely shows how simple life is
/// when emulation is not involved.
fn send_key_events_no_emulation(
    mut keys: EventReader<KeyEvent>,
    window: Query<Entity, With<DummyWindow>>,
    mut keyboard_input: EventWriter<KeyboardInput>,
    mut key_repeat_queue: Local<Vec<KeyboardInput>>,
) {
    for bevy_event in key_repeat_queue.drain(..) {
        keyboard_input.send(bevy_event);
    }
    let bevy_window = window.single();
    for key_event in keys.read() {
        if let Some((bevy_event, _modifiers, repeated)) = key_event_to_bevy(key_event, bevy_window)
        {
            if repeated {
                key_repeat_queue.push(KeyboardInput {
                    state: ButtonState::Pressed,
                    ..bevy_event.clone()
                });
            }
            keyboard_input.send(bevy_event);
        }
    }
}

#[derive(Debug, Component)]
struct DummyWindow;

/// This is a dummy window to satisfy the [KeyboardInput] struct.
fn setup_window(mut commands: Commands) {
    // Insert our window entity so that other parts of our app can use them.
    commands.spawn(DummyWindow);
}

fn modifier_to_bevy(
    modifier: bevy::input::keyboard::Key,
    state: bevy::input::ButtonState,
    window: Entity,
) -> bevy::input::keyboard::KeyboardInput {
    use bevy::input::keyboard::{Key as k, KeyCode as c};
    let key_code = match modifier {
        k::Control => c::ControlLeft,
        k::Shift => c::ShiftLeft,
        k::Alt => c::AltLeft,
        k::Hyper => c::Hyper,
        k::Meta => c::Meta,
        k::Super => c::SuperLeft,
        x => panic!("No such modifier {x:?}"),
    };
    let logical_key = modifier;
    bevy::input::keyboard::KeyboardInput {
        key_code,
        state,
        window,
        logical_key,
    }
}

fn key_event_to_bevy(
    key_event: &crossterm::event::KeyEvent,
    window: Entity,
) -> Option<(
    bevy::input::keyboard::KeyboardInput,
    crossterm::event::KeyModifiers,
    bool,
)> {
    let crossterm::event::KeyEvent {
        code,
        modifiers,
        kind,
        state: _state,
    } = key_event;
    let mut repeated = false;
    let state = match kind {
        crossterm::event::KeyEventKind::Press => bevy::input::ButtonState::Pressed,
        crossterm::event::KeyEventKind::Repeat => {
            repeated = true;
            bevy::input::ButtonState::Released
        }
        crossterm::event::KeyEventKind::Release => bevy::input::ButtonState::Released,
    };
    let key_code = to_bevy_keycode(code);
    let logical_key = to_bevy_key(code);
    key_code
        .zip(logical_key)
        .map(|((key_code, mods), logical_key)| {
            (
                bevy::input::keyboard::KeyboardInput {
                    key_code,
                    state,
                    window,
                    logical_key,
                },
                *modifiers | mods,
                repeated,
            )
        })
}

fn to_bevy_keycode(
    key_code: &crossterm::event::KeyCode,
) -> Option<(
    bevy::input::keyboard::KeyCode,
    crossterm::event::KeyModifiers,
)> {
    use bevy::input::keyboard::KeyCode as b;
    use crossterm::event::{KeyCode as c, KeyModifiers as m};
    let mut mods = crossterm::event::KeyModifiers::empty();
    match key_code {
        c::Backspace => Some(b::Backspace),
        c::Enter => Some(b::Enter),
        c::Left => Some(b::ArrowLeft),
        c::Right => Some(b::ArrowRight),
        c::Up => Some(b::ArrowUp),
        c::Down => Some(b::ArrowDown),
        c::Home => Some(b::Home),
        c::End => Some(b::End),
        c::PageUp => Some(b::PageUp),
        c::PageDown => Some(b::PageDown),
        c::Tab => Some(b::Tab),
        c::BackTab => {
            mods |= m::SHIFT;
            Some(b::Tab)
        }
        c::Delete => Some(b::Delete),
        c::Insert => Some(b::Insert),
        c::F(f) => match f {
            1 => Some(b::F1),
            2 => Some(b::F2),
            3 => Some(b::F3),
            4 => Some(b::F4),
            5 => Some(b::F5),
            6 => Some(b::F6),
            7 => Some(b::F7),
            8 => Some(b::F8),
            9 => Some(b::F9),
            10 => Some(b::F10),
            11 => Some(b::F11),
            12 => Some(b::F12),
            13 => Some(b::F13),
            14 => Some(b::F14),
            15 => Some(b::F15),
            16 => Some(b::F16),
            17 => Some(b::F17),
            18 => Some(b::F18),
            19 => Some(b::F19),
            20 => Some(b::F20),
            31 => Some(b::F31),
            32 => Some(b::F32),
            33 => Some(b::F33),
            34 => Some(b::F34),
            35 => Some(b::F35),
            _ => None,
        },
        c::Char(c) => match c {
            '!' => {
                mods |= m::SHIFT;
                Some(b::Digit1)
            }
            '@' => {
                mods |= m::SHIFT;
                Some(b::Digit2)
            }
            '#' => {
                mods |= m::SHIFT;
                Some(b::Digit3)
            }
            '$' => {
                mods |= m::SHIFT;
                Some(b::Digit4)
            }
            '%' => {
                mods |= m::SHIFT;
                Some(b::Digit5)
            }
            '^' => {
                mods |= m::SHIFT;
                Some(b::Digit6)
            }
            '&' => {
                mods |= m::SHIFT;
                Some(b::Digit7)
            }
            '*' => {
                mods |= m::SHIFT;
                Some(b::Digit8)
            }
            '(' => {
                mods |= m::SHIFT;
                Some(b::Digit9)
            }
            ')' => {
                mods |= m::SHIFT;
                Some(b::Digit0)
            }
            '-' => {
                mods |= m::SHIFT;
                Some(b::Minus)
            }
            '[' => Some(b::BracketLeft),
            ']' => Some(b::BracketRight),
            '{' => {
                mods |= m::SHIFT;
                Some(b::BracketLeft)
            }
            '}' => {
                mods |= m::SHIFT;
                Some(b::BracketRight)
            }
            ',' => Some(b::Comma),
            '=' => Some(b::Equal),
            '<' => {
                mods |= m::SHIFT;
                Some(b::Comma)
            }
            '+' => {
                mods |= m::SHIFT;
                Some(b::Equal)
            }
            '.' => Some(b::Period),
            '>' => {
                mods |= m::SHIFT;
                Some(b::Period)
            }
            '\'' => Some(b::Quote),
            '"' => {
                mods |= m::SHIFT;
                Some(b::Quote)
            }
            ';' => Some(b::Semicolon),
            ':' => {
                mods |= m::SHIFT;
                Some(b::Semicolon)
            }
            '/' => Some(b::Slash),
            '?' => {
                mods |= m::SHIFT;
                Some(b::Slash)
            }
            ' ' => Some(b::Space),
            '1' => Some(b::Digit1),
            '2' => Some(b::Digit2),
            '3' => Some(b::Digit3),
            '4' => Some(b::Digit4),
            '5' => Some(b::Digit5),
            '6' => Some(b::Digit6),
            '7' => Some(b::Digit7),
            '8' => Some(b::Digit8),
            '9' => Some(b::Digit9),
            '0' => Some(b::Digit0),
            'a' => Some(b::KeyA),
            'b' => Some(b::KeyB),
            'c' => Some(b::KeyC),
            'd' => Some(b::KeyD),
            'e' => Some(b::KeyE),
            'f' => Some(b::KeyF),
            'g' => Some(b::KeyG),
            'h' => Some(b::KeyH),
            'i' => Some(b::KeyI),
            'j' => Some(b::KeyJ),
            'k' => Some(b::KeyK),
            'l' => Some(b::KeyL),
            'm' => Some(b::KeyM),
            'n' => Some(b::KeyN),
            'o' => Some(b::KeyO),
            'p' => Some(b::KeyP),
            'q' => Some(b::KeyQ),
            'r' => Some(b::KeyR),
            's' => Some(b::KeyS),
            't' => Some(b::KeyT),
            'u' => Some(b::KeyU),
            'v' => Some(b::KeyV),
            'w' => Some(b::KeyW),
            'x' => Some(b::KeyX),
            'y' => Some(b::KeyY),
            'z' => Some(b::KeyZ),
            'A' => {
                mods |= m::SHIFT;
                Some(b::KeyA)
            }
            'B' => {
                mods |= m::SHIFT;
                Some(b::KeyB)
            }
            'C' => {
                mods |= m::SHIFT;
                Some(b::KeyC)
            }
            'D' => {
                mods |= m::SHIFT;
                Some(b::KeyD)
            }
            'E' => {
                mods |= m::SHIFT;
                Some(b::KeyE)
            }
            'F' => {
                mods |= m::SHIFT;
                Some(b::KeyF)
            }
            'G' => {
                mods |= m::SHIFT;
                Some(b::KeyG)
            }
            'H' => {
                mods |= m::SHIFT;
                Some(b::KeyH)
            }
            'I' => {
                mods |= m::SHIFT;
                Some(b::KeyI)
            }
            'J' => {
                mods |= m::SHIFT;
                Some(b::KeyJ)
            }
            'K' => {
                mods |= m::SHIFT;
                Some(b::KeyK)
            }
            'L' => {
                mods |= m::SHIFT;
                Some(b::KeyL)
            }
            'M' => {
                mods |= m::SHIFT;
                Some(b::KeyM)
            }
            'N' => {
                mods |= m::SHIFT;
                Some(b::KeyN)
            }
            'O' => {
                mods |= m::SHIFT;
                Some(b::KeyO)
            }
            'P' => {
                mods |= m::SHIFT;
                Some(b::KeyP)
            }
            'Q' => {
                mods |= m::SHIFT;
                Some(b::KeyQ)
            }
            'R' => {
                mods |= m::SHIFT;
                Some(b::KeyR)
            }
            'S' => {
                mods |= m::SHIFT;
                Some(b::KeyS)
            }
            'T' => {
                mods |= m::SHIFT;
                Some(b::KeyT)
            }
            'U' => {
                mods |= m::SHIFT;
                Some(b::KeyU)
            }
            'V' => {
                mods |= m::SHIFT;
                Some(b::KeyV)
            }
            'W' => {
                mods |= m::SHIFT;
                Some(b::KeyW)
            }
            'X' => {
                mods |= m::SHIFT;
                Some(b::KeyX)
            }
            'Y' => {
                mods |= m::SHIFT;
                Some(b::KeyY)
            }
            'Z' => {
                mods |= m::SHIFT;
                Some(b::KeyZ)
            }
            _ => None,
        },
        c::Null => None,
        c::Esc => Some(b::Escape),
        c::CapsLock => Some(b::CapsLock),
        c::ScrollLock => Some(b::ScrollLock),
        c::NumLock => Some(b::NumLock),
        c::PrintScreen => Some(b::PrintScreen),
        c::Pause => Some(b::Pause),
        c::Menu => Some(b::ContextMenu),
        c::KeypadBegin => None,
        c::Media(media) => {
            use crossterm::event::MediaKeyCode::*;
            match media {
                Play => Some(b::MediaPlayPause),
                Pause => Some(b::Pause),
                PlayPause => Some(b::MediaPlayPause),
                Reverse => None,
                Stop => Some(b::MediaStop),
                FastForward => Some(b::MediaTrackNext),
                Rewind => Some(b::MediaTrackPrevious),
                TrackNext => Some(b::MediaTrackNext),
                TrackPrevious => Some(b::MediaTrackPrevious),
                Record => None,
                LowerVolume => Some(b::AudioVolumeDown),
                RaiseVolume => Some(b::AudioVolumeUp),
                MuteVolume => Some(b::AudioVolumeMute),
            }
        }
        c::Modifier(modifier) => {
            use crossterm::event::ModifierKeyCode::*;
            match modifier {
                LeftShift => Some(b::ShiftLeft),
                LeftControl => Some(b::ControlLeft),
                LeftAlt => Some(b::AltLeft),
                LeftSuper => Some(b::SuperLeft),
                LeftHyper => Some(b::Hyper),
                LeftMeta => Some(b::Meta),
                RightShift => Some(b::ShiftRight),
                RightControl => Some(b::ControlRight),
                RightAlt => Some(b::AltRight),
                RightSuper => Some(b::SuperRight),
                RightHyper => Some(b::Hyper),
                RightMeta => Some(b::Meta),
                IsoLevel3Shift => None,
                IsoLevel5Shift => None,
            }
        }
    }
    .map(|key_code| (key_code, mods))
}

fn to_bevy_key(key_code: &crossterm::event::KeyCode) -> Option<bevy::input::keyboard::Key> {
    use bevy::input::keyboard::Key as b;
    use crossterm::event::KeyCode as c;
    match key_code {
        c::Backspace => Some(b::Backspace),
        c::Enter => Some(b::Enter),
        c::Left => Some(b::ArrowLeft),
        c::Right => Some(b::ArrowRight),
        c::Up => Some(b::ArrowUp),
        c::Down => Some(b::ArrowDown),
        c::Home => Some(b::Home),
        c::End => Some(b::End),
        c::PageUp => Some(b::PageUp),
        c::PageDown => Some(b::PageDown),
        c::Tab => Some(b::Tab),
        c::BackTab => {
            // mods |= m::SHIFT;
            Some(b::Tab)
        }
        c::Delete => Some(b::Delete),
        c::Insert => Some(b::Insert),
        c::F(f) => match f {
            1 => Some(b::F1),
            2 => Some(b::F2),
            3 => Some(b::F3),
            4 => Some(b::F4),
            5 => Some(b::F5),
            6 => Some(b::F6),
            7 => Some(b::F7),
            8 => Some(b::F8),
            9 => Some(b::F9),
            10 => Some(b::F10),
            11 => Some(b::F11),
            12 => Some(b::F12),
            13 => Some(b::F13),
            14 => Some(b::F14),
            15 => Some(b::F15),
            16 => Some(b::F16),
            17 => Some(b::F17),
            18 => Some(b::F18),
            19 => Some(b::F19),
            20 => Some(b::F20),
            31 => Some(b::F31),
            32 => Some(b::F32),
            33 => Some(b::F33),
            34 => Some(b::F34),
            35 => Some(b::F35),
            _ => None,
        },
        c::Char(c) => Some({
            let mut tmp = [0u8; 4];
            let s = c.encode_utf8(&mut tmp);
            b::Character(smol_str::SmolStr::from(s))
        }),
        c::Null => None,
        c::Esc => Some(b::Escape),
        c::CapsLock => Some(b::CapsLock),
        c::ScrollLock => Some(b::ScrollLock),
        c::NumLock => Some(b::NumLock),
        c::PrintScreen => Some(b::PrintScreen),
        c::Pause => Some(b::Pause),
        c::Menu => Some(b::ContextMenu),
        c::KeypadBegin => None,
        c::Media(media) => {
            use crossterm::event::MediaKeyCode::*;
            match media {
                Play => Some(b::MediaPlay),
                Pause => Some(b::Pause),
                PlayPause => Some(b::MediaPlayPause),
                Reverse => None,
                Stop => Some(b::MediaStop),
                FastForward => Some(b::MediaFastForward),
                Rewind => Some(b::MediaRewind),
                TrackNext => Some(b::MediaTrackNext),
                TrackPrevious => Some(b::MediaTrackPrevious),
                Record => Some(b::MediaRecord),
                LowerVolume => Some(b::AudioVolumeDown),
                RaiseVolume => Some(b::AudioVolumeUp),
                MuteVolume => Some(b::AudioVolumeMute),
            }
        }
        c::Modifier(modifier) => {
            use crossterm::event::ModifierKeyCode::*;
            match modifier {
                LeftShift => Some(b::Shift),
                LeftControl => Some(b::Control),
                LeftAlt => Some(b::Alt),
                LeftSuper => Some(b::Super),
                LeftHyper => Some(b::Hyper),
                LeftMeta => Some(b::Meta),
                RightShift => Some(b::Shift),
                RightControl => Some(b::Control),
                RightAlt => Some(b::Alt),
                RightSuper => Some(b::Super),
                RightHyper => Some(b::Hyper),
                RightMeta => Some(b::Meta),
                IsoLevel3Shift => Some(b::AltGraph),
                IsoLevel5Shift => None,
            }
        }
    }
}

fn crossterm_modifier_to_bevy_key(
    modifier: crossterm::event::KeyModifiers,
) -> bevy::input::keyboard::Key {
    let mut i = modifier.into_iter();
    let modifier = i.next().expect("mod");
    use bevy::input::keyboard::Key as k;
    use crossterm::event::KeyModifiers as c;
    let result = match modifier {
        c::SHIFT => k::Shift,
        c::CONTROL => k::Control,
        c::ALT => k::Alt,
        c::SUPER => k::Super,
        c::HYPER => k::Hyper,
        c::META => k::Meta,
        x => panic!("Given a modifier of {x:?}"),
    };
    assert!(i.next().is_none());
    result
}