vce-engine 0.1.1

The generic state substrate of the Virtual Computing Engine (VCE)
Documentation
//! A generic interactive screen-and-keyboard interface.
//!
//! The terminal interface is an Engine primitive. A rectangular grid of
//! cells, a cursor, and a stream of key presses is not an operating-system
//! concept: editors, games,
//! chat applications, and any other stateful program need the same
//! abstraction. The [`Terminal`] trait and its data types ([`Size`],
//! [`Key`], [`KeyEvent`], [`InputMode`]) therefore live in the Engine, and
//! concrete implementations — a pure-state model, ANSI rendering, a host
//! adapter — live above it (the `terminal` crate and applications).
//!
//! Implementations are pure virtual-terminal state; a host adapter feeds
//! [`KeyEvent`]s in and renders the screen out. Nothing here touches a host
//! terminal.

/// The dimensions of a screen, in rows and columns.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Size {
    /// The number of rows (height).
    pub rows: u16,
    /// The number of columns (width).
    pub cols: u16,
}

impl Size {
    /// Creates a size.
    pub const fn new(rows: u16, cols: u16) -> Self {
        Self { rows, cols }
    }
}

/// A keyboard key, independent of modifiers.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Key {
    /// A printable character (carried in [`KeyEvent::character`]).
    Character,
    /// The Enter / Return key.
    Enter,
    /// The Escape key.
    Escape,
    /// The Backspace key.
    Backspace,
    /// The Tab key.
    Tab,
    /// The Insert key.
    Insert,
    /// The Delete key.
    Delete,
    /// The Home key.
    Home,
    /// The End key.
    End,
    /// The Page Up key.
    PageUp,
    /// The Page Down key.
    PageDown,
    /// The Up arrow.
    ArrowUp,
    /// The Down arrow.
    ArrowDown,
    /// The Left arrow.
    ArrowLeft,
    /// The Right arrow.
    ArrowRight,
    /// A function key F1..F12.
    Function(u8),
    /// An unparsed escape sequence (the raw bytes are preserved for
    /// future handling).
    Unknown(String),
}

impl Key {
    /// Returns `true` for a key that produces text when typed (ignoring
    /// modifiers).
    pub fn is_character(&self) -> bool {
        *self == Key::Character
    }
}

/// A single structured key press.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct KeyEvent {
    /// The pressed key.
    pub key: Key,
    /// The character produced, for character keys.
    pub character: Option<char>,
    /// Whether Ctrl was held.
    pub ctrl: bool,
    /// Whether Alt was held.
    pub alt: bool,
    /// Whether Shift was held.
    pub shift: bool,
}

impl KeyEvent {
    /// Creates a plain character press.
    pub fn character(ch: char) -> Self {
        Self {
            key: Key::Character,
            character: Some(ch),
            ctrl: false,
            alt: false,
            shift: false,
        }
    }

    /// Creates a modifier-free special key press.
    pub fn special(key: Key) -> Self {
        Self {
            key,
            character: None,
            ctrl: false,
            alt: false,
            shift: false,
        }
    }

    /// Creates a Ctrl-modified character press (for example Ctrl+C).
    pub fn ctrl(ch: char) -> Self {
        Self {
            key: Key::Character,
            character: Some(ch),
            ctrl: true,
            alt: false,
            shift: false,
        }
    }

    /// Returns `true` for Ctrl+C.
    pub fn is_ctrl_c(&self) -> bool {
        self.ctrl && self.character == Some('c')
    }

    /// Returns `true` for Ctrl+Z.
    pub fn is_ctrl_z(&self) -> bool {
        self.ctrl && self.character == Some('z')
    }
}

/// The input mode of a terminal.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum InputMode {
    /// Line-oriented canonical input (shell).
    #[default]
    Canonical,
    /// Raw/immediate input (man, nano, vim).
    Raw,
}

/// The interactive terminal facade consumed by interactive programs.
///
/// Implementations are pure virtual-terminal state; a host adapter feeds
/// [`KeyEvent`]s in and renders the screen out.
pub trait Terminal: Send + Sync {
    /// The current screen size.
    fn size(&self) -> Size;

    /// Returns the next pending key event, if any.
    fn next_key(&mut self) -> Option<KeyEvent>;

    /// Queues key events as if typed by the user.
    fn push_keys(&mut self, keys: &[KeyEvent]);

    /// Writes bytes, interpreting ANSI/VT control sequences.
    fn write(&mut self, bytes: &[u8]);

    /// Enters the alternate screen buffer.
    fn enter_alternate_screen(&mut self);

    /// Leaves the alternate screen buffer, restoring the main screen.
    fn leave_alternate_screen(&mut self);

    /// The current input mode.
    fn input_mode(&self) -> InputMode;

    /// Sets the input mode.
    fn set_input_mode(&mut self, mode: InputMode);

    /// Flushes any buffered output.
    fn flush(&mut self);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn character_events_carry_the_character() {
        let event = KeyEvent::character('a');
        assert_eq!(event.key, Key::Character);
        assert_eq!(event.character, Some('a'));
        assert!(event.key.is_character());
    }

    #[test]
    fn ctrl_shortcuts_are_detectable() {
        assert!(KeyEvent::ctrl('c').is_ctrl_c());
        assert!(!KeyEvent::ctrl('z').is_ctrl_c());
        assert!(KeyEvent::ctrl('z').is_ctrl_z());
    }

    #[test]
    fn special_keys_are_created_without_modifiers() {
        let event = KeyEvent::special(Key::ArrowUp);
        assert!(!event.ctrl && !event.alt && !event.shift);
        assert!(!event.key.is_character());
    }

    #[test]
    fn size_holds_rows_and_columns() {
        assert_eq!(Size::new(24, 80), Size { rows: 24, cols: 80 });
    }
}