Krolyxon
Commit 7f77734

rmptuisrctui.rs

62 lines · 1.8 KB · Rust

1use crate::ui;
2use crossterm::event::{DisableMouseCapture, EnableMouseCapture};
3use crossterm::terminal::{self, *};
4use std::io;
5use std::panic;
6
7use crate::{app::App, AppResult};
8
9pub type CrosstermTerminal = ratatui::Terminal<ratatui::backend::CrosstermBackend<std::io::Stderr>>;
10
11#[derive(Debug)]
12pub struct Tui {
13 terminal: CrosstermTerminal,
14}
15
16impl Tui {
17 pub fn new(terminal: CrosstermTerminal) -> Self {
18 Self { terminal }
19 }
20
21 pub fn init(&mut self) -> AppResult<()> {
22 terminal::enable_raw_mode()?;
23 crossterm::execute!(io::stderr(), EnterAlternateScreen, EnableMouseCapture)?;
24
25 let panic_hook = panic::take_hook();
26 panic::set_hook(Box::new(move |panic| {
27 if let Err(error) = Self::reset() {
28 eprintln!("failed to reset the terminal: {error}");
29 }
30 panic_hook(panic);
31 }));
32 Ok(())
33 }
34
35 /// [`Draw`] the terminal interface by [`rendering`] the widgets.
36 ///
37 /// [`Draw`]: ratatui::Terminal::draw
38 /// [`rendering`]: crate::ui::render
39 pub fn draw(&mut self, app: &mut App) -> AppResult<()> {
40 self.terminal.draw(|frame| ui::render(app, frame))?;
41 Ok(())
42 }
43
44 /// Resets the terminal interface.
45 ///
46 /// This function is also used for the panic hook to revert
47 /// the terminal properties if unexpected errors occur.
48 fn reset() -> AppResult<()> {
49 terminal::disable_raw_mode()?;
50 crossterm::execute!(io::stderr(), LeaveAlternateScreen, DisableMouseCapture)?;
51 Ok(())
52 }
53
54 /// Exits the terminal interface.
55 ///
56 /// It disables the raw mode and reverts back the terminal properties.
57 pub fn exit(&mut self) -> AppResult<()> {
58 Self::reset()?;
59 self.terminal.show_cursor()?;
60 Ok(())
61 }
62}