use std::io::{self, Stdout};
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use crossterm::{
cursor,
event::{
DisableFocusChange, DisableMouseCapture, EnableFocusChange,
EnableMouseCapture,
},
execute,
style::{Color, SetBackgroundColor, SetForegroundColor},
terminal::{
self, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen,
},
};
static SESSION_ACTIVE: AtomicBool = AtomicBool::new(false);
static SESSION_COLORS: Mutex<Option<SessionColors>> = Mutex::new(None);
fn remember_colors(colors: Option<SessionColors>) {
if let Ok(mut slot) = SESSION_COLORS.lock() {
*slot = colors;
}
}
fn take_remembered_colors() -> Option<SessionColors> {
match SESSION_COLORS.lock() {
Ok(mut slot) => slot.take(),
Err(poisoned) => poisoned.into_inner().take(),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SessionColors {
pub background: Color,
pub foreground: Color,
}
impl Default for SessionColors {
fn default() -> Self {
Self {
background: Color::Reset,
foreground: Color::Reset,
}
}
}
impl SessionColors {
pub fn is_default(&self) -> bool {
self.background == Color::Reset && self.foreground == Color::Reset
}
}
pub struct TerminalSession {
stdout: Stdout,
mouse_capture: bool,
active: bool,
}
impl TerminalSession {
pub fn enter() -> io::Result<Self> {
Self::enter_with(SessionColors::default())
}
pub fn enter_with(colors: SessionColors) -> io::Result<Self> {
let mut stdout = io::stdout();
terminal::enable_raw_mode()?;
let entered = execute!(
stdout,
EnterAlternateScreen,
cursor::Hide,
Clear(ClearType::All),
EnableFocusChange
);
if let Err(error) = entered.and_then(|()| {
if colors.is_default() {
return Ok(());
}
execute!(
stdout,
SetForegroundColor(colors.foreground),
SetBackgroundColor(colors.background),
)
}) {
let _ = execute!(
stdout,
cursor::Show,
Clear(ClearType::All),
DisableFocusChange,
LeaveAlternateScreen,
);
let _ = terminal::disable_raw_mode();
return Err(error);
}
SESSION_ACTIVE.store(true, Ordering::SeqCst);
remember_colors((!colors.is_default()).then_some(colors));
Ok(Self {
stdout,
mouse_capture: false,
active: true,
})
}
pub fn stdout(&mut self) -> &mut Stdout {
&mut self.stdout
}
pub fn enable_mouse(&mut self) -> io::Result<()> {
self.mouse_capture = true;
execute!(self.stdout, EnableMouseCapture)
}
pub fn restore(&mut self) {
if !self.active {
return;
}
self.active = false;
SESSION_ACTIVE.store(false, Ordering::SeqCst);
if self.mouse_capture {
let _ = execute!(self.stdout, DisableMouseCapture);
}
if take_remembered_colors().is_some() {
let _ = execute!(
self.stdout,
SetForegroundColor(Color::Reset),
SetBackgroundColor(Color::Reset),
);
}
let _ = execute!(
self.stdout,
cursor::Show,
Clear(ClearType::All),
DisableFocusChange,
LeaveAlternateScreen,
);
let _ = terminal::disable_raw_mode();
}
}
impl Drop for TerminalSession {
fn drop(&mut self) {
self.restore();
}
}
pub fn install_panic_hook() {
let previous = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
restore_terminal();
previous(info);
}));
}
pub fn restore_terminal() {
if !SESSION_ACTIVE.swap(false, Ordering::SeqCst) {
return;
}
let mut stdout = io::stdout();
if take_remembered_colors().is_some() {
let _ = execute!(
stdout,
SetForegroundColor(Color::Reset),
SetBackgroundColor(Color::Reset),
);
}
let _ = execute!(
stdout,
DisableMouseCapture,
DisableFocusChange,
cursor::Show,
Clear(ClearType::All),
LeaveAlternateScreen,
);
let _ = terminal::disable_raw_mode();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn restoring_without_a_session_is_a_no_op() {
assert!(!SESSION_ACTIVE.load(Ordering::SeqCst));
restore_terminal();
assert!(!SESSION_ACTIVE.load(Ordering::SeqCst));
}
#[test]
fn the_hook_can_be_installed_more_than_once() {
install_panic_hook();
install_panic_hook();
restore_terminal();
}
static GLOBAL_STATE: Mutex<()> = Mutex::new(());
fn global_state() -> std::sync::MutexGuard<'static, ()> {
GLOBAL_STATE.lock().unwrap_or_else(|e| e.into_inner())
}
#[test]
fn the_default_colours_emit_nothing_at_all() {
assert!(SessionColors::default().is_default());
}
#[test]
fn pinning_either_end_counts_as_pinning() {
let only_background = SessionColors {
background: Color::Black,
foreground: Color::Reset,
};
let only_foreground = SessionColors {
background: Color::Reset,
foreground: Color::Rgb {
r: 0xcc,
g: 0xcc,
b: 0xdd,
},
};
assert!(!only_background.is_default());
assert!(!only_foreground.is_default());
}
#[test]
fn remembered_colours_are_taken_exactly_once() {
let _guard = global_state();
remember_colors(Some(SessionColors {
background: Color::Black,
foreground: Color::Reset,
}));
assert!(take_remembered_colors().is_some());
assert!(take_remembered_colors().is_none());
}
#[test]
fn forgetting_the_colours_leaves_nothing_to_restore() {
let _guard = global_state();
remember_colors(None);
assert!(take_remembered_colors().is_none());
}
}