bath 0.6.0

A TUI tool to manage and export environment variable profiles
use crate::tui::input::{self, Action};
use crate::tui::state::AppState;
use crate::tui::ui;
use crate::tui::util::{self, Input};
use anyhow::Result;
use crossterm::event::{DisableBracketedPaste, EnableBracketedPaste};
use crossterm::execute;
use crossterm::terminal::{
    disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
use ratatui::backend::CrosstermBackend;
use ratatui::Terminal;
use std::io::{stdout, Stdout, Write};

type Tui = Terminal<CrosstermBackend<Stdout>>;

/// Restores the terminal before the previous panic hook runs, so a panic
/// leaves a usable shell.
fn install_panic_hook() {
    let previous = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        let _ = restore_terminal();
        previous(info);
    }));
}

/// Best-effort restore: every step runs even when an earlier one fails, and
/// the first error is reported afterwards.
fn restore_terminal() -> Result<()> {
    let raw = disable_raw_mode();
    let screen = execute!(
        stdout(),
        DisableBracketedPaste,
        LeaveAlternateScreen,
        crossterm::cursor::Show
    );
    raw?;
    screen?;
    Ok(())
}

pub fn run() -> Result<()> {
    install_panic_hook();
    enable_raw_mode()?;
    if let Err(e) = execute!(stdout(), EnterAlternateScreen, EnableBracketedPaste) {
        let _ = restore_terminal();
        return Err(e.into());
    }
    let mut terminal = match Terminal::new(CrosstermBackend::new(stdout())) {
        Ok(terminal) => terminal,
        Err(e) => {
            let _ = restore_terminal();
            return Err(e.into());
        }
    };
    let result = run_event_loop(&mut terminal);
    let restored = restore_terminal();
    result.and(restored)
}

fn run_event_loop(terminal: &mut Tui) -> Result<()> {
    let mut app = AppState::new()?;
    loop {
        terminal.draw(|f| ui::draw(f, &mut app))?;
        let Some(event) = util::next_input(std::time::Duration::from_millis(200))? else {
            continue;
        };
        let action = match event {
            Input::Key(key) => input::handle_key(&mut app, key)?,
            Input::Paste(text) => {
                input::handle_paste(&mut app, &text);
                Action::None
            }
        };
        match action {
            Action::None => {}
            Action::Quit => return Ok(()),
            Action::Copy(text) => {
                let mut out = stdout();
                out.write_all(util::osc52(&text).as_bytes())?;
                out.flush()?;
            }
        }
    }
}