capy-cli 0.7.2

The command-line interface for the Capy web framework.
Documentation
use crossterm::{
    cursor::Show,
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{backend::CrosstermBackend, Terminal};
use std::{
    io::{self, Stdout},
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
};

type PanicHook = Box<dyn Fn(&std::panic::PanicHookInfo<'_>) + Send + Sync + 'static>;

pub struct Session {
    pub terminal: Terminal<CrosstermBackend<Stdout>>,
    guard: Guard,
}
struct Guard {
    active: Arc<AtomicBool>,
    hook: Option<Arc<PanicHook>>,
}
fn restore(active: &AtomicBool) {
    if active.swap(false, Ordering::SeqCst) {
        let _ = disable_raw_mode();
        let _ = execute!(io::stdout(), LeaveAlternateScreen, Show);
    }
}
impl Session {
    pub fn new() -> io::Result<Self> {
        let active = Arc::new(AtomicBool::new(true));
        let mut guard = Guard {
            active: active.clone(),
            hook: None,
        };
        enable_raw_mode()?;
        execute!(io::stdout(), EnterAlternateScreen)?;
        let previous = Arc::new(std::panic::take_hook());
        let hook = previous.clone();
        std::panic::set_hook(Box::new(move |info| {
            restore(&active);
            hook(info);
        }));
        guard.hook = Some(previous);
        let terminal = Terminal::new(CrosstermBackend::new(io::stdout()))?;
        Ok(Self { terminal, guard })
    }
}
impl Drop for Session {
    fn drop(&mut self) {
        restore(&self.guard.active);
    }
}
impl Drop for Guard {
    fn drop(&mut self) {
        restore(&self.active);
        if !std::thread::panicking() {
            if let Some(previous) = self.hook.take() {
                drop(std::panic::take_hook());
                if let Ok(previous) = Arc::try_unwrap(previous) {
                    std::panic::set_hook(previous);
                }
            }
        }
    }
}