Skip to main content

nmbrs_tui/
key_watcher.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Stdin keystroke watcher for terminal-mode display.
5//!
6//! Single responsibility: read single keystrokes from stdin and
7//! fire a signal when the operator hits **Ctrl-T**, which the
8//! [supervisor] uses to toggle between
9//! [`crate::log_only_sink::LogOnlySink`] (the line-mode default)
10//! and the full TUI sink.
11//!
12//! [supervisor]: crate::sink_supervisor
13//!
14//! ## Why a separate module
15//!
16//! Stdin can have only one reader at a time. The full TUI app
17//! takes raw-mode stdin while it owns the screen; in terminal
18//! mode the supervisor wants to listen for Ctrl-T without
19//! interfering. Splitting the watcher out lets the supervisor
20//! start it when in terminal mode and drop it (its thread
21//! exits) when handing stdin off to the TUI.
22//!
23//! ## TTY-only
24//!
25//! The watcher refuses to construct itself unless stdin is a
26//! TTY. Piped / CI invocations get [`KeyWatcher::spawn`] returning
27//! `None` and the supervisor degrades to the no-toggle path
28//! (legacy `tui=off`-equivalent rendering, no Ctrl-T sensing).
29//! Same isatty check the runner already uses to pick the
30//! default mode.
31//!
32//! ## Raw-mode coordination
33//!
34//! Crossterm's raw mode is process-global. The watcher enables
35//! raw mode on `start` and disables on `shutdown`. While the
36//! watcher is up, stderr writes need `\r\n` line endings — see
37//! the [`render_line`] helper in [`crate::log_only_sink`] which
38//! handles that.
39//!
40//! [`render_line`]: crate::log_only_sink
41
42use std::io::IsTerminal;
43use std::sync::Arc;
44use std::sync::atomic::{AtomicBool, Ordering};
45use std::sync::mpsc;
46use std::thread::JoinHandle;
47use std::time::Duration;
48
49use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
50
51/// Signals the watcher emits.
52///
53/// `tui=terminal` runs with stdin in raw mode so the watcher
54/// can detect the toggle key (Ctrl-T). Raw mode also disables
55/// the kernel's normal handling of "shell control" keystrokes
56/// — Ctrl-Z, Ctrl-L, Ctrl-C — which would otherwise be
57/// translated to signals or interpreted by the line discipline.
58/// The watcher recognises those keys explicitly and emits a
59/// signal so the supervisor can reproduce the expected
60/// behaviour (suspend, redraw, graceful shutdown) — anything a
61/// user would normally expect from those keys keeps working.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum WatcherSignal {
64    /// Ctrl-T pressed. Supervisor reaction: swap the active
65    /// display sink (terminal ↔ TUI).
66    ToggleTui,
67    /// Ctrl-C pressed. Supervisor reaction: forward as a
68    /// graceful-shutdown to the runtime, same path the
69    /// `session_signals` SIGINT handler triggers.
70    Interrupt,
71    /// Ctrl-Z pressed. Supervisor reaction: disable raw mode,
72    /// raise SIGTSTP, the OS suspends the whole process. On
73    /// resume (`fg`), the supervisor re-enables raw mode and
74    /// the watcher continues. Same UX a cooked-mode shell would
75    /// have given the user.
76    Suspend,
77    /// Ctrl-L pressed. Supervisor reaction: clear the screen
78    /// — the standard "redraw" behaviour for cooked terminals.
79    Redraw,
80    /// Alt+Up pressed. Supervisor reaction: grow the prompt
81    /// window by one row.
82    GrowPrompt,
83    /// Alt+Down pressed. Supervisor reaction: shrink the
84    /// prompt window by one row.
85    ShrinkPrompt,
86    /// Ctrl-/ pressed. Supervisor reaction: toggle the
87    /// prompt's keystroke-help overlay.
88    ToggleHelp,
89    /// `?` pressed. Supervisor reaction: call
90    /// `observer::toggle_explain()` — toggle the explainer
91    /// overlay on (with a 10 s auto-revert deadline) or off
92    /// (if it was already on). Auto-repeat from holding the
93    /// key is swallowed by the toggle's own debounce.
94    ExplainPulse,
95    /// `~` pressed. Supervisor reaction: cycle the REPL
96    /// visibility through Hidden → Bar → Hidden (and Window
97    /// → Hidden if currently Window). Tilde is the universal
98    /// "toggle off" key — pressing it from any visible state
99    /// returns to Hidden. See [`crate::repl_state`] for the
100    /// full state machine.
101    ReplToggleBar,
102    /// Backtick (`` ` ``) pressed. Supervisor reaction: open
103    /// the full-screen REPL window (or close it if already
104    /// open). Chosen instead of `Ctrl-~` because the latter
105    /// proved unreliable across terminals — many terminal
106    /// emulators intercept or fail to deliver the chord. A
107    /// bare key with a single keysym + no modifier dependency
108    /// works uniformly across stock terminals. See
109    /// [`crate::repl_state`] for the full state machine.
110    ReplToggleWindow,
111    /// Any other keypress — printable chars, line-editing
112    /// chords, history nav, Enter, etc. Forwarded to the
113    /// prompt without interpretation. Supervisor receives the
114    /// raw [`crossterm::event::KeyEvent`] inside [`Self::Key`]
115    /// so the `crate::prompt_state::PromptState` can apply
116    /// the same key translation as a terminal-native editor.
117    Key(crossterm::event::KeyEvent),
118}
119
120/// Handle the supervisor holds while the watcher is running.
121/// Dropping (or calling `shutdown`) tears the thread down,
122/// disables raw mode, and stops keystroke delivery.
123pub struct KeyWatcher {
124    stop: Arc<AtomicBool>,
125    join: Option<JoinHandle<()>>,
126}
127
128impl KeyWatcher {
129    /// Spawn the watcher. Returns `None` when stdin is not a
130    /// TTY (piped / CI / backgrounded — no keystrokes possible).
131    /// The signal channel `tx` receives one [`WatcherSignal`]
132    /// per recognised keystroke; the supervisor owns the
133    /// receiver.
134    ///
135    /// On construction, raw mode is enabled on the process
136    /// terminal. Do not call this if another component
137    /// (e.g. an active TUI app) currently owns stdin — use
138    /// the supervisor's start/stop dance instead.
139    pub fn spawn(tx: mpsc::Sender<WatcherSignal>) -> Option<Self> {
140        if !std::io::stdin().is_terminal() {
141            return None;
142        }
143        // Capture the cooked-mode termios *before* flipping to
144        // raw mode, then install the async-signal-safe terminal-
145        // restore handler the App's TerminalGuard already uses.
146        // Without this, a Ctrl-C → graceful-shutdown → second
147        // Ctrl-C → force-exit path leaves the shell in raw mode
148        // because none of the cooperative `Drop` paths get to
149        // run before `std::process::exit`. Both helpers are
150        // idempotent — calling them twice (e.g. terminal mode
151        // with a later toggle to TUI which constructs a real
152        // `TerminalGuard`) is safe.
153        crate::app::save_pretui_termios();
154        crate::app::install_signal_terminal_restore();
155        // Restore the terminal on PANIC too, not just on signals. Without this a
156        // panic during a run (e.g. a kernel coercion failure) prints its message
157        // while the tty is still in raw mode, stair-stepping every line (`\n`
158        // with no `\r`). Idempotent with the full TUI's identical call.
159        crate::app::install_tui_panic_hook();
160        if let Err(e) = crossterm::terminal::enable_raw_mode() {
161            eprintln!("key_watcher: enable_raw_mode failed: {e} — toggle disabled");
162            return None;
163        }
164        let stop = Arc::new(AtomicBool::new(false));
165        let stop_for_thread = stop.clone();
166        let join = std::thread::Builder::new()
167            .name("key-watcher".into())
168            .spawn(move || run_loop(tx, stop_for_thread))
169            .expect("spawn key-watcher thread");
170        Some(Self {
171            stop,
172            join: Some(join),
173        })
174    }
175
176    /// Cooperative stop. Disables raw mode after the polling
177    /// thread exits so subsequent stderr / stdout writes use
178    /// normal line endings again. Idempotent — safe to call
179    /// after the thread has already exited (the second call is
180    /// a no-op).
181    ///
182    /// The join is BOUNDED. The watcher thread can be wedged in
183    /// a kernel `read()` on a tty that will never deliver
184    /// another byte — observed under PTY test harnesses, where
185    /// crossterm's poll reports readiness but the subsequent
186    /// blocking read never returns. A thread stuck in `read()`
187    /// cannot be interrupted portably; waiting on it wedged the
188    /// entire teardown chain (sink-supervisor → run teardown →
189    /// process exit) behind a keystroke that will never come.
190    /// After the grace window the thread is deliberately leaked
191    /// — process exit reaps it.
192    pub fn shutdown(mut self) {
193        self.stop.store(true, Ordering::Release);
194        if let Some(join) = self.join.take() {
195            let deadline = std::time::Instant::now() + Duration::from_millis(500);
196            loop {
197                if join.is_finished() {
198                    let _ = join.join();
199                    break;
200                }
201                if std::time::Instant::now() >= deadline {
202                    // No logging here on purpose: this runs during
203                    // display-plane teardown, when the log sinks may
204                    // already be gone. The leak is silent and benign
205                    // — process exit reaps the thread.
206                    break;
207                }
208                std::thread::sleep(Duration::from_millis(10));
209            }
210        }
211        let _ = crossterm::terminal::disable_raw_mode();
212    }
213}
214
215fn run_loop(tx: mpsc::Sender<WatcherSignal>, stop: Arc<AtomicBool>) {
216    while !stop.load(Ordering::Acquire) {
217        // 100 ms poll cadence: fast enough that a Ctrl-T feels
218        // immediate, slow enough that idle CPU is negligible.
219        //
220        // On error, sleep the same cadence before retrying: a
221        // dead terminal (PTY master closed under a test harness,
222        // hangup on a real tty) makes poll/read fail INSTANTLY,
223        // and a bare `continue` turns this loop into a 100%-CPU
224        // spin for as long as the process lingers.
225        let ready = match event::poll(Duration::from_millis(100)) {
226            Ok(b) => b,
227            Err(_) => {
228                std::thread::sleep(Duration::from_millis(100));
229                continue;
230            }
231        };
232        if !ready {
233            continue;
234        }
235        let evt = match event::read() {
236            Ok(e) => e,
237            Err(_) => {
238                std::thread::sleep(Duration::from_millis(100));
239                continue;
240            }
241        };
242        match evt {
243            Event::Key(k) if k.kind == KeyEventKind::Press => {
244                // Global hotkeys first — these never reach the
245                // prompt because they have process-wide meaning
246                // (interrupt, suspend, redraw, mode toggle,
247                // window resize, help overlay). Everything else
248                // is forwarded as a raw key for the prompt to
249                // interpret with its own keymap.
250                let signal = match (k.code, k.modifiers) {
251                    (KeyCode::Char('t'), m) | (KeyCode::Char('T'), m)
252                        if m.contains(KeyModifiers::CONTROL) =>
253                    {
254                        WatcherSignal::ToggleTui
255                    }
256                    (KeyCode::Char('c'), m) | (KeyCode::Char('C'), m)
257                        if m.contains(KeyModifiers::CONTROL) =>
258                    {
259                        WatcherSignal::Interrupt
260                    }
261                    (KeyCode::Char('z'), m) | (KeyCode::Char('Z'), m)
262                        if m.contains(KeyModifiers::CONTROL) =>
263                    {
264                        WatcherSignal::Suspend
265                    }
266                    (KeyCode::Char('l'), m) | (KeyCode::Char('L'), m)
267                        if m.contains(KeyModifiers::CONTROL) =>
268                    {
269                        WatcherSignal::Redraw
270                    }
271                    (KeyCode::Up, m) if m.contains(KeyModifiers::ALT) => WatcherSignal::GrowPrompt,
272                    (KeyCode::Down, m) if m.contains(KeyModifiers::ALT) => {
273                        WatcherSignal::ShrinkPrompt
274                    }
275                    (KeyCode::Char('/'), m) if m.contains(KeyModifiers::CONTROL) => {
276                        WatcherSignal::ToggleHelp
277                    }
278                    // `?` (no modifier) — explainer-overlay hold.
279                    // Each press / auto-repeat extends the
280                    // deadline; the readout binder reads
281                    // `observer::is_explain_held()` on each
282                    // fire and renders `ContentMode::Explanation`
283                    // while the deadline hasn't passed. Shift
284                    // is implicit on US layouts; we match the
285                    // `?` character regardless of modifier so
286                    // alternate layouts that produce `?`
287                    // without Shift work too.
288                    (KeyCode::Char('?'), _) => WatcherSignal::ExplainPulse,
289                    // `~` toggles the bar (Hidden ↔ Bar,
290                    // collapses Window → Hidden). Auto-repeat-
291                    // safe via the supervisor's debounce.
292                    (KeyCode::Char('~'), _) => WatcherSignal::ReplToggleBar,
293                    // Backtick `` ` `` toggles the full-screen
294                    // REPL window. Picked over `Ctrl-~` because
295                    // terminals deliver the bare chord more
296                    // reliably than the Ctrl-modified one.
297                    (KeyCode::Char('`'), _) => WatcherSignal::ReplToggleWindow,
298                    _ => WatcherSignal::Key(k),
299                };
300                // Supervisor receiver dropped → run is over,
301                // exit the loop cleanly.
302                if tx.send(signal).is_err() {
303                    return;
304                }
305            }
306            _ => {}
307        }
308    }
309}