use std::io::IsTerminal;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::thread::JoinHandle;
use std::time::Duration;
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WatcherSignal {
ToggleTui,
Interrupt,
Suspend,
Redraw,
GrowPrompt,
ShrinkPrompt,
ToggleHelp,
ExplainPulse,
ReplToggleBar,
ReplToggleWindow,
Key(crossterm::event::KeyEvent),
}
pub struct KeyWatcher {
stop: Arc<AtomicBool>,
join: Option<JoinHandle<()>>,
}
impl KeyWatcher {
pub fn spawn(tx: mpsc::Sender<WatcherSignal>) -> Option<Self> {
if !std::io::stdin().is_terminal() {
return None;
}
crate::app::save_pretui_termios();
crate::app::install_signal_terminal_restore();
crate::app::install_tui_panic_hook();
if let Err(e) = crossterm::terminal::enable_raw_mode() {
eprintln!("key_watcher: enable_raw_mode failed: {e} — toggle disabled");
return None;
}
let stop = Arc::new(AtomicBool::new(false));
let stop_for_thread = stop.clone();
let join = std::thread::Builder::new()
.name("key-watcher".into())
.spawn(move || run_loop(tx, stop_for_thread))
.expect("spawn key-watcher thread");
Some(Self {
stop,
join: Some(join),
})
}
pub fn shutdown(mut self) {
self.stop.store(true, Ordering::Release);
if let Some(join) = self.join.take() {
let deadline = std::time::Instant::now() + Duration::from_millis(500);
loop {
if join.is_finished() {
let _ = join.join();
break;
}
if std::time::Instant::now() >= deadline {
break;
}
std::thread::sleep(Duration::from_millis(10));
}
}
let _ = crossterm::terminal::disable_raw_mode();
}
}
fn run_loop(tx: mpsc::Sender<WatcherSignal>, stop: Arc<AtomicBool>) {
while !stop.load(Ordering::Acquire) {
let ready = match event::poll(Duration::from_millis(100)) {
Ok(b) => b,
Err(_) => {
std::thread::sleep(Duration::from_millis(100));
continue;
}
};
if !ready {
continue;
}
let evt = match event::read() {
Ok(e) => e,
Err(_) => {
std::thread::sleep(Duration::from_millis(100));
continue;
}
};
match evt {
Event::Key(k) if k.kind == KeyEventKind::Press => {
let signal = match (k.code, k.modifiers) {
(KeyCode::Char('t'), m) | (KeyCode::Char('T'), m)
if m.contains(KeyModifiers::CONTROL) =>
{
WatcherSignal::ToggleTui
}
(KeyCode::Char('c'), m) | (KeyCode::Char('C'), m)
if m.contains(KeyModifiers::CONTROL) =>
{
WatcherSignal::Interrupt
}
(KeyCode::Char('z'), m) | (KeyCode::Char('Z'), m)
if m.contains(KeyModifiers::CONTROL) =>
{
WatcherSignal::Suspend
}
(KeyCode::Char('l'), m) | (KeyCode::Char('L'), m)
if m.contains(KeyModifiers::CONTROL) =>
{
WatcherSignal::Redraw
}
(KeyCode::Up, m) if m.contains(KeyModifiers::ALT) => WatcherSignal::GrowPrompt,
(KeyCode::Down, m) if m.contains(KeyModifiers::ALT) => {
WatcherSignal::ShrinkPrompt
}
(KeyCode::Char('/'), m) if m.contains(KeyModifiers::CONTROL) => {
WatcherSignal::ToggleHelp
}
(KeyCode::Char('?'), _) => WatcherSignal::ExplainPulse,
(KeyCode::Char('~'), _) => WatcherSignal::ReplToggleBar,
(KeyCode::Char('`'), _) => WatcherSignal::ReplToggleWindow,
_ => WatcherSignal::Key(k),
};
if tx.send(signal).is_err() {
return;
}
}
_ => {}
}
}
}