rustlings/src/watch/terminal_event.rs

52 lines
1.7 KiB
Rust
Raw Normal View History

2024-09-05 11:23:56 -04:00
use crossterm::event::{self, Event, KeyCode, KeyEventKind};
2024-09-17 19:43:48 -04:00
use std::sync::{atomic::Ordering::Relaxed, mpsc::Sender};
2024-04-10 10:02:12 -04:00
2024-09-17 19:43:48 -04:00
use super::{WatchEvent, EXERCISE_RUNNING};
2024-09-12 11:45:42 -04:00
2024-04-10 10:02:12 -04:00
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-09-12 11:45:42 -04:00
pub fn terminal_event_handler(sender: Sender<WatchEvent>, manual_run: bool) {
let last_watch_event = loop {
match event::read() {
Ok(Event::Key(key)) => {
2024-04-10 10:02:12 -04:00
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-09-17 19:43:48 -04:00
if EXERCISE_RUNNING.load(Relaxed) {
2024-09-12 11:45:42 -04:00
continue;
}
let input_event = match key.code {
KeyCode::Char('n') => InputEvent::Next,
KeyCode::Char('h') => InputEvent::Hint,
2024-09-12 11:45:42 -04:00
KeyCode::Char('l') => break WatchEvent::Input(InputEvent::List),
KeyCode::Char('q') => break WatchEvent::Input(InputEvent::Quit),
KeyCode::Char('r') if manual_run => InputEvent::Run,
_ => continue,
};
2024-09-12 11:45:42 -04:00
if sender.send(WatchEvent::Input(input_event)).is_err() {
return;
2024-04-10 10:02:12 -04:00
}
}
2024-09-12 11:45:42 -04:00
Ok(Event::Resize(width, _)) => {
if sender.send(WatchEvent::TerminalResize { width }).is_err() {
2024-04-10 10:02:12 -04:00
return;
}
}
2024-09-12 11:45:42 -04:00
Ok(Event::FocusGained | Event::FocusLost | Event::Mouse(_)) => continue,
Err(e) => break WatchEvent::TerminalEventErr(e),
2024-04-10 10:02:12 -04:00
}
};
2024-09-12 11:45:42 -04:00
let _ = sender.send(last_watch_event);
2024-04-10 10:02:12 -04:00
}