| 1 | use crate::ui; |
| 2 | use crossterm::event::{DisableMouseCapture, EnableMouseCapture}; |
| 3 | use crossterm::terminal::{self, *}; |
| 4 | use std::io; |
| 5 | use std::panic; |
| 6 | |
| 7 | use crate::{app::App, AppResult}; |
| 8 | |
| 9 | pub type CrosstermTerminal = ratatui::Terminal<ratatui::backend::CrosstermBackend<std::io::Stderr>>; |
| 10 | |
| 11 | #[derive(Debug)] |
| 12 | pub struct Tui { |
| 13 | terminal: CrosstermTerminal, |
| 14 | } |
| 15 | |
| 16 | impl 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 | } |