Guide API
Skip to main content

tvision_rs/backend/
crossterm_backend.rs

1//! `CrosstermBackend`, the production terminal backend (documented on the type).
2
3use std::io::{self, Stdout, Write as _};
4use std::time::Duration;
5
6use crossterm::{
7    cursor::{Hide, MoveTo, SetCursorStyle, Show},
8    event::{
9        self, DisableBracketedPaste, DisableMouseCapture, EnableBracketedPaste, EnableMouseCapture,
10        KeyCode, KeyEventKind, KeyModifiers as CKeyModifiers, MouseEventKind,
11    },
12    execute, queue,
13    style::{Attribute, Color as CColor, Colors, Print, ResetColor, SetAttribute, SetColors},
14    terminal::{
15        BeginSynchronizedUpdate, EndSynchronizedUpdate, EnterAlternateScreen, LeaveAlternateScreen,
16        disable_raw_mode, enable_raw_mode,
17    },
18};
19
20use crate::backend::clipboard::ClipboardChain;
21use crate::backend::{Backend, bios_to_xterm16, rgb_to_xterm256, xterm256_to_xterm16};
22use crate::color::{Color, Style};
23use crate::event::{
24    Event, Key, KeyEvent, KeyModifiers, MouseButtons, MouseEvent, MouseEventFlags, MouseWheel,
25};
26use crate::screen::Cell;
27use crate::view::Point;
28
29// ---------------------------------------------------------------------------
30// ColorDepth
31// ---------------------------------------------------------------------------
32
33/// Terminal color capability level.
34///
35/// Controls which rung of the quantization ladder is used when mapping
36/// `Color` values to crossterm colors.
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
38pub enum ColorDepth {
39    /// 24-bit true color.  `Color::Rgb` is passed through unchanged.
40    #[default]
41    TrueColor,
42    /// xterm-256 palette.  `Color::Rgb` is quantized to the nearest cube/gray entry.
43    Xterm256,
44    /// ANSI 16 colors.  All RGB and indexed colors are reduced to the 16-color set.
45    Ansi16,
46    /// No color.  All colors map to the terminal default (reset).
47    NoColor,
48}
49
50// ---------------------------------------------------------------------------
51// CrosstermBackend
52// ---------------------------------------------------------------------------
53
54/// Production backend backed by crossterm.
55///
56/// Crossterm backend — the production terminal implementation.
57///
58/// Wraps `crossterm` for terminal I/O behind the [`Backend`] trait.
59///
60/// This backend is the production path.  It does not run in CI (no TTY), but it
61/// must compile and be correct/reasonable.
62///
63/// ## Terminal lifecycle (RAII)
64/// `CrosstermBackend::new()` performs the full terminal setup — raw mode,
65/// alternate screen, mouse capture — at construction; `Drop` restores the
66/// terminal (best-effort, errors ignored), so a tvision-rs program never hand-rolls
67/// terminal setup.
68///
69/// Two process-global hooks (installed once, on the first construction) keep
70/// the user's terminal usable when the program does not exit normally:
71///
72/// * a **panic hook** that restores the terminal before delegating to the
73///   previous hook — so the panic message prints on the normal screen, and a
74///   crashed TUI app leaves the shell sane;
75/// * (unix) a **signal thread** that restores the terminal on `SIGINT`,
76///   `SIGTERM`, or `SIGHUP` and exits with status `128 + signal_number` (the
77///   shell convention: 130 for SIGINT, 143 for SIGTERM, 129 for SIGHUP).
78///   Signals are handled on a dedicated thread — not in an async-signal
79///   context — so calling into crossterm is sound. (`SIGKILL` is uncatchable;
80///   a `kill -9` still leaves the terminal dirty — run `reset` to recover.)
81///
82/// The restore sequence is idempotent, so Drop, the panic hook, and the signal
83/// thread may each run it without harm. Both hooks persist for the process
84/// lifetime (a later restore on an already-restored terminal is a no-op).
85///
86/// ## Clipboard
87/// The clipboard is the `ClipboardChain` (see `backend::clipboard`):
88///
89/// - **Copy** (`set_clipboard`): OS-native via arboard (`os-clipboard`
90///   feature, on by default) → OSC 52 escape sequence queued on the normal
91///   output handle (delivered by the next `flush`) → internal string buffer.
92///   Returns `true` only on the native rung (trait contract: `false` = fell
93///   back to internal).
94/// - **Paste** (`get_clipboard`): OS-native → internal buffer → `None`.
95///   There is no OSC 52 *read* rung — the capability probes it needs require
96///   owning the input parser, which crossterm (not tvision-rs) owns.
97///
98/// **SSH story:** with no display, arboard init fails and the chain runs
99/// without its native rung — but the OSC 52 emit still reaches the *local*
100/// terminal's clipboard on copy, which is exactly what a remote TUI wants.
101/// Paste over SSH falls back to the internal buffer (copies made inside the
102/// app) or the terminal's own bracketed paste, which arrives as
103/// [`Event::Paste`](crate::event::Event::Paste).
104///
105/// ## Color depth
106/// `ColorDepth` selects which rung of the quantization ladder to use when
107/// mapping our `Color` enum to crossterm colors.
108///
109/// ## Key/event translation
110/// `crossterm::event::Event` is translated to our `Event` enum.  Only
111/// `KeyEventKind::Press` and `Repeat` are translated; `Release` is ignored.
112///
113/// Construct with [`CrosstermBackend::new`].  Construction performs the full
114/// terminal setup (raw mode, alternate screen, mouse capture) and `Drop`
115/// restores the terminal; see *Terminal lifecycle (RAII)* above.
116///
117/// # Turbo Vision heritage
118///
119/// Replaces the platform driver behind `TScreen` / `THardwareInfo` and the Unix
120/// terminal I/O of `unixcon.cpp` / `termio.cpp` with a crossterm-backed
121/// [`Backend`]. Terminal setup that the original did in the application
122/// constructor chain is RAII here: construction sets the terminal up, `Drop` tears
123/// it down.
124///
125/// The production realization of the [`Backend`] seam.
126///
127/// **tvision-rs extension**: each frame is wrapped in synchronized output (DEC
128/// private mode 2026), so a terminal that supports it shows the frame whole
129/// instead of repainting it part-way. magiblot's terminal driver does not use
130/// the mode.
131pub struct CrosstermBackend {
132    out: Stdout,
133    color_depth: ColorDepth,
134    clipboard: ClipboardChain,
135    /// The caret size last sent to the terminal; `None` until the first one,
136    /// and again after a resume (the restore reset the terminal's shape).
137    caret_size: Option<u8>,
138}
139
140/// Undo the terminal setup: restore the user's caret shape, disable mouse
141/// capture, leave the alternate screen, disable raw mode.  Best-effort and
142/// idempotent — safe to call more than once
143/// (`Drop`, the panic hook, and the signal thread may each run it).
144fn restore_terminal() {
145    let _ = execute!(
146        io::stdout(),
147        SetCursorStyle::DefaultUserShape,
148        DisableBracketedPaste,
149        DisableMouseCapture,
150        LeaveAlternateScreen
151    );
152    let _ = disable_raw_mode();
153}
154
155/// Install the process-global restore hooks: the panic hook (always) and the
156/// unix signal thread, no matter how many backends are constructed.
157///
158/// **What `Ok(())` guarantees:** the panic hook is installed **and** (on
159/// unix) the signal-restore thread is running.  The two are latched
160/// separately:
161///
162/// * the panic-hook install is infallible, so it uses a plain
163///   [`Once`](std::sync::Once);
164/// * the signal-thread setup can fail (`Signals::new`), so it latches
165///   **success-only** (see [`start_signal_thread`]): a transient first
166///   failure is retried on the next construction, and a consistent failure
167///   keeps returning the real `Err` instead of silently reporting `Ok`
168///   without a signal thread.
169///
170/// The panic hook restores the terminal *before* delegating to the previous
171/// hook, so the panic message prints on the normal screen.
172fn install_restore_hooks() -> io::Result<()> {
173    use std::sync::Once;
174    static PANIC_HOOK: Once = Once::new();
175
176    PANIC_HOOK.call_once(|| {
177        let prev = std::panic::take_hook();
178        std::panic::set_hook(Box::new(move |info| {
179            restore_terminal();
180            prev(info);
181        }));
182    });
183
184    #[cfg(unix)]
185    start_signal_thread()?;
186
187    Ok(())
188}
189
190/// Start the unix signal-restore thread, at most once per process
191/// (success-only latching — see [`install_restore_hooks`]).
192///
193/// The thread waits for `SIGINT`/`SIGTERM`/`SIGHUP`, restores the terminal,
194/// and exits with status `128 + signal_number` — the shell convention (130
195/// for SIGINT, 143 for SIGTERM, 129 for SIGHUP).  `Drop` does not run on
196/// `process::exit`, but the terminal has already been restored.
197///
198/// The latch is a `Mutex<bool>` rather than an atomic: the lock is held
199/// across `Signals::new` + spawn, so two backends constructed concurrently
200/// cannot both spawn a thread (an `AtomicBool` checked before the fallible
201/// registration would permit a benign but pointless double-spawn).  This is
202/// cold-path construction code — the lock cost is irrelevant.
203#[cfg(unix)]
204fn start_signal_thread() -> io::Result<()> {
205    use signal_hook::consts::{SIGHUP, SIGINT, SIGTERM};
206    use signal_hook::iterator::Signals;
207    use std::sync::Mutex;
208
209    static STARTED: Mutex<bool> = Mutex::new(false);
210    let mut started = STARTED.lock().unwrap_or_else(|e| e.into_inner());
211    if *started {
212        return Ok(());
213    }
214
215    let mut signals = Signals::new([SIGINT, SIGTERM, SIGHUP])?;
216    std::thread::spawn(move || {
217        if let Some(signum) = signals.forever().next() {
218            restore_terminal();
219            // `128 + signum` is the shell convention for death-by-signal
220            // (130 SIGINT, 143 SIGTERM, 129 SIGHUP).
221            std::process::exit(128 + signum);
222        }
223    });
224    *started = true;
225    Ok(())
226}
227
228impl CrosstermBackend {
229    /// Construct a `CrosstermBackend` writing to stdout, performing the full
230    /// terminal setup: enable raw mode, enter the alternate screen, enable
231    /// mouse capture.  Also installs the process-global restore hooks (panic
232    /// hook + unix signal thread) on first use.
233    ///
234    /// On error the partial setup is rolled back before returning.  The
235    /// terminal is restored when the backend is dropped.
236    ///
237    /// # Note
238    /// See the single-instance contract on [`CrosstermBackend::with_color_depth`].
239    pub fn new() -> io::Result<Self> {
240        Self::with_color_depth(ColorDepth::TrueColor)
241    }
242
243    /// Construct with an explicit color depth (useful when the caller has
244    /// already detected terminal capabilities).  Performs the same terminal
245    /// setup as [`CrosstermBackend::new`].
246    ///
247    /// # Note
248    /// At most one `CrosstermBackend` should be live per process.  A second
249    /// instance re-enters the alternate screen (terminal-dependent visual
250    /// corruption); the `Drop` teardown is idempotent and harmless on its
251    /// own, but two instances with different lifetimes can leave the
252    /// terminal stuck in the alternate screen (the first drop restores the
253    /// terminal out from under the still-live instance).
254    pub fn with_color_depth(depth: ColorDepth) -> io::Result<Self> {
255        enable_raw_mode()?;
256        if let Err(e) = execute!(
257            io::stdout(),
258            EnterAlternateScreen,
259            EnableMouseCapture,
260            EnableBracketedPaste
261        ) {
262            // Full restore, not just disable_raw_mode(): on the Windows-<10
263            // WinAPI fallback crossterm executes the two commands one by one,
264            // so EnterAlternateScreen may have succeeded before
265            // EnableMouseCapture failed.  restore_terminal() is idempotent
266            // and undoes everything in reverse order.
267            restore_terminal();
268            return Err(e);
269        }
270        if let Err(e) = install_restore_hooks() {
271            restore_terminal();
272            return Err(e);
273        }
274        Ok(CrosstermBackend {
275            out: io::stdout(),
276            color_depth: depth,
277            // Constructed after the terminal setup succeeded; arboard init
278            // failure is swallowed inside (clipboard absence must not fail
279            // backend construction).
280            clipboard: ClipboardChain::with_os_native(),
281            caret_size: None,
282        })
283    }
284}
285
286impl Drop for CrosstermBackend {
287    /// Restore the terminal (best-effort; errors during drop are ignored).
288    fn drop(&mut self) {
289        restore_terminal();
290    }
291}
292
293impl Backend for CrosstermBackend {
294    fn size(&self) -> (u16, u16) {
295        crossterm::terminal::size().unwrap_or((80, 25))
296    }
297
298    fn draw(&mut self, content: &[(u16, u16, &Cell)]) {
299        // Begin a synchronized frame (DEC private mode 2026). The renderer
300        // calls `draw` → `set_cursor` → `flush` once per frame, so this brackets
301        // the whole frame with the matching `EndSynchronizedUpdate` in `flush`.
302        //
303        // GPU terminals (kitty/WezTerm/Alacritty) apply our per-cell writes
304        // incrementally and repaint mid-frame, so a fast-moving frame tears: a
305        // partial render leaves a glyph fragment ("ghost") behind a moving
306        // window/sprite, and because the diff treats that cell as unchanged on
307        // the next frame it is never repainted — the ghost persists until
308        // something else happens to overwrite that cell. Mode 2026 makes the
309        // terminal buffer the frame and present it atomically, eliminating the
310        // tear. Terminals that don't support it ignore the unknown private mode
311        // (so it's a no-op on VTE terminals such as mate-terminal, gnome-terminal).
312        let _ = queue!(self.out, BeginSynchronizedUpdate);
313        for &(x, y, cell) in content {
314            // Skip wide-glyph trail cells — the terminal advances automatically
315            // when the lead cell is printed.
316            if cell.is_wide_trail() {
317                continue;
318            }
319
320            let style = cell.style();
321            let colors = map_colors(style, self.color_depth);
322            let attrs = map_attributes(style);
323
324            // Reset attributes first, then apply the cell's style.
325            let _ = queue!(self.out, MoveTo(x, y), ResetColor, SetColors(colors),);
326            for attr in attrs {
327                let _ = queue!(self.out, SetAttribute(attr));
328            }
329            let _ = queue!(self.out, Print(cell.symbol()));
330        }
331    }
332
333    fn flush(&mut self) {
334        // End the synchronized frame opened in `draw` (DEC mode 2026), then
335        // flush the buffered bytes so the terminal presents the frame atomically.
336        // An unmatched end (if `flush` is ever called without a preceding `draw`)
337        // is harmless — the terminal ignores it.
338        let _ = queue!(self.out, EndSynchronizedUpdate);
339        let _ = self.out.flush();
340    }
341
342    fn set_cursor(&mut self, pos: Option<(u16, u16)>) {
343        match pos {
344            Some((x, y)) => {
345                let _ = queue!(self.out, MoveTo(x, y), Show);
346            }
347            None => {
348                let _ = queue!(self.out, Hide);
349            }
350        }
351    }
352
353    /// Map the caret size onto a terminal cursor style, as the terminal
354    /// platform layer of the original does: the full-cell caret (100) is made
355    /// "very visible" — here a blinking block — and every other size keeps the
356    /// terminal's own caret shape. Sent only when the size changes.
357    ///
358    /// # Turbo Vision heritage
359    /// Ports `NcursesDisplay::setCaretSize` (`ncurdisp.cpp:86-97`):
360    /// `curs_set(size == 100 ? 2 : 1)`, where `1` is the terminal's normal
361    /// caret. ncurses' "very visible" (terminfo `cvvis`) varies by terminal;
362    /// a block is the portable way to show it. `DisplayBuffer::flushScreen`
363    /// (`dispbuff.cpp:220-221`) likewise calls `setCaretSize` only on change.
364    fn set_caret_size(&mut self, size: u8) {
365        if self.caret_size == Some(size) {
366            return;
367        }
368        self.caret_size = Some(size);
369        let style = if size == crate::backend::CARET_INSERT {
370            SetCursorStyle::BlinkingBlock
371        } else {
372            SetCursorStyle::DefaultUserShape
373        };
374        let _ = queue!(self.out, style);
375    }
376
377    fn poll_event(&mut self, timeout: Option<Duration>) -> Option<Event> {
378        let timeout = timeout.unwrap_or(Duration::MAX);
379        if event::poll(timeout).ok()? {
380            translate_event(event::read().ok()?)
381        } else {
382            None
383        }
384    }
385
386    /// Run the copy chain (see *Clipboard* in the [`CrosstermBackend`] docs): native → OSC 52 →
387    /// internal. The OSC sequence is queued on the normal output handle and
388    /// delivered by the next `flush` (every pump iteration flushes).
389    fn set_clipboard(&mut self, text: &str) -> bool {
390        self.clipboard.set(text, &mut self.out)
391    }
392
393    /// Run the paste chain: native → internal buffer → `None`.
394    fn get_clipboard(&mut self) -> Option<String> {
395        self.clipboard.get()
396    }
397
398    /// Read the PRIMARY selection — native rung only (see the trait docs).
399    fn get_primary(&mut self) -> Option<String> {
400        self.clipboard.get_primary()
401    }
402
403    /// Own the PRIMARY selection — native rung only (see the trait docs).
404    fn set_primary(&mut self, text: &str) -> bool {
405        self.clipboard.set_primary(text)
406    }
407
408    fn suspend(&mut self) {
409        restore_terminal(); // idempotent teardown (already used in Drop)
410    }
411
412    fn resume(&mut self) {
413        // Best-effort re-setup — mirror the setup in with_color_depth but skip
414        // hook installation (already done once-per-process in the constructor).
415        // The suspend restored the user's caret shape; re-send ours next frame.
416        self.caret_size = None;
417        let _ = enable_raw_mode();
418        let _ = execute!(
419            self.out,
420            EnterAlternateScreen,
421            EnableMouseCapture,
422            EnableBracketedPaste
423        );
424    }
425}
426
427// ---------------------------------------------------------------------------
428// Color mapping helpers
429// ---------------------------------------------------------------------------
430
431/// Map a `Style`'s fg/bg to a crossterm `Colors`, applying the quantization
432/// ladder at the appropriate depth.
433fn map_colors(style: Style, depth: ColorDepth) -> Colors {
434    Colors {
435        foreground: Some(map_color(style.fg, depth)),
436        background: Some(map_color(style.bg, depth)),
437    }
438}
439
440/// Map a single `Color` to a `crossterm::style::Color` at the given depth.
441///
442/// The mapping is:
443/// - `Color::Default` → `CColor::Reset` (always, regardless of depth).
444/// - `Color::Rgb(r,g,b)`:
445///   - TrueColor → `CColor::Rgb{r,g,b}` (passthrough).
446///   - Xterm256  → `CColor::AnsiValue(rgb_to_xterm256(r,g,b))`.
447///   - Ansi16    → 16-color via `rgb_to_xterm16`.
448///   - NoColor   → `CColor::Reset`.
449/// - `Color::Indexed(n)`:
450///   - TrueColor/Xterm256 → `CColor::AnsiValue(n)`.
451///   - Ansi16             → `CColor::AnsiValue(xterm256_to_xterm16(n))`.
452///   - NoColor            → `CColor::Reset`.
453/// - `Color::Bios(n)`:
454///   4-bit BIOS index (bit0=blue, bit1=green, bit2=red, bit3=bright).
455///   Convert to xterm-16 via `bios_to_xterm16(n & 0xF)`, then to a crossterm
456///   16-color variant via `xterm16_to_crossterm`.
457fn map_color(color: Color, depth: ColorDepth) -> CColor {
458    match color {
459        Color::Default => CColor::Reset,
460
461        Color::Rgb(r, g, b) => match depth {
462            ColorDepth::TrueColor => CColor::Rgb { r, g, b },
463            ColorDepth::Xterm256 => CColor::AnsiValue(rgb_to_xterm256(r, g, b)),
464            ColorDepth::Ansi16 => xterm16_to_crossterm(crate::backend::rgb_to_xterm16(r, g, b)),
465            ColorDepth::NoColor => CColor::Reset,
466        },
467
468        Color::Indexed(n) => match depth {
469            ColorDepth::TrueColor | ColorDepth::Xterm256 => CColor::AnsiValue(n),
470            ColorDepth::Ansi16 => CColor::AnsiValue(xterm256_to_xterm16(n)),
471            ColorDepth::NoColor => CColor::Reset,
472        },
473
474        Color::Bios(n) => {
475            // BIOS 4-bit index: mask to 0..=15, then bit-swap to xterm-16 order.
476            let xt16 = bios_to_xterm16(n & 0xF);
477            match depth {
478                ColorDepth::NoColor => CColor::Reset,
479                _ => xterm16_to_crossterm(xt16),
480            }
481        }
482    }
483}
484
485/// Map an xterm-16 index (0..=15) to a `crossterm::style::Color` named-color variant.
486///
487/// xterm-16 layout: bit0=red, bit1=green, bit2=blue, bit3=bright.
488///
489/// ```text
490///  0 = Black          8 = DarkGrey
491///  1 = DarkRed        9 = Red
492///  2 = DarkGreen     10 = Green
493///  3 = DarkYellow    11 = Yellow
494///  4 = DarkBlue      12 = Blue
495///  5 = DarkMagenta   13 = Magenta
496///  6 = DarkCyan      14 = Cyan
497///  7 = Grey          15 = White
498/// ```
499fn xterm16_to_crossterm(idx: u8) -> CColor {
500    match idx & 0xF {
501        0 => CColor::Black,
502        1 => CColor::DarkRed,
503        2 => CColor::DarkGreen,
504        3 => CColor::DarkYellow,
505        4 => CColor::DarkBlue,
506        5 => CColor::DarkMagenta,
507        6 => CColor::DarkCyan,
508        7 => CColor::Grey,
509        8 => CColor::DarkGrey,
510        9 => CColor::Red,
511        10 => CColor::Green,
512        11 => CColor::Yellow,
513        12 => CColor::Blue,
514        13 => CColor::Magenta,
515        14 => CColor::Cyan,
516        15 => CColor::White,
517        _ => unreachable!("masked to 0..=15"),
518    }
519}
520
521/// Map `Style` modifiers to crossterm `Attribute`s.
522///
523/// `no_shadow` is an internal tvision-rs marker with no crossterm equivalent;
524/// it is silently ignored here.
525fn map_attributes(style: Style) -> Vec<Attribute> {
526    let m = style.modifiers;
527    let mut attrs = Vec::new();
528    if m.bold {
529        attrs.push(Attribute::Bold);
530    }
531    if m.italic {
532        attrs.push(Attribute::Italic);
533    }
534    if m.underline {
535        attrs.push(Attribute::Underlined);
536    }
537    if m.blink {
538        attrs.push(Attribute::SlowBlink);
539    }
540    if m.reverse {
541        attrs.push(Attribute::Reverse);
542    }
543    if m.strike {
544        attrs.push(Attribute::CrossedOut);
545    }
546    // m.no_shadow: internal marker, no crossterm equivalent — ignored.
547    attrs
548}
549
550// ---------------------------------------------------------------------------
551// Event translation
552// ---------------------------------------------------------------------------
553
554/// Translate a `crossterm::event::Event` to our `Event`.
555///
556/// Returns `None` for events with no `Event` counterpart: resize (handled by
557/// polling `backend.size()` in the pump) and terminal focus changes.
558fn translate_event(ev: crossterm::event::Event) -> Option<Event> {
559    match ev {
560        crossterm::event::Event::Key(k) => translate_key(k),
561        crossterm::event::Event::Mouse(m) => translate_mouse(m),
562        crossterm::event::Event::Resize(_, _) => {
563            // Resize is handled without an Event variant — the pump
564            // (`Program::pump_once`) polls `backend.size()` each iteration and
565            // calls `renderer.resize` + `group.change_bounds` on change. This
566            // is the equivalent of `setScreenMode`/`cmScreenChanged`, done by
567            // polling rather than via an `Event::Resize` variant (avoids enum
568            // churn).
569            None
570        }
571        crossterm::event::Event::Paste(text) => Some(Event::Paste(text)),
572        crossterm::event::Event::FocusGained | crossterm::event::Event::FocusLost => {
573            // Terminal focus-gained/lost has no Turbo Vision counterpart, so
574            // there is no `Event` variant for it — these are dropped.
575            None
576        }
577    }
578}
579
580/// Translate a crossterm `KeyEvent` to our `Event::KeyDown`.
581///
582/// Only `Press` and `Repeat` kinds are translated; `Release` is ignored.
583fn translate_key(k: crossterm::event::KeyEvent) -> Option<Event> {
584    match k.kind {
585        KeyEventKind::Press | KeyEventKind::Repeat => {}
586        KeyEventKind::Release => return None,
587    }
588
589    let key = translate_key_code(k.code)?;
590    let mut modifiers = translate_modifiers(k.modifiers);
591
592    // crossterm reports BackTab as a separate code; normalize to Tab + shift.
593    if k.code == KeyCode::BackTab {
594        modifiers.shift = true;
595    }
596
597    Some(Event::KeyDown(KeyEvent::new(key, modifiers)))
598}
599
600/// Translate a crossterm `KeyCode` to our `Key`.
601fn translate_key_code(code: KeyCode) -> Option<Key> {
602    match code {
603        KeyCode::Char(c) => Some(Key::Char(c)),
604        KeyCode::F(n) => Some(Key::F(n)),
605        KeyCode::Enter => Some(Key::Enter),
606        KeyCode::Esc => Some(Key::Esc),
607        KeyCode::Backspace => Some(Key::Backspace),
608        KeyCode::Tab | KeyCode::BackTab => Some(Key::Tab),
609        KeyCode::Up => Some(Key::Up),
610        KeyCode::Down => Some(Key::Down),
611        KeyCode::Left => Some(Key::Left),
612        KeyCode::Right => Some(Key::Right),
613        KeyCode::Home => Some(Key::Home),
614        KeyCode::End => Some(Key::End),
615        KeyCode::PageUp => Some(Key::PageUp),
616        KeyCode::PageDown => Some(Key::PageDown),
617        KeyCode::Insert => Some(Key::Insert),
618        KeyCode::Delete => Some(Key::Delete),
619        // All other keycodes (null, modifier-only keys, etc.) are not modeled.
620        _ => None,
621    }
622}
623
624/// Translate crossterm modifier flags to our `KeyModifiers`.
625fn translate_modifiers(mods: CKeyModifiers) -> KeyModifiers {
626    KeyModifiers {
627        shift: mods.contains(CKeyModifiers::SHIFT),
628        ctrl: mods.contains(CKeyModifiers::CONTROL),
629        alt: mods.contains(CKeyModifiers::ALT),
630    }
631}
632
633/// Translate a crossterm `MouseEvent` to one of our mouse `Event` variants.
634fn translate_mouse(m: crossterm::event::MouseEvent) -> Option<Event> {
635    let position = Point::new(m.column as i32, m.row as i32);
636    let modifiers = KeyModifiers {
637        shift: m.modifiers.contains(CKeyModifiers::SHIFT),
638        ctrl: m.modifiers.contains(CKeyModifiers::CONTROL),
639        alt: m.modifiers.contains(CKeyModifiers::ALT),
640    };
641
642    match m.kind {
643        MouseEventKind::Down(btn) => {
644            let mut buttons = MouseButtons::default();
645            set_button(&mut buttons, btn);
646            Some(Event::MouseDown(MouseEvent {
647                position,
648                buttons,
649                modifiers,
650                ..Default::default()
651            }))
652        }
653        MouseEventKind::Up(btn) => {
654            let mut buttons = MouseButtons::default();
655            set_button(&mut buttons, btn);
656            Some(Event::MouseUp(MouseEvent {
657                position,
658                buttons,
659                modifiers,
660                ..Default::default()
661            }))
662        }
663        MouseEventKind::Drag(btn) => {
664            let mut buttons = MouseButtons::default();
665            set_button(&mut buttons, btn);
666            Some(Event::MouseMove(MouseEvent {
667                position,
668                buttons,
669                modifiers,
670                flags: MouseEventFlags {
671                    mouse_moved: true,
672                    ..Default::default()
673                },
674                ..Default::default()
675            }))
676        }
677        MouseEventKind::Moved => Some(Event::MouseMove(MouseEvent {
678            position,
679            modifiers,
680            flags: MouseEventFlags {
681                mouse_moved: true,
682                ..Default::default()
683            },
684            ..Default::default()
685        })),
686        MouseEventKind::ScrollUp => Some(Event::MouseWheel(MouseEvent {
687            position,
688            modifiers,
689            wheel: MouseWheel::Up,
690            ..Default::default()
691        })),
692        MouseEventKind::ScrollDown => Some(Event::MouseWheel(MouseEvent {
693            position,
694            modifiers,
695            wheel: MouseWheel::Down,
696            ..Default::default()
697        })),
698        MouseEventKind::ScrollLeft => Some(Event::MouseWheel(MouseEvent {
699            position,
700            modifiers,
701            wheel: MouseWheel::Left,
702            ..Default::default()
703        })),
704        MouseEventKind::ScrollRight => Some(Event::MouseWheel(MouseEvent {
705            position,
706            modifiers,
707            wheel: MouseWheel::Right,
708            ..Default::default()
709        })),
710    }
711}
712
713/// Set the matching button field on `buttons`.
714fn set_button(buttons: &mut MouseButtons, btn: crossterm::event::MouseButton) {
715    match btn {
716        crossterm::event::MouseButton::Left => buttons.left = true,
717        crossterm::event::MouseButton::Right => buttons.right = true,
718        crossterm::event::MouseButton::Middle => buttons.middle = true,
719    }
720}