Skip to content

Commit

Permalink
Cleanup examples
Browse files Browse the repository at this point in the history
  • Loading branch information
Philipp Reiter committed Sep 7, 2024
1 parent 995572d commit 694a60f
Show file tree
Hide file tree
Showing 4 changed files with 296 additions and 375 deletions.
60 changes: 60 additions & 0 deletions examples/common/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
use crossterm::{
event::{DisableMouseCapture, EnableMouseCapture},
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::prelude::CrosstermBackend;
use std::{
error::Error,
io::{stdout, Stdout},
ops::{Deref, DerefMut},
};

pub type Result<T> = std::result::Result<T, Box<dyn Error>>;

pub struct Terminal(ratatui::Terminal<CrosstermBackend<Stdout>>);

impl Deref for Terminal {
type Target = ratatui::Terminal<CrosstermBackend<Stdout>>;

fn deref(&self) -> &Self::Target {
&self.0
}
}

impl DerefMut for Terminal {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}

impl Terminal {
pub fn init() -> Result<Self> {
crossterm::execute!(stdout(), EnterAlternateScreen, EnableMouseCapture)?;
enable_raw_mode()?;

let backend = CrosstermBackend::new(stdout());

let mut terminal = ratatui::Terminal::new(backend)?;
terminal.hide_cursor()?;

fn panic_hook() {
let original_hook = std::panic::take_hook();

std::panic::set_hook(Box::new(move |panic| {
Terminal::reset().unwrap();
original_hook(panic);
}));
}

panic_hook();

Ok(Self(terminal))
}

pub fn reset() -> Result<()> {
disable_raw_mode()?;
crossterm::execute!(stdout(), LeaveAlternateScreen, DisableMouseCapture)?;

Ok(())
}
}
Loading

0 comments on commit 694a60f

Please sign in to comment.