summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorPiotr Bartoszewicz <89194651+PiotrekB416@users.noreply.github.com>2023-08-14 16:55:17 +0200
committerGitHub <noreply@github.com>2023-08-14 16:55:17 +0200
commitfbf54bbce9aa093d9e32311ad44c4fe6b661b142 (patch)
tree3ef15ffc8a861ce67b8ed741bbaf0f50b49dabe5
parent7975a47ab995cf5fddbcd49cf23ea399e46e085f (diff)
feat: Add panic hook for resetting the terminal (#106)
* Add panic hook * Changed stdout to stderr * refactor(tui): clean up panic hook handling --------- Co-authored-by: Orhun Parmaksız <orhunparmaksiz@gmail.com>
-rw-r--r--src/term/tui.rs14
1 files changed, 13 insertions, 1 deletions
diff --git a/src/term/tui.rs b/src/term/tui.rs
index a29746b..10ddcf8 100644
--- a/src/term/tui.rs
+++ b/src/term/tui.rs
@@ -5,6 +5,7 @@ use anyhow::{Context, Result};
use crossterm::event::{DisableMouseCapture, EnableMouseCapture};
use crossterm::terminal::{self, EnterAlternateScreen, LeaveAlternateScreen};
use std::io;
+use std::panic;
use std::sync::atomic::Ordering;
use tui::backend::Backend;
use tui::Terminal;
@@ -46,6 +47,11 @@ impl<B: Backend> Tui<B> {
EnterAlternateScreen,
EnableMouseCapture
)?;
+ let panic_hook = panic::take_hook();
+ panic::set_hook(Box::new(move |panic| {
+ Self::reset().expect("failed to reset the terminal");
+ panic_hook(panic);
+ }));
self.terminal.hide_cursor()?;
self.terminal.clear()?;
Ok(())
@@ -95,13 +101,19 @@ impl<B: Backend> Tui<B> {
///
/// It disables the raw mode and reverts back the terminal properties.
pub fn exit(&mut self) -> Result<()> {
+ Self::reset()?;
+ self.terminal.show_cursor()?;
+ Ok(())
+ }
+
+ /// Resets the terminal interface.
+ fn reset() -> Result<()> {
terminal::disable_raw_mode()?;
crossterm::execute!(
io::stderr(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
- self.terminal.show_cursor()?;
Ok(())
}
}