Krolyxon
Commit 4993431

rmptuisrctui.rs

62 lines · 1.8 KB · Rust

1use std::io;
2use crate::ui;
3use crossterm::event::{DisableMouseCapture, EnableMouseCapture};
4use crossterm::terminal::{self, *};
5use std::panic;
6
7use crate::app::{App, AppResult};
8use crate::event::EventHandler;
9
10pub type CrosstermTerminal = ratatui::Terminal<ratatui::backend::CrosstermBackend<std::io::Stderr>>;
11
12#[derive(Debug)]
13pub struct Tui {
14 terminal: CrosstermTerminal,
15 pub events: EventHandler,
16}
17
18impl Tui {
19 pub fn new(terminal: CrosstermTerminal, events: EventHandler) -> Self {
20 Self { terminal, events }
21 }
22
23 pub fn init(&mut self) -> AppResult<()> {
24 terminal::enable_raw_mode()?;
25 crossterm::execute!(io::stdout(), EnterAlternateScreen, EnableMouseCapture)?;
26
27 let panic_hook = panic::take_hook();
28 panic::set_hook(Box::new(move |panic| {
29 Self::reset().expect("failed to reset the terminal");
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}