dev_prune/tui/mod.rs
1// Copyright 2026 VKrishna04
2// SPDX-License-Identifier: Apache-2.0
3
4// Terminal UI components for dev-prune.
5
6use std::io::{Stdout, stdout};
7use std::panic::PanicHookInfo;
8use std::sync::Arc;
9use std::time::Duration;
10
11use anyhow::Result;
12use crossterm::ExecutableCommand;
13use crossterm::cursor::Show;
14use crossterm::event;
15use crossterm::terminal::{
16 EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
17};
18use ratatui::Terminal;
19use ratatui::backend::CrosstermBackend;
20
21pub mod config_view;
22pub mod selection_view;
23pub mod status_view;
24
25/// Put the terminal back the way it was found.
26///
27/// Every step is best-effort and independent: if leaving the alternate screen fails there
28/// is still a raw-mode flag to clear, and a terminal left in raw mode with a hidden cursor
29/// is a terminal the user has to close and reopen.
30fn restore_terminal() {
31 let _ = disable_raw_mode();
32 let _ = stdout().execute(LeaveAlternateScreen);
33 let _ = stdout().execute(Show);
34}
35
36/// An entered full-screen terminal session that always exits cleanly.
37///
38/// The three ways out of a TUI are a normal return, an error, and a panic. Before this
39/// guard existed each view handled the first by hand and leaked the terminal on the other
40/// two — `?` between "raw mode on" and the restore call would return with the screen still
41/// swapped and echo still off, which reads to the user as a hung shell.
42pub(crate) struct Tui {
43 pub terminal: Terminal<CrosstermBackend<Stdout>>,
44 prior_hook: Arc<dyn Fn(&PanicHookInfo<'_>) + Sync + Send + 'static>,
45}
46
47impl Tui {
48 /// Enter raw mode and the alternate screen, and arm the restore paths.
49 pub fn new() -> Result<Self> {
50 let prior_hook: Arc<dyn Fn(&PanicHookInfo<'_>) + Sync + Send> =
51 Arc::from(std::panic::take_hook());
52
53 // Restore first, then let the previous hook print: a panic message rendered into
54 // the alternate screen vanishes the moment the screen is dropped.
55 let hook_for_panic = Arc::clone(&prior_hook);
56 std::panic::set_hook(Box::new(move |info| {
57 restore_terminal();
58 hook_for_panic(info);
59 }));
60
61 if let Err(e) = enable_raw_mode() {
62 // The panic hook above is already armed; put the caller's back before
63 // handing the error up, exactly as the late-failure arm below does.
64 std::panic::set_hook(Box::new(move |info| prior_hook(info)));
65 return Err(e.into());
66 }
67 if let Err(e) = stdout().execute(EnterAlternateScreen) {
68 // Raw mode is on but `Self` will never exist, so `Drop` cannot turn it
69 // off — returning through `?` here left the shell in raw mode.
70 restore_terminal();
71 std::panic::set_hook(Box::new(move |info| prior_hook(info)));
72 return Err(e.into());
73 }
74
75 match Terminal::new(CrosstermBackend::new(stdout())) {
76 Ok(terminal) => Ok(Self {
77 terminal,
78 prior_hook,
79 }),
80 Err(e) => {
81 // Constructing the backend failed *after* the screen was swapped. `Drop`
82 // never runs for a `Self` that was never built, so both the screen and
83 // the panic hook have to be put back by hand here. Note this is a
84 // `set_hook`, not a `take_hook`: taking would install std's default and
85 // silently discard whatever hook the caller had before.
86 restore_terminal();
87 std::panic::set_hook(Box::new(move |info| prior_hook(info)));
88 Err(e.into())
89 }
90 }
91 }
92
93 /// Discard input that arrived before the view was ready for it.
94 ///
95 /// The Enter keypress that launched the command is still queued when the loop starts,
96 /// and on Windows its KeyPress/KeyRelease pair arrives inside the loop and confirms
97 /// the selection instantly. The sleep gives the console time to deliver it so that the
98 /// drain below has something to drain.
99 pub fn drain_stale_input(&self, settle: Duration) {
100 std::thread::sleep(settle);
101 // Deliberately not `?`: a failure to drain must never abort the view.
102 while matches!(event::poll(Duration::from_millis(50)), Ok(true)) {
103 let _ = event::read();
104 }
105 }
106}
107
108impl Drop for Tui {
109 fn drop(&mut self) {
110 restore_terminal();
111 let _ = self.terminal.show_cursor();
112 // Hand the panic hook back to whoever owned it, rather than to std's default.
113 let prior = Arc::clone(&self.prior_hook);
114 std::panic::set_hook(Box::new(move |info| prior(info)));
115 }
116}