rustlings/src/watch/terminal_event.rs

87 lines
2.7 KiB
Rust
Raw Normal View History

2024-08-23 18:14:12 -04:00
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
2024-04-10 10:02:12 -04:00
use std::sync::mpsc::Sender;
use super::WatchEvent;
pub enum InputEvent {
2024-04-14 11:10:53 -04:00
Run,
2024-04-12 09:27:29 -04:00
Next,
2024-04-10 10:02:12 -04:00
Hint,
List,
Quit,
2024-05-12 20:32:25 -04:00
Unrecognized,
2024-04-10 10:02:12 -04:00
}
2024-04-14 11:10:53 -04:00
pub fn terminal_event_handler(tx: Sender<WatchEvent>, manual_run: bool) {
// Only send `Unrecognized` on ENTER if the last input wasn't valid.
let mut last_input_valid = false;
2024-04-10 10:02:12 -04:00
let last_input_event = loop {
let terminal_event = match event::read() {
Ok(v) => v,
Err(e) => {
// If `send` returns an error, then the receiver is dropped and
// a shutdown has been already initialized.
let _ = tx.send(WatchEvent::TerminalEventErr(e));
return;
}
};
match terminal_event {
Event::Key(key) => {
match key.kind {
2024-05-12 20:20:04 -04:00
KeyEventKind::Release | KeyEventKind::Repeat => continue,
KeyEventKind::Press => (),
2024-04-10 10:02:12 -04:00
}
2024-05-12 20:20:04 -04:00
if key.modifiers != KeyModifiers::NONE {
last_input_valid = false;
2024-05-12 20:20:04 -04:00
continue;
}
2024-04-10 10:02:12 -04:00
let input_event = match key.code {
KeyCode::Enter => {
if last_input_valid {
continue;
}
InputEvent::Unrecognized
}
KeyCode::Char(c) => {
let input_event = match c {
'n' => InputEvent::Next,
'h' => InputEvent::Hint,
'l' => break InputEvent::List,
'q' => break InputEvent::Quit,
'r' if manual_run => InputEvent::Run,
_ => {
last_input_valid = false;
continue;
}
};
last_input_valid = true;
input_event
2024-04-10 10:02:12 -04:00
}
_ => {
last_input_valid = false;
continue;
}
};
if tx.send(WatchEvent::Input(input_event)).is_err() {
return;
2024-04-10 10:02:12 -04:00
}
}
Event::Resize(_, _) => {
if tx.send(WatchEvent::TerminalResize).is_err() {
return;
}
}
2024-08-23 18:14:12 -04:00
Event::FocusGained | Event::FocusLost | Event::Mouse(_) => continue,
2024-04-10 10:02:12 -04:00
}
};
let _ = tx.send(WatchEvent::Input(last_input_event));
}