Krolyxon
Commit bf11d59

rmptuisrctui.rs

66 lines · 1.9 KB · Rust

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