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
use std::io::{self, Write};
use crate::tui::utils::tty::TtyExt;
use anyhow::{Context, Result};
use ratatui::crossterm::{
cursor::MoveToColumn,
event::{DisableBracketedPaste, DisableFocusChange, EnableBracketedPaste, EnableFocusChange},
execute,
terminal::{self, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use vtcode_commons::MultiErrors;
/// Terminal state that needs to be preserved when entering alternate screen
#[derive(Debug)]
struct TerminalState {
raw_mode_enabled: bool,
bracketed_paste_enabled: bool,
focus_change_enabled: bool,
}
/// Manages entering and exiting alternate screen with proper state preservation
///
/// This struct ensures that terminal state is properly saved before entering
/// alternate screen and restored when exiting, even in the presence of errors.
pub struct AlternateScreenSession {
/// Terminal state before entering alternate screen
original_state: TerminalState,
/// Whether we successfully entered alternate screen
entered: bool,
}
impl AlternateScreenSession {
/// Enter alternate screen, saving current terminal state
///
/// This will:
/// 1. Save the current terminal state
/// 2. Enter alternate screen
/// 3. Enable raw mode
/// 4. Enable bracketed paste
/// 5. Enable focus change events (if supported)
/// 6. Push keyboard enhancement flags (if supported)
///
/// # Errors
///
/// Returns an error if any terminal operation fails.
fn enter() -> Result<Self> {
let mut stdout = io::stdout();
// Check if stdout is a TTY before proceeding
let is_tty = stdout.is_tty_ext();
if !is_tty {
tracing::warn!("stdout is not a TTY, alternate screen features may not work");
}
// Save current state
let original_state = TerminalState {
raw_mode_enabled: false, // We'll enable it fresh
bracketed_paste_enabled: false,
focus_change_enabled: false,
};
// Enter alternate screen first
execute!(stdout, EnterAlternateScreen).context("failed to enter alternate screen for terminal app")?;
crate::tui::core_tui::panic_hook::mark_terminal_modified();
let mut session = Self { original_state, entered: true };
// Enable raw mode
enable_raw_mode().context("failed to enable raw mode for terminal app")?;
session.original_state.raw_mode_enabled = true;
crate::tui::core_tui::panic_hook::mark_terminal_modified();
// Enable bracketed paste (only if TTY)
if is_tty && execute!(stdout, EnableBracketedPaste).is_ok() {
session.original_state.bracketed_paste_enabled = true;
crate::tui::core_tui::panic_hook::mark_terminal_modified();
}
// Enable focus change events (only if TTY)
if is_tty && execute!(stdout, EnableFocusChange).is_ok() {
session.original_state.focus_change_enabled = true;
crate::tui::core_tui::panic_hook::mark_terminal_modified();
}
Ok(session)
}
/// Exit alternate screen, restoring original terminal state
///
/// This will:
/// 1. Pop keyboard enhancement flags (if they were pushed)
/// 2. Disable focus change events (if they were enabled)
/// 3. Disable bracketed paste (if it was enabled)
/// 4. Disable raw mode (if it was enabled)
/// 5. Leave alternate screen
///
/// # Errors
///
/// Returns an error if any terminal operation fails. However, this method
/// will attempt to restore as much state as possible even if some operations fail.
fn exit(mut self) -> Result<()> {
self.restore_state()?;
self.entered = false; // Prevent Drop from trying again
Ok(())
}
/// Run a closure in alternate screen with automatic cleanup
///
/// This is a convenience method that handles entering and exiting alternate
/// screen automatically, ensuring cleanup happens even if the closure panics.
///
/// # Errors
///
/// Returns an error if entering/exiting alternate screen fails, or if the
/// closure returns an error.
fn run<F, T>(f: F) -> Result<T>
where
F: FnOnce() -> Result<T>,
{
let session = Self::enter()?;
let result = f();
session.exit()?;
result
}
/// Internal method to restore terminal state
fn restore_state(&mut self) -> Result<()> {
if !self.entered {
return Ok(());
}
// Drain any pending crossterm events BEFORE leaving alternate screen and disabling raw mode
// to prevent them from leaking to the shell.
crate::tui::core_tui::runner::terminal_io::drain_terminal_events();
let mut stdout = io::stdout();
// Clear current line to remove artifacts like ^C from rapid presses
let _ = execute!(stdout, MoveToColumn(0), Clear(ClearType::CurrentLine));
let mut errors: MultiErrors<String> = MultiErrors::new();
// Restore in proper order to prevent leakage
// Clear the alternate viewport BEFORE leaving so the last TUI frame
// is not revealed in the main scrollback (mirrors the canonical
// `panic_hook::restore_tui` ordering).
let _ = execute!(stdout, Clear(ClearType::All));
// 1. Leave alternate screen FIRST
if let Err(e) = execute!(stdout, LeaveAlternateScreen) {
tracing::warn!(%e, "failed to leave alternate screen");
errors.push(format!("leave alternate screen: {e}"));
}
// 2. Disable focus change (if enabled and TTY)
if self.original_state.focus_change_enabled
&& let Err(e) = execute!(stdout, DisableFocusChange)
{
tracing::warn!(%e, "failed to disable focus change");
errors.push(format!("disable focus change: {e}"));
}
// 3. Disable bracketed paste (if enabled and TTY)
if self.original_state.bracketed_paste_enabled
&& let Err(e) = execute!(stdout, DisableBracketedPaste)
{
tracing::warn!(%e, "failed to disable bracketed paste");
errors.push(format!("disable bracketed paste: {e}"));
}
// Drain any terminal responses from the restore sequences above
// while raw mode is still active so individual bytes remain readable.
crate::tui::core_tui::runner::terminal_io::drain_terminal_events();
// 4. Disable raw mode LAST
if self.original_state.raw_mode_enabled
&& let Err(e) = disable_raw_mode()
{
tracing::warn!(%e, "failed to disable raw mode");
errors.push(format!("disable raw mode: {e}"));
}
// Flush to ensure all changes are applied
if let Err(e) = stdout.flush() {
tracing::warn!(%e, "failed to flush stdout");
errors.push(format!("flush stdout: {e}"));
}
// This session restored the terminal itself. If it ran outside a TUI
// session nothing else will restore it, so clear the global modified
// flag to keep later error reports clean.
if !crate::tui::core_tui::panic_hook::is_tui_initialized() {
crate::tui::core_tui::panic_hook::mark_terminal_restored();
}
if errors.is_empty() {
Ok(())
} else {
tracing::warn!("some terminal operations failed during restore: {errors}");
// Don't fail the operation, just warn - terminal is likely already in a bad state
Ok(())
}
}
}
impl Drop for AlternateScreenSession {
fn drop(&mut self) {
if self.entered {
// Best effort cleanup - ignore errors in Drop
let _ = self.restore_state();
}
}
}
/// Clear the alternate screen
///
/// This is useful when you want to clear the screen before running a terminal app.
pub fn clear_screen() -> Result<()> {
execute!(io::stdout(), Clear(ClearType::All)).context("failed to clear alternate screen")
}
/// Get current terminal size
pub fn terminal_size() -> Result<(u16, u16)> {
terminal::size().context("failed to get terminal size")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_enter_exit_cycle() {
if !io::stdout().is_tty_ext() {
return;
}
// This test verifies that we can enter and exit alternate screen
// without panicking. We can't easily verify the actual terminal state
// in a unit test, but we can at least ensure the code doesn't crash.
let session = AlternateScreenSession::enter();
assert!(session.is_ok());
if let Ok(session) = session {
let result = session.exit();
result.unwrap();
}
}
#[test]
fn test_run_with_closure() {
if !io::stdout().is_tty_ext() {
return;
}
let result = AlternateScreenSession::run(|| {
// Simulate some work in alternate screen
Ok(42)
});
assert!(result.is_ok());
assert_eq!(result.unwrap(), 42);
}
#[test]
fn test_run_with_error() {
let result: Result<()> = AlternateScreenSession::run(|| Err(anyhow::anyhow!("test error")));
assert!(result.is_err());
}
#[test]
fn test_drop_cleanup() {
// Verify that Drop properly cleans up
{
let _session = AlternateScreenSession::enter();
// Session dropped here
}
// If we get here without hanging, Drop worked
}
}