thedes_tui_core/panic/restore/
native.rs1use std::{
2 io::{self, Write},
3 thread,
4};
5
6use crossterm::{Command, cursor, style, terminal};
7
8use super::PanicRestoreGuard;
9
10pub fn open() -> Box<dyn PanicRestoreGuard> {
11 Box::new(NativePanicRestoreGuard::new())
12}
13
14#[derive(Debug)]
15struct NativePanicRestoreGuard {
16 enabled: bool,
17}
18
19impl NativePanicRestoreGuard {
20 pub fn new() -> Self {
21 Self { enabled: true }
22 }
23}
24
25impl PanicRestoreGuard for NativePanicRestoreGuard {
26 fn cancel(mut self: Box<Self>) {
27 self.enabled = false;
28 }
29}
30
31impl Drop for NativePanicRestoreGuard {
32 fn drop(&mut self) {
33 if self.enabled && thread::panicking() {
34 tracing::warn!("Running panic restoration of the terminal");
35
36 let _ = terminal::disable_raw_mode();
37 print!("{}", cursor::Show);
38 print!(
39 "{}",
40 style::SetBackgroundColor(crossterm::style::Color::Reset)
41 );
42 print!(
43 "{}",
44 style::SetForegroundColor(crossterm::style::Color::Reset)
45 );
46 let mut buf = String::new();
47 let _ = terminal::LeaveAlternateScreen.write_ansi(&mut buf);
48 println!("{}", buf);
49 let _ = io::stdout().flush();
50 }
51 }
52}