#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum KeyCode {
Enter,
Escape,
Tab,
Backspace,
Delete,
Up,
Down,
Left,
Right,
Home,
End,
PageUp,
PageDown,
Insert,
F(u8),
Char(char),
Number(u8),
}
impl KeyCode {
pub fn as_char(&self) -> Option<char> {
match self {
KeyCode::Char(c) => Some(*c),
KeyCode::Number(n) => Some(char::from(b'0' + *n)),
_ => None,
}
}
pub fn as_upper(&self) -> Option<char> {
self.as_char().map(|c| c.to_ascii_uppercase())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct KeyModifiers {
pub shift: bool,
pub ctrl: bool,
pub alt: bool,
pub meta: bool,
}
impl KeyModifiers {
pub fn new() -> Self {
Self::default()
}
pub fn with_shift(mut self) -> Self {
self.shift = true;
self
}
pub fn with_ctrl(mut self) -> Self {
self.ctrl = true;
self
}
pub fn with_alt(mut self) -> Self {
self.alt = true;
self
}
pub fn with_meta(mut self) -> Self {
self.meta = true;
self
}
}
#[derive(Debug, Clone)]
pub struct KeyEvent {
pub code: KeyCode,
pub modifiers: KeyModifiers,
}
impl KeyEvent {
pub fn new(code: KeyCode) -> Self {
Self {
code,
modifiers: KeyModifiers::new(),
}
}
pub fn with_modifiers(code: KeyCode, modifiers: KeyModifiers) -> Self {
Self { code, modifiers }
}
pub fn is_ctrl(&self) -> bool {
self.modifiers.ctrl
}
pub fn is_alt(&self) -> bool {
self.modifiers.alt
}
pub fn is_shift(&self) -> bool {
self.modifiers.shift
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MouseButton {
Left,
Right,
Middle,
None,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MouseEventKind {
Press,
Release,
Click,
DoubleClick,
Drag,
ScrollUp,
ScrollDown,
}
#[derive(Debug, Clone)]
pub struct MouseEvent {
pub kind: MouseEventKind,
pub button: MouseButton,
pub row: u16,
pub col: u16,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ResizeEvent {
pub width: u16,
pub height: u16,
}
#[derive(Debug, Clone)]
pub enum Event {
Key(KeyEvent),
Mouse(MouseEvent),
Resize(ResizeEvent),
FocusGained,
FocusLost,
Paste(String),
None,
}
impl Event {
pub fn key(code: KeyCode) -> Self {
Event::Key(KeyEvent::new(code))
}
pub fn key_with(code: KeyCode, modifiers: KeyModifiers) -> Self {
Event::Key(KeyEvent::with_modifiers(code, modifiers))
}
pub fn resize(width: u16, height: u16) -> Self {
Event::Resize(ResizeEvent { width, height })
}
pub fn mouse(kind: MouseEventKind, button: MouseButton, row: u16, col: u16) -> Self {
Event::Mouse(MouseEvent {
kind,
button,
row,
col,
})
}
}
impl Default for Event {
fn default() -> Self {
Event::None
}
}