tv 0.1.1

Terminal User Interface 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
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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
//! Kitty keyboard protocol support.
//!
//! Implements the progressive-enhancement keyboard protocol pioneered by
//! kitty and now adopted by foot, WezTerm, ghostty, and others. The
//! protocol allows unambiguous reporting of key events, including
//! modifier-only presses, release events, repeat events, alternate
//! keycodes, and associated text.
//!
//! Spec: <https://sw.kovidgoyal.net/kitty/keyboard-protocol/>
//!
//! # Wire format
//!
//! A kitty-encoded key event is a CSI `u` (or CSI letter) sequence with
//! three optional fields separated by `;`, each of which may have
//! `:`-separated sub-fields:
//!
//! ```text
//! CSI <keycode>[:<shifted>[:<base>]] ; <mods>[:<event_type>] ; <text codepoints> u
//! ```
//!
//! - `keycode`: the base unicode codepoint (or a PUA code for functional
//!   keys). Missing → defaults to `1`.
//! - `shifted` / `base`: alternate keycodes reported when
//!   `ALTERNATE_KEYS` is enabled.
//! - `mods`: `bitmask + 1`. Missing → `1` (no modifiers). The `+1` keeps
//!   the common no-modifier case non-zero so the field can be omitted.
//! - `event_type`: `1` = press (default), `2` = repeat, `3` = release.
//! - `text`: `:`-separated list of unicode codepoints produced by the
//!   key, reported when `ASSOCIATED_TEXT` is enabled.
//!
//! # Stack protocol
//!
//! Terminals maintain a per-screen stack of active flag sets. Applications
//! should `push` their desired flags on entry and `pop` on exit so they
//! don't clobber the surrounding shell or parent process's configuration.

use bitflags::bitflags;

bitflags! {
    /// Progressive-enhancement flags for the Kitty keyboard protocol.
    ///
    /// Each bit unlocks a specific reporting behavior. Terminals that
    /// don't support the protocol ignore the enable sequences entirely,
    /// so it is safe to push them unconditionally.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct KittyFlags: u32 {
        /// Disambiguate escape codes (e.g., distinguish Esc from Alt+key).
        const DISAMBIGUATE       = 0b00001;
        /// Report press, repeat, and release events separately.
        const EVENT_TYPES        = 0b00010;
        /// Include shifted and base-layout keycodes when they differ.
        const ALTERNATE_KEYS     = 0b00100;
        /// Report every key (including plain ASCII) as a CSI ... u escape.
        const ALL_AS_ESCAPES     = 0b01000;
        /// Report the associated text (what typing the key would produce).
        const ASSOCIATED_TEXT    = 0b10000;
    }
}

impl Default for KittyFlags {
    fn default() -> Self {
        KittyFlags::DISAMBIGUATE
    }
}

bitflags! {
    /// Keyboard modifiers, encoded in the spec's bitmask order.
    ///
    /// These values are the *decoded* bitmask — on the wire the kitty
    /// protocol transmits `bitmask + 1` so that the no-modifier case has a
    /// value of `1` rather than `0`. [`KeyEvent::from_sequence`] does the
    /// subtraction for you.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
    pub struct Modifiers: u8 {
        const SHIFT     = 0b00000001;
        const ALT       = 0b00000010;
        const CTRL      = 0b00000100;
        const SUPER     = 0b00001000;
        const HYPER     = 0b00010000;
        const META      = 0b00100000;
        const CAPS_LOCK = 0b01000000;
        const NUM_LOCK  = 0b10000000;
    }
}

impl Modifiers {
    /// Decode a wire-format modifier value (`bitmask + 1`) into a
    /// `Modifiers` set. A value of `0` or `1` means no modifiers.
    pub(crate) fn from_wire(value: u32) -> Self {
        // Spec: "If the modifier field is not present ... its default
        // value is 1 which means no modifiers." Both 0 (absent) and 1
        // (explicit no-mod) decode to empty.
        let bits = value.saturating_sub(1) as u8;
        Modifiers::from_bits_truncate(bits)
    }
}

/// Type of a key event.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyEventType {
    /// Initial key press.
    Press,
    /// Auto-repeat while held.
    Repeat,
    /// Key release.
    Release,
}

impl Default for KeyEventType {
    fn default() -> Self {
        KeyEventType::Press
    }
}

impl KeyEventType {
    fn from_wire(value: u32) -> Self {
        match value {
            // Spec: absent or 1 → press.
            0 | 1 => KeyEventType::Press,
            2 => KeyEventType::Repeat,
            3 => KeyEventType::Release,
            // Unknown values fall back to press — conservative behavior
            // matches notcurses's handling.
            _ => KeyEventType::Press,
        }
    }
}

/// Enhanced key event carrying full kitty-protocol information.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct KeyEvent {
    /// Unicode codepoint, or a PUA code for a functional key.
    /// Use [`KeyEvent::functional`] to resolve it to a named key.
    pub code: u32,
    /// Modifiers held during the event.
    pub modifiers: Modifiers,
    /// Press, repeat, or release.
    pub event_type: KeyEventType,
    /// Shifted keycode (if `ALTERNATE_KEYS` is enabled and it differs).
    pub shifted_key: Option<u32>,
    /// Base-layout keycode (if `ALTERNATE_KEYS` is enabled and it differs).
    pub base_key: Option<u32>,
    /// Associated text codepoints (if `ASSOCIATED_TEXT` is enabled).
    pub text: Option<String>,
}

/// Named functional keys carried on PUA codepoints.
///
/// Kitty reserves codepoints `57344..=63743` for keys that have no printable
/// representation (arrows, F-keys, keypad keys, media keys, and lone
/// modifier presses). Resolve a raw `code` with [`KeyEvent::functional`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FunctionalKey {
    Escape,
    Enter,
    Tab,
    Backspace,
    Insert,
    Delete,
    Left,
    Right,
    Up,
    Down,
    PageUp,
    PageDown,
    Home,
    End,
    CapsLock,
    ScrollLock,
    NumLock,
    PrintScreen,
    Pause,
    Menu,
    /// F1..F35.
    F(u8),
    // Keypad
    Kp0,
    Kp1,
    Kp2,
    Kp3,
    Kp4,
    Kp5,
    Kp6,
    Kp7,
    Kp8,
    Kp9,
    KpDecimal,
    KpDivide,
    KpMultiply,
    KpSubtract,
    KpAdd,
    KpEnter,
    KpEqual,
    KpSeparator,
    KpLeft,
    KpRight,
    KpUp,
    KpDown,
    KpPageUp,
    KpPageDown,
    KpHome,
    KpEnd,
    KpInsert,
    KpDelete,
    KpBegin,
    // Media
    MediaPlay,
    MediaPause,
    MediaPlayPause,
    MediaReverse,
    MediaStop,
    MediaFastForward,
    MediaRewind,
    MediaTrackNext,
    MediaTrackPrev,
    MediaRecord,
    LowerVolume,
    RaiseVolume,
    MuteVolume,
    // Lone modifier presses (reported when ALL_AS_ESCAPES is enabled)
    LeftShift,
    LeftCtrl,
    LeftAlt,
    LeftSuper,
    LeftHyper,
    LeftMeta,
    RightShift,
    RightCtrl,
    RightAlt,
    RightSuper,
    RightHyper,
    RightMeta,
    IsoLevel3Shift,
    IsoLevel5Shift,
}

impl KeyEvent {
    /// New press event for `code` with no modifiers.
    pub fn new(code: u32) -> Self {
        Self {
            code,
            ..Default::default()
        }
    }

    /// New press event for `code` with the given modifiers.
    pub fn with_modifiers(code: u32, modifiers: Modifiers) -> Self {
        Self {
            code,
            modifiers,
            ..Default::default()
        }
    }

    pub fn is_shift(&self) -> bool {
        self.modifiers.contains(Modifiers::SHIFT)
    }

    pub fn is_ctrl(&self) -> bool {
        self.modifiers.contains(Modifiers::CTRL)
    }

    pub fn is_alt(&self) -> bool {
        self.modifiers.contains(Modifiers::ALT)
    }

    pub fn is_super(&self) -> bool {
        self.modifiers.contains(Modifiers::SUPER)
    }

    pub fn is_press(&self) -> bool {
        matches!(self.event_type, KeyEventType::Press)
    }

    pub fn is_repeat(&self) -> bool {
        matches!(self.event_type, KeyEventType::Repeat)
    }

    pub fn is_release(&self) -> bool {
        matches!(self.event_type, KeyEventType::Release)
    }

    /// Resolve a PUA functional keycode, if this event carries one.
    pub fn functional(&self) -> Option<FunctionalKey> {
        functional_from_code(self.code)
    }

    /// Parse a CSI-u or CSI-letter kitty sequence into a KeyEvent.
    ///
    /// Accepts both the canonical `\x1b[...u` form and the legacy
    /// CSI-letter forms (`\x1b[...A/B/C/D/E/F/H` and `\x1b[...~`) that
    /// kitty still uses for arrows, Home/End, function keys, etc. when
    /// only partial flags are enabled.
    pub(crate) fn from_sequence(seq: &[u8]) -> Option<Self> {
        // Must begin with ESC '[' and have at least a terminator byte.
        if seq.len() < 3 || seq[0] != 0x1b || seq[1] != b'[' {
            return None;
        }
        let terminator = *seq.last()?;

        let params = std::str::from_utf8(&seq[2..seq.len() - 1]).ok()?;

        // Parse the `;`-separated primary fields. Each field may contain
        // `:`-separated sub-parameters. We collect as Vec<Vec<Option<u32>>>
        // so the default-when-empty semantics are explicit.
        let primary: Vec<Vec<Option<u32>>> = params
            .split(';')
            .map(|field| {
                field
                    .split(':')
                    .map(|sub| {
                        if sub.is_empty() {
                            None
                        } else {
                            sub.parse::<u32>().ok().map(Some).unwrap_or(None)
                        }
                    })
                    .collect()
            })
            .collect();

        // Helper: primary[i].sub[j], substituting default when absent.
        let sub = |i: usize, j: usize, default: u32| -> u32 {
            primary
                .get(i)
                .and_then(|v| v.get(j).copied().flatten())
                .unwrap_or(default)
        };
        let sub_opt = |i: usize, j: usize| -> Option<u32> {
            primary.get(i).and_then(|v| v.get(j).copied().flatten())
        };

        // Field 1: keycode[:shifted[:base]]. Default keycode is 1 per spec.
        let code = match terminator {
            // For CSI-letter forms the first parameter is "1" (a function
            // key marker) — the real key is identified by the terminator.
            // We synthesize the PUA codepoint below.
            b'u' | b'~' => sub(0, 0, 1),
            _ => 1,
        };
        let shifted_key = sub_opt(0, 1);
        let base_key = sub_opt(0, 2);

        // Field 2: modifiers[:event_type]. Both default to 1 (no-op).
        let mods_wire = sub(1, 0, 1);
        let event_wire = sub(1, 1, 1);
        let modifiers = Modifiers::from_wire(mods_wire);
        let event_type = KeyEventType::from_wire(event_wire);

        // Field 3: associated text codepoints, `:`-separated.
        let text = primary.get(2).and_then(|field| {
            let mut s = String::new();
            for cp in field.iter().flatten() {
                if let Some(c) = char::from_u32(*cp) {
                    s.push(c);
                }
            }
            if s.is_empty() { None } else { Some(s) }
        });

        // Resolve the terminator to a semantic codepoint. For letter
        // terminators we substitute the matching PUA code so downstream
        // consumers can treat all forms uniformly via `.functional()`.
        let resolved_code = match terminator {
            b'u' => code,
            b'~' => functional_tilde_code(code).unwrap_or(code),
            b'A' => PUA_UP,
            b'B' => PUA_DOWN,
            b'C' => PUA_RIGHT,
            b'D' => PUA_LEFT,
            b'E' => PUA_KP_BEGIN,
            b'F' => PUA_END,
            b'H' => PUA_HOME,
            b'P' => PUA_F1,
            b'Q' => PUA_F2,
            b'R' => PUA_F3,
            b'S' => PUA_F4,
            // BackTab — xterm encodes Shift+Tab as a bare `\x1b[Z`, with
            // no modifier field. Surface it as Tab+Shift so the input
            // layer can collapse it back to a semantic BackTab.
            b'Z' => {
                return Some(KeyEvent {
                    code: PUA_TAB,
                    modifiers: Modifiers::SHIFT,
                    event_type: KeyEventType::Press,
                    shifted_key: None,
                    base_key: None,
                    text: None,
                });
            }
            _ => return None,
        };

        Some(KeyEvent {
            code: resolved_code,
            modifiers,
            event_type,
            shifted_key,
            base_key,
            text,
        })
    }
}

// Kitty assigns codepoints in the Private Use Area (57344..=63743) to keys
// with no printable representation. Anything outside this range that isn't
// a real Unicode scalar is left alone.

const PUA_ESCAPE: u32 = 57344;
const PUA_ENTER: u32 = 57345;
const PUA_TAB: u32 = 57346;
const PUA_BACKSPACE: u32 = 57347;
const PUA_INSERT: u32 = 57348;
const PUA_DELETE: u32 = 57349;
const PUA_LEFT: u32 = 57350;
const PUA_RIGHT: u32 = 57351;
const PUA_UP: u32 = 57352;
const PUA_DOWN: u32 = 57353;
const PUA_PAGE_UP: u32 = 57354;
const PUA_PAGE_DOWN: u32 = 57355;
const PUA_HOME: u32 = 57356;
const PUA_END: u32 = 57357;
const PUA_CAPS_LOCK: u32 = 57358;
const PUA_SCROLL_LOCK: u32 = 57359;
const PUA_NUM_LOCK: u32 = 57360;
const PUA_PRINT_SCREEN: u32 = 57361;
const PUA_PAUSE: u32 = 57362;
const PUA_MENU: u32 = 57363;
const PUA_F1: u32 = 57364;
const PUA_F2: u32 = 57365;
const PUA_F3: u32 = 57366;
const PUA_F4: u32 = 57367;
// F5..F12 = 57368..=57375; F13..F35 = 57376..=57398 (per spec).
// Keypad digits 0..9 = 57399..=57408; keypad cluster ends at
// KpBegin = 57427. Media keys 57428..=57440; lone-modifier presses
// 57441..=57454. Everything outside this densely-packed run is handled
// as individual match arms in `functional_from_code`.
const PUA_KP_BEGIN: u32 = 57427;

fn functional_from_code(code: u32) -> Option<FunctionalKey> {
    use FunctionalKey::*;
    // F1..F35 are contiguous 57364..=57398.
    if (57364..=57398).contains(&code) {
        let n = (code - 57364 + 1) as u8;
        return Some(F(n));
    }
    // Keypad digits 0..9: 57399..=57408.
    if (57399..=57408).contains(&code) {
        let k = match code - 57399 {
            0 => Kp0,
            1 => Kp1,
            2 => Kp2,
            3 => Kp3,
            4 => Kp4,
            5 => Kp5,
            6 => Kp6,
            7 => Kp7,
            8 => Kp8,
            _ => Kp9,
        };
        return Some(k);
    }
    match code {
        PUA_ESCAPE => Some(Escape),
        PUA_ENTER => Some(Enter),
        PUA_TAB => Some(Tab),
        PUA_BACKSPACE => Some(Backspace),
        PUA_INSERT => Some(Insert),
        PUA_DELETE => Some(Delete),
        PUA_LEFT => Some(Left),
        PUA_RIGHT => Some(Right),
        PUA_UP => Some(Up),
        PUA_DOWN => Some(Down),
        PUA_PAGE_UP => Some(PageUp),
        PUA_PAGE_DOWN => Some(PageDown),
        PUA_HOME => Some(Home),
        PUA_END => Some(End),
        PUA_CAPS_LOCK => Some(CapsLock),
        PUA_SCROLL_LOCK => Some(ScrollLock),
        PUA_NUM_LOCK => Some(NumLock),
        PUA_PRINT_SCREEN => Some(PrintScreen),
        PUA_PAUSE => Some(Pause),
        PUA_MENU => Some(Menu),
        // Keypad cluster (the digits were handled above)
        57409 => Some(KpDecimal),
        57410 => Some(KpDivide),
        57411 => Some(KpMultiply),
        57412 => Some(KpSubtract),
        57413 => Some(KpAdd),
        57414 => Some(KpEnter),
        57415 => Some(KpEqual),
        57416 => Some(KpSeparator),
        57417 => Some(KpLeft),
        57418 => Some(KpRight),
        57419 => Some(KpUp),
        57420 => Some(KpDown),
        57421 => Some(KpPageUp),
        57422 => Some(KpPageDown),
        57423 => Some(KpHome),
        57424 => Some(KpEnd),
        57425 => Some(KpInsert),
        57426 => Some(KpDelete),
        PUA_KP_BEGIN => Some(KpBegin),
        // Media
        57428 => Some(MediaPlay),
        57429 => Some(MediaPause),
        57430 => Some(MediaPlayPause),
        57431 => Some(MediaReverse),
        57432 => Some(MediaStop),
        57433 => Some(MediaFastForward),
        57434 => Some(MediaRewind),
        57435 => Some(MediaTrackNext),
        57436 => Some(MediaTrackPrev),
        57437 => Some(MediaRecord),
        57438 => Some(LowerVolume),
        57439 => Some(RaiseVolume),
        57440 => Some(MuteVolume),
        // Lone modifier presses
        57441 => Some(LeftShift),
        57442 => Some(LeftCtrl),
        57443 => Some(LeftAlt),
        57444 => Some(LeftSuper),
        57445 => Some(LeftHyper),
        57446 => Some(LeftMeta),
        57447 => Some(RightShift),
        57448 => Some(RightCtrl),
        57449 => Some(RightAlt),
        57450 => Some(RightSuper),
        57451 => Some(RightHyper),
        57452 => Some(RightMeta),
        57453 => Some(IsoLevel3Shift),
        57454 => Some(IsoLevel5Shift),
        // Some terminals send legacy C0 codepoints instead of the PUA
        // ones when only DISAMBIGUATE is enabled. Recognize them so
        // `\x1b[9;2u` (Shift+Tab) surfaces as Tab rather than a Char('\t').
        0x08 => Some(Backspace),
        0x09 => Some(Tab),
        0x0d => Some(Enter),
        0x1b => Some(Escape),
        0x7f => Some(Backspace),
        _ => None,
    }
}

// Map a `\x1b[N~` parameter to its PUA-equivalent codepoint so callers can
// treat legacy and kitty sequences uniformly. These numbers are the classic
// VT220 function-key codes.
fn functional_tilde_code(n: u32) -> Option<u32> {
    match n {
        // Some terminals (rxvt, older xterm) emit 1~/4~ for Home/End
        // instead of H/F. kitty accepts both.
        1 => Some(PUA_HOME),
        2 => Some(PUA_INSERT),
        3 => Some(PUA_DELETE),
        4 => Some(PUA_END),
        5 => Some(PUA_PAGE_UP),
        6 => Some(PUA_PAGE_DOWN),
        7 => Some(PUA_HOME),
        8 => Some(PUA_END),
        11 => Some(PUA_F1),
        12 => Some(PUA_F2),
        13 => Some(PUA_F3),
        14 => Some(PUA_F4),
        15 => Some(57368), // F5
        17 => Some(57369), // F6
        18 => Some(57370), // F7
        19 => Some(57371), // F8
        20 => Some(57372), // F9
        21 => Some(57373), // F10
        23 => Some(57374), // F11
        24 => Some(57375), // F12
        _ => None,
    }
}

/// `CSI > flags u` — push `flags` onto the terminal's keyboard-mode stack.
/// This is the primary "enable" operation: the terminal remembers the
/// previous state so [`pop_sequence`] can restore it.
pub(crate) fn push_sequence(flags: KittyFlags) -> String {
    format!("\x1b[>{}u", flags.bits())
}

/// `CSI < n u` — pop `n` entries from the keyboard-mode stack. Use this
/// on exit to restore the parent process's configuration.
pub(crate) fn pop_n_sequence(n: u32) -> String {
    format!("\x1b[<{}u", n)
}

/// `CSI < u` — pop one entry from the keyboard-mode stack.
pub(crate) fn pop_sequence() -> String {
    "\x1b[<u".to_string()
}

/// Mode argument to [`set_sequence`].
///
/// Controls how the flags given to `set_sequence` combine with the current
/// set. Not all terminals implement every mode; `Replace` is the most
/// portable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SetMode {
    /// Replace the current set with the given flags (default).
    Replace = 1,
    /// OR the given flags into the current set.
    Union = 2,
    /// Clear the given flags from the current set.
    Difference = 3,
}

/// `CSI = flags ; mode u` — set the top-of-stack flags directly, without
/// pushing a new entry. Prefer [`push_sequence`] for most uses.
pub(crate) fn set_sequence(flags: KittyFlags, mode: SetMode) -> String {
    format!("\x1b[={};{}u", flags.bits(), mode as u8)
}

/// `CSI ? u` — query the terminal for the currently active flags. The
/// reply comes back as `CSI ? <flags> u`, which [`KeyEvent::from_sequence`]
/// does *not* parse (this is an initialization-time message, not a key
/// event).
pub(crate) fn query_sequence() -> String {
    "\x1b[?u".to_string()
}

#[cfg(test)]
fn enable_sequence(flags: KittyFlags) -> String {
    push_sequence(flags)
}

#[cfg(test)]
fn disable_sequence() -> String {
    pop_sequence()
}

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

    #[test]
    fn flag_bits_match_spec() {
        assert_eq!(KittyFlags::DISAMBIGUATE.bits(), 1);
        assert_eq!(KittyFlags::EVENT_TYPES.bits(), 2);
        assert_eq!(KittyFlags::ALTERNATE_KEYS.bits(), 4);
        assert_eq!(KittyFlags::ALL_AS_ESCAPES.bits(), 8);
        assert_eq!(KittyFlags::ASSOCIATED_TEXT.bits(), 16);
    }

    #[test]
    fn default_is_disambiguate() {
        assert_eq!(KittyFlags::default(), KittyFlags::DISAMBIGUATE);
    }

    #[test]
    fn modifier_wire_subtracts_one() {
        // 1 (absent or explicit "no mods") decodes to empty.
        assert_eq!(Modifiers::from_wire(1), Modifiers::empty());
        assert_eq!(Modifiers::from_wire(0), Modifiers::empty());
        // 2 means Shift alone (bitmask 1).
        assert_eq!(Modifiers::from_wire(2), Modifiers::SHIFT);
        // 5 means Ctrl alone (bitmask 4) — NOT Ctrl+Shift.
        assert_eq!(Modifiers::from_wire(5), Modifiers::CTRL);
        // 6 means Ctrl+Shift (bitmask 5 = 4|1).
        assert_eq!(Modifiers::from_wire(6), Modifiers::CTRL | Modifiers::SHIFT);
        // 8 means Ctrl+Alt (bitmask 7 = 4|2|1) — wait that's 3 mods.
        // 8 means bitmask 7 = SHIFT|ALT|CTRL.
        assert_eq!(
            Modifiers::from_wire(8),
            Modifiers::SHIFT | Modifiers::ALT | Modifiers::CTRL
        );
    }

    #[test]
    fn parse_simple_u() {
        let e = KeyEvent::from_sequence(b"\x1b[65u").unwrap();
        assert_eq!(e.code, 65);
        assert_eq!(e.modifiers, Modifiers::empty());
        assert_eq!(e.event_type, KeyEventType::Press);
    }

    #[test]
    fn parse_defaults_keycode_to_one() {
        // "CSI u" with no keycode — spec says default is 1.
        let e = KeyEvent::from_sequence(b"\x1b[u").unwrap();
        assert_eq!(e.code, 1);
    }

    #[test]
    fn parse_ctrl_alone_is_wire_five() {
        // ctrl bit = 4, wire value = 5.
        let e = KeyEvent::from_sequence(b"\x1b[65;5u").unwrap();
        assert!(e.is_ctrl());
        assert!(!e.is_shift());
    }

    #[test]
    fn parse_ctrl_shift_is_wire_six() {
        // ctrl|shift = 5, wire = 6.
        let e = KeyEvent::from_sequence(b"\x1b[65;6u").unwrap();
        assert!(e.is_ctrl());
        assert!(e.is_shift());
    }

    #[test]
    fn parse_release_is_colon_subfield() {
        // Event type is a SUB-field of modifiers, not a new `;` field.
        // wire: codepoint=97, mods=1 (none), event_type=3 (release).
        let e = KeyEvent::from_sequence(b"\x1b[97;1:3u").unwrap();
        assert_eq!(e.code, 97);
        assert_eq!(e.event_type, KeyEventType::Release);
        assert!(e.is_release());
    }

    #[test]
    fn parse_repeat_with_ctrl() {
        let e = KeyEvent::from_sequence(b"\x1b[97;5:2u").unwrap();
        assert!(e.is_ctrl());
        assert_eq!(e.event_type, KeyEventType::Repeat);
        assert!(e.is_repeat());
    }

    #[test]
    fn parse_alternate_keys_are_subfields_of_keycode() {
        // 'a' with shift, shifted to 'A'. Spec form: `97:65;2u`.
        // (shift wire = 2).
        let e = KeyEvent::from_sequence(b"\x1b[97:65;2u").unwrap();
        assert_eq!(e.code, 97);
        assert_eq!(e.shifted_key, Some(65));
        assert!(e.is_shift());
    }

    #[test]
    fn parse_base_key_is_second_subfield() {
        // shifted 65, base 97 (imagine a Dvorak user pressing
        // the position that maps to 'a' in QWERTY but producing 'a').
        let e = KeyEvent::from_sequence(b"\x1b[97:65:97;2u").unwrap();
        assert_eq!(e.code, 97);
        assert_eq!(e.shifted_key, Some(65));
        assert_eq!(e.base_key, Some(97));
    }

    #[test]
    fn parse_associated_text() {
        // 'a' with text codepoint 97.
        let e = KeyEvent::from_sequence(b"\x1b[97;1;97u").unwrap();
        assert_eq!(e.text.as_deref(), Some("a"));
    }

    #[test]
    fn parse_associated_text_multi_codepoint() {
        // dead-key composition producing "é" (U+00E9).
        let e = KeyEvent::from_sequence(b"\x1b[101;1;233u").unwrap();
        assert_eq!(e.text.as_deref(), Some("é"));
    }

    #[test]
    fn parse_rejects_malformed() {
        assert!(KeyEvent::from_sequence(b"").is_none());
        assert!(KeyEvent::from_sequence(b"\x1b[").is_none());
        assert!(KeyEvent::from_sequence(b"hi").is_none());
        // Unknown terminator.
        assert!(KeyEvent::from_sequence(b"\x1b[65x").is_none());
    }

    #[test]
    fn parse_legacy_arrow_uses_pua_code() {
        // `\x1b[1;5A` = Ctrl+Up in xterm-style. Modifier wire = 5.
        let e = KeyEvent::from_sequence(b"\x1b[1;5A").unwrap();
        assert_eq!(e.functional(), Some(FunctionalKey::Up));
        assert!(e.is_ctrl());
    }

    #[test]
    fn parse_legacy_tilde_with_modifiers() {
        // Delete with Shift: `\x1b[3;2~`.
        let e = KeyEvent::from_sequence(b"\x1b[3;2~").unwrap();
        assert_eq!(e.functional(), Some(FunctionalKey::Delete));
        assert!(e.is_shift());
    }

    #[test]
    fn parse_kitty_arrow_with_event_type() {
        // kitty: `\x1b[1;2:3A` = Shift+Up release.
        let e = KeyEvent::from_sequence(b"\x1b[1;2:3A").unwrap();
        assert_eq!(e.functional(), Some(FunctionalKey::Up));
        assert!(e.is_shift());
        assert_eq!(e.event_type, KeyEventType::Release);
    }

    #[test]
    fn parse_function_key_legacy() {
        // F5: `\x1b[15~`.
        let e = KeyEvent::from_sequence(b"\x1b[15~").unwrap();
        assert_eq!(e.functional(), Some(FunctionalKey::F(5)));
    }

    #[test]
    fn parse_function_key_kitty_pua() {
        // F5 via kitty PUA: `\x1b[57368u`.
        let e = KeyEvent::from_sequence(b"\x1b[57368u").unwrap();
        assert_eq!(e.functional(), Some(FunctionalKey::F(5)));
    }

    #[test]
    fn parse_f1_legacy_letter() {
        // F1 via `\x1bOP` is handled in input.rs; here we test the CSI
        // letter form `\x1b[1;2P` = Shift+F1.
        let e = KeyEvent::from_sequence(b"\x1b[1;2P").unwrap();
        assert_eq!(e.functional(), Some(FunctionalKey::F(1)));
        assert!(e.is_shift());
    }

    #[test]
    fn parse_functional_resolves_pua_enter() {
        let e = KeyEvent::from_sequence(b"\x1b[57345u").unwrap();
        assert_eq!(e.functional(), Some(FunctionalKey::Enter));
    }

    #[test]
    fn parse_functional_resolves_keypad_digit() {
        let e = KeyEvent::from_sequence(b"\x1b[57404u").unwrap();
        assert_eq!(e.functional(), Some(FunctionalKey::Kp5));
    }

    #[test]
    fn parse_functional_resolves_lone_modifier() {
        // PUA for LeftShift = 57441.
        let e = KeyEvent::from_sequence(b"\x1b[57441u").unwrap();
        assert_eq!(e.functional(), Some(FunctionalKey::LeftShift));
    }

    #[test]
    fn push_sequence_encodes_flag_bits() {
        assert_eq!(push_sequence(KittyFlags::DISAMBIGUATE), "\x1b[>1u");
        assert_eq!(
            push_sequence(KittyFlags::DISAMBIGUATE | KittyFlags::EVENT_TYPES),
            "\x1b[>3u"
        );
        let all = KittyFlags::DISAMBIGUATE
            | KittyFlags::EVENT_TYPES
            | KittyFlags::ALTERNATE_KEYS
            | KittyFlags::ALL_AS_ESCAPES
            | KittyFlags::ASSOCIATED_TEXT;
        assert_eq!(push_sequence(all), "\x1b[>31u");
    }

    #[test]
    fn pop_sequences() {
        assert_eq!(pop_sequence(), "\x1b[<u");
        assert_eq!(pop_n_sequence(3), "\x1b[<3u");
    }

    #[test]
    fn set_sequence_encodes_mode() {
        let flags = KittyFlags::DISAMBIGUATE | KittyFlags::EVENT_TYPES;
        assert_eq!(set_sequence(flags, SetMode::Replace), "\x1b[=3;1u");
        assert_eq!(set_sequence(flags, SetMode::Union), "\x1b[=3;2u");
        assert_eq!(set_sequence(flags, SetMode::Difference), "\x1b[=3;3u");
    }

    #[test]
    fn query_returns_csi_question_u() {
        assert_eq!(query_sequence(), "\x1b[?u");
    }

    #[test]
    fn legacy_aliases_delegate() {
        assert_eq!(
            enable_sequence(KittyFlags::DISAMBIGUATE),
            push_sequence(KittyFlags::DISAMBIGUATE),
        );
        assert_eq!(disable_sequence(), pop_sequence());
    }
}