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 enable_raw_mode()?;
62 stdout().execute(EnterAlternateScreen)?;
63
64 match Terminal::new(CrosstermBackend::new(stdout())) {
65 Ok(terminal) => Ok(Self {
66 terminal,
67 prior_hook,
68 }),
69 Err(e) => {
70 // Constructing the backend failed *after* the screen was swapped. `Drop`
71 // never runs for a `Self` that was never built, so both the screen and
72 // the panic hook have to be put back by hand here. Note this is a
73 // `set_hook`, not a `take_hook`: taking would install std's default and
74 // silently discard whatever hook the caller had before.
75 restore_terminal();
76 std::panic::set_hook(Box::new(move |info| prior_hook(info)));
77 Err(e.into())
78 }
79 }
80 }
81
82 /// Discard input that arrived before the view was ready for it.
83 ///
84 /// The Enter keypress that launched the command is still queued when the loop starts,
85 /// and on Windows its KeyPress/KeyRelease pair arrives inside the loop and confirms
86 /// the selection instantly. The sleep gives the console time to deliver it so that the
87 /// drain below has something to drain.
88 pub fn drain_stale_input(&self, settle: Duration) {
89 std::thread::sleep(settle);
90 // Deliberately not `?`: a failure to drain must never abort the view.
91 while matches!(event::poll(Duration::from_millis(50)), Ok(true)) {
92 let _ = event::read();
93 }
94 }
95}
96
97impl Drop for Tui {
98 fn drop(&mut self) {
99 restore_terminal();
100 let _ = self.terminal.show_cursor();
101 // Hand the panic hook back to whoever owned it, rather than to std's default.
102 let prior = Arc::clone(&self.prior_hook);
103 std::panic::set_hook(Box::new(move |info| prior(info)));
104 }
105}