turbo-vision 2.3.1

A Rust implementation of the classic Borland Turbo Vision text-mode UI framework
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
// (C) 2025 - Enzo Lombardi

//! Event system - keyboard and mouse event handling with Borland-compatible key codes.

use super::command::CommandId;
use super::geometry::Point;
use crossterm::event::{KeyCode as CKC, KeyEvent, KeyModifiers};
use std::fmt;
use std::time::{Duration, Instant};

/// Keyboard code (scan code + character)
pub type KeyCode = u16;

// Special key codes (high byte = scan code, low byte = char)
pub const KB_ESC: KeyCode = 0x011B;
pub const KB_ENTER: KeyCode = 0x1C0D;
pub const KB_BACKSPACE: KeyCode = 0x0E08;
pub const KB_TAB: KeyCode = 0x0F09;
pub const KB_SHIFT_TAB: KeyCode = 0x0F00; // Shift+Tab for reverse focus

// Function keys
pub const KB_F1: KeyCode = 0x3B00;
pub const KB_F2: KeyCode = 0x3C00;
pub const KB_F3: KeyCode = 0x3D00;
pub const KB_F4: KeyCode = 0x3E00;
pub const KB_F5: KeyCode = 0x3F00;
pub const KB_F6: KeyCode = 0x4000;
pub const KB_F7: KeyCode = 0x4100;
pub const KB_F8: KeyCode = 0x4200;
pub const KB_F9: KeyCode = 0x4300;
pub const KB_F10: KeyCode = 0x4400;
pub const KB_F11: KeyCode = 0x8500;
pub const KB_F12: KeyCode = 0x8600; // F12 for ASCII screen dump
pub const KB_CTRL_F12: KeyCode = 0x8A00; // Ctrl+F12 (Borland/BIOS kbCtrlF12) — bound to PNG screenshot

// Arrow keys
pub const KB_UP: KeyCode = 0x4800;
pub const KB_DOWN: KeyCode = 0x5000;
pub const KB_LEFT: KeyCode = 0x4B00;
pub const KB_RIGHT: KeyCode = 0x4D00;

pub const KB_HOME: KeyCode = 0x4700;
pub const KB_END: KeyCode = 0x4F00;
pub const KB_PGUP: KeyCode = 0x4900;
pub const KB_PGDN: KeyCode = 0x5100;
pub const KB_INS: KeyCode = 0x5200;
pub const KB_DEL: KeyCode = 0x5300;

// Alt + letter (scan codes from PC keyboard)
pub const KB_ALT_A: KeyCode = 0x1E00;
pub const KB_ALT_B: KeyCode = 0x3000;
pub const KB_ALT_C: KeyCode = 0x2E00;
pub const KB_ALT_D: KeyCode = 0x2000;
pub const KB_ALT_E: KeyCode = 0x1200;
pub const KB_ALT_F: KeyCode = 0x2100;
pub const KB_ALT_G: KeyCode = 0x2200;
pub const KB_ALT_H: KeyCode = 0x2300;
pub const KB_ALT_I: KeyCode = 0x1700;
pub const KB_ALT_J: KeyCode = 0x2400;
pub const KB_ALT_K: KeyCode = 0x2500;
pub const KB_ALT_L: KeyCode = 0x2600;
pub const KB_ALT_M: KeyCode = 0x3200;
pub const KB_ALT_N: KeyCode = 0x3100;
pub const KB_ALT_O: KeyCode = 0x1800;
pub const KB_ALT_P: KeyCode = 0x1900;
pub const KB_ALT_Q: KeyCode = 0x1000;
pub const KB_ALT_R: KeyCode = 0x1300;
pub const KB_ALT_S: KeyCode = 0x1F00;
pub const KB_ALT_T: KeyCode = 0x1400;
pub const KB_ALT_U: KeyCode = 0x1600;
pub const KB_ALT_V: KeyCode = 0x2F00;
pub const KB_ALT_W: KeyCode = 0x1100;
pub const KB_ALT_X: KeyCode = 0x2D00;
pub const KB_ALT_Y: KeyCode = 0x1500;
pub const KB_ALT_Z: KeyCode = 0x2C00;
// Alt + digit (BIOS scan codes) — window selection (Borland cmSelectWindowNum)
pub const KB_ALT_1: KeyCode = 0x7800;
pub const KB_ALT_2: KeyCode = 0x7900;
pub const KB_ALT_3: KeyCode = 0x7A00;
pub const KB_ALT_4: KeyCode = 0x7B00;
pub const KB_ALT_5: KeyCode = 0x7C00;
pub const KB_ALT_6: KeyCode = 0x7D00;
pub const KB_ALT_7: KeyCode = 0x7E00;
pub const KB_ALT_8: KeyCode = 0x7F00;
pub const KB_ALT_9: KeyCode = 0x8000;

pub const KB_ALT_F1: KeyCode = 0x6800; // Alt+F1 for help history back
pub const KB_ALT_F3: KeyCode = 0x6A00;

// ESC + letter (for macOS Alt emulation)
pub const KB_ESC_F: KeyCode = 0x2101; // ESC+F
pub const KB_ESC_H: KeyCode = 0x2301; // ESC+H
pub const KB_ESC_X: KeyCode = 0x2D01; // ESC+X
pub const KB_ESC_A: KeyCode = 0x1E01; // ESC+A
pub const KB_ESC_O: KeyCode = 0x1801; // ESC+O
pub const KB_ESC_E: KeyCode = 0x1201; // ESC+E (Edit menu)
pub const KB_ESC_S: KeyCode = 0x1F01; // ESC+S (Search menu)
pub const KB_ESC_V: KeyCode = 0x2F01; // ESC+V (View menu)

pub const KB_CTRL_A: KeyCode = 0x0001; // CTRL+A
pub const KB_CTRL_B: KeyCode = 0x0002; // CTRL+B
pub const KB_CTRL_C: KeyCode = 0x0003; // CTRL+C
pub const KB_CTRL_D: KeyCode = 0x0004; // CTRL+D
pub const KB_CTRL_E: KeyCode = 0x0005; // CTRL+E
pub const KB_CTRL_F: KeyCode = 0x0006; // CTRL+F
pub const KB_CTRL_G: KeyCode = 0x0007; // CTRL+G
pub const KB_CTRL_H: KeyCode = 0x0008; // CTRL+H
pub const KB_CTRL_I: KeyCode = 0x0009; // CTRL+I
pub const KB_CTRL_J: KeyCode = 0x000a; // CTRL+J
pub const KB_CTRL_K: KeyCode = 0x000b; // CTRL+K
pub const KB_CTRL_L: KeyCode = 0x000c; // CTRL+L
pub const KB_CTRL_M: KeyCode = 0x000d; // CTRL+M
pub const KB_CTRL_N: KeyCode = 0x000e; // CTRL+N
pub const KB_CTRL_O: KeyCode = 0x000f; // CTRL+O
pub const KB_CTRL_P: KeyCode = 0x0010; // CTRL+P
pub const KB_CTRL_Q: KeyCode = 0x0011; // CTRL+Q
pub const KB_CTRL_R: KeyCode = 0x0012; // CTRL+R
pub const KB_CTRL_S: KeyCode = 0x0013; // CTRL+S
pub const KB_CTRL_T: KeyCode = 0x0014; // CTRL+T
pub const KB_CTRL_U: KeyCode = 0x0015; // CTRL+U
pub const KB_CTRL_V: KeyCode = 0x0016; // CTRL+V
pub const KB_CTRL_W: KeyCode = 0x0017; // CTRL+W
pub const KB_CTRL_X: KeyCode = 0x0018; // CTRL+X
pub const KB_CTRL_Y: KeyCode = 0x0019; // CTRL+Y
pub const KB_CTRL_Z: KeyCode = 0x001a; // CTRL+Z

// Double ESC for closing dialogs
pub const KB_ESC_ESC: KeyCode = 0x011C; // Double ESC

/// Event types (matching original Turbo Vision)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EventType {
    Nothing,
    Keyboard,
    MouseDown,
    MouseUp,
    MouseMove,
    MouseAuto,
    MouseWheelUp,   // Mouse wheel scrolled up
    MouseWheelDown, // Mouse wheel scrolled down
    Command,
    Broadcast,
}

// Event masks (for filtering)
pub const EV_NOTHING: u16 = 0x0000;
pub const EV_MOUSE_DOWN: u16 = 0x0001;
pub const EV_MOUSE_UP: u16 = 0x0002;
pub const EV_MOUSE_MOVE: u16 = 0x0004;
pub const EV_MOUSE_AUTO: u16 = 0x0008;
pub const EV_MOUSE_WHEEL_UP: u16 = 0x0010;
pub const EV_MOUSE_WHEEL_DOWN: u16 = 0x0020;
pub const EV_MOUSE: u16 = 0x003F; // All mouse events (including wheel)
pub const EV_KEYBOARD: u16 = 0x0040;
pub const EV_COMMAND: u16 = 0x0100;
pub const EV_BROADCAST: u16 = 0x0200;
pub const EV_MESSAGE: u16 = 0xFF00; // Command | Broadcast

// Mouse button masks
pub const MB_LEFT_BUTTON: u8 = 0x01;
pub const MB_MIDDLE_BUTTON: u8 = 0x02;
pub const MB_RIGHT_BUTTON: u8 = 0x04;

/// Mouse event data
#[derive(Debug, Clone, Copy)]
pub struct MouseEvent {
    pub pos: Point,
    pub buttons: u8, // button state (bit flags)
    pub double_click: bool,
}

/// A unified event structure
///
/// # Examples
///
/// ```
/// use turbo_vision::core::event::{Event, EventType, KB_ESC, KB_ENTER};
/// use turbo_vision::core::command::CM_QUIT;
///
/// // Create keyboard event
/// let esc_event = Event::keyboard(KB_ESC);
/// assert_eq!(esc_event.key_code, KB_ESC);
///
/// // Create command event
/// let quit_cmd = Event::command(CM_QUIT);
/// assert_eq!(quit_cmd.command, CM_QUIT);
///
/// // Clear an event to mark it as handled
/// let mut event = Event::keyboard(KB_ENTER);
/// event.clear();
/// assert_eq!(event.what, EventType::Nothing);
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Event {
    pub what: EventType,
    pub key_code: KeyCode,
    pub key_modifiers: KeyModifiers,
    pub mouse: MouseEvent,
    pub command: CommandId,
    /// Extra data carried by command/broadcast events.
    ///
    /// Matches Borland's TEvent.message.infoPtr/infoInt (e.g. the radio-button
    /// group id on a selection broadcast). Zero when unused.
    pub info: u16,
}

impl Event {
    pub fn nothing() -> Self {
        Self {
            what: EventType::Nothing,
            key_code: 0,
            key_modifiers: KeyModifiers::empty(),
            mouse: MouseEvent {
                pos: Point::zero(),
                buttons: 0,
                double_click: false,
            },
            command: 0,
            info: 0,
        }
    }

    pub fn keyboard(key_code: KeyCode) -> Self {
        Self {
            what: EventType::Keyboard,
            key_code,
            key_modifiers: KeyModifiers::empty(),
            ..Self::nothing()
        }
    }

    pub fn command(cmd: CommandId) -> Self {
        Self {
            what: EventType::Command,
            command: cmd,
            ..Self::nothing()
        }
    }

    pub fn broadcast(cmd: CommandId) -> Self {
        Self {
            what: EventType::Broadcast,
            command: cmd,
            ..Self::nothing()
        }
    }

    /// Create a broadcast event carrying extra data in `info`.
    pub fn broadcast_with_info(cmd: CommandId, info: u16) -> Self {
        Self {
            what: EventType::Broadcast,
            command: cmd,
            info,
            ..Self::nothing()
        }
    }

    pub fn mouse(event_type: EventType, pos: Point, buttons: u8, double_click: bool) -> Self {
        Self {
            what: event_type,
            mouse: MouseEvent {
                pos,
                buttons,
                double_click,
            },
            ..Self::nothing()
        }
    }

    pub fn from_crossterm_key(key_event: KeyEvent) -> Self {
        let key_code = crossterm_to_keycode(key_event);
        Self {
            what: EventType::Keyboard,
            key_code,
            key_modifiers: key_event.modifiers,
            ..Self::nothing()
        }
    }

    /// Mark this event as handled (clear it)
    pub fn clear(&mut self) {
        self.what = EventType::Nothing;
    }
}

impl Default for Event {
    fn default() -> Self {
        Self::nothing()
    }
}

impl fmt::Display for Event {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.what {
            EventType::Nothing => write!(f, "Event::Nothing"),
            EventType::Keyboard => {
                write!(f, "Event::Keyboard(key_code={:#06x}", self.key_code)?;
                if !self.key_modifiers.is_empty() {
                    write!(f, ", modifiers={:?}", self.key_modifiers)?;
                }
                write!(f, ")")
            }
            EventType::MouseDown => write!(
                f,
                "Event::MouseDown({}, buttons={:#04x}{})",
                self.mouse.pos,
                self.mouse.buttons,
                if self.mouse.double_click {
                    ", double_click"
                } else {
                    ""
                }
            ),
            EventType::MouseUp => write!(
                f,
                "Event::MouseUp({}, buttons={:#04x})",
                self.mouse.pos, self.mouse.buttons
            ),
            EventType::MouseMove => write!(
                f,
                "Event::MouseMove({}, buttons={:#04x})",
                self.mouse.pos, self.mouse.buttons
            ),
            EventType::MouseAuto => write!(
                f,
                "Event::MouseAuto({}, buttons={:#04x})",
                self.mouse.pos, self.mouse.buttons
            ),
            EventType::MouseWheelUp => write!(f, "Event::MouseWheelUp({})", self.mouse.pos),
            EventType::MouseWheelDown => write!(f, "Event::MouseWheelDown({})", self.mouse.pos),
            EventType::Command => write!(f, "Event::Command({:#06x})", self.command),
            EventType::Broadcast => write!(f, "Event::Broadcast({:#06x})", self.command),
        }
    }
}

/// Convert a lowercase letter to its Alt+letter key code
/// Returns None if the character is not a letter
fn char_to_alt_code(c: char) -> Option<KeyCode> {
    match c {
        '1' => Some(KB_ALT_1),
        '2' => Some(KB_ALT_2),
        '3' => Some(KB_ALT_3),
        '4' => Some(KB_ALT_4),
        '5' => Some(KB_ALT_5),
        '6' => Some(KB_ALT_6),
        '7' => Some(KB_ALT_7),
        '8' => Some(KB_ALT_8),
        '9' => Some(KB_ALT_9),
        'a' => Some(KB_ALT_A),
        'b' => Some(KB_ALT_B),
        'c' => Some(KB_ALT_C),
        'd' => Some(KB_ALT_D),
        'e' => Some(KB_ALT_E),
        'f' => Some(KB_ALT_F),
        'g' => Some(KB_ALT_G),
        'h' => Some(KB_ALT_H),
        'i' => Some(KB_ALT_I),
        'j' => Some(KB_ALT_J),
        'k' => Some(KB_ALT_K),
        'l' => Some(KB_ALT_L),
        'm' => Some(KB_ALT_M),
        'n' => Some(KB_ALT_N),
        'o' => Some(KB_ALT_O),
        'p' => Some(KB_ALT_P),
        'q' => Some(KB_ALT_Q),
        'r' => Some(KB_ALT_R),
        's' => Some(KB_ALT_S),
        't' => Some(KB_ALT_T),
        'u' => Some(KB_ALT_U),
        'v' => Some(KB_ALT_V),
        'w' => Some(KB_ALT_W),
        'x' => Some(KB_ALT_X),
        'y' => Some(KB_ALT_Y),
        'z' => Some(KB_ALT_Z),
        _ => None,
    }
}

/// ESC sequence tracker for macOS Alt emulation
pub struct EscSequenceTracker {
    last_esc_time: Option<Instant>,
    waiting_for_char: bool,
    timeout_ms: u64,
}

impl EscSequenceTracker {
    pub fn new() -> Self {
        Self::with_timeout(500)
    }

    pub fn with_timeout(timeout_ms: u64) -> Self {
        Self {
            last_esc_time: None,
            waiting_for_char: false,
            timeout_ms,
        }
    }

    /// Set the ESC timeout in milliseconds
    pub fn set_timeout(&mut self, timeout_ms: u64) {
        self.timeout_ms = timeout_ms;
    }

    /// Check whether a pending ESC has timed out without a follow-up key.
    ///
    /// Call this from `poll_event` when no crossterm event is available.
    /// Returns `Some(KB_ESC)` if the ESC timeout expired and the pending
    /// ESC should be delivered as a standalone key press.
    pub fn check_timeout(&mut self) -> Option<KeyCode> {
        if self.waiting_for_char {
            if let Some(last_time) = self.last_esc_time {
                if Instant::now().duration_since(last_time) > Duration::from_millis(self.timeout_ms)
                {
                    self.last_esc_time = None;
                    self.waiting_for_char = false;
                    return Some(KB_ESC);
                }
            }
        }
        None
    }

    /// Process a key event, handling ESC sequences.
    ///
    /// Returns 0 when ESC is held pending (waiting for a follow-up key),
    /// or the resolved `KeyCode` otherwise.
    pub fn process_key(&mut self, key: KeyEvent) -> KeyCode {
        // Check if this is ESC
        if matches!(key.code, CKC::Esc) {
            let now = Instant::now();

            // Check if this is a second ESC within timeout
            if let Some(last_time) = self.last_esc_time {
                if now.duration_since(last_time) < Duration::from_millis(self.timeout_ms) {
                    // Double ESC!
                    self.last_esc_time = None;
                    self.waiting_for_char = false;
                    return KB_ESC_ESC;
                }
            }

            // First ESC - wait for next character
            self.last_esc_time = Some(now);
            self.waiting_for_char = true;
            return 0; // Don't generate event yet
        }

        // If we're waiting for a character after ESC
        if self.waiting_for_char {
            self.waiting_for_char = false;
            let esc_time = self.last_esc_time;
            self.last_esc_time = None;

            // Check if within time limit (treat as ALT+letter)
            if let Some(last_time) = esc_time {
                if Instant::now().duration_since(last_time)
                    <= Duration::from_millis(self.timeout_ms)
                {
                    // Map ESC+letter to ALT codes (for macOS Alt emulation)
                    // This makes ESC+F identical to Alt+F from the application's perspective
                    if let CKC::Char(c) = key.code {
                        if let Some(alt_code) = char_to_alt_code(c.to_ascii_lowercase()) {
                            return alt_code;
                        }
                    }
                }
            }

            // Timeout expired or non-letter follow-up — deliver as normal key.
            // The pending ESC was already lost; check_timeout() handles the
            // case where no follow-up key arrives at all.
            return crossterm_to_keycode(key);
        }

        crossterm_to_keycode(key)
    }
}

/// Parse a base (non-modifier) key name into a crossterm key code.
///
/// `upper` is the upper-cased token; `original` preserves the original case so
/// single characters keep their casing.
fn parse_base_key(upper: &str, original: &str) -> Option<CKC> {
    // Function keys: F1..=F12
    if let Some(num) = upper.strip_prefix('F') {
        if let Ok(n) = num.parse::<u8>() {
            if (1..=12).contains(&n) {
                return Some(CKC::F(n));
            }
        }
    }

    let code = match upper {
        "ENTER" | "RETURN" => CKC::Enter,
        "ESC" | "ESCAPE" => CKC::Esc,
        "TAB" => CKC::Tab,
        "BACKTAB" => CKC::BackTab,
        "SPACE" => CKC::Char(' '),
        "BACKSPACE" | "BKSP" | "BS" => CKC::Backspace,
        "DEL" | "DELETE" => CKC::Delete,
        "INS" | "INSERT" => CKC::Insert,
        "HOME" => CKC::Home,
        "END" => CKC::End,
        "PGUP" | "PAGEUP" => CKC::PageUp,
        "PGDN" | "PAGEDOWN" => CKC::PageDown,
        "UP" => CKC::Up,
        "DOWN" => CKC::Down,
        "LEFT" => CKC::Left,
        "RIGHT" => CKC::Right,
        _ => {
            // Any single character is taken literally (preserving its case).
            let mut chars = original.chars();
            let c = chars.next()?;
            if chars.next().is_some() {
                return None; // multi-character unknown token
            }
            CKC::Char(c)
        }
    };
    Some(code)
}

/// Parse a human-readable key chord into an [`Event`].
///
/// A chord is a base key optionally prefixed with `+`-joined modifiers, for
/// example `"CTRL+F12"`, `"ALT+X"`, `"SHIFT+TAB"`, `"ENTER"`, or `"a"`. Parsing
/// is case-insensitive for key names and modifiers.
///
/// Recognized modifiers: `CTRL`/`CONTROL`, `ALT`/`OPT`/`OPTION`/`META`, `SHIFT`.
/// Recognized keys: `F1`..`F12`, `ENTER`/`RETURN`, `ESC`/`ESCAPE`, `TAB`,
/// `BACKTAB`, `SPACE`, `BACKSPACE`, `DEL`/`DELETE`, `INS`/`INSERT`, `HOME`,
/// `END`, `PGUP`/`PAGEUP`, `PGDN`/`PAGEDOWN`, `UP`, `DOWN`, `LEFT`, `RIGHT`,
/// and any single character.
///
/// Returns `None` if the chord cannot be parsed into a known key code. The
/// resulting event is identical to what the corresponding physical key press
/// would produce, because it routes through the same conversion logic.
pub fn parse_key_chord(chord: &str) -> Option<Event> {
    let mut modifiers = KeyModifiers::empty();
    let mut base: Option<CKC> = None;

    for part in chord.split('+') {
        let part = part.trim();
        if part.is_empty() {
            continue;
        }
        let upper = part.to_ascii_uppercase();
        match upper.as_str() {
            "CTRL" | "CONTROL" => modifiers |= KeyModifiers::CONTROL,
            "ALT" | "OPT" | "OPTION" | "META" => modifiers |= KeyModifiers::ALT,
            "SHIFT" => modifiers |= KeyModifiers::SHIFT,
            _ => {
                if base.is_some() {
                    return None; // more than one base key
                }
                base = Some(parse_base_key(&upper, part)?);
            }
        }
    }

    let code = base?;
    let key = KeyEvent::new(code, modifiers);
    let key_code = crossterm_to_keycode(key);
    if key_code == 0 {
        return None;
    }
    Some(Event {
        what: EventType::Keyboard,
        key_code,
        key_modifiers: modifiers,
        ..Event::nothing()
    })
}

/// Convert crossterm KeyEvent to our KeyCode
fn crossterm_to_keycode(key: KeyEvent) -> KeyCode {
    match key.code {
        CKC::Char(c) => {
            // Check for Ctrl modifier first (Ctrl+letter generates ASCII control codes)
            if key.modifiers.contains(KeyModifiers::CONTROL) {
                // Ctrl + letter produces ASCII control codes (0x01-0x1A for A-Z)
                let c_lower = c.to_ascii_lowercase();
                if c_lower >= 'a' && c_lower <= 'z' {
                    return (c_lower as u16) - ('a' as u16) + 1; // Ctrl+A = 0x01, Ctrl+B = 0x02, etc.
                }
            }

            // Check for Alt modifier
            if key.modifiers.contains(KeyModifiers::ALT) {
                // Alt + letter
                if let Some(alt_code) = char_to_alt_code(c.to_ascii_lowercase()) {
                    return alt_code;
                }
            }

            c as u16
        }
        CKC::Enter => KB_ENTER,
        CKC::Backspace => KB_BACKSPACE,
        CKC::Tab => {
            if key.modifiers.contains(KeyModifiers::SHIFT) {
                KB_SHIFT_TAB
            } else {
                KB_TAB
            }
        }
        CKC::BackTab => KB_SHIFT_TAB, // Some terminals send BackTab for Shift+Tab
        CKC::Esc => KB_ESC,
        CKC::Up => KB_UP,
        CKC::Down => KB_DOWN,
        CKC::Left => KB_LEFT,
        CKC::Right => KB_RIGHT,
        CKC::Home => KB_HOME,
        CKC::End => KB_END,
        CKC::PageUp => KB_PGUP,
        CKC::PageDown => KB_PGDN,
        CKC::Insert => KB_INS,
        CKC::Delete => KB_DEL,
        CKC::F(1) => {
            if key.modifiers.contains(KeyModifiers::ALT) {
                KB_ALT_F1
            } else {
                KB_F1
            }
        }
        CKC::F(2) => KB_F2,
        CKC::F(3) => {
            if key.modifiers.contains(KeyModifiers::ALT) {
                KB_ALT_F3
            } else {
                KB_F3
            }
        }
        CKC::F(4) => KB_F4,
        CKC::F(5) => KB_F5,
        CKC::F(6) => KB_F6,
        CKC::F(7) => KB_F7,
        CKC::F(8) => KB_F8,
        CKC::F(9) => KB_F9,
        CKC::F(10) => KB_F10,
        CKC::F(11) => KB_F11,
        CKC::F(12) => {
            if key.modifiers.contains(KeyModifiers::CONTROL) {
                KB_CTRL_F12
            } else {
                KB_F12
            }
        }
        _ => 0,
    }
}

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

    #[test]
    fn parses_ctrl_f12() {
        let ev = parse_key_chord("CTRL+F12").unwrap();
        assert_eq!(ev.what, EventType::Keyboard);
        assert_eq!(ev.key_code, KB_CTRL_F12);
    }

    #[test]
    fn parses_plain_and_shift_f12() {
        assert_eq!(parse_key_chord("F12").unwrap().key_code, KB_F12);
        assert_eq!(parse_key_chord("ctrl+f12").unwrap().key_code, KB_CTRL_F12);
    }

    #[test]
    fn parses_alt_x_case_insensitive() {
        assert_eq!(parse_key_chord("ALT+X").unwrap().key_code, KB_ALT_X);
        assert_eq!(parse_key_chord("alt+x").unwrap().key_code, KB_ALT_X);
    }

    #[test]
    fn parses_named_keys() {
        assert_eq!(parse_key_chord("ENTER").unwrap().key_code, KB_ENTER);
        assert_eq!(parse_key_chord("esc").unwrap().key_code, KB_ESC);
        assert_eq!(parse_key_chord("Tab").unwrap().key_code, KB_TAB);
    }

    #[test]
    fn rejects_garbage() {
        assert!(parse_key_chord("NOPEKEY").is_none());
        assert!(parse_key_chord("CTRL+").is_none());
        assert!(parse_key_chord("").is_none());
    }
}