tui-framework-experiment 0.4.0

An set of harmonious Ratatui widgets with a goal of building a proper widget framework.
Documentation
//! Events module.
//!
//! This module provides a cross-backend interface for handling the events that are generated by
//! the terminal.
//!
//! This is not yet stable and will likely change in the future - each backend has some quirks that
//! are difficult to handle in a generic way.

use bitflags::bitflags;
use strum::EnumIs;

#[cfg(feature = "crossterm")]
mod crossterm;

#[cfg(feature = "termion")]
mod termion;

#[cfg(feature = "termwiz")]
mod termwiz;

pub trait EventHandler {
    fn handle_event(&mut self, event: Event) {
        match event {
            Event::KeyPressed(key_pressed_event) => self.handle_key(key_pressed_event),
            Event::Mouse(mouse_event) => self.handle_mouse(mouse_event),
        }
    }

    #[allow(unused_variables)]
    fn handle_key(&mut self, event: KeyPressedEvent) {}

    #[allow(unused_variables)]
    fn handle_mouse(&mut self, event: MouseEvent) {}
}

pub enum Event {
    KeyPressed(KeyPressedEvent),
    Mouse(MouseEvent),
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct KeyPressedEvent {
    pub key: Key,
    pub modifiers: KeyModifiers,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, EnumIs)]
pub enum Key {
    Char(char),
    Backspace,
    Delete,
    Insert,
    Enter,
    Left,
    Right,
    Up,
    Esc,
    Down,
    Home,
    End,
    PageUp,
    PageDown,
    Tab,
    BackTab,
    F(u8),
    Null,
}

bitflags! {
    #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct KeyModifiers: u8 {
        /// Shift key
        const SHIFT = 1;
        /// Control key
        const CTRL = 1 << 1;
        /// Alias for `CTRL`
        const CONTROL = KeyModifiers::CTRL.bits();
        /// Alt key (Option on macOS)
        const ALT = 1 << 2;
        /// Alias for `ALT`
        const OPTION = KeyModifiers::ALT.bits();
        /// Super key (Windows key on Windows, Command key on macOS)
        const SUPER = 1 << 3;
        /// Alias for `SUPER`
        const WIN = KeyModifiers::SUPER.bits();
        /// Alias for `SUPER`
        const COMMAND = KeyModifiers::SUPER.bits();
        /// Hyper key
        const HYPER = 1 << 4;
        /// Meta key
        const META = 1 << 5;
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MouseEvent {
    pub column: u16,
    pub row: u16,
    pub kind: MouseEventKind,
    pub modifiers: KeyModifiers,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MouseEventKind {
    Down(MouseButton),
    Up(MouseButton),
    Drag(MouseButton),
    Moved,
    ScrollUp,
    ScrollDown,
    ScrollLeft,
    ScrollRight,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MouseButton {
    Left,
    Right,
    Middle,
}