Skip to main content

engine/io/
terminal.rs

1//! A generic interactive screen-and-keyboard interface.
2//!
3//! The terminal interface is an Engine primitive. A rectangular grid of
4//! cells, a cursor, and a stream of key presses is not an operating-system
5//! concept: editors, games,
6//! chat applications, and any other stateful program need the same
7//! abstraction. The [`Terminal`] trait and its data types ([`Size`],
8//! [`Key`], [`KeyEvent`], [`InputMode`]) therefore live in the Engine, and
9//! concrete implementations — a pure-state model, ANSI rendering, a host
10//! adapter — live above it (the `terminal` crate and applications).
11//!
12//! Implementations are pure virtual-terminal state; a host adapter feeds
13//! [`KeyEvent`]s in and renders the screen out. Nothing here touches a host
14//! terminal.
15
16/// The dimensions of a screen, in rows and columns.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub struct Size {
19    /// The number of rows (height).
20    pub rows: u16,
21    /// The number of columns (width).
22    pub cols: u16,
23}
24
25impl Size {
26    /// Creates a size.
27    pub const fn new(rows: u16, cols: u16) -> Self {
28        Self { rows, cols }
29    }
30}
31
32/// A keyboard key, independent of modifiers.
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub enum Key {
35    /// A printable character (carried in [`KeyEvent::character`]).
36    Character,
37    /// The Enter / Return key.
38    Enter,
39    /// The Escape key.
40    Escape,
41    /// The Backspace key.
42    Backspace,
43    /// The Tab key.
44    Tab,
45    /// The Insert key.
46    Insert,
47    /// The Delete key.
48    Delete,
49    /// The Home key.
50    Home,
51    /// The End key.
52    End,
53    /// The Page Up key.
54    PageUp,
55    /// The Page Down key.
56    PageDown,
57    /// The Up arrow.
58    ArrowUp,
59    /// The Down arrow.
60    ArrowDown,
61    /// The Left arrow.
62    ArrowLeft,
63    /// The Right arrow.
64    ArrowRight,
65    /// A function key F1..F12.
66    Function(u8),
67    /// An unparsed escape sequence (the raw bytes are preserved for
68    /// future handling).
69    Unknown(String),
70}
71
72impl Key {
73    /// Returns `true` for a key that produces text when typed (ignoring
74    /// modifiers).
75    pub fn is_character(&self) -> bool {
76        *self == Key::Character
77    }
78}
79
80/// A single structured key press.
81#[derive(Clone, Debug, PartialEq, Eq)]
82pub struct KeyEvent {
83    /// The pressed key.
84    pub key: Key,
85    /// The character produced, for character keys.
86    pub character: Option<char>,
87    /// Whether Ctrl was held.
88    pub ctrl: bool,
89    /// Whether Alt was held.
90    pub alt: bool,
91    /// Whether Shift was held.
92    pub shift: bool,
93}
94
95impl KeyEvent {
96    /// Creates a plain character press.
97    pub fn character(ch: char) -> Self {
98        Self {
99            key: Key::Character,
100            character: Some(ch),
101            ctrl: false,
102            alt: false,
103            shift: false,
104        }
105    }
106
107    /// Creates a modifier-free special key press.
108    pub fn special(key: Key) -> Self {
109        Self {
110            key,
111            character: None,
112            ctrl: false,
113            alt: false,
114            shift: false,
115        }
116    }
117
118    /// Creates a Ctrl-modified character press (for example Ctrl+C).
119    pub fn ctrl(ch: char) -> Self {
120        Self {
121            key: Key::Character,
122            character: Some(ch),
123            ctrl: true,
124            alt: false,
125            shift: false,
126        }
127    }
128
129    /// Returns `true` for Ctrl+C.
130    pub fn is_ctrl_c(&self) -> bool {
131        self.ctrl && self.character == Some('c')
132    }
133
134    /// Returns `true` for Ctrl+Z.
135    pub fn is_ctrl_z(&self) -> bool {
136        self.ctrl && self.character == Some('z')
137    }
138}
139
140/// The input mode of a terminal.
141#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
142pub enum InputMode {
143    /// Line-oriented canonical input (shell).
144    #[default]
145    Canonical,
146    /// Raw/immediate input (man, nano, vim).
147    Raw,
148}
149
150/// The interactive terminal facade consumed by interactive programs.
151///
152/// Implementations are pure virtual-terminal state; a host adapter feeds
153/// [`KeyEvent`]s in and renders the screen out.
154pub trait Terminal: Send + Sync {
155    /// The current screen size.
156    fn size(&self) -> Size;
157
158    /// Returns the next pending key event, if any.
159    fn next_key(&mut self) -> Option<KeyEvent>;
160
161    /// Queues key events as if typed by the user.
162    fn push_keys(&mut self, keys: &[KeyEvent]);
163
164    /// Writes bytes, interpreting ANSI/VT control sequences.
165    fn write(&mut self, bytes: &[u8]);
166
167    /// Enters the alternate screen buffer.
168    fn enter_alternate_screen(&mut self);
169
170    /// Leaves the alternate screen buffer, restoring the main screen.
171    fn leave_alternate_screen(&mut self);
172
173    /// The current input mode.
174    fn input_mode(&self) -> InputMode;
175
176    /// Sets the input mode.
177    fn set_input_mode(&mut self, mode: InputMode);
178
179    /// Flushes any buffered output.
180    fn flush(&mut self);
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    #[test]
188    fn character_events_carry_the_character() {
189        let event = KeyEvent::character('a');
190        assert_eq!(event.key, Key::Character);
191        assert_eq!(event.character, Some('a'));
192        assert!(event.key.is_character());
193    }
194
195    #[test]
196    fn ctrl_shortcuts_are_detectable() {
197        assert!(KeyEvent::ctrl('c').is_ctrl_c());
198        assert!(!KeyEvent::ctrl('z').is_ctrl_c());
199        assert!(KeyEvent::ctrl('z').is_ctrl_z());
200    }
201
202    #[test]
203    fn special_keys_are_created_without_modifiers() {
204        let event = KeyEvent::special(Key::ArrowUp);
205        assert!(!event.ctrl && !event.alt && !event.shift);
206        assert!(!event.key.is_character());
207    }
208
209    #[test]
210    fn size_holds_rows_and_columns() {
211        assert_eq!(Size::new(24, 80), Size { rows: 24, cols: 80 });
212    }
213}