quadraui 0.6.1

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
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
//! Crossterm → `crate::UiEvent` translation.
//!
//! Phase B.4 Stage 4. This module is the boundary between crossterm's
//! native event types (`KeyEvent`, `MouseEvent`, `Event::Resize`,
//! `Event::Paste`, `Event::FocusGained`/`FocusLost`) and quadraui's
//! backend-agnostic [`UiEvent`] enum. Once the event loop migrates
//! (Stage 5), every native event reaches the engine via this layer
//! instead of being decoded inline.
//!
//! # What this does
//!
//! - **Keys** ([`crossterm_key_to_uievent`]): map `KeyCode` → `Key`,
//!   `KeyModifiers` → `Modifiers`. Press events emit
//!   `UiEvent::KeyPressed`; releases are dropped (the engine doesn't
//!   distinguish them today).
//! - **Mouse** ([`crossterm_mouse_to_uievent`]): map `MouseEventKind`
//!   to `MouseDown` / `MouseUp` / `MouseMoved` / `Scroll`. The
//!   `widget` field stays `None` — actual hit-testing happens in
//!   [`crate::dispatch`] / [`crate::dispatch::dispatch_mouse_down`].
//! - **Window resize** → `UiEvent::WindowResized { viewport }`.
//! - **Bracketed paste** → `UiEvent::ClipboardPaste(text)`.
//! - **Focus gained / lost** (kitty protocol) → `UiEvent::WindowFocused(true/false)`.
//!
//! # What this does NOT do
//!
//! - Vim-style key-name strings (`"Escape"`, `"Shift_Up"`, `"Return"`)
//!   that the engine's `handle_key` expects — those still come from
//!   the existing [`the app`] function.
//!   Stage 5 either keeps that as a separate adapter or refactors it
//!   to consume `UiEvent::KeyPressed` directly.
//! - Accelerator matching. Stage 6's [`Backend::register_accelerator`]
//!   path will compare the registered list against the translated
//!   `Key + Modifiers` and emit `UiEvent::Accelerator(id, mods)`.
//! - Hit-testing. Mouse events come out with `widget: None`; the
//!   trait-side dispatch fills that in via the modal stack and per-
//!   primitive layout hit_test.

use crate::{ButtonMask, Key, Modifiers, MouseButton, NamedKey, TerminalCellSize, UiEvent};
use ratatui::crossterm::event::{
    Event as CtEvent, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton as CtMouseButton,
    MouseEvent, MouseEventKind,
};

/// The identity cell size — dividing by this leaves `event.column`/`.row`
/// unchanged, so [`crossterm_mouse_to_uievent`] and [`crossterm_to_uievents`]
/// delegating to their `_scaled` sibling with this value is exactly
/// today's cell-quantised behaviour.
const UNSCALED_CELL: TerminalCellSize = TerminalCellSize {
    width: 1.0,
    height: 1.0,
};

/// Translate one crossterm event to zero or more quadraui events, treating
/// `event.column`/`.row` (mouse events only) as whole terminal cells.
///
/// Single events translate one-to-one (Vec of length 1); some
/// crossterm events have no quadraui equivalent and translate to
/// an empty Vec (e.g. `KeyEventKind::Release`). Returning `Vec`
/// instead of `Option` keeps the door open for future
/// composite events without a breaking change.
pub fn crossterm_to_uievents(event: CtEvent) -> Vec<UiEvent> {
    crossterm_to_uievents_scaled(event, UNSCALED_CELL)
}

/// Like [`crossterm_to_uievents`], but a mouse event's `column`/`row` are
/// divided by `cell_size` before becoming a [`UiEvent`] `Point` — see
/// [`crossterm_mouse_to_uievent_scaled`]'s doc for why this matters and
/// when `cell_size` is anything other than [`UNSCALED_CELL`].
pub fn crossterm_to_uievents_scaled(event: CtEvent, cell_size: TerminalCellSize) -> Vec<UiEvent> {
    match event {
        CtEvent::Key(k) => crossterm_key_to_uievent(k).into_iter().collect(),
        CtEvent::Mouse(m) => crossterm_mouse_to_uievent_scaled(m, cell_size)
            .into_iter()
            .collect(),
        CtEvent::Resize(w, h) => vec![crate::event::window_resized(w as f32, h as f32, 1.0)],
        CtEvent::Paste(text) => vec![UiEvent::ClipboardPaste(text)],
        CtEvent::FocusGained => vec![UiEvent::WindowFocused(true)],
        CtEvent::FocusLost => vec![UiEvent::WindowFocused(false)],
    }
}

/// Translate one crossterm key event. `None` means the event has no
/// quadraui counterpart (releases, repeats not surfaced as
/// `KeyPressed`, etc.).
pub fn crossterm_key_to_uievent(event: KeyEvent) -> Option<UiEvent> {
    if event.kind == KeyEventKind::Release {
        return None;
    }
    let key = crossterm_keycode_to_key(event.code)?;
    let modifiers = crossterm_modifiers_to_quadraui(event.modifiers);
    let repeat = event.kind == KeyEventKind::Repeat;
    Some(UiEvent::KeyPressed {
        key,
        modifiers,
        repeat,
    })
}

/// Translate one crossterm mouse event, treating `column`/`row` as whole
/// terminal cells. Equivalent to
/// `crossterm_mouse_to_uievent_scaled(event, UNSCALED_CELL)` — see that
/// function's doc for the SGR-Pixels-aware behaviour this
/// leaves on the table.
pub fn crossterm_mouse_to_uievent(event: MouseEvent) -> Option<UiEvent> {
    crossterm_mouse_to_uievent_scaled(event, UNSCALED_CELL)
}

/// Translate one crossterm mouse event, dividing `column`/`row` by
/// `cell_size` before they become a [`UiEvent`] `Point`.
///
/// `event.column`/`.row` are always plain integers — crossterm has no
/// separate "pixel" mouse-event shape. What they *mean* depends entirely on
/// which mouse-tracking mode the terminal is actually reporting in:
///
/// - In ordinary SGR mode (`?1006h`, what [`super::run::run`] always
///   enables), they are cell indices, and `cell_size` should be
///   [`UNSCALED_CELL`] (dividing by 1 is a no-op) — that's what
///   [`crossterm_mouse_to_uievent`] does.
/// - In SGR-Pixels mode (`?1016h`, negotiated by
///   [`super::caps::probe_sgr_pixel_mouse`] and enabled by
///   [`super::run::run`] only when that probe *and* a live pixel cell size
///   both succeed — see that module's doc), they are pixel offsets, and
///   `cell_size` must be the real [`TerminalCellSize`]
///   [`super::backend::TuiBackend::cell_pixel_size`] reports, so this
///   division recovers a fractional cell coordinate — exactly the sub-cell
///   resolution this issue exists to deliver.
///
/// Passing the wrong `cell_size` for the mode the terminal is actually in
/// is worse than not calling this at all (a pixel coordinate divided by 1
/// puts a click 8-20x too far right/down on a typical terminal) — callers
/// must gate `cell_size` on [`super::backend::TuiBackend::sgr_pixel_mouse`]
/// being `true`, never guess.
///
/// A degenerate `cell_size` (`width`/`height` `<= 0.0` — a value this
/// crate's own runner never produces, since its live pixel-size query
/// already refuses to report one, but this function is `pub` and reachable
/// directly) falls back to the identity cell size rather than dividing by
/// zero and handing the caller an `inf`/`NaN` coordinate — mirroring
/// [`crate::primitives::terminal::TerminalLayout::hit_test`]'s own
/// zero-guard on the same [`TerminalCellSize`] type.
pub fn crossterm_mouse_to_uievent_scaled(
    event: MouseEvent,
    cell_size: TerminalCellSize,
) -> Option<UiEvent> {
    let cell_size = if cell_size.width <= 0.0 || cell_size.height <= 0.0 {
        UNSCALED_CELL
    } else {
        cell_size
    };
    let x = event.column as f32 / cell_size.width;
    let y = event.row as f32 / cell_size.height;
    let modifiers = crossterm_modifiers_to_quadraui(event.modifiers);
    match event.kind {
        MouseEventKind::Down(b) => Some(crate::event::mouse_down(
            crossterm_mouse_button_to_quadraui(b),
            x,
            y,
            modifiers,
        )),
        MouseEventKind::Up(b) => Some(crate::event::mouse_up(
            crossterm_mouse_button_to_quadraui(b),
            x,
            y,
        )),
        MouseEventKind::Drag(b) => Some(crate::event::mouse_moved(x, y, button_mask_with_held(b))),
        MouseEventKind::Moved => Some(crate::event::mouse_moved(x, y, ButtonMask::default())),
        // crossterm reports discrete scroll "notches" rather than a
        // continuous native delta; each direction maps to the raw
        // native-down-positive value `crate::event::scroll` expects a
        // continuous GTK/Cocoa wheel delta to carry, so up/down = ∓1.0
        // and left/right pass straight through as `dx` (unflipped, same
        // as every other backend).
        MouseEventKind::ScrollUp => Some(crate::event::scroll(0.0, -1.0, x, y)),
        MouseEventKind::ScrollDown => Some(crate::event::scroll(0.0, 1.0, x, y)),
        MouseEventKind::ScrollLeft => Some(crate::event::scroll(-1.0, 0.0, x, y)),
        MouseEventKind::ScrollRight => Some(crate::event::scroll(1.0, 0.0, x, y)),
    }
}

// ── Double-click synthesis ───────────────────────────────────────────────
//
// Relocated to `crate::dispatch` so `macos::run` can reuse
// the same detector without pulling in the `tui` feature. Re-exported
// here so existing `super::events::DoubleClickDetector` references
// (this module's own `TuiBackend` usage) keep working.
pub use crate::dispatch::DoubleClickDetector;

fn crossterm_keycode_to_key(code: KeyCode) -> Option<Key> {
    let named = match code {
        KeyCode::Char(c) => return Some(Key::Char(c)),
        KeyCode::Esc => NamedKey::Escape,
        KeyCode::Tab => NamedKey::Tab,
        KeyCode::BackTab => NamedKey::BackTab,
        KeyCode::Enter => NamedKey::Enter,
        KeyCode::Backspace => NamedKey::Backspace,
        KeyCode::Delete => NamedKey::Delete,
        KeyCode::Insert => NamedKey::Insert,
        KeyCode::Home => NamedKey::Home,
        KeyCode::End => NamedKey::End,
        KeyCode::PageUp => NamedKey::PageUp,
        KeyCode::PageDown => NamedKey::PageDown,
        KeyCode::Up => NamedKey::Up,
        KeyCode::Down => NamedKey::Down,
        KeyCode::Left => NamedKey::Left,
        KeyCode::Right => NamedKey::Right,
        KeyCode::F(n) => NamedKey::F(n),
        KeyCode::CapsLock => NamedKey::CapsLock,
        KeyCode::NumLock => NamedKey::NumLock,
        KeyCode::ScrollLock => NamedKey::ScrollLock,
        KeyCode::Menu => NamedKey::Menu,
        // Crossterm has Null, Modifier, Pause, PrintScreen, Media,
        // KeypadBegin etc. that quadraui's NamedKey doesn't yet model.
        // Drop them — the existing engine doesn't act on these either.
        _ => return None,
    };
    Some(Key::Named(named))
}

fn crossterm_modifiers_to_quadraui(m: KeyModifiers) -> Modifiers {
    Modifiers {
        shift: m.contains(KeyModifiers::SHIFT),
        ctrl: m.contains(KeyModifiers::CONTROL),
        alt: m.contains(KeyModifiers::ALT),
        cmd: m.contains(KeyModifiers::SUPER) | m.contains(KeyModifiers::META),
    }
}

fn crossterm_mouse_button_to_quadraui(b: CtMouseButton) -> MouseButton {
    match b {
        CtMouseButton::Left => MouseButton::Left,
        CtMouseButton::Right => MouseButton::Right,
        CtMouseButton::Middle => MouseButton::Middle,
    }
}

/// Synthesise a crossterm `Event` from any single `UiEvent` that has
/// a crossterm equivalent. The migrated event loop in
/// [`the runner loop`] uses this to feed `UiEvent`s back
/// into the existing match-on-`Event::*` dispatch without rewriting
/// every legacy handler. Returns `None` for `UiEvent` variants that
/// don't round-trip (`Accelerator`, `Tree(...)`, etc.).
pub fn uievent_to_crossterm(ev: UiEvent) -> Option<CtEvent> {
    match ev {
        UiEvent::KeyPressed {
            key,
            modifiers,
            repeat,
        } => synth_keyevent(&key, modifiers, repeat).map(CtEvent::Key),
        UiEvent::CharTyped(_) => None, // crossterm doesn't have a separate variant
        UiEvent::MouseDown { .. }
        | UiEvent::MouseUp { .. }
        | UiEvent::MouseMoved { .. }
        | UiEvent::Scroll { .. } => synth_mouseevent(&ev).map(CtEvent::Mouse),
        UiEvent::WindowResized { viewport } => Some(CtEvent::Resize(
            viewport.width as u16,
            viewport.height as u16,
        )),
        UiEvent::ClipboardPaste(text) => Some(CtEvent::Paste(text)),
        UiEvent::WindowFocused(true) => Some(CtEvent::FocusGained),
        UiEvent::WindowFocused(false) => Some(CtEvent::FocusLost),
        // No equivalent: WindowClose, DpiChanged, FilesDropped, primitive
        // events (Tree/List/...), Accelerator, etc.
        _ => None,
    }
}

// ─── Inverse: UiEvent → crossterm::Event ────────────────────────────────────
//
// Stage 5b's loop migration consumes `UiEvent` from `backend.wait_events`
// but the existing handlers (translate_key, handle_mouse, …) take
// crossterm types. Rather than duplicate all that decode logic, the
// migrated loop synthesises a crossterm event from each `UiEvent` and
// feeds the legacy handler unchanged. The translation is lossy in
// principle (we don't preserve `KeyEventState` or wide-mouse-button
// indices) but the existing handlers only consult the fields we
// faithfully round-trip.

/// Synthesise a crossterm `KeyEvent` from a `UiEvent::KeyPressed`'s
/// payload. Returns `None` if the `Key` doesn't have a crossterm
/// equivalent (won't happen for events we translated ourselves —
/// every variant we emit round-trips).
pub fn synth_keyevent(key: &Key, modifiers: Modifiers, repeat: bool) -> Option<KeyEvent> {
    use ratatui::crossterm::event::KeyEventState;
    let code = match key {
        Key::Char(c) => KeyCode::Char(*c),
        Key::Named(n) => match n {
            NamedKey::Escape => KeyCode::Esc,
            NamedKey::Tab => KeyCode::Tab,
            NamedKey::BackTab => KeyCode::BackTab,
            NamedKey::Enter => KeyCode::Enter,
            NamedKey::Backspace => KeyCode::Backspace,
            NamedKey::Delete => KeyCode::Delete,
            NamedKey::Insert => KeyCode::Insert,
            NamedKey::Home => KeyCode::Home,
            NamedKey::End => KeyCode::End,
            NamedKey::PageUp => KeyCode::PageUp,
            NamedKey::PageDown => KeyCode::PageDown,
            NamedKey::Up => KeyCode::Up,
            NamedKey::Down => KeyCode::Down,
            NamedKey::Left => KeyCode::Left,
            NamedKey::Right => KeyCode::Right,
            NamedKey::F(n) => KeyCode::F(*n),
            NamedKey::CapsLock => KeyCode::CapsLock,
            NamedKey::NumLock => KeyCode::NumLock,
            NamedKey::ScrollLock => KeyCode::ScrollLock,
            NamedKey::Menu => KeyCode::Menu,
        },
    };
    let mut mods = KeyModifiers::empty();
    if modifiers.shift {
        mods |= KeyModifiers::SHIFT;
    }
    if modifiers.ctrl {
        mods |= KeyModifiers::CONTROL;
    }
    if modifiers.alt {
        mods |= KeyModifiers::ALT;
    }
    if modifiers.cmd {
        mods |= KeyModifiers::SUPER;
    }
    let kind = if repeat {
        KeyEventKind::Repeat
    } else {
        KeyEventKind::Press
    };
    Some(KeyEvent {
        code,
        modifiers: mods,
        kind,
        state: KeyEventState::empty(),
    })
}

/// Synthesise a crossterm `MouseEvent` from any `UiEvent::Mouse*`
/// variant. Returns `None` for `UiEvent`s that aren't mouse events
/// (or for `MouseEntered`/`Left`, which crossterm doesn't surface
/// natively).
pub fn synth_mouseevent(ev: &UiEvent) -> Option<MouseEvent> {
    let (kind, position, modifiers) = match ev {
        UiEvent::MouseDown {
            button,
            position,
            modifiers,
            ..
        } => (
            MouseEventKind::Down(quadraui_button_to_crossterm(*button)?),
            *position,
            *modifiers,
        ),
        UiEvent::MouseUp {
            button, position, ..
        } => (
            MouseEventKind::Up(quadraui_button_to_crossterm(*button)?),
            *position,
            Modifiers::default(),
        ),
        UiEvent::MouseMoved { position, buttons } => {
            let kind = if buttons.left {
                MouseEventKind::Drag(CtMouseButton::Left)
            } else if buttons.right {
                MouseEventKind::Drag(CtMouseButton::Right)
            } else if buttons.middle {
                MouseEventKind::Drag(CtMouseButton::Middle)
            } else {
                MouseEventKind::Moved
            };
            (kind, *position, Modifiers::default())
        }
        UiEvent::Scroll {
            delta, position, ..
        } => {
            let kind = if delta.y > 0.0 {
                MouseEventKind::ScrollUp
            } else if delta.y < 0.0 {
                MouseEventKind::ScrollDown
            } else if delta.x < 0.0 {
                MouseEventKind::ScrollLeft
            } else {
                MouseEventKind::ScrollRight
            };
            (kind, *position, Modifiers::default())
        }
        _ => return None,
    };
    Some(MouseEvent {
        kind,
        column: position.x.max(0.0) as u16,
        row: position.y.max(0.0) as u16,
        modifiers: quadraui_modifiers_to_crossterm(modifiers),
    })
}

fn quadraui_button_to_crossterm(b: MouseButton) -> Option<CtMouseButton> {
    match b {
        MouseButton::Left => Some(CtMouseButton::Left),
        MouseButton::Right => Some(CtMouseButton::Right),
        MouseButton::Middle => Some(CtMouseButton::Middle),
        // X1/X2/Other don't have crossterm equivalents.
        _ => None,
    }
}

fn quadraui_modifiers_to_crossterm(m: Modifiers) -> KeyModifiers {
    let mut out = KeyModifiers::empty();
    if m.shift {
        out |= KeyModifiers::SHIFT;
    }
    if m.ctrl {
        out |= KeyModifiers::CONTROL;
    }
    if m.alt {
        out |= KeyModifiers::ALT;
    }
    if m.cmd {
        out |= KeyModifiers::SUPER;
    }
    out
}

/// Crossterm's `MouseEventKind::Drag(b)` carries the held button as
/// the variant payload; the quadraui `ButtonMask` reflects which
/// buttons are down at that moment. We only know the *one* button
/// crossterm reports, so the mask has just that bit set.
fn button_mask_with_held(b: CtMouseButton) -> ButtonMask {
    match b {
        CtMouseButton::Left => ButtonMask {
            left: true,
            right: false,
            middle: false,
        },
        CtMouseButton::Right => ButtonMask {
            left: false,
            right: true,
            middle: false,
        },
        CtMouseButton::Middle => ButtonMask {
            left: false,
            right: false,
            middle: true,
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui::crossterm::event::{
        KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers, MouseButton as CtMouseButton,
        MouseEvent, MouseEventKind,
    };

    fn key(code: KeyCode, mods: KeyModifiers) -> KeyEvent {
        KeyEvent {
            code,
            modifiers: mods,
            kind: KeyEventKind::Press,
            state: KeyEventState::empty(),
        }
    }

    fn mouse(kind: MouseEventKind, col: u16, row: u16) -> MouseEvent {
        MouseEvent {
            kind,
            column: col,
            row,
            modifiers: KeyModifiers::empty(),
        }
    }

    #[test]
    fn char_keypress_translates_to_keypressed_char() {
        let ev = crossterm_key_to_uievent(key(KeyCode::Char('a'), KeyModifiers::empty()));
        assert_eq!(
            ev,
            Some(UiEvent::KeyPressed {
                key: Key::Char('a'),
                modifiers: Modifiers::default(),
                repeat: false,
            })
        );
    }

    #[test]
    fn ctrl_p_translates_with_ctrl_modifier() {
        let ev = crossterm_key_to_uievent(key(KeyCode::Char('p'), KeyModifiers::CONTROL)).unwrap();
        match ev {
            UiEvent::KeyPressed { key, modifiers, .. } => {
                assert_eq!(key, Key::Char('p'));
                assert!(modifiers.ctrl);
                assert!(!modifiers.shift);
            }
            other => panic!("unexpected variant: {:?}", other),
        }
    }

    #[test]
    fn named_keys_translate() {
        for (code, named) in &[
            (KeyCode::Esc, NamedKey::Escape),
            (KeyCode::Enter, NamedKey::Enter),
            (KeyCode::Backspace, NamedKey::Backspace),
            (KeyCode::Tab, NamedKey::Tab),
            (KeyCode::BackTab, NamedKey::BackTab),
            (KeyCode::Up, NamedKey::Up),
            (KeyCode::Down, NamedKey::Down),
            (KeyCode::Left, NamedKey::Left),
            (KeyCode::Right, NamedKey::Right),
            (KeyCode::PageUp, NamedKey::PageUp),
            (KeyCode::PageDown, NamedKey::PageDown),
            (KeyCode::Home, NamedKey::Home),
            (KeyCode::End, NamedKey::End),
            (KeyCode::Delete, NamedKey::Delete),
            (KeyCode::Insert, NamedKey::Insert),
            (KeyCode::F(1), NamedKey::F(1)),
            (KeyCode::F(12), NamedKey::F(12)),
        ] {
            let ev = crossterm_key_to_uievent(key(*code, KeyModifiers::empty())).unwrap();
            match ev {
                UiEvent::KeyPressed { key, .. } => {
                    assert_eq!(key, Key::Named(*named), "for code {:?}", code);
                }
                other => panic!("unexpected variant: {:?}", other),
            }
        }
    }

    #[test]
    fn key_release_drops() {
        let mut ev = key(KeyCode::Char('a'), KeyModifiers::empty());
        ev.kind = KeyEventKind::Release;
        assert!(crossterm_key_to_uievent(ev).is_none());
    }

    #[test]
    fn key_repeat_marks_repeat_true() {
        let mut ev = key(KeyCode::Char('a'), KeyModifiers::empty());
        ev.kind = KeyEventKind::Repeat;
        let translated = crossterm_key_to_uievent(ev).unwrap();
        match translated {
            UiEvent::KeyPressed { repeat, .. } => assert!(repeat),
            other => panic!("unexpected variant: {:?}", other),
        }
    }

    #[test]
    fn mouse_down_left_translates() {
        let ev =
            crossterm_mouse_to_uievent(mouse(MouseEventKind::Down(CtMouseButton::Left), 10, 5))
                .unwrap();
        assert!(matches!(
            ev,
            UiEvent::MouseDown {
                widget: None,
                button: MouseButton::Left,
                ..
            }
        ));
        if let UiEvent::MouseDown { position, .. } = ev {
            assert_eq!(position.x, 10.0);
            assert_eq!(position.y, 5.0);
        }
    }

    #[test]
    fn mouse_drag_carries_held_button() {
        let ev =
            crossterm_mouse_to_uievent(mouse(MouseEventKind::Drag(CtMouseButton::Right), 12, 8))
                .unwrap();
        match ev {
            UiEvent::MouseMoved { buttons, .. } => {
                assert!(!buttons.left);
                assert!(buttons.right);
                assert!(!buttons.middle);
            }
            other => panic!("unexpected variant: {:?}", other),
        }
    }

    #[test]
    fn mouse_scroll_up_translates_to_positive_y() {
        let ev = crossterm_mouse_to_uievent(mouse(MouseEventKind::ScrollUp, 0, 0)).unwrap();
        match ev {
            UiEvent::Scroll { delta, .. } => {
                assert_eq!(delta.y, 1.0);
                assert_eq!(delta.x, 0.0);
            }
            other => panic!("unexpected variant: {:?}", other),
        }
    }

    #[test]
    fn mouse_scroll_down_translates_to_negative_y() {
        let ev = crossterm_mouse_to_uievent(mouse(MouseEventKind::ScrollDown, 0, 0)).unwrap();
        match ev {
            UiEvent::Scroll { delta, .. } => assert_eq!(delta.y, -1.0),
            other => panic!("unexpected variant: {:?}", other),
        }
    }

    // ── SGR-Pixels sub-cell scaling ─────────────────────────────────────────

    /// `crossterm_mouse_to_uievent` divides mouse coordinates by
    /// `UNSCALED_CELL` — i.e. whole cell indices straight through with
    /// no fractional component.
    #[test]
    fn unscaled_mouse_translation_is_byte_identical_to_scaled_with_unit_cell() {
        let raw = mouse(MouseEventKind::Down(CtMouseButton::Left), 37, 21);
        let unscaled = crossterm_mouse_to_uievent(raw);
        let scaled = crossterm_mouse_to_uievent_scaled(raw, UNSCALED_CELL);
        assert_eq!(unscaled, scaled);
        match unscaled.unwrap() {
            UiEvent::MouseDown { position, .. } => {
                assert_eq!(position.x, 37.0);
                assert_eq!(position.y, 21.0);
            }
            other => panic!("unexpected variant: {:?}", other),
        }
    }

    /// A real SGR-Pixels-mode terminal reports `column`/`row` in pixels;
    /// dividing by a non-unit `cell_size` recovers a fractional cell
    /// coordinate instead of quantising to the nearest whole cell.
    #[test]
    fn pixel_mode_scaling_produces_fractional_coordinates() {
        let cell = TerminalCellSize::new(10.0, 20.0);
        // Pixel column 25 / cell-width 10 = 2.5 cells; pixel row 13 /
        // cell-height 20 = 0.65 cells.
        let raw = mouse(MouseEventKind::Moved, 25, 13);
        let ev = crossterm_mouse_to_uievent_scaled(raw, cell).unwrap();
        match ev {
            UiEvent::MouseMoved { position, .. } => {
                assert_eq!(position.x, 2.5);
                assert!((position.y - 0.65).abs() < f32::EPSILON);
            }
            other => panic!("unexpected variant: {:?}", other),
        }
    }

    /// The whole point of pixel mode: a drag whose raw pixel columns all
    /// quantise to the *same* terminal cell in cell-mode (so a cell-mode
    /// caller would see one repeated position) resolves to several
    /// distinct fractional positions once divided by the real cell size —
    /// the sub-cell resolution a scrollbar/minimap drag needs
    #[test]
    fn pixel_mode_resolves_finer_than_a_single_cell() {
        let cell = TerminalCellSize::new(10.0, 20.0);
        // Four consecutive drag samples a pixel-mode terminal reports while
        // the pointer crosses exactly one cell's worth (10px) of horizontal
        // travel.
        let raw_columns = [10u16, 13, 16, 19];

        let pixel_mode_xs: Vec<f32> = raw_columns
            .iter()
            .map(|&col| {
                let ev =
                    crossterm_mouse_to_uievent_scaled(mouse(MouseEventKind::Moved, col, 0), cell)
                        .unwrap();
                match ev {
                    UiEvent::MouseMoved { position, .. } => position.x,
                    other => panic!("unexpected variant: {:?}", other),
                }
            })
            .collect();

        // What a cell-mode (non-pixel) terminal would have reported for the
        // identical physical pointer travel: it only ever emits a whole
        // cell index, so every one of these four samples floors to the same
        // cell (10..=19 all floor-divide to cell 1 at a 10px cell width).
        // Flooring the pixel-mode result reproduces that coarser reporting
        // cadence without inventing a second, real cell-mode data source.
        let mut cell_quantised: Vec<i32> = pixel_mode_xs.iter().map(|x| x.floor() as i32).collect();
        cell_quantised.dedup();
        assert_eq!(
            cell_quantised.len(),
            1,
            "cell-quantised reporting of this same travel must collapse to one position, \
             got {pixel_mode_xs:?}"
        );

        let mut distinct_pixel_mode: Vec<f32> = pixel_mode_xs.clone();
        distinct_pixel_mode.dedup_by(|a, b| (*a - *b).abs() < f32::EPSILON);
        assert!(
            distinct_pixel_mode.len() > 1,
            "pixel-mode division must yield several distinct positions across one cell's \
             worth of pixel travel, got {pixel_mode_xs:?}"
        );
    }

    /// A degenerate `cell_size` (zero or negative width/height — never
    /// produced by this crate's own runner, but reachable through this
    /// `pub` function directly) must fall back to the identity cell size
    /// instead of dividing by zero and handing the caller an `inf`/`NaN`
    /// coordinate.
    #[test]
    fn degenerate_cell_size_falls_back_to_identity_instead_of_producing_nan() {
        let raw = mouse(MouseEventKind::Down(CtMouseButton::Left), 37, 21);
        for degenerate in [
            TerminalCellSize::new(0.0, 0.0),
            TerminalCellSize::new(-1.0, 1.0),
            TerminalCellSize::new(1.0, -1.0),
        ] {
            let ev = crossterm_mouse_to_uievent_scaled(raw, degenerate).unwrap();
            match ev {
                UiEvent::MouseDown { position, .. } => {
                    assert!(position.x.is_finite() && position.y.is_finite());
                    assert_eq!(position.x, 37.0);
                    assert_eq!(position.y, 21.0);
                }
                other => panic!("unexpected variant: {:?}", other),
            }
        }
    }

    #[test]
    fn resize_translates_to_window_resized() {
        let evs = crossterm_to_uievents(CtEvent::Resize(120, 40));
        assert_eq!(evs.len(), 1);
        match &evs[0] {
            UiEvent::WindowResized { viewport } => {
                assert_eq!(viewport.width, 120.0);
                assert_eq!(viewport.height, 40.0);
                assert_eq!(viewport.scale, 1.0);
            }
            other => panic!("unexpected variant: {:?}", other),
        }
    }

    #[test]
    fn paste_translates_to_clipboard_paste() {
        let evs = crossterm_to_uievents(CtEvent::Paste("hello".into()));
        assert_eq!(evs, vec![UiEvent::ClipboardPaste("hello".into())]);
    }

    #[test]
    fn focus_gained_translates() {
        let evs = crossterm_to_uievents(CtEvent::FocusGained);
        assert_eq!(evs, vec![UiEvent::WindowFocused(true)]);
    }

    #[test]
    fn focus_lost_translates() {
        let evs = crossterm_to_uievents(CtEvent::FocusLost);
        assert_eq!(evs, vec![UiEvent::WindowFocused(false)]);
    }

    #[test]
    fn shift_ctrl_modifiers_combine() {
        let mods = crossterm_modifiers_to_quadraui(KeyModifiers::SHIFT | KeyModifiers::CONTROL);
        assert!(mods.shift);
        assert!(mods.ctrl);
        assert!(!mods.alt);
        assert!(!mods.cmd);
    }

    #[test]
    fn super_modifier_maps_to_cmd() {
        let mods = crossterm_modifiers_to_quadraui(KeyModifiers::SUPER);
        assert!(mods.cmd);
    }

    // ─── Inverse: round-trip tests ──────────────────────────────────────────
    //
    // Stage 5b's loop migration relies on `synth_keyevent` /
    // `synth_mouseevent` giving back a crossterm event the existing
    // legacy handlers will accept. The round-trip through
    // `crossterm → UiEvent → synth_*` must preserve the fields
    // those handlers consult.

    #[test]
    fn key_roundtrips_through_synth() {
        for code in &[
            KeyCode::Char('a'),
            KeyCode::Char('Z'),
            KeyCode::Esc,
            KeyCode::Enter,
            KeyCode::Tab,
            KeyCode::BackTab,
            KeyCode::Backspace,
            KeyCode::Delete,
            KeyCode::Up,
            KeyCode::Down,
            KeyCode::Left,
            KeyCode::Right,
            KeyCode::Home,
            KeyCode::End,
            KeyCode::PageUp,
            KeyCode::PageDown,
            KeyCode::Insert,
            KeyCode::F(7),
        ] {
            let original = key(*code, KeyModifiers::CONTROL | KeyModifiers::SHIFT);
            let ui = crossterm_key_to_uievent(original).unwrap();
            let UiEvent::KeyPressed {
                key: k,
                modifiers,
                repeat,
            } = ui
            else {
                panic!("not a key press for {:?}", code);
            };
            let round = synth_keyevent(&k, modifiers, repeat).unwrap();
            assert_eq!(round.code, *code, "code mismatch for {:?}", code);
            assert_eq!(round.modifiers, original.modifiers);
            assert_eq!(round.kind, KeyEventKind::Press);
        }
    }

    #[test]
    fn mouse_down_roundtrips() {
        let original = mouse(MouseEventKind::Down(CtMouseButton::Left), 7, 12);
        let ui = crossterm_mouse_to_uievent(original).unwrap();
        let round = synth_mouseevent(&ui).unwrap();
        assert!(matches!(
            round.kind,
            MouseEventKind::Down(CtMouseButton::Left)
        ));
        assert_eq!(round.column, 7);
        assert_eq!(round.row, 12);
    }

    #[test]
    fn mouse_drag_roundtrips() {
        let original = mouse(MouseEventKind::Drag(CtMouseButton::Right), 30, 5);
        let ui = crossterm_mouse_to_uievent(original).unwrap();
        let round = synth_mouseevent(&ui).unwrap();
        assert!(matches!(
            round.kind,
            MouseEventKind::Drag(CtMouseButton::Right)
        ));
    }

    #[test]
    fn scroll_up_roundtrips() {
        let original = mouse(MouseEventKind::ScrollUp, 0, 0);
        let ui = crossterm_mouse_to_uievent(original).unwrap();
        let round = synth_mouseevent(&ui).unwrap();
        assert!(matches!(round.kind, MouseEventKind::ScrollUp));
    }

    // DoubleClickDetector tests moved to `crate::dispatch` alongside its
    // new home.
}