use crossterm::event::{Event as CTEvent,
Event::{self},
KeyEvent, MouseEvent};
use super::{KeyPress, MouseInput};
use crate::{Size, height, width};
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InputEvent {
Keyboard(KeyPress),
Resize(Size),
Mouse(MouseInput),
Focus(FocusEvent),
BracketedPaste(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FocusEvent {
Gained,
Lost,
}
mod helpers {
use super::{InputEvent, KeyPress};
impl InputEvent {
#[must_use]
pub fn matches_keypress(&self, other: KeyPress) -> bool {
if let InputEvent::Keyboard(this) = self
&& this == &other
{
return true;
}
false
}
#[must_use]
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 {
#[must_use]
pub fn matches(&self, exit_keys: &[InputEvent]) -> bool {
for exit_key in exit_keys {
if self == exit_key {
return true;
}
}
false
}
}
}
pub(crate) mod converters {
use super::{CTEvent, Event, FocusEvent, InputEvent, KeyEvent, MouseEvent, height,
width};
impl TryFrom<Event> for InputEvent {
type Error = ();
fn try_from(event: Event) -> Result<Self, Self::Error> {
match event {
CTEvent::Key(key_event) => Ok(key_event.try_into()?),
CTEvent::Mouse(mouse_event) => Ok(mouse_event.into()),
CTEvent::Resize(columns, rows) => {
Ok(InputEvent::Resize(width(columns) + height(rows)))
}
CTEvent::FocusGained => Ok(InputEvent::Focus(FocusEvent::Gained)),
CTEvent::FocusLost => Ok(InputEvent::Focus(FocusEvent::Lost)),
CTEvent::Paste(text) => Ok(InputEvent::BracketedPaste(text)),
}
}
}
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()?))
}
}
}