1use 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
22pub type CrosstermTerminal = Terminal<CrosstermBackend<Stdout>>;
24
25type PanicHandler = Box<dyn Fn(&PanicHookInfo<'_>) + 'static + Sync + Send>;
26
27#[derive(Clone, Copy, Debug, Eq, PartialEq)]
29pub enum TuiMode {
30 Interactive,
32 Fallback(TuiFallbackReason),
34}
35
36impl TuiMode {
37 pub const fn is_interactive(self) -> bool {
39 matches!(self, Self::Interactive)
40 }
41}
42
43#[derive(Clone, Copy, Debug, Eq, PartialEq)]
45pub enum TuiFallbackReason {
46 Ci,
48 StdinNotTerminal,
50 StdoutNotTerminal,
52}
53
54impl TuiFallbackReason {
55 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
67pub struct TuiEnvironment {
68 pub stdin_is_terminal: bool,
70 pub stdout_is_terminal: bool,
72 pub is_ci: bool,
74}
75
76impl TuiEnvironment {
77 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 pub fn detect() -> Self {
84 Self::new(stdin().is_terminal(), stdout().is_terminal(), env::var_os("CI").is_some())
85 }
86
87 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
101pub fn tui_mode() -> TuiMode {
103 TuiEnvironment::detect().mode()
104}
105
106pub trait TuiApp {
108 type Exit;
110
111 fn draw(&mut self, frame: &mut Frame<'_>);
113
114 fn handle_event(&mut self, event: Event) -> ControlFlow<Self::Exit>;
116}
117
118pub fn run_app<App: TuiApp>(app: &mut App) -> IoResult<App::Exit> {
120 with_terminal(|terminal| run_app_inner(terminal, app))?
121}
122
123pub 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#[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 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 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 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
206pub 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
213pub 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 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}