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
//! GDK → `quadraui::UiEvent` translation.
//!
//! Phase B.5 Stage 4. This module is the boundary between GTK's
//! native event types (`gdk::Key`, `gdk::ModifierType`,
//! `GestureClick` button presses, drawing-area resize signals) and
//! quadraui's backend-agnostic [`UiEvent`] enum.
//!
//! GTK is callback-driven: signals fire from inside the GTK main
//! loop via Relm4 widget templates. The architectural pattern (B.5
//! option A — the event-queue adapter) is:
//!
//! 1. Each signal callback closure captures
//!    `events_handle: Rc<RefCell<VecDeque<UiEvent>>>` cloned from
//!    `GtkBackend::events_handle()`.
//! 2. Inside the callback, translate the native event to a `UiEvent`
//!    via the helpers in this module.
//! 3. `events_handle.borrow_mut().push_back(ui_event)`.
//! 4. The driver code (Stage 5+) drains the queue via
//!    `Backend::wait_events` / `poll_events`.
//!
//! Stage 4 ships the translation helpers + unit tests; Stage 5 wires
//! actual signal callbacks to use them. The functions are
//! standalone (no Rc/RefCell), so they're trivially testable.

use gtk4::gdk;
use gtk4::glib;
use gtk4::prelude::*;

use crate::{Key, Modifiers, MouseButton, NamedKey, UiEvent};

/// Translate a GDK key event from `EventControllerKey::connect_key_pressed`
/// into a [`UiEvent::KeyPressed`]. Returns `None` for keysyms that
/// don't map to a `Key` value (modifier-only presses, dead keys, etc.).
///
/// `repeat` should be the value the controller's repeat flag reports —
/// today GTK doesn't surface a stable repeat flag through the
/// gtk4-rs binding, so callers pass `false`. The trait honours the
/// field but vimcode's engine doesn't currently distinguish first-press
/// from repeat at this layer.
pub fn gdk_key_to_uievent(
    key: gdk::Key,
    modifiers: gdk::ModifierType,
    repeat: bool,
) -> Option<UiEvent> {
    let key = gdk_key_to_quadraui_key(key)?;
    let modifiers = gdk_modifiers_to_quadraui(modifiers);
    Some(UiEvent::KeyPressed {
        key,
        modifiers,
        repeat,
    })
}

/// Translate a GDK button press from `GestureClick::connect_pressed`
/// into a [`UiEvent::MouseDown`]. The button index follows GTK's
/// convention (1 = primary / left, 2 = middle, 3 = secondary / right);
/// `n_press` is GTK's click count (used by callers to distinguish
/// double-click via `UiEvent::DoubleClick` if desired). The translator
/// here always emits `MouseDown` — caller handles double-click
/// detection if needed.
pub fn gdk_button_to_mouse_down(
    button: u32,
    x: f64,
    y: f64,
    modifiers: gdk::ModifierType,
) -> UiEvent {
    crate::event::mouse_down(
        gdk_button_to_quadraui(button),
        x as f32,
        y as f32,
        gdk_modifiers_to_quadraui(modifiers),
    )
}

/// Translate a GDK button release into [`UiEvent::MouseUp`].
pub fn gdk_button_to_mouse_up(button: u32, x: f64, y: f64) -> UiEvent {
    crate::event::mouse_up(gdk_button_to_quadraui(button), x as f32, y as f32)
}

/// Translate a GDK motion event into [`UiEvent::MouseMoved`]. GTK
/// doesn't surface which buttons are held in the basic motion
/// signal — callers tracking drag state pass an explicit `buttons`
/// mask (today: filled by `GestureDrag` consumers from gesture state).
pub fn gdk_motion_to_uievent(x: f64, y: f64, buttons: crate::ButtonMask) -> UiEvent {
    crate::event::mouse_moved(x as f32, y as f32, buttons)
}

/// Translate a GDK scroll event into [`UiEvent::Scroll`]. `dx`/`dy`
/// are GTK's `EventControllerScroll` deltas (positive `dy` = down —
/// this is the sign GTK4 apps consume directly when driving a
/// `GtkAdjustment`, e.g. `value += dy`; wheel-down / two-finger-down
/// on a non-natural-scroll touchpad reports positive `dy`). We negate
/// `dy` for `UiEvent::Scroll`'s convention (positive y = up toward
/// the top of content) — same as the TUI translator does for
/// crossterm scroll events, and the same negation `macos::events::ns_scroll`
/// applies to `NSEvent` deltas. Win32 is the one native backend that
/// *doesn't* negate — see `win::events::win_wheel_to_uievent`'s doc
/// for why.
///
/// This is the `natural_scroll = false` case of
/// [`gdk_scroll_to_uievent_with_direction`]; kept as its own function
/// so existing callers (and the GTK runner's default wiring) don't
/// need to thread an extra argument through for the common case.
pub fn gdk_scroll_to_uievent(dx: f64, dy: f64, x: f64, y: f64) -> UiEvent {
    gdk_scroll_to_uievent_with_direction(dx, dy, x, y, false)
}

/// Translate a GDK scroll event into [`UiEvent::Scroll`], with an
/// explicit natural-scroll override.
///
/// `dx`/`dy` carry their real magnitude straight through to
/// `delta.x`/`delta.y` (only sign and the `f64` → `f32` cast change) —
/// they are never reduced to ±1. `gtk4::EventControllerScroll`'s
/// `scroll` signal already unifies discrete wheel notches and smooth
/// trackpad deltas into one continuous `(dx, dy)` pair before this
/// function ever sees it (see `src/gtk/run.rs`'s `setup_scroll_controller`,
/// which doesn't set `EventControllerScrollFlags::DISCRETE`), so a
/// wheel step scaled by an OS "lines per notch" setting and a sub-row
/// trackpad nudge both arrive here as, and leave here as, their real
/// `f32` magnitude.
///
/// `natural_scroll = false` reproduces [`gdk_scroll_to_uievent`]'s
/// traditional-direction behavior exactly: wheel-down (positive raw
/// `dy`) becomes negative `delta.y`, i.e. "not up", so compose
/// controllers (`TreeController`, `SidebarSystem`, `ChatController`,
/// `FormController`) scroll the view toward later content.
///
/// `natural_scroll = true` flips the sign again — content follows the
/// gesture, matching touchscreen/trackpad "natural scrolling"
/// semantics — for apps that want an in-app toggle independent of (or
/// layered on top of) the OS-level libinput natural-scroll setting.
/// [`crate::AppLogic::natural_scroll`] is the trait hook the GTK
/// runner reads to pick the flag; `wire_da_events_with_scroll_direction`
/// is the equivalent for consumers wiring their own `DrawingArea`.
pub fn gdk_scroll_to_uievent_with_direction(
    dx: f64,
    dy: f64,
    x: f64,
    y: f64,
    natural_scroll: bool,
) -> UiEvent {
    // `crate::event::scroll` always negates its `dy_native_down_positive`
    // argument to reach quadraui's convention. The natural-scroll flag
    // needs the *opposite* of that negation, so feed it `-dy` — the
    // shared constructor's negation then cancels back out to `+dy`.
    let dy_native_down_positive = if natural_scroll { -dy } else { dy };
    crate::event::scroll(
        dx as f32,
        dy_native_down_positive as f32,
        x as f32,
        y as f32,
    )
}

/// Translate a `GtkDrawingArea` resize into [`UiEvent::WindowResized`].
/// `scale` is the surface scale factor (HiDPI multiplier) — typically
/// `widget.scale_factor() as f32`.
///
/// Apps with side effects on resize (e.g. resizing a PTY) need an actual
/// event, not just an updated viewport. `src/gtk/run.rs` wires
/// `DrawingArea::connect_resize` to this translator.
pub fn gdk_resize_to_uievent(width: i32, height: i32, scale: f32) -> UiEvent {
    crate::event::window_resized(width as f32, height as f32, scale)
}

/// Translate a `gtk::DropTarget`'s `drop` signal payload (already
/// resolved from the dragged `gdk::FileList` into real filesystem paths
/// — see `src/gtk/run.rs`'s `connect_drop` closure) into
/// [`UiEvent::FilesDropped`]. `x`/`y` are the signal's own
/// coordinates, already in the same DIP space every other GTK pointer
/// event uses — unlike Win's `WM_DROPFILES` translator, no
/// `scale_factor()` division is needed here.
pub fn gtk_drop_to_uievent(paths: Vec<std::path::PathBuf>, x: f64, y: f64) -> UiEvent {
    crate::event::files_dropped(paths, x as f32, y as f32)
}

/// Translate a `gio::Application`'s `open` signal payload —
/// a slice of `gio::File`s the OS handed the app, either from `argv` at
/// launch (`ApplicationFlags::HANDLES_OPEN` routes file/URI positional
/// arguments to `open` instead of `activate`) or forwarded from a second
/// launch to the already-running primary instance — into
/// [`UiEvent::OpenRequested`].
///
/// Each `gio::File` is classified by `File::path()`: `Some(_)` means a
/// local filesystem path (bucketed into `files`); `None` means a
/// non-local URI (`http://`, a custom app scheme, a GVfs mount) that
/// `File::uri()` still resolves to a string (bucketed into `urls`).
/// Unlike Win's plain-`String` `argv`, GTK's `gio::File` arrives
/// pre-classified by GLib itself, so this doesn't need
/// [`crate::event::classify_open_args`]'s `"://"` heuristic.
pub fn gtk_open_to_uievent(files: &[gtk4::gio::File]) -> UiEvent {
    let mut local_paths = Vec::new();
    let mut urls = Vec::new();
    for file in files {
        match file.path() {
            Some(path) => local_paths.push(path),
            None => urls.push(file.uri().to_string()),
        }
    }
    UiEvent::OpenRequested {
        urls,
        files: local_paths,
    }
}

/// Translate `gdk::ModifierType` to `quadraui::Modifiers`. Maps the
/// four standard modifiers — Ctrl, Shift, Alt, Super (Cmd on macOS;
/// Win/Meta key on X11). The other GDK bits (Lock, Hyper, Mod1–5)
/// don't have quadraui equivalents and are dropped.
pub fn gdk_modifiers_to_quadraui(m: gdk::ModifierType) -> Modifiers {
    Modifiers {
        shift: m.contains(gdk::ModifierType::SHIFT_MASK),
        ctrl: m.contains(gdk::ModifierType::CONTROL_MASK),
        alt: m.contains(gdk::ModifierType::ALT_MASK),
        cmd: m.contains(gdk::ModifierType::SUPER_MASK) || m.contains(gdk::ModifierType::META_MASK),
    }
}

/// Translate a `gdk::Key` keysym to a `quadraui::Key`. Unicode
/// keysyms map to `Key::Char`; named non-printables map to
/// `Key::Named`. Returns `None` for keysyms with no quadraui
/// counterpart (modifier keys, function keys above F24, dead keys,
/// etc.).
pub fn gdk_key_to_quadraui_key(key: gdk::Key) -> Option<Key> {
    if let Some(c) = key.to_unicode() {
        if !c.is_control() {
            return Some(Key::Char(c));
        }
        // Ctrl+letter produces a control character (e.g. \x03 for Ctrl+C).
        // Recover the base letter from the keysym name so the app sees
        // Key::Char('c') with modifiers.ctrl == true.
        if let Some(name) = key.name() {
            let bytes = name.as_bytes();
            if bytes.len() == 1 && bytes[0].is_ascii_alphabetic() {
                return Some(Key::Char(bytes[0] as char));
            }
        }
    }
    let name = key.name()?;
    let named = gdk_keyname_to_named_key(&name)?;
    Some(Key::Named(named))
}

/// Map a GDK keysym name to a `quadraui::NamedKey`. Mirrors the
/// `crossterm_keycode_to_key` shape in `tui_main/events.rs`.
pub fn gdk_keyname_to_named_key(name: &str) -> Option<NamedKey> {
    let named = match name {
        "Escape" => NamedKey::Escape,
        "Tab" => NamedKey::Tab,
        "ISO_Left_Tab" => NamedKey::BackTab,
        "Return" | "KP_Enter" => NamedKey::Enter,
        "BackSpace" => NamedKey::Backspace,
        "Delete" | "KP_Delete" => NamedKey::Delete,
        "Insert" | "KP_Insert" => NamedKey::Insert,
        "Home" | "KP_Home" => NamedKey::Home,
        "End" | "KP_End" => NamedKey::End,
        "Page_Up" | "KP_Page_Up" => NamedKey::PageUp,
        "Page_Down" | "KP_Page_Down" => NamedKey::PageDown,
        "Up" | "KP_Up" => NamedKey::Up,
        "Down" | "KP_Down" => NamedKey::Down,
        "Left" | "KP_Left" => NamedKey::Left,
        "Right" | "KP_Right" => NamedKey::Right,
        "Caps_Lock" => NamedKey::CapsLock,
        "Num_Lock" => NamedKey::NumLock,
        "Scroll_Lock" => NamedKey::ScrollLock,
        "Menu" => NamedKey::Menu,
        s if s.starts_with('F') && s[1..].chars().all(|c| c.is_ascii_digit()) => {
            let n: u8 = s[1..].parse().ok()?;
            if (1..=24).contains(&n) {
                NamedKey::F(n)
            } else {
                return None;
            }
        }
        _ => return None,
    };
    Some(named)
}

/// Map a GDK button index to a `quadraui::MouseButton`.
/// GTK convention: 1 = primary (left), 2 = middle, 3 = secondary
/// (right), 8 / 9 = back / forward (X1 / X2 on most mice).
pub fn gdk_button_to_quadraui(button: u32) -> MouseButton {
    match button {
        1 => MouseButton::Left,
        2 => MouseButton::Middle,
        3 => MouseButton::Right,
        8 => MouseButton::X1,
        9 => MouseButton::X2,
        n => MouseButton::Other(n.min(255) as u8),
    }
}

/// Attach mouse, scroll, and click event controllers to a
/// `DrawingArea` and translate all native events to [`UiEvent`].
///
/// The `on_event` callback fires for every translated event. The
/// consumer routes it (e.g. to `SidebarSystem::handle_cached`) and
/// triggers a redraw if needed.
///
/// Covers: MouseDown (left+right), MouseUp, DoubleClick, MouseMoved
/// (with button mask for drag detection), and Scroll (with correct
/// sign convention).
///
/// This eliminates ~40 lines of per-DrawingArea signal wiring that
/// every GTK consumer otherwise needs to write manually.
///
/// Scroll direction always follows [`gdk_scroll_to_uievent`]'s
/// traditional (`natural_scroll = false`) convention. Use
/// [`wire_da_events_with_scroll_direction`] to make it configurable
pub fn wire_da_events<F>(da: &gtk4::DrawingArea, on_event: F)
where
    F: Fn(UiEvent) + Clone + 'static,
{
    wire_da_events_with_scroll_direction(da, on_event, false);
}

/// Same as [`wire_da_events`], with an explicit natural-scroll flag
/// passed straight through to
/// [`gdk_scroll_to_uievent_with_direction`]. Consumers building their
/// own `DrawingArea` outside [`crate::gtk::run`] (which reads
/// [`crate::AppLogic::natural_scroll`] instead) use this to honour
/// the same preference.
pub fn wire_da_events_with_scroll_direction<F>(
    da: &gtk4::DrawingArea,
    on_event: F,
    natural_scroll: bool,
) where
    F: Fn(UiEvent) + Clone + 'static,
{
    use gtk4::{
        EventControllerMotion, EventControllerScroll, EventControllerScrollFlags, GestureClick,
    };

    let click = GestureClick::builder().button(0).build();
    {
        let on_event = on_event.clone();
        // Double-click detection uses a shared `DoubleClickDetector` instance
        // scoped to this `DrawingArea`, rather than reading GDK's native
        // `n_press` counter, to align with the detector used elsewhere in the crate.
        let double_click = std::rc::Rc::new(std::cell::RefCell::new(
            crate::dispatch::DoubleClickDetector::with_radius(
                super::backend::GTK_DOUBLE_CLICK_RADIUS,
            ),
        ));
        click.connect_pressed(move |gesture, _n_press, x, y| {
            let button = gesture.current_button();
            let modifier = gesture.current_event_state();
            let mut ev = gdk_button_to_mouse_down(button, x, y, modifier);
            double_click
                .borrow_mut()
                .process(std::slice::from_mut(&mut ev));
            on_event(ev);
        });
    }
    {
        let on_event = on_event.clone();
        click.connect_released(move |gesture, _n_press, x, y| {
            on_event(gdk_button_to_mouse_up(gesture.current_button(), x, y));
        });
    }
    da.add_controller(click);

    // `cursor_pos` is shared between the motion and scroll controllers.
    // GTK's `EventControllerScroll` callback only delivers `(dx, dy)`;
    // the pointer coordinates are not available from inside the callback.
    // Tracking the last known position from the motion controller and
    // reading it in the scroll handler is the standard GTK idiom.
    let cursor_pos = std::rc::Rc::new(std::cell::Cell::new((0.0_f64, 0.0_f64)));
    let motion = EventControllerMotion::new();
    {
        let on_event = on_event.clone();
        let cursor_pos = cursor_pos.clone();
        motion.connect_motion(move |ctrl, x, y| {
            cursor_pos.set((x, y));
            let modifier = ctrl.current_event_state();
            let buttons = crate::ButtonMask {
                left: modifier.contains(gdk::ModifierType::BUTTON1_MASK),
                middle: modifier.contains(gdk::ModifierType::BUTTON2_MASK),
                right: modifier.contains(gdk::ModifierType::BUTTON3_MASK),
            };
            on_event(gdk_motion_to_uievent(x, y, buttons));
        });
    }
    da.add_controller(motion);

    let scroll = EventControllerScroll::new(EventControllerScrollFlags::BOTH_AXES);
    {
        let on_event = on_event.clone();
        scroll.connect_scroll(move |_ctrl, dx, dy| {
            let (x, y) = cursor_pos.get();
            on_event(gdk_scroll_to_uievent_with_direction(
                dx,
                dy,
                x,
                y,
                natural_scroll,
            ));
            glib::Propagation::Stop
        });
    }
    da.add_controller(scroll);
}

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

    /// `gtk_drop_to_uievent` builds a `FilesDropped` with the given paths
    /// and position untouched (GTK's drop coordinates are already DIPs,
    /// no scale conversion).
    #[test]
    fn drop_to_uievent_carries_paths_and_position() {
        let paths = vec![
            std::path::PathBuf::from("/tmp/a.txt"),
            std::path::PathBuf::from("/tmp/b.txt"),
        ];
        let ev = gtk_drop_to_uievent(paths.clone(), 12.0, 34.0);
        match ev {
            UiEvent::FilesDropped {
                paths: got,
                position,
            } => {
                assert_eq!(got, paths);
                assert_eq!((position.x, position.y), (12.0, 34.0));
            }
            other => panic!("expected UiEvent::FilesDropped, got {other:?}"),
        }
    }

    /// Local files go to `files` (via `File::path()`), non-local URIs go
    /// to `urls` (via `File::uri()`) — GTK's `open` signal arrives
    /// pre-classified, unlike Win's plain-string `argv`.
    #[test]
    fn open_to_uievent_splits_local_files_from_uris() {
        let files = vec![
            gtk4::gio::File::for_path("/tmp/report.pdf"),
            gtk4::gio::File::for_uri("https://example.com/oauth/callback"),
        ];
        let ev = gtk_open_to_uievent(&files);
        match ev {
            UiEvent::OpenRequested { urls, files } => {
                assert_eq!(files, vec![std::path::PathBuf::from("/tmp/report.pdf")]);
                assert_eq!(urls, vec!["https://example.com/oauth/callback".to_string()]);
            }
            other => panic!("expected UiEvent::OpenRequested, got {other:?}"),
        }
    }

    #[test]
    fn open_to_uievent_handles_empty_list() {
        let ev = gtk_open_to_uievent(&[]);
        assert_eq!(
            ev,
            UiEvent::OpenRequested {
                urls: vec![],
                files: vec![],
            }
        );
    }

    #[test]
    fn modifiers_translate() {
        let m = gdk::ModifierType::CONTROL_MASK | gdk::ModifierType::SHIFT_MASK;
        let q = gdk_modifiers_to_quadraui(m);
        assert!(q.ctrl);
        assert!(q.shift);
        assert!(!q.alt);
        assert!(!q.cmd);
    }

    #[test]
    fn alt_modifier_translates() {
        let q = gdk_modifiers_to_quadraui(gdk::ModifierType::ALT_MASK);
        assert!(q.alt);
        assert!(!q.ctrl);
    }

    #[test]
    fn super_or_meta_maps_to_cmd() {
        assert!(gdk_modifiers_to_quadraui(gdk::ModifierType::SUPER_MASK).cmd);
        assert!(gdk_modifiers_to_quadraui(gdk::ModifierType::META_MASK).cmd);
    }

    #[test]
    fn keyname_named_keys() {
        for (name, expected) in &[
            ("Escape", NamedKey::Escape),
            ("Tab", NamedKey::Tab),
            ("ISO_Left_Tab", NamedKey::BackTab),
            ("Return", NamedKey::Enter),
            ("KP_Enter", NamedKey::Enter),
            ("BackSpace", NamedKey::Backspace),
            ("Delete", NamedKey::Delete),
            ("Up", NamedKey::Up),
            ("Down", NamedKey::Down),
            ("Left", NamedKey::Left),
            ("Right", NamedKey::Right),
            ("Page_Up", NamedKey::PageUp),
            ("Page_Down", NamedKey::PageDown),
            ("Home", NamedKey::Home),
            ("End", NamedKey::End),
            ("F1", NamedKey::F(1)),
            ("F12", NamedKey::F(12)),
        ] {
            assert_eq!(
                gdk_keyname_to_named_key(name),
                Some(*expected),
                "for {name}"
            );
        }
    }

    #[test]
    fn keyname_function_out_of_range() {
        assert_eq!(gdk_keyname_to_named_key("F0"), None);
        assert_eq!(gdk_keyname_to_named_key("F25"), None);
        assert_eq!(gdk_keyname_to_named_key("F99"), None);
    }

    #[test]
    fn keyname_unknown() {
        assert_eq!(gdk_keyname_to_named_key("Unknown_Foo"), None);
        assert_eq!(gdk_keyname_to_named_key(""), None);
    }

    #[test]
    fn button_translates() {
        assert_eq!(gdk_button_to_quadraui(1), MouseButton::Left);
        assert_eq!(gdk_button_to_quadraui(2), MouseButton::Middle);
        assert_eq!(gdk_button_to_quadraui(3), MouseButton::Right);
        assert_eq!(gdk_button_to_quadraui(8), MouseButton::X1);
        assert_eq!(gdk_button_to_quadraui(9), MouseButton::X2);
        assert_eq!(gdk_button_to_quadraui(7), MouseButton::Other(7));
    }

    #[test]
    fn mouse_down_translation() {
        let ev = gdk_button_to_mouse_down(1, 50.0, 100.0, gdk::ModifierType::CONTROL_MASK);
        match ev {
            UiEvent::MouseDown {
                widget,
                button,
                position,
                modifiers,
            } => {
                assert!(widget.is_none());
                assert_eq!(button, MouseButton::Left);
                assert_eq!(position.x, 50.0);
                assert_eq!(position.y, 100.0);
                assert!(modifiers.ctrl);
            }
            other => panic!("expected MouseDown, got {other:?}"),
        }
    }

    #[test]
    fn scroll_negates_dy_for_quadraui_convention() {
        // GTK reports positive dy = scroll down. quadraui's
        // `Scroll.delta.y` follows the convention positive y = up.
        let ev = gdk_scroll_to_uievent(0.0, 1.0, 10.0, 20.0);
        match ev {
            UiEvent::Scroll {
                delta, position, ..
            } => {
                assert_eq!(delta.y, -1.0);
                assert_eq!(delta.x, 0.0);
                assert_eq!(position.x, 10.0);
                assert_eq!(position.y, 20.0);
            }
            _ => panic!(),
        }
    }

    #[test]
    fn scroll_with_direction_false_matches_default_translator() {
        let a = gdk_scroll_to_uievent(0.0, 1.0, 10.0, 20.0);
        let b = gdk_scroll_to_uievent_with_direction(0.0, 1.0, 10.0, 20.0, false);
        match (a, b) {
            (UiEvent::Scroll { delta: da, .. }, UiEvent::Scroll { delta: db, .. }) => {
                assert_eq!(da, db);
            }
            _ => panic!(),
        }
    }

    #[test]
    fn scroll_with_direction_true_flips_sign() {
        // Same raw wheel-down gesture (dy = 1.0), but with the
        // natural-scroll override on: the sign flips relative to
        // `gdk_scroll_to_uievent`'s traditional -1.0.
        let ev = gdk_scroll_to_uievent_with_direction(0.0, 1.0, 10.0, 20.0, true);
        match ev {
            UiEvent::Scroll { delta, .. } => assert_eq!(delta.y, 1.0),
            _ => panic!(),
        }
    }

    #[test]
    fn scroll_preserves_fractional_smooth_scroll_magnitude() {
        // `GDK_SCROLL_SMOOTH` (trackpad) deltas are sub-unit, e.g. a
        // light two-finger nudge might report dy = 0.35. The
        // translator must carry that magnitude through unreduced
        // (not rounded/clamped to a whole row), or sub-row trackpad
        // scrolling degrades back to the old wheel-only ±1 behavior.
        let ev = gdk_scroll_to_uievent(0.2, 0.35, 10.0, 20.0);
        match ev {
            UiEvent::Scroll { delta, .. } => {
                assert_eq!(delta.x, 0.2);
                assert_eq!(delta.y, -0.35);
            }
            _ => panic!(),
        }
    }

    #[test]
    fn scroll_preserves_multi_line_discrete_scroll_magnitude() {
        // An OS-configured "scroll N lines per wheel notch" setting
        // (or a fast flick) reaches this translator as a single
        // `dy` larger than 1.0. That full magnitude must survive,
        // not collapse to a sign-only ±1.
        let ev = gdk_scroll_to_uievent(0.0, 4.5, 10.0, 20.0);
        match ev {
            UiEvent::Scroll { delta, .. } => assert_eq!(delta.y, -4.5),
            _ => panic!(),
        }
    }

    #[test]
    fn resize_translation() {
        let ev = gdk_resize_to_uievent(1920, 1080, 2.0);
        match ev {
            UiEvent::WindowResized { viewport } => {
                assert_eq!(viewport.width, 1920.0);
                assert_eq!(viewport.height, 1080.0);
                assert_eq!(viewport.scale, 2.0);
            }
            _ => panic!(),
        }
    }
}