This commit is contained in:
Crispy 2023-03-22 20:17:50 +01:00
parent 8ffd34dcfa
commit c7836ca6d3

View file

@ -67,22 +67,47 @@ impl Events {
} }
} }
fn first_byte(&mut self) -> u8 {
let byte = self.buffer[0];
self.buffer = self.buffer[1..].to_vec();
byte
}
fn parse(&mut self) -> Event {
let byte = self.first_byte();
match byte {
ESC => self.parse_esc(),
BS => Event::Key(Key::Backspace, Mod::None),
DEL => Event::Key(Key::Delete, Mod::None),
LF | CR => Event::Key(Key::Enter, Mod::None),
TAB => Event::Key(Key::Tab, Mod::None),
x @ 1..=26 => Event::Key(Key::Char((x + 96).into()), Mod::Ctrl), // ctrl + letter
x @ b' '..=b'~' => Event::Key(Key::Char(x.into()), Mod::None), // regular ascii charaters
x => Event::Unsupported(vec![x]),
}
}
fn parse_esc(&mut self) -> Event { fn parse_esc(&mut self) -> Event {
if self.buffer.is_empty() { if self.buffer.is_empty() {
return Event::Key(Key::Escape, Mod::None); return Event::Key(Key::Escape, Mod::None);
} }
let byte = self.buffer[0]; let byte = self.first_byte();
self.buffer = self.buffer[1..].to_vec();
match byte { match byte {
ESC => Event::Key(Key::Escape, Mod::None), ESC => {
// Two ESC chars in a row probably means that the first one was an escape key press
// and the second one was for something else, possibly because input is coming all at once from a file.
// Therefore reinsert the second ESC byte so it can be processed next iteration.
self.buffer.insert(0, ESC);
Event::Key(Key::Escape, Mod::None)
}
BS => Event::Key(Key::Backspace, Mod::Alt), BS => Event::Key(Key::Backspace, Mod::Alt),
DEL => Event::Key(Key::Delete, Mod::Alt), DEL => Event::Key(Key::Delete, Mod::Alt),
LF | CR => Event::Key(Key::Enter, Mod::Alt), LF | CR => Event::Key(Key::Enter, Mod::Alt),
TAB => Event::Key(Key::Tab, Mod::Alt), TAB => Event::Key(Key::Tab, Mod::Alt),
c @ 1..=26 => Event::Key(Key::Char((c + 96).into()), Mod::CtrlAlt), // ctrl + letter x @ 1..=26 => Event::Key(Key::Char((x + 96).into()), Mod::CtrlAlt), // ctrl + letter
c @ b' '..=b'~' => Event::Key(Key::Char(c.into()), Mod::Alt), // regular ascii charaters x @ b' '..=b'~' => Event::Key(Key::Char(x.into()), Mod::Alt), // regular ascii charaters
_ => Event::Unsupported(vec![ESC, byte]), x => Event::Unsupported(vec![ESC, x]),
} }
} }
} }
@ -96,17 +121,6 @@ impl Iterator for Events {
return None; return None;
} }
let byte = self.buffer[0]; Some(self.parse())
self.buffer = self.buffer[1..].to_vec();
Some(match byte {
ESC => self.parse_esc(),
BS => Event::Key(Key::Backspace, Mod::None),
DEL => Event::Key(Key::Delete, Mod::None),
LF | CR => Event::Key(Key::Enter, Mod::None),
TAB => Event::Key(Key::Tab, Mod::None),
c @ 1..=26 => Event::Key(Key::Char((c + 96).into()), Mod::Ctrl), // ctrl + letter
c @ b' '..=b'~' => Event::Key(Key::Char(c.into()), Mod::None), // regular ascii charaters
_ => Event::Unsupported(vec![byte]),
})
} }
} }