[go: up one dir, main page]

panic/
panic.rs

1//! # [Ratatui] Panic Hook example
2//!
3//! The latest version of this example is available in the [examples] folder in the repository.
4//!
5//! Please note that the examples are designed to be run against the `main` branch of the Github
6//! repository. This means that you may not be able to compile with the latest release version on
7//! crates.io, or the one that you have installed locally.
8//!
9//! See the [examples readme] for more information on finding examples that match the version of the
10//! library you are using.
11//!
12//! [Ratatui]: https://github.com/ratatui/ratatui
13//! [examples]: https://github.com/ratatui/ratatui/blob/main/examples
14//! [examples readme]: https://github.com/ratatui/ratatui/blob/main/examples/README.md
15//!
16//! Prior to Ratatui 0.28.1, a panic hook had to be manually set up to ensure that the terminal was
17//! reset when a panic occurred. This was necessary because a panic would interrupt the normal
18//! control flow and leave the terminal in a distorted state.
19//!
20//! Starting with Ratatui 0.28.1, the panic hook is automatically set up by the new `ratatui::init`
21//! function, so you no longer need to manually set up the panic hook. This example now demonstrates
22//! how the panic hook acts when it is enabled by default.
23//!
24//! When exiting normally or when handling `Result::Err`, we can reset the terminal manually at the
25//! end of `main` just before we print the error.
26//!
27//! Because a panic interrupts the normal control flow, manually resetting the terminal at the end
28//! of `main` won't do us any good. Instead, we need to make sure to set up a panic hook that first
29//! resets the terminal before handling the panic. This both reuses the standard panic hook to
30//! ensure a consistent panic handling UX and properly resets the terminal to not distort the
31//! output.
32//!
33//! That's why this example is set up to show both situations, with and without the panic hook, to
34//! see the difference.
35//!
36//! For more information on how to set this up manually, see the [Color Eyre recipe] in the Ratatui
37//! website.
38//!
39//! [Color Eyre recipe]: https://ratatui.rs/recipes/apps/color-eyre
40
41use color_eyre::{eyre::bail, Result};
42use ratatui::{
43    crossterm::event::{self, Event, KeyCode},
44    text::Line,
45    widgets::{Block, Paragraph},
46    DefaultTerminal, Frame,
47};
48
49fn main() -> Result<()> {
50    color_eyre::install()?;
51    let terminal = ratatui::init();
52    let app_result = App::new().run(terminal);
53    ratatui::restore();
54    app_result
55}
56struct App {
57    hook_enabled: bool,
58}
59
60impl App {
61    const fn new() -> Self {
62        Self { hook_enabled: true }
63    }
64
65    fn run(mut self, mut terminal: DefaultTerminal) -> Result<()> {
66        loop {
67            terminal.draw(|frame| self.draw(frame))?;
68
69            if let Event::Key(key) = event::read()? {
70                match key.code {
71                    KeyCode::Char('p') => panic!("intentional demo panic"),
72                    KeyCode::Char('e') => bail!("intentional demo error"),
73                    KeyCode::Char('h') => {
74                        let _ = std::panic::take_hook();
75                        self.hook_enabled = false;
76                    }
77                    KeyCode::Char('q') => return Ok(()),
78                    _ => {}
79                }
80            }
81        }
82    }
83
84    fn draw(&self, frame: &mut Frame) {
85        let text = vec![
86            if self.hook_enabled {
87                Line::from("HOOK IS CURRENTLY **ENABLED**")
88            } else {
89                Line::from("HOOK IS CURRENTLY **DISABLED**")
90            },
91            Line::from(""),
92            Line::from("Press `p` to cause a panic"),
93            Line::from("Press `e` to cause an error"),
94            Line::from("Press `h` to disable the panic hook"),
95            Line::from("Press `q` to quit"),
96            Line::from(""),
97            Line::from("When your app panics without a panic hook, you will likely have to"),
98            Line::from("reset your terminal afterwards with the `reset` command"),
99            Line::from(""),
100            Line::from("Try first with the panic handler enabled, and then with it disabled"),
101            Line::from("to see the difference"),
102        ];
103
104        let paragraph = Paragraph::new(text)
105            .block(Block::bordered().title("Panic Handler Demo"))
106            .centered();
107
108        frame.render_widget(paragraph, frame.area());
109    }
110}