Skip to main content

vtcode_ui/tui/core_tui/
alternate_screen.rs

1use std::io::{self, Write};
2
3use crate::tui::utils::tty::TtyExt;
4use anyhow::{Context, Result};
5use ratatui::crossterm::{
6    cursor::MoveToColumn,
7    event::{DisableBracketedPaste, DisableFocusChange, EnableBracketedPaste, EnableFocusChange},
8    execute,
9    terminal::{self, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
10};
11use vtcode_commons::MultiErrors;
12
13/// Terminal state that needs to be preserved when entering alternate screen
14#[derive(Debug)]
15struct TerminalState {
16    raw_mode_enabled: bool,
17    bracketed_paste_enabled: bool,
18    focus_change_enabled: bool,
19}
20
21/// Manages entering and exiting alternate screen with proper state preservation
22///
23/// This struct ensures that terminal state is properly saved before entering
24/// alternate screen and restored when exiting, even in the presence of errors.
25pub struct AlternateScreenSession {
26    /// Terminal state before entering alternate screen
27    original_state: TerminalState,
28    /// Whether we successfully entered alternate screen
29    entered: bool,
30}
31
32impl AlternateScreenSession {
33    /// Enter alternate screen, saving current terminal state
34    ///
35    /// This will:
36    /// 1. Save the current terminal state
37    /// 2. Enter alternate screen
38    /// 3. Enable raw mode
39    /// 4. Enable bracketed paste
40    /// 5. Enable focus change events (if supported)
41    /// 6. Push keyboard enhancement flags (if supported)
42    ///
43    /// # Errors
44    ///
45    /// Returns an error if any terminal operation fails.
46    fn enter() -> Result<Self> {
47        let mut stdout = io::stdout();
48
49        // Check if stdout is a TTY before proceeding
50        let is_tty = stdout.is_tty_ext();
51        if !is_tty {
52            tracing::warn!("stdout is not a TTY, alternate screen features may not work");
53        }
54
55        // Save current state
56        let original_state = TerminalState {
57            raw_mode_enabled: false, // We'll enable it fresh
58            bracketed_paste_enabled: false,
59            focus_change_enabled: false,
60        };
61
62        // Enter alternate screen first
63        execute!(stdout, EnterAlternateScreen).context("failed to enter alternate screen for terminal app")?;
64        crate::tui::core_tui::panic_hook::mark_terminal_modified();
65
66        let mut session = Self { original_state, entered: true };
67
68        // Enable raw mode
69        enable_raw_mode().context("failed to enable raw mode for terminal app")?;
70        session.original_state.raw_mode_enabled = true;
71        crate::tui::core_tui::panic_hook::mark_terminal_modified();
72
73        // Enable bracketed paste (only if TTY)
74        if is_tty && execute!(stdout, EnableBracketedPaste).is_ok() {
75            session.original_state.bracketed_paste_enabled = true;
76            crate::tui::core_tui::panic_hook::mark_terminal_modified();
77        }
78
79        // Enable focus change events (only if TTY)
80        if is_tty && execute!(stdout, EnableFocusChange).is_ok() {
81            session.original_state.focus_change_enabled = true;
82            crate::tui::core_tui::panic_hook::mark_terminal_modified();
83        }
84
85        Ok(session)
86    }
87
88    /// Exit alternate screen, restoring original terminal state
89    ///
90    /// This will:
91    /// 1. Pop keyboard enhancement flags (if they were pushed)
92    /// 2. Disable focus change events (if they were enabled)
93    /// 3. Disable bracketed paste (if it was enabled)
94    /// 4. Disable raw mode (if it was enabled)
95    /// 5. Leave alternate screen
96    ///
97    /// # Errors
98    ///
99    /// Returns an error if any terminal operation fails. However, this method
100    /// will attempt to restore as much state as possible even if some operations fail.
101    fn exit(mut self) -> Result<()> {
102        self.restore_state()?;
103        self.entered = false; // Prevent Drop from trying again
104        Ok(())
105    }
106
107    /// Run a closure in alternate screen with automatic cleanup
108    ///
109    /// This is a convenience method that handles entering and exiting alternate
110    /// screen automatically, ensuring cleanup happens even if the closure panics.
111    ///
112    /// # Errors
113    ///
114    /// Returns an error if entering/exiting alternate screen fails, or if the
115    /// closure returns an error.
116    fn run<F, T>(f: F) -> Result<T>
117    where
118        F: FnOnce() -> Result<T>,
119    {
120        let session = Self::enter()?;
121        let result = f();
122        session.exit()?;
123        result
124    }
125
126    /// Internal method to restore terminal state
127    fn restore_state(&mut self) -> Result<()> {
128        if !self.entered {
129            return Ok(());
130        }
131
132        // Drain any pending crossterm events BEFORE leaving alternate screen and disabling raw mode
133        // to prevent them from leaking to the shell.
134        crate::tui::core_tui::runner::terminal_io::drain_terminal_events();
135
136        let mut stdout = io::stdout();
137
138        // Clear current line to remove artifacts like ^C from rapid presses
139        let _ = execute!(stdout, MoveToColumn(0), Clear(ClearType::CurrentLine));
140
141        let mut errors: MultiErrors<String> = MultiErrors::new();
142
143        // Restore in proper order to prevent leakage
144
145        // Clear the alternate viewport BEFORE leaving so the last TUI frame
146        // is not revealed in the main scrollback (mirrors the canonical
147        // `panic_hook::restore_tui` ordering).
148        let _ = execute!(stdout, Clear(ClearType::All));
149
150        // 1. Leave alternate screen FIRST
151        if let Err(e) = execute!(stdout, LeaveAlternateScreen) {
152            tracing::warn!(%e, "failed to leave alternate screen");
153            errors.push(format!("leave alternate screen: {e}"));
154        }
155
156        // 2. Disable focus change (if enabled and TTY)
157        if self.original_state.focus_change_enabled
158            && let Err(e) = execute!(stdout, DisableFocusChange)
159        {
160            tracing::warn!(%e, "failed to disable focus change");
161            errors.push(format!("disable focus change: {e}"));
162        }
163
164        // 3. Disable bracketed paste (if enabled and TTY)
165        if self.original_state.bracketed_paste_enabled
166            && let Err(e) = execute!(stdout, DisableBracketedPaste)
167        {
168            tracing::warn!(%e, "failed to disable bracketed paste");
169            errors.push(format!("disable bracketed paste: {e}"));
170        }
171
172        // Drain any terminal responses from the restore sequences above
173        // while raw mode is still active so individual bytes remain readable.
174        crate::tui::core_tui::runner::terminal_io::drain_terminal_events();
175
176        // 4. Disable raw mode LAST
177        if self.original_state.raw_mode_enabled
178            && let Err(e) = disable_raw_mode()
179        {
180            tracing::warn!(%e, "failed to disable raw mode");
181            errors.push(format!("disable raw mode: {e}"));
182        }
183
184        // Flush to ensure all changes are applied
185        if let Err(e) = stdout.flush() {
186            tracing::warn!(%e, "failed to flush stdout");
187            errors.push(format!("flush stdout: {e}"));
188        }
189
190        // This session restored the terminal itself. If it ran outside a TUI
191        // session nothing else will restore it, so clear the global modified
192        // flag to keep later error reports clean.
193        if !crate::tui::core_tui::panic_hook::is_tui_initialized() {
194            crate::tui::core_tui::panic_hook::mark_terminal_restored();
195        }
196
197        if errors.is_empty() {
198            Ok(())
199        } else {
200            tracing::warn!("some terminal operations failed during restore: {errors}");
201            // Don't fail the operation, just warn - terminal is likely already in a bad state
202            Ok(())
203        }
204    }
205}
206
207impl Drop for AlternateScreenSession {
208    fn drop(&mut self) {
209        if self.entered {
210            // Best effort cleanup - ignore errors in Drop
211            let _ = self.restore_state();
212        }
213    }
214}
215
216/// Clear the alternate screen
217///
218/// This is useful when you want to clear the screen before running a terminal app.
219pub fn clear_screen() -> Result<()> {
220    execute!(io::stdout(), Clear(ClearType::All)).context("failed to clear alternate screen")
221}
222
223/// Get current terminal size
224pub fn terminal_size() -> Result<(u16, u16)> {
225    terminal::size().context("failed to get terminal size")
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231
232    #[test]
233    fn test_enter_exit_cycle() {
234        if !io::stdout().is_tty_ext() {
235            return;
236        }
237
238        // This test verifies that we can enter and exit alternate screen
239        // without panicking. We can't easily verify the actual terminal state
240        // in a unit test, but we can at least ensure the code doesn't crash.
241        let session = AlternateScreenSession::enter();
242        assert!(session.is_ok());
243
244        if let Ok(session) = session {
245            let result = session.exit();
246            result.unwrap();
247        }
248    }
249
250    #[test]
251    fn test_run_with_closure() {
252        if !io::stdout().is_tty_ext() {
253            return;
254        }
255
256        let result = AlternateScreenSession::run(|| {
257            // Simulate some work in alternate screen
258            Ok(42)
259        });
260
261        assert!(result.is_ok());
262        assert_eq!(result.unwrap(), 42);
263    }
264
265    #[test]
266    fn test_run_with_error() {
267        let result: Result<()> = AlternateScreenSession::run(|| Err(anyhow::anyhow!("test error")));
268
269        assert!(result.is_err());
270    }
271
272    #[test]
273    fn test_drop_cleanup() {
274        // Verify that Drop properly cleans up
275        {
276            let _session = AlternateScreenSession::enter();
277            // Session dropped here
278        }
279        // If we get here without hanging, Drop worked
280    }
281}