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
use std::{
sync::mpsc::{SendError, Sender},
thread::{self, JoinHandle},
time::Instant,
};
use crossterm::event::{self, Event, KeyEvent, KeyEventKind};
use falling_tetromino_engine::Button;
use crate::keybinds_presets::{normalize, Keybinds};
pub enum LiveTermSignal {
RecognizedButton(Button, KeyEventKind),
RawEvent(Event),
}
pub fn spawn(
input_sender: Sender<(LiveTermSignal, Instant)>,
keybinds: Keybinds,
) -> JoinHandle<()> {
thread::spawn(move || {
'detect_events: loop {
// Read event.
match event::read() {
Ok(event) => {
let timestamp = Instant::now();
let mut stop_thread = false;
let signal = match event {
Event::Key(KeyEvent {
code,
modifiers,
kind,
..
}) => {
let is_press_or_repeat = matches!(
kind,
event::KeyEventKind::Press | event::KeyEventKind::Repeat
);
// FIXME: What about forfeiting a game with [Ctrl+D]?
let escape = matches!(code, event::KeyCode::Esc);
let ctrl_c = matches!(code, event::KeyCode::Char('c' | 'C'))
&& matches!(modifiers, event::KeyModifiers::CONTROL);
if is_press_or_repeat && (escape || ctrl_c) {
stop_thread = true;
}
match keybinds.get(&normalize((code, modifiers))) {
// No binding: Just send directly transmit whatever the event was.
None => LiveTermSignal::RawEvent(event),
// Binding found: send button un-/press.
Some(&button) => LiveTermSignal::RecognizedButton(button, kind),
}
}
// Not a key event, just send directly.
_ => LiveTermSignal::RawEvent(event),
};
// Send signal.
match input_sender.send((signal, timestamp)) {
Ok(()) => {}
Err(SendError(_event_which_failed_to_transmit)) => {
break 'detect_events;
}
}
if stop_thread {
break 'detect_events;
}
}
// FIXME: Handle io::Error? If not, why not?
Err(_e) => {}
}
}
})
}