rustlings/src/watch/terminal_event.rs

74 lines
2.3 KiB
Rust
Raw Normal View History

2024-04-11 09:08:46 -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,
Unrecognized(String),
}
2024-04-14 11:10:53 -04:00
pub fn terminal_event_handler(tx: Sender<WatchEvent>, manual_run: bool) {
2024-04-10 10:02:12 -04:00
let mut input = String::with_capacity(8);
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) => {
2024-04-11 09:08:46 -04:00
if key.modifiers != KeyModifiers::NONE {
continue;
}
2024-04-10 10:02:12 -04:00
match key.kind {
KeyEventKind::Release => continue,
KeyEventKind::Press | KeyEventKind::Repeat => (),
}
match key.code {
KeyCode::Enter => {
let input_event = match input.trim() {
2024-04-12 09:27:29 -04:00
"n" | "next" => InputEvent::Next,
2024-04-10 10:02:12 -04:00
"h" | "hint" => InputEvent::Hint,
"l" | "list" => break InputEvent::List,
"q" | "quit" => break InputEvent::Quit,
2024-04-14 11:10:53 -04:00
"r" | "run" if manual_run => InputEvent::Run,
2024-04-10 10:02:12 -04:00
_ => InputEvent::Unrecognized(input.clone()),
};
if tx.send(WatchEvent::Input(input_event)).is_err() {
return;
}
input.clear();
}
KeyCode::Char(c) => {
input.push(c);
}
_ => (),
}
}
Event::Resize(_, _) => {
if tx.send(WatchEvent::TerminalResize).is_err() {
return;
}
}
Event::FocusGained | Event::FocusLost | Event::Mouse(_) | Event::Paste(_) => continue,
}
};
let _ = tx.send(WatchEvent::Input(last_input_event));
}