tastty-core 0.1.0

Sans-IO core of the tastty terminal session library: VT parser, screen buffer, and byte encoders.
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
//! [Kitty keyboard protocol] CSI u encoding: progressive-enhancement flags,
//! alternate-key reporting, functional-key codepoints in the U+E000 range.
//!
//! [Kitty keyboard protocol]: https://sw.kovidgoyal.net/kitty/keyboard-protocol/

use crate::input::{
    KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers, MediaKeyCode, ModifierKeyCode,
};

const FLAG_DISAMBIGUATE: u8 = 1;
const FLAG_REPORT_EVENTS: u8 = 2;
const FLAG_REPORT_ALTERNATE: u8 = 4;
const FLAG_REPORT_ALL: u8 = 8;

/// Encode a key event using the Kitty keyboard protocol.
///
/// `flags` is the active enhancement flags bitmask from the inner app's flag stack.
/// Returns `Some(bytes)` to send to the PTY, or `None` if the key has no
/// Kitty keyboard encoding (e.g. unrecognized `KeyCode` variants). Returning
/// `None` is the correct response. The previous fallback to `codepoint=0`
/// silently injected NUL bytes into the child's input stream.
pub(crate) fn key_to_bytes_kitty(key: &KeyEvent, flags: u8) -> Option<Vec<u8>> {
    let report_all = flags & FLAG_REPORT_ALL != 0;
    let disambiguate = flags & FLAG_DISAMBIGUATE != 0;
    let report_events = flags & FLAG_REPORT_EVENTS != 0;
    let report_alternate = flags & FLAG_REPORT_ALTERNATE != 0;

    let event_type = match key.kind {
        KeyEventKind::Press => 1,
        KeyEventKind::Repeat => 2,
        KeyEventKind::Release => 3,
    };

    let modifiers = kitty_modifier(key);
    let encoding = kitty_key_encoding(key)?;
    let shifted_key = if report_alternate {
        shifted_key_codepoint(key)
    } else {
        0
    };

    match encoding {
        KittyEncoding::Char(codepoint) => {
            let is_ambiguous = is_ambiguous_key(key.code);
            let has_modifiers = modifiers > 1;
            let is_non_press = event_type != 1;

            // disambiguate-only path: emit a literal byte when the key is
            // unmodified, unambiguous, and a press of a text-generating char.
            if !report_all
                && !is_ambiguous
                && !has_modifiers
                && !is_non_press
                && let KeyCode::Char(c) = key.code
            {
                let mut buf = [0u8; 4];
                let s = c.encode_utf8(&mut buf);
                return Some(s.as_bytes().to_vec());
            }

            if report_all || (disambiguate && is_ambiguous) || has_modifiers || is_non_press {
                return Some(encode_csi_u(
                    codepoint,
                    shifted_key,
                    modifiers,
                    event_type,
                    report_events,
                ));
            }

            if let KeyCode::Char(c) = key.code {
                let mut buf = [0u8; 4];
                let s = c.encode_utf8(&mut buf);
                return Some(s.as_bytes().to_vec());
            }
            Some(encode_csi_u(
                codepoint,
                shifted_key,
                modifiers,
                event_type,
                report_events,
            ))
        }
        KittyEncoding::Functional { number, final_byte } => Some(encode_functional(
            number,
            final_byte,
            modifiers,
            event_type,
            report_events,
        )),
        KittyEncoding::Ss3(final_byte) => {
            // F1-F4 fall back from SS3 to CSI when modified or when reporting
            // a non-press event.
            if modifiers > 1 || (report_events && event_type != 1) {
                Some(encode_functional(
                    1,
                    final_byte,
                    modifiers,
                    event_type,
                    report_events,
                ))
            } else {
                Some(vec![0x1b, b'O', final_byte])
            }
        }
    }
}

fn kitty_modifier(key: &KeyEvent) -> u16 {
    // Consumed modifiers were used by the input system to produce the key
    // code and must not be reported again to the app.
    let effective = key.modifiers - key.consumed_modifiers;
    let mut m: u16 = 1;
    if effective.contains(KeyModifiers::SHIFT) {
        m += 1;
    }
    if effective.contains(KeyModifiers::ALT) {
        m += 2;
    }
    if effective.contains(KeyModifiers::CONTROL) {
        m += 4;
    }
    if effective.contains(KeyModifiers::SUPER) {
        m += 8;
    }
    if effective.contains(KeyModifiers::HYPER) {
        m += 16;
    }
    if effective.contains(KeyModifiers::META) {
        m += 32;
    }
    if key.state.contains(KeyEventState::CAPS_LOCK) {
        m += 64;
    }
    if key.state.contains(KeyEventState::NUM_LOCK) {
        m += 128;
    }
    m
}

/// Resolve the shifted-key codepoint for the report_alternate flag.
///
/// When `KeyEvent::unshifted_codepoint` is set, it provides the base codepoint
/// for the CSI u sequence and `key.code` is the shifted character. Otherwise
/// fall back to ASCII heuristics: uppercase for shifted letters.
fn shifted_key_codepoint(key: &KeyEvent) -> u32 {
    let effective = key.modifiers - key.consumed_modifiers;
    if !effective.contains(KeyModifiers::SHIFT) {
        return 0;
    }
    if let (Some(unshifted), KeyCode::Char(c)) = (key.unshifted_codepoint, key.code)
        && c != unshifted
    {
        return u32::from(c);
    }
    match key.code {
        KeyCode::Char(c) if c.is_ascii_alphabetic() => u32::from(c.to_ascii_uppercase()),
        _ => 0,
    }
}

fn is_ambiguous_key(code: KeyCode) -> bool {
    matches!(
        code,
        KeyCode::Esc | KeyCode::Enter | KeyCode::Tab | KeyCode::BackTab | KeyCode::Backspace
    )
}

enum KittyEncoding {
    /// CSI u encoding with the given Unicode codepoint
    Char(u32),
    /// Legacy CSI encoding: CSI [number] ; [modifiers] [final_byte]
    Functional { number: u16, final_byte: u8 },
    /// SS3 encoding for F1-F4: ESC O [final_byte]
    Ss3(u8),
}

fn kitty_key_encoding(key: &KeyEvent) -> Option<KittyEncoding> {
    let is_keypad = key.state.contains(KeyEventState::KEYPAD);

    Some(match key.code {
        KeyCode::Modifier(m) => KittyEncoding::Char(modifier_codepoint(m)),

        KeyCode::Esc => KittyEncoding::Char(27),
        KeyCode::Enter => KittyEncoding::Char(13),
        KeyCode::Tab => KittyEncoding::Char(9),
        // BackTab shares Tab's codepoint; the SHIFT modifier byte
        // distinguishes the two on the wire.
        KeyCode::BackTab => KittyEncoding::Char(9),
        KeyCode::Backspace => KittyEncoding::Char(127),
        KeyCode::Delete => KittyEncoding::Functional {
            number: 3,
            final_byte: b'~',
        },
        KeyCode::Insert => KittyEncoding::Functional {
            number: 2,
            final_byte: b'~',
        },
        KeyCode::PageUp => KittyEncoding::Functional {
            number: 5,
            final_byte: b'~',
        },
        KeyCode::PageDown => KittyEncoding::Functional {
            number: 6,
            final_byte: b'~',
        },

        KeyCode::Up => KittyEncoding::Functional {
            number: 1,
            final_byte: b'A',
        },
        KeyCode::Down => KittyEncoding::Functional {
            number: 1,
            final_byte: b'B',
        },
        KeyCode::Right => KittyEncoding::Functional {
            number: 1,
            final_byte: b'C',
        },
        KeyCode::Left => KittyEncoding::Functional {
            number: 1,
            final_byte: b'D',
        },
        KeyCode::Home => KittyEncoding::Functional {
            number: 1,
            final_byte: b'H',
        },
        KeyCode::End => KittyEncoding::Functional {
            number: 1,
            final_byte: b'F',
        },

        // F1-F4 use SS3 format
        KeyCode::F(1) => KittyEncoding::Ss3(b'P'),
        KeyCode::F(2) => KittyEncoding::Ss3(b'Q'),
        KeyCode::F(3) => KittyEncoding::Ss3(b'R'),
        KeyCode::F(4) => KittyEncoding::Ss3(b'S'),

        // F5-F12 use legacy CSI tilde format
        KeyCode::F(n @ 5..=12) => {
            let number = match n {
                5 => 15,
                6 => 17,
                7 => 18,
                8 => 19,
                9 => 20,
                10 => 21,
                11 => 23,
                12 => 24,
                _ => unreachable!(),
            };
            KittyEncoding::Functional {
                number,
                final_byte: b'~',
            }
        }

        // F13-F35 use Kitty keyboard codepoints
        KeyCode::F(n @ 13..=35) => KittyEncoding::Char(57376 + u32::from(n) - 13),

        KeyCode::Char(c) if is_keypad => {
            let cp = numpad_codepoint(c);
            KittyEncoding::Char(cp.unwrap_or(u32::from(c)))
        }
        KeyCode::Char(c) => {
            let base = key
                .unshifted_codepoint
                .unwrap_or_else(|| c.to_ascii_lowercase());
            KittyEncoding::Char(u32::from(base))
        }

        KeyCode::CapsLock => KittyEncoding::Char(57358),
        KeyCode::ScrollLock => KittyEncoding::Char(57359),
        KeyCode::NumLock => KittyEncoding::Char(57360),
        KeyCode::PrintScreen => KittyEncoding::Char(57361),
        KeyCode::Pause => KittyEncoding::Char(57362),
        KeyCode::Menu => KittyEncoding::Char(57363),
        KeyCode::KeypadBegin => KittyEncoding::Char(57427),

        KeyCode::Media(m) => KittyEncoding::Char(media_codepoint(m)),

        // None for unmapped codes; the historic fallback emitted codepoint 0
        // and silently injected NUL bytes into the child.
        _ => return None,
    })
}

fn modifier_codepoint(m: ModifierKeyCode) -> u32 {
    match m {
        ModifierKeyCode::LeftShift => 57441,
        ModifierKeyCode::LeftControl => 57442,
        ModifierKeyCode::LeftAlt => 57443,
        ModifierKeyCode::LeftSuper => 57444,
        ModifierKeyCode::LeftHyper => 57445,
        ModifierKeyCode::LeftMeta => 57446,
        ModifierKeyCode::RightShift => 57447,
        ModifierKeyCode::RightControl => 57448,
        ModifierKeyCode::RightAlt => 57449,
        ModifierKeyCode::RightSuper => 57450,
        ModifierKeyCode::RightHyper => 57451,
        ModifierKeyCode::RightMeta => 57452,
        ModifierKeyCode::IsoLevel3Shift => 57453,
        ModifierKeyCode::IsoLevel5Shift => 57454,
    }
}

fn numpad_codepoint(c: char) -> Option<u32> {
    match c {
        '0' => Some(57399),
        '1' => Some(57400),
        '2' => Some(57401),
        '3' => Some(57402),
        '4' => Some(57403),
        '5' => Some(57404),
        '6' => Some(57405),
        '7' => Some(57406),
        '8' => Some(57407),
        '9' => Some(57408),
        '.' => Some(57409),
        '/' => Some(57410),
        '*' => Some(57411),
        '-' => Some(57412),
        '+' => Some(57413),
        '=' => Some(57415),
        _ => None,
    }
}

fn media_codepoint(m: MediaKeyCode) -> u32 {
    match m {
        MediaKeyCode::Play => 57428,
        MediaKeyCode::Pause => 57429,
        MediaKeyCode::PlayPause => 57430,
        MediaKeyCode::Reverse => 57431,
        MediaKeyCode::Stop => 57432,
        MediaKeyCode::FastForward => 57433,
        MediaKeyCode::Rewind => 57434,
        MediaKeyCode::TrackNext => 57435,
        MediaKeyCode::TrackPrevious => 57436,
        MediaKeyCode::Record => 57437,
        MediaKeyCode::LowerVolume => 57438,
        MediaKeyCode::RaiseVolume => 57439,
        MediaKeyCode::MuteVolume => 57440,
    }
}

/// `CSI codepoint[:shifted_key] ; modifiers[:event_type] u`.
fn encode_csi_u(
    codepoint: u32,
    shifted_key: u32,
    modifiers: u16,
    event_type: u8,
    report_events: bool,
) -> Vec<u8> {
    let mut out = format!("\x1b[{codepoint}");

    if shifted_key != 0 {
        out.push(':');
        out.push_str(&shifted_key.to_string());
    }

    let need_event = report_events && event_type != 1;

    if modifiers > 1 || need_event {
        out.push(';');
        out.push_str(&modifiers.to_string());
        if need_event {
            out.push(':');
            out.push_str(&event_type.to_string());
        }
    }

    out.push('u');
    out.into_bytes()
}

/// `CSI number ; modifiers[:event_type] final_byte`.
fn encode_functional(
    number: u16,
    final_byte: u8,
    modifiers: u16,
    event_type: u8,
    report_events: bool,
) -> Vec<u8> {
    let need_event = report_events && event_type != 1;
    let need_modifier = modifiers > 1 || need_event;

    let mut out = String::from("\x1b[");

    // Arrow/Home/End (final not `~`) drop the leading number when unmodified.
    if final_byte != b'~' && !need_modifier {
        out.push(final_byte as char);
        return out.into_bytes();
    }

    out.push_str(&number.to_string());

    if need_modifier {
        out.push(';');
        out.push_str(&modifiers.to_string());
        if need_event {
            out.push(':');
            out.push_str(&event_type.to_string());
        }
    }

    out.push(final_byte as char);
    out.into_bytes()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    fn ctrl_key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::CONTROL)
    }

    fn shift_key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::SHIFT)
    }

    fn key_with_kind(code: KeyCode, kind: KeyEventKind) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE).with_kind(kind)
    }

    fn key_with_state(code: KeyCode, modifiers: KeyModifiers, state: KeyEventState) -> KeyEvent {
        KeyEvent::new(code, modifiers).with_state(state)
    }

    #[test]
    fn kitty_plain_letter_sends_literal() {
        // Flag bit 0 only: unmodified 'a' sends literal byte
        let result = key_to_bytes_kitty(&key(KeyCode::Char('a')), FLAG_DISAMBIGUATE).unwrap();
        assert_eq!(result, b"a");
    }

    #[test]
    fn kitty_ctrl_c_uses_csi_u() {
        // Flag bit 0: Ctrl+c -> CSI 99 ; 5 u
        let result = key_to_bytes_kitty(&ctrl_key(KeyCode::Char('c')), FLAG_DISAMBIGUATE).unwrap();
        assert_eq!(result, b"\x1b[99;5u");
    }

    #[test]
    fn kitty_ctrl_i_disambiguated_from_tab() {
        // Flag bit 0: Ctrl+i -> CSI 105 ; 5 u (not Tab/0x09)
        let result = key_to_bytes_kitty(&ctrl_key(KeyCode::Char('i')), FLAG_DISAMBIGUATE).unwrap();
        assert_eq!(result, b"\x1b[105;5u");
    }

    #[test]
    fn kitty_escape_uses_csi_u() {
        let result = key_to_bytes_kitty(&key(KeyCode::Esc), FLAG_DISAMBIGUATE).unwrap();
        assert_eq!(result, b"\x1b[27u");
    }

    #[test]
    fn kitty_enter_uses_csi_u() {
        let result = key_to_bytes_kitty(&key(KeyCode::Enter), FLAG_DISAMBIGUATE).unwrap();
        assert_eq!(result, b"\x1b[13u");
    }

    #[test]
    fn kitty_tab_uses_csi_u() {
        let result = key_to_bytes_kitty(&key(KeyCode::Tab), FLAG_DISAMBIGUATE).unwrap();
        assert_eq!(result, b"\x1b[9u");
    }

    #[test]
    fn kitty_backspace_uses_csi_u() {
        let result = key_to_bytes_kitty(&key(KeyCode::Backspace), FLAG_DISAMBIGUATE).unwrap();
        assert_eq!(result, b"\x1b[127u");
    }

    #[test]
    fn kitty_report_all_letter() {
        // Flag bit 3: unmodified 'a' -> CSI 97 u
        let result = key_to_bytes_kitty(&key(KeyCode::Char('a')), FLAG_REPORT_ALL).unwrap();
        assert_eq!(result, b"\x1b[97u");
    }

    #[test]
    fn kitty_release_event() {
        // Flag bits 1+0: release 'a' -> CSI 97 ; 1:3 u
        let k = key_with_kind(KeyCode::Char('a'), KeyEventKind::Release);
        let result = key_to_bytes_kitty(&k, FLAG_DISAMBIGUATE | FLAG_REPORT_EVENTS).unwrap();
        assert_eq!(result, b"\x1b[97;1:3u");
    }

    #[test]
    fn kitty_repeat_event() {
        let k = key_with_kind(KeyCode::Char('a'), KeyEventKind::Repeat);
        let result = key_to_bytes_kitty(&k, FLAG_DISAMBIGUATE | FLAG_REPORT_EVENTS).unwrap();
        assert_eq!(result, b"\x1b[97;1:2u");
    }

    #[test]
    fn kitty_ctrl_shift_a() {
        // Ctrl+Shift+a -> CSI 97 ; 6 u (1 + shift(1) + ctrl(4) = 6)
        let k = KeyEvent::new(
            KeyCode::Char('a'),
            KeyModifiers::CONTROL | KeyModifiers::SHIFT,
        );
        let result = key_to_bytes_kitty(&k, FLAG_DISAMBIGUATE).unwrap();
        assert_eq!(result, b"\x1b[97;6u");
    }

    #[test]
    fn kitty_shift_a_with_report_alternate() {
        // With FLAG_REPORT_ALTERNATE (4), the shifted key codepoint is included.
        // Shift+A: base='a' (97), shifted='A' (65) -> CSI 97:65;2u
        // crossterm reports Shift+A as Char('A') with SHIFT modifier.
        let k = KeyEvent::new(KeyCode::Char('A'), KeyModifiers::SHIFT);
        let result = key_to_bytes_kitty(&k, FLAG_DISAMBIGUATE | FLAG_REPORT_ALTERNATE).unwrap();
        assert_eq!(result, b"\x1b[97:65;2u");
    }

    #[test]
    fn kitty_shift_a_without_report_alternate() {
        // Without FLAG_REPORT_ALTERNATE, no shifted key is included.
        let k = KeyEvent::new(KeyCode::Char('A'), KeyModifiers::SHIFT);
        let result = key_to_bytes_kitty(&k, FLAG_DISAMBIGUATE).unwrap();
        assert_eq!(result, b"\x1b[97;2u");
    }

    #[test]
    fn kitty_super_modifier() {
        let k = KeyEvent::new(KeyCode::Char('a'), KeyModifiers::SUPER);
        let result = key_to_bytes_kitty(&k, FLAG_DISAMBIGUATE).unwrap();
        assert_eq!(result, b"\x1b[97;9u");
    }

    #[test]
    fn kitty_capslock_modifier() {
        let k = key_with_state(
            KeyCode::Char('a'),
            KeyModifiers::NONE,
            KeyEventState::CAPS_LOCK,
        );
        let result = key_to_bytes_kitty(&k, FLAG_REPORT_ALL).unwrap();
        assert_eq!(result, b"\x1b[97;65u"); // 1 + 64 = 65
    }

    #[test]
    fn kitty_arrow_up_ctrl() {
        let result = key_to_bytes_kitty(&ctrl_key(KeyCode::Up), FLAG_DISAMBIGUATE).unwrap();
        assert_eq!(result, b"\x1b[1;5A");
    }

    #[test]
    fn kitty_f5_shift() {
        let result = key_to_bytes_kitty(&shift_key(KeyCode::F(5)), FLAG_DISAMBIGUATE).unwrap();
        assert_eq!(result, b"\x1b[15;2~");
    }

    #[test]
    fn kitty_f13() {
        let result = key_to_bytes_kitty(&key(KeyCode::F(13)), FLAG_DISAMBIGUATE).unwrap();
        assert_eq!(result, b"\x1b[57376u");
    }

    #[test]
    fn kitty_f20_ctrl() {
        let result = key_to_bytes_kitty(&ctrl_key(KeyCode::F(20)), FLAG_DISAMBIGUATE).unwrap();
        assert_eq!(result, b"\x1b[57383;5u");
    }

    #[test]
    fn kitty_numpad_5() {
        let k = key_with_state(
            KeyCode::Char('5'),
            KeyModifiers::NONE,
            KeyEventState::KEYPAD,
        );
        let result = key_to_bytes_kitty(&k, FLAG_REPORT_ALL).unwrap();
        assert_eq!(result, b"\x1b[57404u");
    }

    #[test]
    fn kitty_modifier_left_shift() {
        let k = key(KeyCode::Modifier(ModifierKeyCode::LeftShift));
        let result = key_to_bytes_kitty(&k, FLAG_REPORT_ALL).unwrap();
        assert_eq!(result, b"\x1b[57441u");
    }

    #[test]
    fn kitty_modifier_left_shift_release() {
        let k = KeyEvent::new(
            KeyCode::Modifier(ModifierKeyCode::LeftShift),
            KeyModifiers::NONE,
        )
        .with_kind(KeyEventKind::Release);
        let result = key_to_bytes_kitty(&k, FLAG_REPORT_ALL | FLAG_REPORT_EVENTS).unwrap();
        assert_eq!(result, b"\x1b[57441;1:3u");
    }

    #[test]
    fn kitty_arrow_release() {
        let k = key_with_kind(KeyCode::Up, KeyEventKind::Release);
        let result = key_to_bytes_kitty(&k, FLAG_DISAMBIGUATE | FLAG_REPORT_EVENTS).unwrap();
        assert_eq!(result, b"\x1b[1;1:3A");
    }

    #[test]
    fn kitty_consumed_shift_no_alternate() {
        // Shift+a -> 'A' with shift consumed: report_alternate should NOT
        // emit a shifted codepoint because shift was consumed by the input
        // system.
        let k = KeyEvent::new(KeyCode::Char('A'), KeyModifiers::SHIFT)
            .with_unshifted_codepoint('a')
            .with_consumed_modifiers(KeyModifiers::SHIFT);
        let result = key_to_bytes_kitty(&k, FLAG_DISAMBIGUATE | FLAG_REPORT_ALTERNATE).unwrap();
        // Base codepoint 'a' (97), no shifted key, no modifier bits -> literal
        assert_eq!(result, b"A");
    }

    #[test]
    fn kitty_unshifted_codepoint_symbol() {
        // Shift+1 -> '!' with unshifted '1': the base codepoint is '1',
        // shifted codepoint is '!'.
        let k =
            KeyEvent::new(KeyCode::Char('!'), KeyModifiers::SHIFT).with_unshifted_codepoint('1');
        let result = key_to_bytes_kitty(&k, FLAG_DISAMBIGUATE | FLAG_REPORT_ALTERNATE).unwrap();
        // CSI 49:33 ; 2 u  ('1'=49, '!'=33, shift=2)
        assert_eq!(result, b"\x1b[49:33;2u");
    }

    #[test]
    fn kitty_consumed_modifiers_subtract() {
        // Ctrl+Shift+a -> ctrl-A, shift consumed, ctrl not consumed.
        // Effective modifiers = CONTROL only -> 1+4=5
        let k = KeyEvent::new(
            KeyCode::Char('A'),
            KeyModifiers::CONTROL | KeyModifiers::SHIFT,
        )
        .with_unshifted_codepoint('a')
        .with_consumed_modifiers(KeyModifiers::SHIFT);
        let result = key_to_bytes_kitty(&k, FLAG_DISAMBIGUATE).unwrap();
        // Base 'a' (97), modifier 5 (ctrl only)
        assert_eq!(result, b"\x1b[97;5u");
    }

    #[test]
    fn kitty_unmapped_key_returns_none() {
        // F(0) has no Kitty keyboard mapping (the F-ranges start at 1). The previous
        // fallback silently encoded unmapped keys as NUL (codepoint 0),
        // injecting a bogus null byte into the PTY; the current behavior is
        // to drop the key entirely.
        let k = key(KeyCode::F(0));
        assert_eq!(key_to_bytes_kitty(&k, FLAG_DISAMBIGUATE), None);
        // Also verify under FLAG_REPORT_ALL where every key becomes CSI u.
        assert_eq!(key_to_bytes_kitty(&k, FLAG_REPORT_ALL), None);
    }
}