#![deny(unsafe_code)]
mod parse;
#[cfg(test)]
mod tests;
pub(crate) const ESC: u8 = 0x1b;
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, Hash)]
pub struct Mods {
pub shift: bool,
pub alt: bool,
pub ctrl: bool,
}
impl Mods {
pub const NONE: Mods = Mods {
shift: false,
alt: false,
ctrl: false,
};
pub const ALT: Mods = Mods {
shift: false,
alt: true,
ctrl: false,
};
pub fn from_param(p: u32) -> Mods {
let b = p.saturating_sub(1);
Mods {
shift: b & 1 != 0,
alt: b & 2 != 0,
ctrl: b & 4 != 0,
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum Key {
Char(char),
Ctrl(char),
Alt(char),
Enter,
Tab,
BackTab,
Backspace,
Esc,
Up,
Down,
Left,
Right,
Home,
End,
PageUp,
PageDown,
Delete,
Insert,
F(u8),
Unknown,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub struct KeyEvent {
pub key: Key,
pub mods: Mods,
}
impl KeyEvent {
pub const fn plain(key: Key) -> KeyEvent {
KeyEvent {
key,
mods: Mods::NONE,
}
}
pub const fn with(key: Key, mods: Mods) -> KeyEvent {
KeyEvent { key, mods }
}
}
pub(crate) enum Step {
Emit(KeyEvent, usize),
Skip(usize),
Need,
}
pub fn decode(bytes: &[u8]) -> (Vec<KeyEvent>, &[u8]) {
let mut out = Vec::new();
let mut i = 0usize;
while i < bytes.len() {
match parse::step(&bytes[i..]) {
Step::Need => return (out, &bytes[i..]),
Step::Skip(n) => i += n,
Step::Emit(ev, n) => {
out.push(ev);
i += n;
}
}
}
(out, &bytes[bytes.len()..])
}
#[cfg(test)]
pub fn decode_keys(bytes: &[u8]) -> (Vec<Key>, &[u8]) {
let (evs, rest) = decode(bytes);
(evs.into_iter().map(|e| e.key).collect(), rest)
}
#[derive(Default)]
pub struct Decoder {
pending: Vec<u8>,
}
impl Decoder {
pub fn new() -> Decoder {
Decoder {
pending: Vec::new(),
}
}
pub fn feed(&mut self, bytes: &[u8]) -> Vec<KeyEvent> {
self.pending.extend_from_slice(bytes);
let (mut evs, rest) = decode(&self.pending);
let mut leftover = rest.to_vec();
if leftover.len() == 1 && leftover[0] == ESC {
evs.push(KeyEvent::plain(Key::Esc));
leftover.clear();
}
self.pending = leftover;
evs
}
#[cfg(test)]
pub fn feed_keys(&mut self, bytes: &[u8]) -> Vec<Key> {
self.feed(bytes).into_iter().map(|e| e.key).collect()
}
#[cfg(test)]
pub fn pending(&self) -> &[u8] {
&self.pending
}
}