uncurses 0.0.3

A Rust terminal rendering library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! CSI (Control Sequence Introducer) decoder.
//!
//! ## Purpose
//!
//! CSI is the largest single class of terminal control sequence. This module
//! parses the CSI grammar, dispatches inline forms that need decoder state, and
//! recognizes keys, mouse reports, focus events, geometry reports, mode reports,
//! colors, and capability replies.
//!
//! ```text
//! ESC [ / 0x9B ──▶ params + intermediates + final byte
//!        │
//!        ├─ key / mouse / focus reports ──▶ Event::Key* / Event::Mouse*
//!        ├─ terminal replies ─────────────▶ Event::Resize / colors / modes
//!        └─ unrecognized complete CSI ────▶ Event::UnknownCsi
//! ```
//!
//! ## Wire format
//!
//! CSI starts with `ESC [` or the 8-bit C1 byte `0x9B`, followed by optional
//! parameter bytes (`0x30..=0x3F`), optional intermediate bytes
//! (`0x20..=0x2F`), and one final byte (`0x40..=0x7E`). URxvt legacy modifier
//! suffixes such as `$` are handled as complete key sequences when they are not
//! part of a private/intermediate sequence.
//!
//! ## Gotchas
//!
//! X10 and UTF-8 mouse reports (`CSI M ...`) consume bytes after the CSI final
//! byte, so they are dispatched before the pure recognizer. Win32 input-mode
//! packets also stay inline because they can queue repeated key events.
use super::Decoder;
use super::DecoderFlags;
use super::kitty;
use super::result::ParseResult;
use super::util::{
    Params, csi_kitty_phase, csi_modifiers, intro_prefix_len, key_event_for_phase, key_with_mods,
    lookup_legacy_key, remap_tilde, tilde_code_to_keycode, xterm_modifiers,
};
use crate::event::mouse::{
    decode_sgr_mouse, decode_urxvt_mouse, decode_utf8_mouse, decode_x10_mouse,
};
use crate::event::{ColorScheme, Event, Key, KeyCode, KeyModifiers, Visibility};

impl Decoder {
    pub(super) fn parse_csi(&self, buf: &[u8]) -> ParseResult {
        let prefix_len = intro_prefix_len(buf[0]);
        // CSI body starts at buf[prefix_len..]; need at least the final byte.
        if buf.len() < prefix_len + 1 {
            return ParseResult::Incomplete;
        }

        // Find the final byte (0x40-0x7e)
        let mut i = prefix_len;
        let mut has_private = false;
        if i < buf.len() && (buf[i] == b'?' || buf[i] == b'<' || buf[i] == b'>' || buf[i] == b'=') {
            has_private = true;
            i += 1;
        }

        while i < buf.len() {
            let b = buf[i];
            if (0x40..=0x7e).contains(&b) {
                // Found final byte
                let seq = &buf[prefix_len..=i];
                let consumed = i + 1;
                return self.dispatch_csi(buf, seq, has_private, consumed);
            }
            // URxvt-style: `$` after digits/separators is treated as a final byte
            // (e.g. `\x1b[23$` for Shift+F11). Skip this when `$` is followed by
            // another final byte (e.g. DECRPM `\x1b[?1;1$y`), in which case `$`
            // is a real intermediate.
            if b == b'$' && !has_private {
                // URxvt: `\x1b[23$` (Shift+F11) — `$` is a final byte when
                // there's no private prefix. With a private prefix (e.g.
                // DECRPM `\x1b[?1;1$y`), `$` remains an intermediate.
                let seq = &buf[prefix_len..=i];
                let consumed = i + 1;
                return self.dispatch_csi(buf, seq, has_private, consumed);
            }
            if !((0x30..=0x3f).contains(&b) || b == b';' || b == b':') {
                // Intermediate byte
                if !(0x20..=0x2f).contains(&b) {
                    // Invalid
                    return ParseResult::None(i + 1);
                }
            }
            i += 1;
        }

        ParseResult::Incomplete
    }

    pub(super) fn dispatch_csi(
        &self,
        buf: &[u8],
        seq: &[u8],
        has_private: bool,
        consumed: usize,
    ) -> ParseResult {
        let view = split_csi(seq);
        let final_byte = view.final_byte;

        // X10 / UTF-8 mouse: CSI M followed by 3 raw bytes (or 3 UTF-8
        // codepoints in mode 1005). Needs access to the input buffer
        // beyond `consumed`, so it stays inline above `recognize`. The
        // byte-level `params_raw.is_empty()` check avoids a parameter
        // allocation on every CSI.
        if !has_private && final_byte == b'M' && view.params_raw.is_empty() {
            if self.utf8_mouse {
                if let Some((event, n)) = decode_utf8_mouse(&buf[consumed..]) {
                    return ParseResult::Event(event, consumed + n);
                }
                return ParseResult::Incomplete;
            }
            if buf.len() >= consumed + 3 {
                let cb = buf[consumed];
                let cx = buf[consumed + 1];
                let cy = buf[consumed + 2];
                if let Some(event) = decode_x10_mouse(cb, cx, cy) {
                    return ParseResult::Event(event, consumed + 3);
                }
            }
            return ParseResult::Incomplete;
        }

        // Win32 input mode: CSI vk;sc;ch;kd;cks;rep _ . Mutates
        // `self.pending` so it stays inline above `recognize`. Pre-check
        // the body shape (5 `;` separators, no private prefix) before
        // allocating to parse the parameter list.
        if final_byte == b'_'
            && !has_private
            && view.params_raw.iter().filter(|&&b| b == b';').count() == 5
        {
            return self.dispatch_win32_input(view.params(), consumed);
        }

        // The builtin recogniser, then `Event::UnknownCsi`. The lazy
        // [`Params`] walker is stateless and cheap to re-create.
        let raw_with_intro = &buf[..consumed];
        let evt = recognize(&view, raw_with_intro, self.flags)
            .unwrap_or_else(|| Event::UnknownCsi(raw_with_intro.to_vec()));
        ParseResult::Event(evt, consumed)
    }
}

/// Builtin CSI recogniser. Pure: produces an [`Event`] from a fully-parsed
/// CSI view, or `None` when the sequence isn't one this library knows
/// about. `raw_with_intro` is the original byte slice including the
/// `ESC [` introducer, used by the legacy-key lookup table.
fn recognize(view: &Csi<'_>, raw_with_intro: &[u8], flags: DecoderFlags) -> Option<Event> {
    let final_byte = view.final_byte;
    let params = view.params();
    // Currently the spec uses at most one intermediate; expose it as
    // `Option<u8>` to mirror the previous single-byte detection.
    let intermediate = view.intermediates.last().copied();
    let no_private = view.private.is_none();
    let no_intermediate = intermediate.is_none();

    // URxvt mouse: CSI Cb;Cx;Cy M  (no `<` prefix, semicolon params,
    // no intermediate, exactly 3 params)
    if no_private
        && no_intermediate
        && final_byte == b'M'
        && params.len() == 3
        && let Some(event) = decode_urxvt_mouse(params)
    {
        return Some(event);
    }

    // SGR mouse: CSI < Cb ; Cx ; Cy M/m. Coordinates are always reported
    // 0-based regardless of encoding; callers using SGR-Pixel (1016)
    // interpret the result as pixel offsets. Exactly 3 params, no
    // intermediate.
    if view.private == Some(b'<')
        && no_intermediate
        && (final_byte == b'M' || final_byte == b'm')
        && params.len() == 3
    {
        let is_release = final_byte == b'm';
        if let Some(event) = decode_sgr_mouse(params, is_release) {
            return Some(event);
        }
    }

    // Kitty keyboard: CSI ... u  (sub-parameter aware). No private byte,
    // no intermediate. Param count is variable.
    if final_byte == b'u'
        && no_private
        && no_intermediate
        && let Some(ev) = kitty::decode_kitty_key(view.params(), &[])
    {
        return Some(ev);
    }

    // Focus events: CSI I / CSI O. No private, no intermediate, no params.
    if final_byte == b'I' && no_private && no_intermediate && params.is_empty() {
        return Some(Event::FocusIn);
    }
    if final_byte == b'O' && no_private && no_intermediate && params.is_empty() {
        return Some(Event::FocusOut);
    }

    // Cursor position report: CSI row ; col R. No private, no
    // intermediate, exactly 2 params. Ambiguous with the modified-F3
    // form `CSI 1 ; <mod> R` when the cursor is at row 1 (column - 1
    // fits in the 4-bit modifier mask). In that case emit both events
    // as a Multi and let the consumer decide.
    if final_byte == b'R' && no_private && no_intermediate && params.len() == 2 {
        let row = params.get_or(0, 1).max(1);
        let col = params.get_or(1, 1).max(1);
        let cpr = Event::CursorPosition(crate::layout::Position::new(
            (col - 1) as u16,
            (row - 1) as u16,
        ));
        if row == 1 && col >= 1 && col - 1 <= 15 {
            let mods = xterm_modifiers(col as u16);
            let f3 = Event::KeyPress(Key::new(KeyCode::F(3), mods).normalized());
            return Some(Event::Multi(vec![f3, cpr]));
        }
        return Some(cpr);
    }

    // Light/dark color scheme report: CSI ? 997 ; {1|2} n.
    // Sent both as reply to `CSI ? 996 n` and unsolicited when DEC mode
    // 2031 is enabled. Exactly two params and no intermediate.
    if final_byte == b'n'
        && view.private == Some(b'?')
        && no_intermediate
        && params.len() == 2
        && params.get_or(0, 0) == 997
    {
        return match params.get_or(1, 0) {
            1 => Some(Event::ColorScheme(ColorScheme::Dark)),
            2 => Some(Event::ColorScheme(ColorScheme::Light)),
            _ => None,
        };
    }

    // Terminal visibility report: CSI ? 999 ; {1|2} n.
    // Sent both as reply to `CSI ? 998 n` and unsolicited when DEC mode
    // 2033 is enabled. Exactly two params and no intermediate.
    if final_byte == b'n'
        && view.private == Some(b'?')
        && no_intermediate
        && params.len() == 2
        && params.get_or(0, 0) == 999
    {
        return match params.get_or(1, 0) {
            1 => Some(Event::Visibility(Visibility::Visible)),
            2 => Some(Event::Visibility(Visibility::Hidden)),
            _ => None,
        };
    }

    // DA1 response: CSI ? ... c. No intermediate.
    if final_byte == b'c' && view.private == Some(b'?') && no_intermediate {
        return Some(Event::PrimaryDeviceAttributes(
            params.iter().map(|g| g.first()).collect(),
        ));
    }

    // DA2 response: CSI > ... c. No intermediate.
    if final_byte == b'c' && view.private == Some(b'>') && no_intermediate {
        return Some(Event::SecondaryDeviceAttributes(
            params.iter().map(|g| g.first()).collect(),
        ));
    }

    // Mode report: CSI ? Ps ; Pm $ y (DECRPM) or CSI Ps ; Pm $ y
    // (RM-style). Intermediate `$`, exactly 2 params.
    if final_byte == b'y' && intermediate == Some(b'$') && params.len() == 2 {
        let mode_n = params.get_or(0, 0) as u16;
        let setting_n = params.get_or(1, 0) as u16;
        let mode = if no_private {
            crate::ansi::mode::Mode::Ansi(mode_n)
        } else {
            crate::ansi::mode::Mode::Dec(mode_n)
        };
        let setting = crate::ansi::mode::ModeSetting::from_value(setting_n);
        return Some(Event::ModeReport { mode, setting });
    }

    // Kitty keyboard protocol active-enhancements report: CSI ? flags u.
    // No intermediate, exactly 1 param.
    if final_byte == b'u' && view.private == Some(b'?') && no_intermediate && params.len() == 1 {
        let bits = params.get_or(0, 0) as u8;
        return Some(Event::KittyKeyboardEnhancements(
            crate::ansi::kitty::KittyKeyboardFlags::from_bits_truncate(bits),
        ));
    }

    // Window size in pixels: CSI 4 ; height ; width t. No private, no
    // intermediate, exactly 3 params.
    if final_byte == b't'
        && no_private
        && no_intermediate
        && params.len() == 3
        && params.get_or(0, 0) == 4
    {
        return Some(Event::WindowPixelSize {
            width: params.get_or(2, 0) as u16,
            height: params.get_or(1, 0) as u16,
        });
    }

    // Cell size in pixels: CSI 6 ; height ; width t. No private, no
    // intermediate, exactly 3 params.
    if final_byte == b't'
        && no_private
        && no_intermediate
        && params.len() == 3
        && params.get_or(0, 0) == 6
    {
        return Some(Event::CellPixelSize {
            width: params.get_or(2, 0) as u16,
            height: params.get_or(1, 0) as u16,
        });
    }

    // Window size in chars: CSI 8 ; height ; width t — reply to the
    // application's CSI 18 t query. This is a query reply, not a change
    // notification; surface it as such. No private, no intermediate,
    // exactly 3 params.
    if final_byte == b't'
        && no_private
        && no_intermediate
        && params.len() == 3
        && params.get_or(0, 0) == 8
    {
        return Some(Event::WindowCellSize {
            width: params.get_or(2, 0) as u16,
            height: params.get_or(1, 0) as u16,
        });
    }

    // In-band resize report (mode 2048):
    // CSI 48 ; height_chars ; width_chars ; height_pix ; width_pix t.
    // The pixel fields are optional: terminals that omit them send just
    // CSI 48 ; height ; width t, so accept three or more params (the `48`
    // discriminator distinguishes this from the generic window-op `t`
    // reports below) and default any absent pixel size to zero.
    if final_byte == b't'
        && no_private
        && no_intermediate
        && params.len() >= 3
        && params.get_or(0, 0) == 48
    {
        return Some(Event::Resize(crate::terminal::Winsize {
            row: params.get_or(1, 0) as u16,
            col: params.get_or(2, 0) as u16,
            ypixel: params.get_or(3, 0) as u16,
            xpixel: params.get_or(4, 0) as u16,
        }));
    }

    // Generic window-op fallback for other CSI t variants. No private,
    // no intermediate.
    if final_byte == b't' && no_private && no_intermediate && !params.is_empty() {
        return Some(Event::WindowOp {
            op: params.get_or(0, 0),
            args: params.slice_from(1).iter().map(|g| g.first()).collect(),
        });
    }

    // modifyOtherKeys report: CSI > 4 ; Pn m. No intermediate, exactly
    // 2 params.
    if final_byte == b'm'
        && view.private == Some(b'>')
        && no_intermediate
        && params.len() == 2
        && params.get_or(0, 0) == 4
    {
        return Some(Event::ModifyOtherKeys(
            crate::event::ModifyOtherKeysMode::from_value(params.get_or(1, 0) as u8),
        ));
    }

    // Standard final-byte cursor / function-key dispatch. No private,
    // no intermediate.
    if no_private && no_intermediate {
        let key_code = match final_byte {
            b'A' => Some(KeyCode::Up),
            b'B' => Some(KeyCode::Down),
            b'C' => Some(KeyCode::Right),
            b'D' => Some(KeyCode::Left),
            b'E' => Some(KeyCode::KpBegin),
            b'H' => Some(KeyCode::Home),
            b'F' => Some(KeyCode::End),
            b'P' => Some(KeyCode::F(1)),
            b'Q' => Some(KeyCode::F(2)),
            b'S' => Some(KeyCode::F(4)),
            _ => None,
        };
        if let Some(kc) = key_code {
            let key = key_with_mods(kc, csi_modifiers(params));
            return Some(key_event_for_phase(key, csi_kitty_phase(params)));
        }
        match final_byte {
            b'Z' => {
                // Legacy single-byte spelling for Shift+Tab. Emit the
                // uniform `Tab + SHIFT` identity directly.
                let key = Key::new(KeyCode::Tab, KeyModifiers::SHIFT).normalized();
                return Some(key_event_for_phase(key, csi_kitty_phase(params)));
            }
            b'~' => {
                if let Some(ev) = recognize_tilde(params, flags) {
                    return Some(ev);
                }
            }
            _ => {}
        }
    }

    // Last resort before falling back to `Event::UnknownCsi`: the legacy
    // key table for terminals (like URxvt) that use the bare sequence as
    // the identifier.
    lookup_legacy_key(raw_with_intro, flags).map(Event::KeyPress)
}

/// Builtin handler for the `CSI Pn ~` family (PgUp, F-keys 5+,
/// bracketed-paste boundaries, …).
fn recognize_tilde(params: Params<'_>, flags: DecoderFlags) -> Option<Event> {
    let code = params.get_or(0, 0);

    // XTerm modifyOtherKeys-2: CSI 27 ; <modifier> ; <code> ~
    if code == 27 && params.len() >= 3 {
        let mods = xterm_modifiers(params.get_or(1, 1) as u16);
        let r = params.get_or(2, 0);
        let key_code = match r {
            0x08 => KeyCode::Backspace,
            0x09 => KeyCode::Tab,
            0x0d => KeyCode::Enter,
            0x1b => KeyCode::Escape,
            0x20 => KeyCode::Space,
            0x7f => KeyCode::Backspace,
            _ => KeyCode::Char(char::from_u32(r)?),
        };
        let key = Key::new(key_code, mods).normalized();
        return Some(Event::KeyPress(key));
    }

    let mods = csi_modifiers(params);

    if code == 200 {
        return Some(Event::PasteStart);
    }
    if code == 201 {
        return Some(Event::PasteEnd);
    }
    let key_code = u16::try_from(code)
        .ok()
        .and_then(tilde_code_to_keycode)
        .map(|kc| remap_tilde(code as u16, kc, flags))?;

    Some(key_event_for_phase(
        key_with_mods(key_code, mods),
        csi_kitty_phase(params),
    ))
}

/// Structured view over a CSI body: the private prefix, parameter and
/// intermediate regions, and final byte split out so the recogniser can
/// match on shape. The parameter body is exposed lazily via [`Csi::params`];
/// no parameter `Vec` is ever materialised.
struct Csi<'a> {
    private: Option<u8>,
    params_raw: &'a [u8],
    intermediates: &'a [u8],
    final_byte: u8,
}

impl<'a> Csi<'a> {
    /// Lazy walker over the `;`-separated parameter list. Each group
    /// may carry colon-separated sub-parameters; see
    /// [`crate::ansi::params::Params`].
    #[inline]
    fn params(&self) -> Params<'a> {
        Params::from_raw(self.params_raw)
    }
}

/// Split a CSI body (private prefix + params + intermediates + final byte)
/// into a structured view. `seq` must end with the final byte.
fn split_csi(seq: &[u8]) -> Csi<'_> {
    let final_byte = *seq.last().unwrap_or(&0);
    let body = &seq[..seq.len().saturating_sub(1)];
    let (private, rest) = match body.first() {
        Some(&b) if matches!(b, b'?' | b'<' | b'>' | b'=') => (Some(b), &body[1..]),
        _ => (None, body),
    };
    let mid = rest
        .iter()
        .position(|&b| (0x20..=0x2f).contains(&b))
        .unwrap_or(rest.len());
    let (params_raw, intermediates) = rest.split_at(mid);
    Csi {
        private,
        params_raw,
        intermediates,
        final_byte,
    }
}