use crate::app::{App, AppResult};
use crate::events::EventHandler;
use crate::fs::{DataStore, DataStoreKey};
use crossterm::event::{DisableMouseCapture, EnableMouseCapture};
use crossterm::terminal::{self, EnterAlternateScreen, LeaveAlternateScreen};
use ratatui::backend::Backend;
use ratatui::Terminal;
use std::io;
use std::marker::PhantomData;
use std::panic;
#[derive(Debug)]
pub struct Tui<B: Backend, S: DataStore<DataStoreKey>> {
terminal: Terminal<B>,
pub events: EventHandler,
_store: PhantomData<S>,
}
impl<B: Backend, S: DataStore<DataStoreKey>> Tui<B, S> {
pub fn new(terminal: Terminal<B>, events: EventHandler) -> Self {
Self {
terminal,
events,
_store: PhantomData,
}
}
pub fn init(&mut self) -> AppResult<()> {
terminal::enable_raw_mode()?;
crossterm::execute!(io::stderr(), EnterAlternateScreen, EnableMouseCapture)?;
let panic_hook = panic::take_hook();
panic::set_hook(Box::new(move |panic| {
Self::reset().expect("failed to reset the terminal");
panic_hook(panic);
}));
self.terminal.hide_cursor()?;
self.terminal.clear()?;
Ok(())
}
pub fn draw(&mut self, app: &mut App<S>) -> AppResult<()> {
self.terminal
.draw(|frame| frame.render_widget(app, frame.size()))?;
Ok(())
}
fn reset() -> AppResult<()> {
terminal::disable_raw_mode()?;
crossterm::execute!(io::stderr(), LeaveAlternateScreen, DisableMouseCapture)?;
Ok(())
}
pub fn exit(&mut self) -> AppResult<()> {
Self::reset()?;
self.terminal.show_cursor()?;
Ok(())
}
}