use std::fmt::{Display, Formatter};
use crossterm::event::{Event::*, *};
use r3bl_rs_utils_core::*;
use serde::*;
use crate::*;
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum InputEvent {
Keyboard(KeyPress),
Resize(Size),
Mouse(MouseInput),
Focus(FocusEvent),
Paste(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum FocusEvent {
Gained,
Lost,
}
mod helpers {
use super::*;
impl InputEvent {
pub fn matches_keypress(&self, other: KeyPress) -> bool {
if let InputEvent::Keyboard(this) = self {
if this == &other {
return true;
}
}
false
}
pub fn matches_any_of_these_keypresses(&self, others: &[KeyPress]) -> bool {
for other in others {
if self.matches_keypress(*other) {
return true;
}
}
false
}
}
impl InputEvent {
pub fn matches(&self, exit_keys: &[InputEvent]) -> bool {
for exit_key in exit_keys {
if self == exit_key {
return true;
}
}
false
}
}
impl Display for InputEvent {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{self:?}") }
}
}
pub(crate) mod converters {
use super::*;
impl TryFrom<Event> for InputEvent {
type Error = ();
fn try_from(event: Event) -> Result<Self, Self::Error> {
match event {
Key(key_event) => Ok(key_event.try_into()?),
Mouse(mouse_event) => Ok(mouse_event.into()),
Resize(cols, rows) => Ok((rows, cols).into()),
FocusGained => Ok(InputEvent::Focus(FocusEvent::Gained)),
FocusLost => Ok(InputEvent::Focus(FocusEvent::Lost)),
Paste(text) => Ok(InputEvent::Paste(text)),
}
}
}
impl From<(/* rows: */ u16, /* cols: */ u16)> for InputEvent {
fn from(size: (u16, u16)) -> Self {
let (rows, cols) = size;
InputEvent::Resize(size! { col_count: cols, row_count: rows })
}
}
impl From<MouseEvent> for InputEvent {
fn from(mouse_event: MouseEvent) -> Self { InputEvent::Mouse(mouse_event.into()) }
}
impl TryFrom<KeyEvent> for InputEvent {
type Error = ();
fn try_from(key_event: KeyEvent) -> Result<Self, Self::Error> {
Ok(InputEvent::Keyboard(key_event.try_into()?))
}
}
}