cgd 0.1.0-alpha.2

Official command-line interface for Coragrid source-linked private-market data infrastructure
Documentation
use std::io::{self, stdout, Stdout};
use std::panic::{self, PanicHookInfo};
use std::sync::{Arc, Mutex};

use crossterm::cursor::{Hide, Show};
use crossterm::event::{
    DisableBracketedPaste, DisableMouseCapture, EnableBracketedPaste, EnableMouseCapture,
};
use crossterm::execute;
use crossterm::terminal::{
    disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
use ratatui::backend::CrosstermBackend;
use ratatui::Terminal;

use crate::error::CgdError;

pub type InteractiveTerminal = Terminal<CrosstermBackend<Stdout>>;
type PanicHook = Box<dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static>;

pub struct TerminalSession {
    terminal: InteractiveTerminal,
    mouse: bool,
    active: bool,
}

impl TerminalSession {
    pub fn enter(mouse: bool) -> Result<Self, CgdError> {
        enable_raw_mode().map_err(CgdError::from)?;
        let mut output = stdout();
        if let Err(error) = execute!(output, EnterAlternateScreen, EnableBracketedPaste, Hide) {
            let _ = disable_raw_mode();
            return Err(CgdError::Io(error));
        }
        if mouse && let Err(error) = execute!(output, EnableMouseCapture) {
            let _ = execute!(output, Show, DisableBracketedPaste, LeaveAlternateScreen);
            let _ = disable_raw_mode();
            return Err(CgdError::Io(error));
        }
        let backend = CrosstermBackend::new(output);
        let terminal = match Terminal::new(backend) {
            Ok(terminal) => terminal,
            Err(error) => {
                emergency_restore(mouse);
                return Err(CgdError::Io(error));
            }
        };
        let mut session = Self {
            terminal,
            mouse,
            active: true,
        };
        if let Err(error) = session.terminal.clear() {
            let _ = session.deactivate();
            return Err(CgdError::Io(error));
        }
        Ok(session)
    }

    pub fn terminal_mut(&mut self) -> &mut InteractiveTerminal {
        &mut self.terminal
    }

    #[cfg(unix)]
    pub fn suspend(&mut self) -> Result<(), CgdError> {
        use nix::sys::signal::{raise, Signal};

        self.deactivate()?;
        if let Err(error) = raise(Signal::SIGSTOP) {
            self.activate()?;
            return Err(CgdError::Io(io::Error::other(error)));
        }
        self.activate()
    }

    fn activate(&mut self) -> Result<(), CgdError> {
        if self.active {
            return Ok(());
        }
        enable_raw_mode().map_err(CgdError::from)?;
        if let Err(error) = execute!(
            self.terminal.backend_mut(),
            EnterAlternateScreen,
            EnableBracketedPaste,
            Hide
        ) {
            let _ = disable_raw_mode();
            return Err(CgdError::Io(error));
        }
        self.active = true;
        if self.mouse
            && let Err(error) = execute!(self.terminal.backend_mut(), EnableMouseCapture)
        {
            let _ = self.deactivate();
            return Err(CgdError::Io(error));
        }
        if let Err(error) = self.terminal.clear() {
            let _ = self.deactivate();
            return Err(CgdError::Io(error));
        }
        Ok(())
    }

    fn deactivate(&mut self) -> Result<(), CgdError> {
        if !self.active {
            return Ok(());
        }
        self.active = false;
        let mut first_error = None;
        if let Err(error) = self.terminal.show_cursor() {
            first_error = Some(error);
        }
        if self.mouse
            && let Err(error) = execute!(self.terminal.backend_mut(), DisableMouseCapture)
            && first_error.is_none()
        {
            first_error = Some(error);
        }
        if let Err(error) = execute!(
            self.terminal.backend_mut(),
            Show,
            DisableBracketedPaste,
            LeaveAlternateScreen
        ) && first_error.is_none()
        {
            first_error = Some(error);
        }
        if let Err(error) = disable_raw_mode()
            && first_error.is_none()
        {
            first_error = Some(error);
        }
        match first_error {
            Some(error) => Err(CgdError::Io(error)),
            None => Ok(()),
        }
    }
}

impl Drop for TerminalSession {
    fn drop(&mut self) {
        let _ = self.deactivate();
    }
}

pub struct PanicRestoreGuard {
    previous: Arc<Mutex<Option<PanicHook>>>,
    mouse: bool,
}

impl PanicRestoreGuard {
    pub fn install(mouse: bool) -> Self {
        let previous = Arc::new(Mutex::new(Some(panic::take_hook())));
        let hook_previous = Arc::clone(&previous);
        panic::set_hook(Box::new(move |information| {
            emergency_restore(mouse);
            if let Ok(previous) = hook_previous.lock()
                && let Some(previous) = previous.as_ref()
            {
                previous(information);
            }
        }));
        Self { previous, mouse }
    }
}

impl Drop for PanicRestoreGuard {
    fn drop(&mut self) {
        let _installed_hook = panic::take_hook();
        if let Ok(mut previous) = self.previous.lock()
            && let Some(previous) = previous.take()
        {
            panic::set_hook(previous);
        }
        // Restore is idempotent and protects initialization failures where the
        // terminal session was only partially constructed.
        emergency_restore(self.mouse);
    }
}

fn emergency_restore(mouse: bool) {
    let mut output = io::stdout();
    if mouse {
        let _ = execute!(output, DisableMouseCapture);
    }
    let _ = execute!(output, Show, DisableBracketedPaste, LeaveAlternateScreen);
    let _ = disable_raw_mode();
}

#[cfg(test)]
mod tests {
    #[cfg(target_os = "linux")]
    #[test]
    fn panic_restores_the_alternate_screen_in_a_pseudo_terminal() {
        use std::io::Write as _;
        use std::process::{Command, Stdio};
        use std::thread;
        use std::time::{Duration, Instant};

        const CHILD_ENV: &str = "CGD_TERMINAL_PANIC_FIXTURE";
        if std::env::var_os(CHILD_ENV).is_some() {
            let _panic_restore = super::PanicRestoreGuard::install(false);
            let _terminal = super::TerminalSession::enter(false).unwrap();
            panic!("injected terminal lifecycle panic");
        }
        if Command::new("script").arg("--version").output().is_err() {
            return;
        }

        let executable = std::env::current_exe().unwrap();
        let executable = executable.to_string_lossy().replace('\'', "'\\''");
        let test_name =
            "tui::terminal::tests::panic_restores_the_alternate_screen_in_a_pseudo_terminal";
        let command_line = format!("'{executable}' --exact '{test_name}' --nocapture");
        let mut child = Command::new("script")
            .args(["-qefc", &command_line, "/dev/null"])
            .env(CHILD_ENV, "1")
            .env("TERM", "xterm-256color")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap();
        thread::sleep(Duration::from_millis(100));
        child.stdin.take().unwrap().write_all(b"\x1b[1;1R").unwrap();

        let deadline = Instant::now() + Duration::from_secs(5);
        while child.try_wait().unwrap().is_none() {
            if Instant::now() >= deadline {
                let _ = child.kill();
                panic!("panic fixture did not exit");
            }
            thread::sleep(Duration::from_millis(25));
        }
        let output = child.wait_with_output().unwrap();
        assert!(
            !output.status.success(),
            "panic fixture unexpectedly passed"
        );

        let enter = output
            .stdout
            .windows(b"\x1b[?1049h".len())
            .position(|window| window == b"\x1b[?1049h")
            .expect("panic fixture did not enter the alternate screen");
        let leave = output
            .stdout
            .windows(b"\x1b[?1049l".len())
            .rposition(|window| window == b"\x1b[?1049l")
            .expect("panic fixture did not leave the alternate screen");
        assert!(leave > enter, "panic restoration preceded terminal entry");
    }
}