Skip to main content

foundry_tui/
lib.rs

1//! Shared terminal UI utilities for Foundry.
2
3use crossterm::{
4    cursor::Show,
5    event::{DisableMouseCapture, EnableMouseCapture, Event, read},
6    execute,
7    terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
8};
9use ratatui::{
10    Frame, Terminal,
11    backend::{Backend, CrosstermBackend},
12};
13use std::{
14    env,
15    io::{IsTerminal, Result as IoResult, Stdout, Write, stdin, stdout},
16    ops::ControlFlow,
17    panic::{PanicHookInfo, set_hook, take_hook},
18    sync::Arc,
19    thread::panicking,
20};
21
22/// The default terminal backend used by Foundry TUIs.
23pub type CrosstermTerminal = Terminal<CrosstermBackend<Stdout>>;
24
25type PanicHandler = Box<dyn Fn(&PanicHookInfo<'_>) + 'static + Sync + Send>;
26
27/// The resolved mode for a requested TUI run.
28#[derive(Clone, Copy, Debug, Eq, PartialEq)]
29pub enum TuiMode {
30    /// The process can open an interactive TUI.
31    Interactive,
32    /// The process should use a line-oriented fallback.
33    Fallback(TuiFallbackReason),
34}
35
36impl TuiMode {
37    /// Returns whether the mode can run an interactive TUI.
38    pub const fn is_interactive(self) -> bool {
39        matches!(self, Self::Interactive)
40    }
41}
42
43/// Why an interactive TUI should not be opened.
44#[derive(Clone, Copy, Debug, Eq, PartialEq)]
45pub enum TuiFallbackReason {
46    /// Foundry is running in a CI environment.
47    Ci,
48    /// Standard input is not connected to a terminal.
49    StdinNotTerminal,
50    /// Standard output is not connected to a terminal.
51    StdoutNotTerminal,
52}
53
54impl TuiFallbackReason {
55    /// Returns a short stable description of the fallback reason.
56    pub const fn as_str(self) -> &'static str {
57        match self {
58            Self::Ci => "running in CI",
59            Self::StdinNotTerminal => "stdin is not a terminal",
60            Self::StdoutNotTerminal => "stdout is not a terminal",
61        }
62    }
63}
64
65/// Runtime environment details used to decide whether a TUI can run interactively.
66#[derive(Clone, Copy, Debug, Eq, PartialEq)]
67pub struct TuiEnvironment {
68    /// Whether standard input is connected to a terminal.
69    pub stdin_is_terminal: bool,
70    /// Whether standard output is connected to a terminal.
71    pub stdout_is_terminal: bool,
72    /// Whether Foundry appears to be running in CI.
73    pub is_ci: bool,
74}
75
76impl TuiEnvironment {
77    /// Creates a new environment descriptor.
78    pub const fn new(stdin_is_terminal: bool, stdout_is_terminal: bool, is_ci: bool) -> Self {
79        Self { stdin_is_terminal, stdout_is_terminal, is_ci }
80    }
81
82    /// Detects the current process environment.
83    pub fn detect() -> Self {
84        Self::new(stdin().is_terminal(), stdout().is_terminal(), env::var_os("CI").is_some())
85    }
86
87    /// Resolves the TUI mode for this environment.
88    pub const fn mode(self) -> TuiMode {
89        if self.is_ci {
90            TuiMode::Fallback(TuiFallbackReason::Ci)
91        } else if !self.stdin_is_terminal {
92            TuiMode::Fallback(TuiFallbackReason::StdinNotTerminal)
93        } else if !self.stdout_is_terminal {
94            TuiMode::Fallback(TuiFallbackReason::StdoutNotTerminal)
95        } else {
96            TuiMode::Interactive
97        }
98    }
99}
100
101/// Detects whether a requested TUI should run interactively or fall back to line output.
102pub fn tui_mode() -> TuiMode {
103    TuiEnvironment::detect().mode()
104}
105
106/// An interactive terminal application.
107pub trait TuiApp {
108    /// The reason the application exited.
109    type Exit;
110
111    /// Draws one frame.
112    fn draw(&mut self, frame: &mut Frame<'_>);
113
114    /// Handles one terminal event.
115    fn handle_event(&mut self, event: Event) -> ControlFlow<Self::Exit>;
116}
117
118/// Runs an interactive terminal application with the default Foundry terminal setup.
119pub fn run_app<App: TuiApp>(app: &mut App) -> IoResult<App::Exit> {
120    with_terminal(|terminal| run_app_inner(terminal, app))?
121}
122
123/// Runs an app only when the current environment supports an interactive TUI.
124pub fn run_app_if_interactive<App: TuiApp>(app: &mut App) -> IoResult<Option<App::Exit>> {
125    match tui_mode() {
126        TuiMode::Interactive => run_app(app).map(Some),
127        TuiMode::Fallback(_) => Ok(None),
128    }
129}
130
131fn run_app_inner<App: TuiApp>(
132    terminal: &mut CrosstermTerminal,
133    app: &mut App,
134) -> IoResult<App::Exit> {
135    loop {
136        terminal.draw(|frame| app.draw(frame))?;
137        match app.handle_event(read()?) {
138            ControlFlow::Continue(()) => {}
139            ControlFlow::Break(reason) => return Ok(reason),
140        }
141    }
142}
143
144/// Handles terminal setup and teardown for interactive TUIs.
145#[must_use]
146pub struct TerminalGuard<B: Backend + Write> {
147    terminal: Terminal<B>,
148    hook: Option<Arc<PanicHandler>>,
149}
150
151impl<B: Backend + Write> TerminalGuard<B> {
152    /// Runs a closure while the terminal is in alternate-screen raw mode.
153    pub fn with<T>(terminal: Terminal<B>, mut f: impl FnMut(&mut Terminal<B>) -> T) -> T {
154        let mut guard = Self { terminal, hook: None };
155        guard.setup();
156        f(&mut guard.terminal)
157    }
158
159    fn setup(&mut self) {
160        let previous = Arc::new(take_hook());
161        self.hook = Some(previous.clone());
162        // Restore terminal state before displaying the panic message.
163        set_hook(Box::new(move |info| {
164            Self::half_restore(&mut stdout());
165            (previous)(info)
166        }));
167
168        let _ = enable_raw_mode();
169        let _ = execute!(*self.terminal.backend_mut(), EnterAlternateScreen, EnableMouseCapture);
170        let _ = self.terminal.hide_cursor();
171        let _ = self.terminal.clear();
172    }
173
174    fn restore(&mut self) {
175        // Always restore terminal state on drop, even during panic unwinding.
176        // The panic hook installed in `setup()` may be replaced by external code,
177        // so `Drop` must not rely on it as the sole cleanup path.
178        Self::half_restore(self.terminal.backend_mut());
179
180        if !panicking() {
181            let _ = take_hook();
182            let prev = self.hook.take().unwrap();
183            let prev = match Arc::try_unwrap(prev) {
184                Ok(prev) => prev,
185                Err(_) => unreachable!("`self.hook` is not the only reference to the panic hook"),
186            };
187            set_hook(prev);
188        }
189
190        let _ = self.terminal.show_cursor();
191    }
192
193    fn half_restore(w: &mut impl Write) {
194        let _ = disable_raw_mode();
195        let _ = execute!(*w, LeaveAlternateScreen, DisableMouseCapture);
196    }
197}
198
199impl<B: Backend + Write> Drop for TerminalGuard<B> {
200    #[inline]
201    fn drop(&mut self) {
202        self.restore();
203    }
204}
205
206/// Runs a closure with the default Foundry terminal setup.
207pub fn with_terminal<T>(f: impl FnMut(&mut CrosstermTerminal) -> T) -> IoResult<T> {
208    let backend = CrosstermBackend::new(stdout());
209    let terminal = Terminal::new(backend)?;
210    Ok(TerminalGuard::with(terminal, f))
211}
212
213/// Runs a closure that sets up its own raw-mode alternate screen, restoring the terminal before a
214/// panic message is displayed.
215///
216/// Release builds abort on panic, so the closure's own cleanup on drop never runs.
217pub fn restore_terminal_on_panic<T>(f: impl FnOnce() -> T) -> T {
218    let previous = Arc::new(take_hook());
219    let hook = previous.clone();
220    set_hook(Box::new(move |info| {
221        let _ = disable_raw_mode();
222        let _ = execute!(stdout(), LeaveAlternateScreen, DisableMouseCapture, Show);
223        (hook)(info)
224    }));
225    let output = f();
226    drop(take_hook());
227    // The previous hook is still shared only if the closure kept this hook elsewhere.
228    if let Ok(previous) = Arc::try_unwrap(previous) {
229        set_hook(previous);
230    }
231    output
232}
233
234#[cfg(test)]
235mod tests {
236    use super::{TuiEnvironment, TuiFallbackReason, TuiMode};
237
238    #[test]
239    fn detects_interactive_mode() {
240        let env = TuiEnvironment::new(true, true, false);
241
242        assert_eq!(env.mode(), TuiMode::Interactive);
243        assert!(env.mode().is_interactive());
244    }
245
246    #[test]
247    fn ci_forces_fallback() {
248        let env = TuiEnvironment::new(true, true, true);
249
250        assert_eq!(env.mode(), TuiMode::Fallback(TuiFallbackReason::Ci));
251        assert!(!env.mode().is_interactive());
252    }
253
254    #[test]
255    fn stdin_must_be_terminal() {
256        let env = TuiEnvironment::new(false, true, false);
257
258        assert_eq!(env.mode(), TuiMode::Fallback(TuiFallbackReason::StdinNotTerminal));
259    }
260
261    #[test]
262    fn stdout_must_be_terminal() {
263        let env = TuiEnvironment::new(true, false, false);
264
265        assert_eq!(env.mode(), TuiMode::Fallback(TuiFallbackReason::StdoutNotTerminal));
266    }
267
268    #[test]
269    fn ci_reason_takes_precedence() {
270        let env = TuiEnvironment::new(false, false, true);
271
272        assert_eq!(env.mode(), TuiMode::Fallback(TuiFallbackReason::Ci));
273    }
274
275    #[test]
276    fn fallback_reasons_have_stable_descriptions() {
277        assert_eq!(TuiFallbackReason::Ci.as_str(), "running in CI");
278        assert_eq!(TuiFallbackReason::StdinNotTerminal.as_str(), "stdin is not a terminal");
279        assert_eq!(TuiFallbackReason::StdoutNotTerminal.as_str(), "stdout is not a terminal");
280    }
281}