1
//! Decoder for keystroke byte streams arriving over a russh data
2
//! channel.
3
//!
4
//! `ratatui::crossterm::event::read` can't be used here because it reads from
5
//! `/dev/tty`. Russh hands us raw bytes from the wire instead, so we
6
//! parse the relevant subset of xterm / VT100 escape sequences in
7
//! process and emit [`tui::transport::RawEvent`]s shaped exactly
8
//! like the ones [`crate::handler`] would receive from a local
9
//! transport.
10
//!
11
//! Coverage matches what crossterm produces against a typical PTY:
12
//!
13
//! - ASCII 0x20–0x7E → `Char(c)` (Shift implied for upper case to
14
//!   match crossterm's behaviour).
15
//! - Ctrl-letter (0x01–0x1A, with 0x09/0x0a/0x0d/0x1b carrying
16
//!   their own [`KeyCode`]).
17
//! - Tab, Enter, Backspace, Esc, plus arrow keys, Home/End/PageUp/
18
//!   PageDown/Insert/Delete, F1–F12 (`ESC O P` and `ESC [ NN ~`
19
//!   forms).
20
//! - Modifier-encoded forms `ESC [ 1 ; 5 A` per xterm convention.
21
//! - `ESC` + printable as Alt-letter.
22
//! - UTF-8 continuation bytes are accumulated until a full code
23
//!   point is decoded.
24
//!
25
//! - SGR mouse reports, decoded by [`crate::mouse_report`]; a report cut
26
//!   short is dropped, never turned into keys.
27
//!
28
//! The parser is deliberately minimal — bracketed paste and the rest of
29
//! the VT200/CSI zoo are unrecognised and left as inert bytes.
30

            
31
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
32
use std::time::Duration;
33

            
34
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
35
use tokio::sync::mpsc::{Sender, error::TrySendError};
36
use tui::transport::RawEvent;
37

            
38
use crate::eval_channel::Backlog;
39
use crate::mouse_report;
40

            
41
/// How long a lone Esc waits for the rest of an escape sequence.
42
const ESC_TIMEOUT: Duration = Duration::from_millis(40);
43

            
44
/// Longest `ESC [` sequence waited for; an unfinished longer one is dropped.
45
const MAX_CSI_LEN: usize = 64;
46

            
47
/// Stateful byte → `RawEvent` decoder.
48
#[derive(Debug, Default)]
49
pub struct KeyDecoder {
50
    buf: Vec<u8>,
51
    /// Counts the feeds, so a timeout armed for an older feed can tell that
52
    /// more bytes arrived since.
53
    feeds: u64,
54
}
55

            
56
/// A decoder shared between the channel handler and its Esc timeouts.
57
pub type SharedDecoder = Arc<Mutex<KeyDecoder>>;
58

            
59
737
fn lock(decoder: &SharedDecoder) -> MutexGuard<'_, KeyDecoder> {
60
737
    decoder.lock().unwrap_or_else(PoisonError::into_inner)
61
737
}
62

            
63
/// A full queue is a backlog; a closed one means the session is already ending.
64
737
fn send_all(tx: &Sender<RawEvent>, events: Vec<RawEvent>) -> Result<(), Backlog> {
65
737
    for event in events {
66
33325
        match tx.try_send(event) {
67
33322
            Ok(()) => {}
68
2
            Err(TrySendError::Full(_)) => return Err(Backlog),
69
1
            Err(TrySendError::Closed(_)) => return Ok(()),
70
        }
71
    }
72
734
    Ok(())
73
737
}
74

            
75
/// Feed `bytes` and send the decoded events. Events are sent under the lock so
76
/// a timeout cannot reorder them; an unfinished escape sequence is resolved
77
/// after [`ESC_TIMEOUT`] unless more bytes arrive first.
78
///
79
/// # Errors
80
/// The queue is full: the consumer is not keeping up with the client.
81
503
pub fn feed_shared(
82
503
    decoder: &SharedDecoder,
83
503
    bytes: &[u8],
84
503
    tx: &Sender<RawEvent>,
85
503
) -> Result<(), Backlog> {
86
503
    let mut guard = lock(decoder);
87
503
    let events = guard.feed(bytes);
88
503
    send_all(tx, events)?;
89
501
    if let Some(feeds) = guard.pending_escape() {
90
235
        arm_timeout(decoder, tx, feeds);
91
266
    }
92
501
    Ok(())
93
503
}
94

            
95
235
fn arm_timeout(decoder: &SharedDecoder, tx: &Sender<RawEvent>, feeds: u64) {
96
235
    let decoder = Arc::clone(decoder);
97
235
    let tx = tx.clone();
98
235
    tokio::spawn(async move {
99
234
        tokio::time::sleep(ESC_TIMEOUT).await;
100
234
        let mut guard = lock(&decoder);
101
234
        let events = guard.resolve(feeds);
102
234
        let _ = send_all(&tx, events);
103
234
        if let Some(feeds) = guard.pending_escape() {
104
            arm_timeout(&decoder, &tx, feeds);
105
234
        }
106
234
    });
107
235
}
108

            
109
impl KeyDecoder {
110
    /// Append `bytes` to the internal accumulator and yield every
111
    /// `RawEvent` we can decode without consuming an incomplete
112
    /// trailing sequence.
113
6495
    pub fn feed(&mut self, bytes: &[u8]) -> Vec<RawEvent> {
114
6495
        self.feeds += 1;
115
6495
        self.buf.extend_from_slice(bytes);
116
6495
        let mut events = Vec::new();
117
6495
        let mut consumed = 0usize;
118
243791
        while consumed < self.buf.len() {
119
237556
            match decode_one(&self.buf[consumed..]) {
120
                Decoded::Event(ev, n) => {
121
237275
                    events.push(ev);
122
237275
                    consumed += n;
123
                }
124
21
                Decoded::Skip(n) => consumed += n,
125
260
                Decoded::Incomplete => break,
126
            }
127
        }
128
6495
        if consumed > 0 {
129
6235
            self.buf.drain(..consumed);
130
260
        }
131
6495
        events
132
6495
    }
133

            
134
    /// The feed number to resolve when the buffer holds an unfinished escape.
135
969
    fn pending_escape(&self) -> Option<u64> {
136
969
        (self.buf.first() == Some(&0x1b)).then_some(self.feeds)
137
969
    }
138

            
139
    /// Settle the unfinished escape left by feed number `feeds`, if nothing
140
    /// arrived since: Esc alone, Alt-key for Esc plus one printable byte,
141
    /// otherwise Esc followed by the remaining bytes as plain keys.
142
234
    fn resolve(&mut self, feeds: u64) -> Vec<RawEvent> {
143
234
        if self.pending_escape() != Some(feeds) {
144
96
            return Vec::new();
145
138
        }
146
138
        self.feeds += 1;
147
138
        let bytes = std::mem::take(&mut self.buf);
148
138
        match bytes[..] {
149
134
            [_] => vec![esc_key(KeyCode::Esc, KeyModifiers::NONE)],
150
            [_, 0x0a | 0x0d] => vec![esc_key(KeyCode::Enter, KeyModifiers::ALT)],
151
            [_, b @ 0x20..=0x7e] => {
152
2
                let shift = if b.is_ascii_uppercase() {
153
1
                    KeyModifiers::SHIFT
154
                } else {
155
1
                    KeyModifiers::NONE
156
                };
157
2
                vec![esc_key(KeyCode::Char(b as char), KeyModifiers::ALT | shift)]
158
            }
159
1
            [0x1b, b'[', b'<', ..] => Vec::new(),
160
            _ => {
161
1
                let mut events = vec![esc_key(KeyCode::Esc, KeyModifiers::NONE)];
162
1
                events.extend(self.feed(&bytes[1..]));
163
1
                events
164
            }
165
        }
166
234
    }
167
}
168

            
169
137
fn esc_key(code: KeyCode, mods: KeyModifiers) -> RawEvent {
170
137
    RawEvent::Key(KeyEvent::new(code, mods))
171
137
}
172

            
173
pub(crate) enum Decoded {
174
    Event(RawEvent, usize),
175
    /// Bytes we recognise but don't translate. Drop them to keep the
176
    /// buffer flowing.
177
    Skip(usize),
178
    /// Need more bytes before we can finalise.
179
    Incomplete,
180
}
181

            
182
237556
fn decode_one(input: &[u8]) -> Decoded {
183
237556
    if input.is_empty() {
184
        return Decoded::Incomplete;
185
237556
    }
186
237556
    let b0 = input[0];
187
237556
    match b0 {
188
1
        0x09 => key(KeyCode::Tab, KeyModifiers::NONE, 1),
189
5
        0x0a | 0x0d => key(KeyCode::Enter, KeyModifiers::NONE, 1),
190
1
        0x7f | 0x08 => key(KeyCode::Backspace, KeyModifiers::NONE, 1),
191
457
        0x1b => decode_escape(input),
192
        0x01..=0x1a => {
193
1
            let letter = (b0 - 1 + b'a') as char;
194
1
            key(KeyCode::Char(letter), KeyModifiers::CONTROL, 1)
195
        }
196
237089
        0x20..=0x7e => key(KeyCode::Char(b0 as char), modifiers_for_ascii(b0), 1),
197
2
        _ => decode_utf8(input),
198
    }
199
237556
}
200

            
201
237089
fn modifiers_for_ascii(b: u8) -> KeyModifiers {
202
237089
    if b.is_ascii_uppercase() {
203
2
        KeyModifiers::SHIFT
204
    } else {
205
237087
        KeyModifiers::NONE
206
    }
207
237089
}
208

            
209
237228
fn key(code: KeyCode, mods: KeyModifiers, consumed: usize) -> Decoded {
210
237228
    Decoded::Event(RawEvent::Key(KeyEvent::new(code, mods)), consumed)
211
237228
}
212

            
213
2
fn decode_utf8(input: &[u8]) -> Decoded {
214
    // Fast path for ASCII-only callers; we only land here for >=0x80.
215
2
    let needed = utf8_width(input[0]);
216
2
    if needed == 0 {
217
        return Decoded::Skip(1);
218
2
    }
219
2
    if input.len() < needed {
220
1
        return Decoded::Incomplete;
221
1
    }
222
1
    match std::str::from_utf8(&input[..needed]) {
223
        Ok(s) => {
224
1
            if let Some(c) = s.chars().next() {
225
1
                key(KeyCode::Char(c), KeyModifiers::NONE, needed)
226
            } else {
227
                Decoded::Skip(needed)
228
            }
229
        }
230
        Err(_) => Decoded::Skip(1),
231
    }
232
2
}
233

            
234
2
const fn utf8_width(b: u8) -> usize {
235
2
    match b {
236
        0x00..=0x7f => 1,
237
2
        0xc2..=0xdf => 2,
238
        0xe0..=0xef => 3,
239
        0xf0..=0xf4 => 4,
240
        _ => 0,
241
    }
242
2
}
243

            
244
457
fn decode_escape(input: &[u8]) -> Decoded {
245
457
    if input.len() == 1 {
246
        // ambiguous: lone Esc or start of an escape sequence
247
        // — wait one round to disambiguate.
248
216
        return Decoded::Incomplete;
249
241
    }
250
241
    let b1 = input[1];
251
241
    match b1 {
252
152
        b'[' => decode_csi(input),
253
11
        b'O' => decode_ss3(input),
254
4
        0x0a | 0x0d => key(KeyCode::Enter, KeyModifiers::ALT, 2),
255
        0x20..=0x7e => {
256
            // Esc + printable → Alt-letter
257
73
            let code = KeyCode::Char(b1 as char);
258
73
            let mut mods = KeyModifiers::ALT;
259
73
            if b1.is_ascii_uppercase() {
260
                mods |= KeyModifiers::SHIFT;
261
73
            }
262
73
            key(code, mods, 2)
263
        }
264
        _ => {
265
            // Fallback: surface a bare Esc and let the next byte be
266
            // re-decoded on its own.
267
1
            key(KeyCode::Esc, KeyModifiers::NONE, 1)
268
        }
269
    }
270
457
}
271

            
272
152
fn decode_csi(input: &[u8]) -> Decoded {
273
152
    if input.get(2) == Some(&b'<') {
274
76
        return mouse_report::decode(input);
275
76
    }
276
    // Format: ESC [ <params> <final>
277
    // Params are ASCII digits and ';'. Final is 0x40..=0x7e.
278
76
    let window = &input[..input.len().min(MAX_CSI_LEN)];
279
642
    match window[2..].iter().position(|b| (0x40..=0x7e).contains(b)) {
280
44
        Some(end) => finalise_csi(&window[2..2 + end], window[2 + end], end + 3),
281
32
        None if input.len() >= MAX_CSI_LEN => Decoded::Skip(input.len()),
282
29
        None => Decoded::Incomplete,
283
    }
284
152
}
285

            
286
44
fn finalise_csi(params: &[u8], final_byte: u8, consumed: usize) -> Decoded {
287
44
    let parts = parse_params(params);
288
44
    let mods = parts
289
44
        .get(1)
290
44
        .copied()
291
44
        .map_or(KeyModifiers::NONE, modifiers_from_xterm);
292
44
    match final_byte {
293
16
        b'A' => key(KeyCode::Up, mods, consumed),
294
1
        b'B' => key(KeyCode::Down, mods, consumed),
295
1
        b'C' => key(KeyCode::Right, mods, consumed),
296
3
        b'D' => key(KeyCode::Left, mods, consumed),
297
        b'H' => key(KeyCode::Home, mods, consumed),
298
        b'F' => key(KeyCode::End, mods, consumed),
299
        // Modified F1-F4 are `CSI 1;m P/Q/R/S`; sshd never asks for a cursor report, so `R` is Alt-F3.
300
1
        b'P' => key(KeyCode::F(1), mods, consumed),
301
1
        b'Q' => key(KeyCode::F(2), mods, consumed),
302
2
        b'R' => key(KeyCode::F(3), mods, consumed),
303
1
        b'S' => key(KeyCode::F(4), mods, consumed),
304
        b'Z' => key(KeyCode::BackTab, KeyModifiers::SHIFT, consumed),
305
18
        b'~' => match parts.first().copied().unwrap_or(0) {
306
1
            1 | 7 => key(KeyCode::Home, mods, consumed),
307
            2 => key(KeyCode::Insert, mods, consumed),
308
3
            3 => key(KeyCode::Delete, mods, consumed),
309
            4 | 8 => key(KeyCode::End, mods, consumed),
310
1
            5 => key(KeyCode::PageUp, mods, consumed),
311
1
            6 => key(KeyCode::PageDown, mods, consumed),
312
            // xterm convention for F5-F12; F1-F4 take the SS3 form
313
            // `ESC O P/Q/R/S` instead.
314
6
            15 => key(KeyCode::F(5), mods, consumed),
315
1
            17 => key(KeyCode::F(6), mods, consumed),
316
            18 => key(KeyCode::F(7), mods, consumed),
317
            19 => key(KeyCode::F(8), mods, consumed),
318
            20 => key(KeyCode::F(9), mods, consumed),
319
            21 => key(KeyCode::F(10), mods, consumed),
320
            23 => key(KeyCode::F(11), mods, consumed),
321
5
            24 => key(KeyCode::F(12), mods, consumed),
322
            // rxvt-style F1-F4 fallback so screen/tmux clients aren't
323
            // mute on those keys.
324
            11 => key(KeyCode::F(1), mods, consumed),
325
            12 => key(KeyCode::F(2), mods, consumed),
326
            13 => key(KeyCode::F(3), mods, consumed),
327
            14 => key(KeyCode::F(4), mods, consumed),
328
            _ => Decoded::Skip(consumed),
329
        },
330
        _ => Decoded::Skip(consumed),
331
    }
332
44
}
333

            
334
11
fn decode_ss3(input: &[u8]) -> Decoded {
335
11
    if input.len() < 3 {
336
3
        return Decoded::Incomplete;
337
8
    }
338
8
    let code = match input[2] {
339
3
        b'P' => KeyCode::F(1),
340
1
        b'Q' => KeyCode::F(2),
341
1
        b'R' => KeyCode::F(3),
342
1
        b'S' => KeyCode::F(4),
343
2
        b'A' => KeyCode::Up,
344
        b'B' => KeyCode::Down,
345
        b'C' => KeyCode::Right,
346
        b'D' => KeyCode::Left,
347
        b'H' => KeyCode::Home,
348
        b'F' => KeyCode::End,
349
        _ => return Decoded::Skip(3),
350
    };
351
8
    key(code, KeyModifiers::NONE, 3)
352
11
}
353

            
354
44
fn parse_params(raw: &[u8]) -> Vec<u32> {
355
117
    raw.split(|b| *b == b';')
356
57
        .map(|seg| std::str::from_utf8(seg).ok().and_then(|s| s.parse().ok()))
357
57
        .map(|v| v.unwrap_or(0))
358
        .collect()
359
44
}
360

            
361
13
fn modifiers_from_xterm(code: u32) -> KeyModifiers {
362
13
    if code == 0 {
363
1
        return KeyModifiers::NONE;
364
12
    }
365
12
    let bits = code.saturating_sub(1);
366
12
    let mut mods = KeyModifiers::NONE;
367
12
    if bits & 0b001 != 0 {
368
1
        mods |= KeyModifiers::SHIFT;
369
11
    }
370
12
    if bits & 0b010 != 0 {
371
2
        mods |= KeyModifiers::ALT;
372
10
    }
373
12
    if bits & 0b100 != 0 {
374
9
        mods |= KeyModifiers::CONTROL;
375
3
    }
376
12
    mods
377
13
}