1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
//! Terminal abstraction for TUI.
//!
//! Provides a trait for terminal operations and a `ProcessTerminal` implementation
//! using crossterm.
use std::io::{self, IsTerminal, Write};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use crossterm::{
event::{self, Event, KeyEvent, MouseEvent},
terminal as cterm,
};
use thiserror::Error;
/// Mouse tracking prevents native text selection in macOS terminal emulators.
/// RPI only consumes wheel events, so keep the platform default selectable.
const fn mouse_tracking_enabled_for(is_macos: bool) -> bool {
!is_macos
}
const fn mouse_tracking_enabled_by_default() -> bool {
mouse_tracking_enabled_for(cfg!(target_os = "macos"))
}
/// Errors that can occur during terminal operations.
#[derive(Debug, Error)]
pub enum TerminalError {
#[error("IO error: {0}")]
Io(#[from] io::Error),
#[error("Terminal error: {0}")]
Terminal(String),
}
/// Terminal capabilities and state.
#[derive(Debug, Clone, Default)]
pub struct TerminalInfo {
pub columns: usize,
pub rows: usize,
pub supports_true_color: bool,
pub supports_mouse: bool,
pub supports_kitty_keyboard: bool,
}
/// Input event types.
#[derive(Debug, Clone)]
pub enum InputEvent {
Key(KeyEvent),
Mouse(MouseEvent),
Resize(usize, usize),
FocusGained,
FocusLost,
}
/// Terminal trait for abstracting terminal operations.
///
/// This allows for different terminal implementations (real terminal, virtual terminal for testing).
pub trait Terminal: Send + Sync {
/// Get terminal information (columns, rows, capabilities).
fn info(&self) -> TerminalInfo;
/// Get current terminal width in columns.
fn columns(&self) -> usize {
self.info().columns
}
/// Get current terminal height in rows.
fn rows(&self) -> usize {
self.info().rows
}
/// Write raw bytes to the terminal.
fn write(&self, data: &str);
/// Hide the cursor.
fn hide_cursor(&self);
/// Show the cursor.
fn show_cursor(&self);
/// Move cursor to position (0-indexed).
fn move_cursor(&self, row: usize, col: usize);
/// Clear the screen.
fn clear_screen(&self);
/// Set terminal title.
fn set_title(&self, title: &str);
/// Enable mouse events.
fn enable_mouse(&self);
/// Disable mouse events.
fn disable_mouse(&self);
/// Enter terminal raw mode (required for `event::read()` to deliver
/// individual key events without line buffering). Pairs with
/// [`Terminal::stop`], which exits raw mode.
///
/// Callers that drive their own input loop (instead of the reader thread
/// spawned by [`Terminal::start`]) use this to set up the tty without
/// spawning a competing reader — see `TuiAltScreen::start_readerless`.
fn enter_raw_mode(&self);
/// Leave raw mode *without* stopping the terminal, so the shell gets a
/// working line discipline back. Pairs with [`Terminal::enter_raw_mode`];
/// a `Ctrl+Z` suspend uses it, then re-enters raw mode on resume.
fn exit_raw_mode(&self);
/// Re-read the current terminal size into the cached [`TerminalInfo`].
/// Called on `Event::Resize` so subsequent renders use the new dimensions.
fn refresh_size(&self);
/// Start terminal raw mode.
fn start(
&self,
on_input: Box<dyn Fn(InputEvent) + Send + Sync>,
on_resize: Box<dyn Fn() + Send + Sync>,
);
/// Stop terminal and restore original state.
fn stop(&self);
/// Check if terminal is a TTY.
fn is_tty(&self) -> bool;
/// Set progress indicator (terminal progress bar support).
fn set_progress(&self, active: bool);
/// Flush output buffer.
fn flush(&self);
}
/// Process-based terminal using crossterm.
pub struct ProcessTerminal {
info: Mutex<TerminalInfo>,
running: Mutex<bool>,
writer: Mutex<Box<dyn Write + Send + Sync>>,
}
impl ProcessTerminal {
/// Create a new process terminal.
pub fn new() -> Self {
let (cols, rows) = cterm::size().unwrap_or((80, 24));
let info = TerminalInfo {
columns: cols as usize,
rows: rows as usize,
supports_true_color: true, // Assume true color support
supports_mouse: true,
supports_kitty_keyboard: false, // Will be detected
};
Self {
info: Mutex::new(info),
running: Mutex::new(false),
writer: Mutex::new(Box::new(io::stdout())),
}
}
/// Update terminal size.
fn update_size(&self) {
if let Ok(size) = cterm::size() {
if let Ok(mut info) = self.info.lock() {
info.columns = size.0 as usize;
info.rows = size.1 as usize;
}
}
}
fn configure_mouse_tracking(&self) {
if mouse_tracking_enabled_by_default() {
self.enable_mouse();
} else {
self.disable_mouse();
}
}
}
impl Default for ProcessTerminal {
fn default() -> Self {
Self::new()
}
}
impl Terminal for ProcessTerminal {
fn info(&self) -> TerminalInfo {
self.info.lock().map(|i| i.clone()).unwrap_or_default()
}
fn write(&self, data: &str) {
if let Ok(mut writer) = self.writer.lock() {
let _ = writer.write_all(data.as_bytes());
}
}
fn hide_cursor(&self) {
self.write("\x1b[?25l");
}
fn show_cursor(&self) {
self.write("\x1b[?25h");
}
fn move_cursor(&self, row: usize, col: usize) {
// ANSI escape: ESC [ row ; col H (1-indexed)
self.write(&format!("\x1b[{};{}H", row + 1, col + 1));
}
fn clear_screen(&self) {
self.write("\x1b[2J\x1b[H");
}
fn set_title(&self, title: &str) {
self.write(&format!("\x1b]2;{}\x07", title));
}
fn enable_mouse(&self) {
// Enable mouse tracking (SGR mode)
self.write("\x1b[?1000h\x1b[?1002h\x1b[?1006h");
}
fn disable_mouse(&self) {
self.write("\x1b[?1006l\x1b[?1002l\x1b[?1000l");
}
fn enter_raw_mode(&self) {
let _ = cterm::enable_raw_mode();
if let Ok(mut running) = self.running.lock() {
*running = true;
}
self.configure_mouse_tracking();
self.hide_cursor();
// Enable bracketed paste mode so pasted text arrives as a single
// Event::Paste instead of individual key events (which would trigger
// submit per line for multi-line pastes).
self.write("\x1b[?2004h");
self.update_size();
self.flush();
}
fn exit_raw_mode(&self) {
// Mirror `enter_raw_mode` without tearing the terminal down: drop the
// bracketed-paste mode it turned on and restore the line discipline.
self.write("\x1b[?2004l");
self.flush();
let _ = cterm::disable_raw_mode();
}
fn refresh_size(&self) {
self.update_size();
}
fn start(
&self,
on_input: Box<dyn Fn(InputEvent) + Send + Sync>,
on_resize: Box<dyn Fn() + Send + Sync>,
) {
// Enter raw mode
let _ = cterm::enable_raw_mode();
if let Ok(mut running) = self.running.lock() {
*running = true;
}
self.configure_mouse_tracking();
self.hide_cursor();
self.flush();
// Update size initially
self.update_size();
// Spawn input handling thread
let running = Arc::new(Mutex::new(true));
let running_clone = running.clone();
let info_clone = Arc::new(Mutex::new(self.info()));
std::thread::spawn(move || {
loop {
// Check if we're still running
if !*running_clone.lock().unwrap() {
break;
}
// Poll for events with timeout
match event::poll(Duration::from_millis(100)) {
Ok(true) => {
if let Ok(event) = event::read() {
match event {
Event::Key(key) => on_input(InputEvent::Key(key)),
Event::Mouse(mouse) => on_input(InputEvent::Mouse(mouse)),
Event::Resize(cols, rows) => {
if let Ok(mut info) = info_clone.lock() {
info.columns = cols as usize;
info.rows = rows as usize;
}
on_resize();
}
Event::FocusGained => on_input(InputEvent::FocusGained),
Event::FocusLost => on_input(InputEvent::FocusLost),
Event::Paste(_) => { /* Ignore paste events for now */ }
}
}
}
Ok(false) => {} // Timeout, continue polling
Err(_) => break, // Error, stop the thread
}
}
});
// Store running flag
if let Ok(mut r) = self.running.lock() {
*r = true;
}
}
fn stop(&self) {
if let Ok(mut running) = self.running.lock() {
*running = false;
}
self.disable_mouse();
self.show_cursor();
// Disable bracketed paste mode before exiting raw mode.
self.write("\x1b[?2004l");
self.flush();
// Exit raw mode
let _ = cterm::disable_raw_mode();
}
fn is_tty(&self) -> bool {
std::io::stdout().is_terminal()
}
fn set_progress(&self, active: bool) {
// OSC 9;4 is supported by modern terminal emulators (including
// Windows Terminal, iTerm2-compatible terminals, and many Linux
// terminals). State 1 starts an indeterminate progress indicator and
// state 0 clears it.
let state = if active { 1 } else { 0 };
self.write(&format!("\x1b]9;4;{state};0\x07"));
self.flush();
}
fn flush(&self) {
if let Ok(mut writer) = self.writer.lock() {
let _ = writer.flush();
}
}
}
#[cfg(test)]
mod tests {
use super::mouse_tracking_enabled_for;
#[test]
fn mouse_tracking_default_preserves_native_selection_on_macos() {
assert!(!mouse_tracking_enabled_for(true));
assert!(mouse_tracking_enabled_for(false));
}
}