Skip to content

Commit

Permalink
Simplify handling terminal events for unbuffered stdin
Browse files Browse the repository at this point in the history
  • Loading branch information
mo8it committed Sep 5, 2024
1 parent 2d0860f commit aa3eda7
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 37 deletions.
1 change: 0 additions & 1 deletion src/watch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@ fn run_watch(
break;
}
WatchEvent::Input(InputEvent::Run) => watch_state.run_current_exercise(&mut stdout)?,
WatchEvent::Input(InputEvent::Unrecognized) => watch_state.render(&mut stdout)?,
WatchEvent::FileChange { exercise_ind } => {
watch_state.handle_file_change(exercise_ind, &mut stdout)?;
}
Expand Down
42 changes: 6 additions & 36 deletions src/watch/terminal_event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,9 @@ pub enum InputEvent {
Hint,
List,
Quit,
Unrecognized,
}

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;

let last_input_event = loop {
let terminal_event = match event::read() {
Ok(v) => v,
Expand All @@ -34,39 +30,13 @@ pub fn terminal_event_handler(tx: Sender<WatchEvent>, manual_run: bool) {
KeyEventKind::Press => (),
}

if key.modifiers != KeyModifiers::NONE {
last_input_valid = false;
continue;
}

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
}
_ => {
last_input_valid = false;
continue;
}
KeyCode::Char('n') => InputEvent::Next,
KeyCode::Char('h') => InputEvent::Hint,
KeyCode::Char('l') => break InputEvent::List,
KeyCode::Char('q') => break InputEvent::Quit,
KeyCode::Char('r') if manual_run => InputEvent::Run,
_ => continue,
};

if tx.send(WatchEvent::Input(input_event)).is_err() {
Expand Down

0 comments on commit aa3eda7

Please sign in to comment.