quadraui 0.6.0

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
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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
//! In-process headless test driver for [`AppLogic`] GTK apps.
//!
//! [`GtkDriver`] mirrors [`crate::tui::testing::TuiDriver`]'s surface —
//! `new`, `render`, `dispatch`/`press`/`type_char`/`click` — so the same
//! scripted [`UiEvent`]s that drive `TuiDriver` also drive the GTK
//! backend (quadraui#446, GD-1).
//!
//! ## Display-free (verified in-repo)
//!
//! Renders into a headless `cairo::ImageSurface` (`Format::ARgb32`) — no
//! `gtk::init`, no `Application`, no window, no `GdkDisplay`. This is the
//! exact display-free path `gtk/pipeline_view.rs` and `gtk/tab_bar.rs`
//! already prove works for per-primitive paint tests; `GtkDriver` lifts
//! it to the whole-`AppLogic` level.
//!
//! ## No drift from production
//!
//! [`Self::render`] and [`Self::dispatch`] call the same
//! [`super::run::render_frame`] / [`super::run::dispatch_event`] the live
//! `quadraui::gtk::run` runner uses (mirroring quadraui#300's TUI split),
//! so the test path paints and pre-processes events (ActivityBar focus
//! intercept, accelerators, Ctrl-C/V/A, text selection) identically to
//! production. [`Self::click`] / [`Self::drag`] route through the same
//! [`crate::dispatch::route_pointer`] the live click/motion/
//! release handlers use, so text-region and scrollbar drags behave the
//! same under test.
//!
//! ## Limitations
//!
//! It renders into an in-memory `ImageSurface`, so it does **not**
//! exercise real GDK signal delivery — raw keycode translation
//! (`gdk_key_to_uievent`), IME, or actual `EventController` wiring are
//! out of scope and need a live-display smoke test instead. There is
//! also no character grid to string-match the way `TuiDriver::screen`
//! does; use [`Self::pixel`] to assert on rendered pixel colour instead.
//!
//! ```no_run
//! # use quadraui::gtk::testing::GtkDriver;
//! # use quadraui::{AppLogic, Backend, Reaction, UiEvent};
//! # fn demo<A: AppLogic + Default>() {
//! let mut driver = GtkDriver::new(A::default(), 100, 30);
//! driver.type_char('x');
//! let _ = driver.pixel(0, 0);
//! # }
//! ```

use pangocairo::cairo::{Context, Format, ImageSurface};

use crate::backend::Backend;
use crate::dispatch::route_pointer;
use crate::runner::{AppLogic, Reaction};
use crate::shell::{ShellApp, ShellConfig};
use crate::testing::driver_core::DriverCore;
use crate::testing::{
    Anchor, ConformanceDriver, DriverInput, FrameInventory, LogicalViewport, PixelClickConformance,
    TextRun,
};
use crate::{ButtonMask, Key, Modifiers, MouseButton, NamedKey, Point, UiEvent, WidgetId};

use super::backend::GtkBackend;
use super::run::{dispatch_event, render_frame};

/// Build a [`GtkDriver`] that wraps `app` in the full
/// [`crate::shell_adapter::ShellAdapter`] stack, mirroring exactly what
/// [`crate::gtk::shell_runner::run_with_shell`] does at runtime — but
/// returning a testable driver instead of entering the live event loop.
/// The GTK twin of [`crate::tui::testing::driver_with_shell`]; the two share
/// the same [`crate::shell::ShellApp`] + [`ShellConfig`] input, differing
/// only in the native units their respective drivers take (TUI cells vs
/// GTK pixels, per [`GtkDriver::new`]).
///
/// Use this constructor in tests that need to verify the full
/// `ShellApp → ShellAdapter → dispatch_event` integration path on the GTK
/// backend — e.g. confirming that shell chrome (activity bar, sidebar
/// panel) renders and that panel switches reach the real [`AppShell`]
/// instance [`crate::shell_adapter::ShellAdapter`] paints, not a shadow
/// copy.
///
/// [`AppShell`]: crate::compose::app_shell::AppShell
///
/// # Example
///
/// ```no_run
/// # use quadraui::gtk::testing::driver_with_shell;
/// # use quadraui::{ShellApp, ShellConfig, Backend, ShellContext, Reaction, UiEvent};
/// # struct MyApp;
/// # impl ShellApp for MyApp {
/// #     fn render_content(&self, _: &mut dyn Backend, _: &quadraui::compose::app_shell::AppShellLayout) {}
/// #     fn handle(&mut self, _: UiEvent, _: &mut dyn Backend, _: &ShellContext) -> Reaction { Reaction::Continue }
/// # }
/// let config = ShellConfig::new("Demo", vec![]);
/// let mut driver = driver_with_shell(MyApp, config, 800, 480);
/// let _ = driver.pixel(0, 0);
/// ```
pub fn driver_with_shell<A: ShellApp + 'static>(
    app: A,
    config: ShellConfig,
    width: i32,
    height: i32,
) -> GtkDriver<impl AppLogic> {
    let adapter = crate::shell_adapter::build_shell_adapter(app, config);
    GtkDriver::new(adapter, width, height)
}

/// Drives an [`AppLogic`] impl headlessly against the GTK backend for
/// tests. Construct with [`Self::new`] (runs `setup` + paints the first
/// frame), poke it with [`Self::press`] / [`Self::type_char`] /
/// [`Self::click`] / [`Self::drag`], and read painted pixels back with
/// [`Self::pixel`].
pub struct GtkDriver<A: AppLogic> {
    core: DriverCore<GtkBackend, A>,
    surface: ImageSurface,
    width: i32,
    height: i32,
}

impl<A: AppLogic> GtkDriver<A> {
    /// Build a driver for `app` on a `width`×`height` pixel surface, run
    /// the app's `setup` hook, and paint the first frame.
    pub fn new(app: A, width: i32, height: i32) -> Self {
        let surface =
            ImageSurface::create(Format::ARgb32, width, height).expect("create ImageSurface");
        let mut backend = GtkBackend::new();
        // Record every painted text run into `GtkBackend::painted_text`
        // so `find`/`find_bounds`/`screen_contains` can locate text from
        // *any* primitive, not just the three whose trait methods
        // hand-roll a `record_painted_text` call. Off in
        // production runners — a live app never reads the map.
        backend.set_painted_text_recording(true);
        // Seed the backend's persistent Pango context, exactly as
        // `gtk::run::activate` does from the realized `DrawingArea`
        // (same `"Sans 11"` UI font it sets there). Without this, every
        // `*_layout()` method called *outside* a frame scope — which is
        // where all click hit-testing happens, since `AppLogic::handle`
        // runs between frames — had no Pango layout at all and silently
        // fell back to `chars().count() * char_width`. That estimate is
        // only accurate for a monospace font, so the driver's hit
        // regions drifted off the painted labels for any chrome painted
        // in the proportional `ui_font`, while the same
        // click landed correctly in a real window. Seeding it here makes
        // the harness measure clicks the way production does.
        {
            let cr = Context::new(&surface).expect("Context::new on headless ImageSurface");
            let pctx = pangocairo::functions::create_context(&cr);
            pctx.set_font_description(&pangocairo::pango::FontDescription::from_string("Sans 11"));
            backend.set_pango_context(pctx);
        }
        // Seed the viewport from the driver's surface size BEFORE setup,
        // exactly as the live `gtk::run::activate` does:
        // without this, `app.setup()` would read `GtkBackend::new()`'s
        // zeroed default viewport instead of the requested
        // `width`×`height`.
        backend.begin_frame(crate::Viewport::new(width as f32, height as f32, 1.0));
        let mut app = app;
        app.setup(&mut backend);
        let mut driver = Self {
            core: DriverCore::new(app, backend),
            surface,
            width,
            height,
        };
        driver.render();
        driver
    }

    /// Repaint one frame through the shared production render path.
    pub fn render(&mut self) {
        let cr = Context::new(&self.surface).expect("Context::new on headless ImageSurface");
        let (backend, app) = self.core.parts_mut();
        render_frame(backend, app, &cr, self.width, self.height);
    }

    /// Feed one synthetic event through the shared production
    /// [`dispatch_event`] path. Repaints on redraw and latches `exited`.
    pub fn dispatch(&mut self, event: UiEvent) -> Reaction {
        if self.core.exited() {
            return Reaction::Exit;
        }
        let outcome = {
            let (backend, app) = self.core.parts_mut();
            dispatch_event(event, backend, app)
        };
        let surface = &self.surface;
        let width = self.width;
        let height = self.height;
        self.core.apply_outcome(outcome, |backend, app| {
            let cr = Context::new(surface).expect("Context::new on headless ImageSurface");
            render_frame(backend, app, &cr, width, height);
        })
    }

    /// Toggle whether [`Self::dispatch`] (and every click helper built on
    /// it) folds a `MouseDown` into `DoubleClick` when it lands at the
    /// same spot as the previous one within [`crate::dispatch::DoubleClickDetector`]'s
    /// window. Defaults to `true` — real folding, matching
    /// the live GTK app and `TuiDriver`'s own default. Pass `false` when
    /// a test dispatches two deliberate single clicks at the same
    /// position in immediate succession (no real GDK press-count or
    /// wall-clock gap between them) and needs two `MouseDown`s rather
    /// than a coin-flip on wall-clock timing. Mirrors
    /// `TuiDriver::set_double_click_folding` exactly.
    pub fn set_double_click_folding(&mut self, enabled: bool) {
        self.core.backend_mut().set_double_click_folding(enabled);
    }

    /// Press a key (no modifiers).
    pub fn press(&mut self, key: Key) -> Reaction {
        DriverInput::press(self, key)
    }

    /// Type a single character key (no modifiers).
    pub fn type_char(&mut self, c: char) -> Reaction {
        DriverInput::type_char(self, c)
    }

    /// Press a named (non-printable) key, e.g. [`NamedKey::Enter`].
    pub fn press_named(&mut self, key: NamedKey) -> Reaction {
        DriverInput::press_named(self, key)
    }

    /// Press a character key with Ctrl held (e.g. `ctrl_char('c')` to
    /// trigger the runner's copy-on-selection path).
    pub fn ctrl_char(&mut self, c: char) -> Reaction {
        DriverInput::ctrl_char(self, c)
    }

    /// Left-click at surface coordinates `(x, y)` (pixels), routed
    /// through the same [`route_pointer`] the live click handler uses —
    /// so a click on a registered text region or scrollbar begins a drag
    /// exactly as it would live.
    pub fn click(&mut self, x: f32, y: f32) -> Reaction {
        DriverInput::click(self, x, y)
    }

    /// Press the left mouse button down at `(x, y)`. Begins a drag if it
    /// lands on a draggable target (text region, scrollbar thumb).
    pub fn mouse_down(&mut self, x: f32, y: f32) -> Reaction {
        let position = Point::new(x, y);
        let events = {
            let backend = self.core.backend_mut();
            let stack_rc = backend.modal_stack_handle();
            let drag_rc = backend.drag_state_handle();
            let stack = stack_rc.borrow();
            let mut drag = drag_rc.borrow_mut();
            route_pointer(
                &stack,
                &mut drag,
                backend.text_selection_state_mut(),
                UiEvent::MouseDown {
                    widget: None,
                    button: MouseButton::Left,
                    position,
                    modifiers: Modifiers::default(),
                },
            )
        };
        self.dispatch_all(events)
    }

    /// Move the cursor to `(x, y)` with the left button held. During an
    /// active drag this is translated to the drag's high-level event
    /// (e.g. [`UiEvent::TextSelectionChanged`] /
    /// [`UiEvent::ScrollOffsetChanged`]).
    pub fn mouse_move(&mut self, x: f32, y: f32) -> Reaction {
        let position = Point::new(x, y);
        let events = {
            let backend = self.core.backend_mut();
            let stack_rc = backend.modal_stack_handle();
            let drag_rc = backend.drag_state_handle();
            let stack = stack_rc.borrow();
            let mut drag = drag_rc.borrow_mut();
            route_pointer(
                &stack,
                &mut drag,
                backend.text_selection_state_mut(),
                UiEvent::MouseMoved {
                    position,
                    buttons: ButtonMask {
                        left: true,
                        ..ButtonMask::default()
                    },
                },
            )
        };
        self.dispatch_all(events)
    }

    /// Release the left mouse button at `(x, y)`, ending any active drag.
    pub fn mouse_up(&mut self, x: f32, y: f32) -> Reaction {
        let position = Point::new(x, y);
        let events = {
            let backend = self.core.backend_mut();
            let stack_rc = backend.modal_stack_handle();
            let drag_rc = backend.drag_state_handle();
            let stack = stack_rc.borrow();
            let mut drag = drag_rc.borrow_mut();
            route_pointer(
                &stack,
                &mut drag,
                backend.text_selection_state_mut(),
                UiEvent::MouseUp {
                    widget: None,
                    button: MouseButton::Left,
                    position,
                },
            )
        };
        self.dispatch_all(events)
    }

    /// Left-button drag from `(x0, y0)` to `(x1, y1)`: down → move → up.
    pub fn drag(&mut self, x0: f32, y0: f32, x1: f32, y1: f32) -> Reaction {
        DriverInput::drag(self, x0, y0, x1, y1)
    }

    /// Dispatch each of `events` in order, short-circuiting on `Exit` and
    /// returning the strongest [`Reaction`] observed (`Exit` beats
    /// `Redraw` beats `RedrawAfter`, and two `RedrawAfter`s keep the
    /// earlier deadline — see [`Reaction::merge`]) — mirrors the live
    /// click/motion/release handlers' per-event loop.
    fn dispatch_all(&mut self, events: Vec<UiEvent>) -> Reaction {
        let mut result = Reaction::Continue;
        for ev in events {
            let step = self.dispatch(ev);
            if step == Reaction::Exit {
                return Reaction::Exit;
            }
            result = result.merge(step);
        }
        result
    }

    /// Whether the app has returned [`Reaction::Exit`].
    pub fn exited(&self) -> bool {
        self.core.exited()
    }

    /// Access the app state for test assertions.
    pub fn app(&self) -> &A {
        self.core.app()
    }

    /// Mutable access to the app state for tests that need to poke state
    /// directly rather than through a scripted [`UiEvent`] — mirrors
    /// [`crate::tui::testing::TuiDriver::app_mut`].
    pub fn app_mut(&mut self) -> &mut A {
        self.core.app_mut()
    }

    /// Access the backend for test assertions (e.g. active selection
    /// state, drag state).
    pub fn backend(&self) -> &GtkBackend {
        self.core.backend()
    }

    /// Read an RGB triple from the rendered surface at pixel `(x, y)`.
    ///
    /// Cairo's `ARgb32` stores each pixel as four bytes in native
    /// (little-endian) byte order: `[B, G, R, A]` — the same decode
    /// `gtk/tab_bar.rs`'s and `gtk/pipeline_view.rs`'s paint tests use.
    /// Flushes pending Cairo operations first so the readback reflects
    /// the last [`Self::render`].
    pub fn pixel(&mut self, x: i32, y: i32) -> (u8, u8, u8) {
        self.surface.flush();
        let stride = self.surface.stride() as usize;
        let data = self.surface.data().expect("surface data");
        let off = y as usize * stride + x as usize * 4;
        (data[off + 2], data[off + 1], data[off])
    }

    /// Raw `ARgb32` pixel buffer of the last [`Self::render`] — the
    /// `screen()`-equivalent GD-2 raw-buffer accessor. Four bytes per
    /// pixel, `[B, G, R, A]` (see [`Self::pixel`]); row stride is
    /// [`Self::stride`], not necessarily `width * 4`. Copies out of the
    /// surface (Cairo's borrow guard can't outlive this call) — prefer
    /// [`Self::pixel`] / [`Self::find`] / [`Self::screen_contains`] for
    /// assertions; this is the escape hatch for tests that need the whole
    /// buffer (e.g. diffing two frames).
    pub fn screen(&mut self) -> Vec<u8> {
        self.surface.flush();
        self.surface.data().expect("surface data").to_vec()
    }

    /// Row stride (bytes per row) of the surface [`Self::screen`] reads
    /// back from. Cairo pads rows for alignment, so this can exceed
    /// `width * 4`.
    pub fn stride(&self) -> i32 {
        self.surface.stride()
    }

    /// All text painted during the last [`Self::render`], as recorded by
    /// [`super::backend::GtkBackend::record_painted_text`] — the
    /// `(text, bounds)` map [`Self::find`] / [`Self::find_bounds`] /
    /// [`Self::screen_contains`] query.
    ///
    /// Every text-bearing primitive reports in, recorded at
    /// the `show_layout` choke point every GTK rasteriser paints through —
    /// so a run here is one Pango run, which for multi-span content (a
    /// styled tree row, a syntax-highlighted editor line) means one entry
    /// *per span* rather than one per logical row. Match on a substring
    /// within a span, the way [`Self::screen_contains`] does, rather than
    /// on a phrase that straddles a style change. The exceptions are
    /// `draw_terminal` (a per-cell grid — deliberately not recorded) and
    /// the primitives that paint no text at all (`draw_split`,
    /// `draw_split_tree`, `draw_scrollbar`, `draw_drop_overlay`).
    pub fn painted_texts(&self) -> Vec<&str> {
        self.core
            .backend()
            .painted_text
            .iter()
            .map(|p| p.text.as_str())
            .collect()
    }

    /// True if any painted label contains `needle` — the GTK analogue of
    /// [`crate::tui::testing::TuiDriver::screen_contains`].
    pub fn screen_contains(&self, needle: &str) -> bool {
        self.core
            .backend()
            .painted_text
            .iter()
            .any(|p| p.text.contains(needle))
    }

    /// Pixel bounds (backend coordinates) of the first painted label
    /// containing `needle`, resolved from Pango-measured layout geometry
    /// rather than a character grid — mirrors the `TuiDriver::find` rule
    /// (*locate targets with `find`, never hardcode coords*).
    pub fn find_bounds(&self, needle: &str) -> Option<crate::Rect> {
        self.core
            .backend()
            .painted_text
            .iter()
            .find(|p| p.text.contains(needle))
            .map(|p| p.bounds)
    }

    /// Center coordinates (pixels) of the first painted label containing
    /// `needle` — pass straight to [`Self::click`]. `None` if nothing
    /// painted this frame matched.
    pub fn find(&self, needle: &str) -> Option<(f32, f32)> {
        self.find_bounds(needle)
            .map(|b| (b.x + b.width / 2.0, b.y + b.height / 2.0))
    }

    /// Pixel coordinates of tab `tab_idx`'s center in the tab bar `bar`,
    /// for [`Self::click`] to land on that specific tab.
    ///
    /// `find` can't do this job: every tab paints the same chrome (and a
    /// closed/active tab's label may repeat elsewhere on screen), so there
    /// is no needle that disambiguates "tab 3" from "tab 0". This instead
    /// resolves against the [`crate::TabBarLayout`] `GtkBackend::draw_tab_bar`
    /// cached the last time `bar` painted — `None` if `bar` didn't paint
    /// this frame, or if `tab_idx` is scrolled out of view behind the
    /// bar's `scroll_offset`.
    pub fn tab_center(&self, bar: &WidgetId, tab_idx: usize) -> Option<(f32, f32)> {
        let (rect, layout) = self.core.backend().cached_tab_bar_layout(bar)?;
        let (cx, cy) = layout.tab_center(tab_idx)?;
        Some((rect.x + cx, rect.y + cy))
    }

    /// Pixel coordinates of tab `tab_idx`'s close-button center in the tab
    /// bar `bar` — the `×`/`●` glyph every tab shares, so [`Self::find`]
    /// can't target one tab's close button over another's.
    ///
    /// `None` for the same reasons as [`Self::tab_center`], plus: the tab
    /// drew no close button this frame (`is_closable: false` on the tab,
    /// or `show_tab_close: false` on the bar).
    pub fn tab_close_center(&self, bar: &WidgetId, tab_idx: usize) -> Option<(f32, f32)> {
        let (rect, layout) = self.core.backend().cached_tab_bar_layout(bar)?;
        let (cx, cy) = layout.tab_close_center(tab_idx)?;
        Some((rect.x + cx, rect.y + cy))
    }
}

/// The four raw primitives [`DriverInput`]'s default `press`/`type_char`/
/// `press_named`/`ctrl_char`/`click`/`drag` methods build on — see that
/// trait's doc for why `dispatch`/`mouse_down`/`mouse_move`/`mouse_up`
/// stay required (genuinely per-backend) rather than shared.
impl<A: AppLogic> DriverInput for GtkDriver<A> {
    fn dispatch(&mut self, event: UiEvent) -> Reaction {
        self.dispatch(event)
    }

    fn mouse_down(&mut self, x: f32, y: f32) -> Reaction {
        self.mouse_down(x, y)
    }

    fn mouse_move(&mut self, x: f32, y: f32) -> Reaction {
        self.mouse_move(x, y)
    }

    fn mouse_up(&mut self, x: f32, y: f32) -> Reaction {
        self.mouse_up(x, y)
    }
}

/// Backs [`ConformanceDriver::click_text_at`]/`drag_text`/`scroll_at`'s
/// shared pixel-unit bodies.
impl<A: AppLogic> PixelClickConformance for GtkDriver<A> {
    const NAME: &'static str = "GtkDriver";

    fn find_bounds(&self, needle: &str) -> Option<crate::Rect> {
        self.find_bounds(needle)
    }

    fn find(&self, needle: &str) -> Option<(f32, f32)> {
        self.find(needle)
    }

    fn conformance_line_height(&self) -> f32 {
        self.core.backend().line_height()
    }
}

impl<A: AppLogic> ConformanceDriver for GtkDriver<A> {
    type App = A;

    fn new_fixture(app: Self::App, viewport: LogicalViewport) -> Self {
        // GTK's native unit is the pixel. Scale the logical cols/rows by
        // `GtkBackend::new()`'s nominal char_width/line_height (8px/16px)
        // — the driver's first frame (and therefore the app's real font
        // metrics) doesn't exist yet to measure from, so this is the same
        // nominal default the backend itself starts with.
        const NOMINAL_CHAR_WIDTH: i32 = 8;
        const NOMINAL_LINE_HEIGHT: i32 = 16;
        GtkDriver::new(
            app,
            viewport.cols as i32 * NOMINAL_CHAR_WIDTH,
            viewport.rows as i32 * NOMINAL_LINE_HEIGHT,
        )
    }

    fn backend_caps(&self) -> crate::BackendCaps {
        // Straight off the real `GtkBackend` this driver wraps — never a
        // re-statement.
        crate::Backend::backend_caps(self.core.backend())
    }

    fn press_named(&mut self, key: NamedKey) {
        GtkDriver::press_named(self, key);
    }

    fn type_char(&mut self, c: char) {
        GtkDriver::type_char(self, c);
    }

    fn ctrl_char(&mut self, c: char) {
        GtkDriver::ctrl_char(self, c);
    }

    fn click_text_at(&mut self, needle: &str, at: Anchor) {
        PixelClickConformance::click_text_at(self, needle, at)
    }

    fn drag_text(&mut self, from: &str, to: &str) {
        PixelClickConformance::drag_text(self, from, to)
    }

    fn scroll_at(&mut self, needle: &str, lines: i32) {
        PixelClickConformance::scroll_at(self, needle, lines)
    }

    fn inventory(&self) -> FrameInventory {
        FrameInventory {
            text_runs: self
                .core
                .backend()
                .painted_text
                .iter()
                .map(|p| TextRun {
                    text: p.text.clone(),
                    bounds: p.bounds,
                })
                .collect(),
            // Zones registered this frame via `Backend::register_zone` —
            // currently the shell-chrome zones `AppShell::render` records
            // (activity-bar items, sidebar header/content, status bar,
            // ...). Primitives that don't yet call `register_zone`
            // contribute no zone.
            zones: self.core.backend().zones.clone(),
        }
    }

    fn screen_has(&self, needle: &str) -> bool {
        self.screen_contains(needle)
    }

    fn exited(&self) -> bool {
        GtkDriver::exited(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::status_bar::{StatusBar, StatusBarSegment};
    use crate::types::{Color, WidgetId};
    use crate::Rect;

    const W: i32 = 120;
    const H: i32 = 24;
    // Distinct from the default theme background so a match can only
    // come from the segment actually being painted.
    const KNOWN_BG: Color = Color::rgb(0, 255, 0);

    /// Minimal app that draws one `StatusBar` segment filling the whole
    /// surface with [`KNOWN_BG`].
    struct StatusBarApp;

    impl AppLogic for StatusBarApp {
        type AreaId = ();

        fn render(&self, backend: &mut dyn Backend, _area: ()) {
            backend.draw_status_bar_interactive(
                Rect::new(0.0, 0.0, W as f32, H as f32),
                &StatusBar {
                    id: WidgetId::new("status"),
                    left_segments: vec![StatusBarSegment {
                        text: "known-pixel".to_string(),
                        fg: Color::rgb(255, 255, 255),
                        bg: KNOWN_BG,
                        bold: false,
                        action_id: None,
                    }],
                    right_segments: vec![],
                },
                &crate::InteractionState::new(),
            );
        }

        fn handle(&mut self, _event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
            Reaction::Continue
        }
    }

    /// GD-1 acceptance test: build an `AppLogic`, render a frame
    /// offscreen (no display, no `gtk::init`), and read back a known
    /// pixel. `draw_status_bar` fills the bar with the first segment's
    /// `bg` when there's no gap to the right segments, so every pixel in
    /// the bar's rect that the segment's *label glyphs* don't cover
    /// should be [`KNOWN_BG`].
    ///
    /// The sample is taken near the bar's right edge, not its left.
    /// #624 made chrome paint in [`GtkBackend`]'s `ui_font` (`"Sans 11"`)
    /// rather than the editor font the shared Pango layout happened to
    /// carry, which widened the left-aligned `"known-pixel"` label to
    /// ~86px — wide enough that the old `pixel(4, H / 2)` sample landed
    /// on an anti-aliased glyph stroke and read back a green/white blend
    /// instead of the fill. The `assert!` below re-derives the label's
    /// real extent so that a future font change growing it past the
    /// sample point fails with that width named, rather than resurfacing
    /// as an opaque colour mismatch.
    #[test]
    fn renders_offscreen_and_reads_back_known_pixel() {
        let mut driver = GtkDriver::new(StatusBarApp, W, H);

        let sample_x = W - 4;
        let label = driver
            .find_bounds("known-pixel")
            .expect("the segment's label should have been painted");
        assert!(
            (sample_x as f32) > label.x + label.width,
            "sample x={sample_x} must sit right of the label's own bounds \
             (x={}, width={}) so it reads the bar's fill, not a glyph stroke",
            label.x,
            label.width
        );

        let (r, g, b) = driver.pixel(sample_x, H / 2);
        assert_eq!(
            (r, g, b),
            (KNOWN_BG.r, KNOWN_BG.g, KNOWN_BG.b),
            "expected the status bar segment's known background colour, got ({r}, {g}, {b})"
        );
    }

    /// `find`/`find_bounds` locate the segment's label via the
    /// `(text, bounds)` map [`GtkBackend::draw_status_bar`] records —
    /// the coordinate-free alternative to hardcoding a pixel sample.
    #[test]
    fn find_locates_status_bar_segment_by_text() {
        let mut driver = GtkDriver::new(StatusBarApp, W, H);

        let bounds = driver
            .find_bounds("known-pixel")
            .expect("find_bounds should locate the painted segment");
        assert_eq!(
            (bounds.x, bounds.y),
            (crate::primitives::status_bar::PIXEL_EDGE_INSET, 0.0),
            "the only segment should start `PIXEL_EDGE_INSET` in from the bar's \
             own left edge (issue #1155), not flush at its origin"
        );

        let (x, y) = driver
            .find("known-pixel")
            .expect("find should locate the painted segment label");
        assert!(
            x >= bounds.x && x <= bounds.x + bounds.width,
            "find()'s x should fall within the segment's own bounds"
        );
        assert!(
            y >= bounds.y && y <= bounds.y + bounds.height,
            "find()'s y should fall within the segment's own bounds"
        );

        // Sample the whole segment bounds and take the most common
        // colour — the background fill, since it covers far more area
        // than the label's thin anti-aliased glyph strokes — rather than
        // guessing a coordinate known to dodge the text.
        let (r, g, b) = dominant_pixel(&mut driver, bounds);
        assert_eq!(
            (r, g, b),
            (KNOWN_BG.r, KNOWN_BG.g, KNOWN_BG.b),
            "dominant colour within find_bounds() should be the segment's bg, got ({r}, {g}, {b})"
        );

        assert!(driver.screen_contains("known-pixel"));
        assert!(!driver.screen_contains("no such label"));
    }

    /// Most common `(r, g, b)` pixel within `bounds` — the background
    /// colour, since it covers far more area than a label's thin
    /// anti-aliased glyph strokes. Used to assert on a text-tight
    /// segment's fill colour without hardcoding a coordinate known to
    /// dodge the text.
    fn dominant_pixel<A: AppLogic>(driver: &mut GtkDriver<A>, bounds: Rect) -> (u8, u8, u8) {
        use std::collections::HashMap;

        let mut counts: HashMap<(u8, u8, u8), u32> = HashMap::new();
        for py in bounds.y as i32..(bounds.y + bounds.height) as i32 {
            for px in bounds.x as i32..(bounds.x + bounds.width) as i32 {
                *counts.entry(driver.pixel(px, py)).or_insert(0) += 1;
            }
        }
        counts
            .into_iter()
            .max_by_key(|(_, count)| *count)
            .map(|(color, _)| color)
            .expect("bounds should contain at least one pixel")
    }

    /// Fixture analogous to the issue's `make_test_app(BoardData)`: a
    /// full GTK view built purely from in-memory state — one clickable
    /// `StatusBar` segment that flips its background colour on click.
    /// No live app, no example wiring — just an `AppLogic` a test can
    /// hand straight to [`GtkDriver::new`].
    struct ToggleStatusBarApp {
        on: bool,
    }

    impl ToggleStatusBarApp {
        const OFF_BG: Color = Color::rgb(40, 40, 40);
        const ON_BG: Color = Color::rgb(0, 200, 0);

        fn bar(&self) -> StatusBar {
            StatusBar {
                id: WidgetId::new("status"),
                left_segments: vec![StatusBarSegment {
                    text: "Toggle".to_string(),
                    fg: Color::rgb(255, 255, 255),
                    bg: if self.on { Self::ON_BG } else { Self::OFF_BG },
                    bold: false,
                    action_id: Some(WidgetId::new("toggle")),
                }],
                right_segments: vec![],
            }
        }
    }

    impl AppLogic for ToggleStatusBarApp {
        type AreaId = ();

        fn render(&self, backend: &mut dyn Backend, _area: ()) {
            backend.draw_status_bar_interactive(
                Rect::new(0.0, 0.0, W as f32, H as f32),
                &self.bar(),
                &crate::InteractionState::new(),
            );
        }

        fn handle(&mut self, event: UiEvent, backend: &mut dyn Backend) -> Reaction {
            // Hit-test via the non-painting `status_bar_layout` query
            // (mirrors CLAUDE.md's "cached layout hit-test pattern" —
            // recompute the layout from state, don't repaint to hit-test).
            if let UiEvent::MouseDown { position, .. } = event {
                let layout =
                    backend.status_bar_layout(Rect::new(0.0, 0.0, W as f32, H as f32), &self.bar());
                if layout.hit_test(position.x, position.y)
                    == crate::primitives::status_bar::StatusBarHit::Segment(WidgetId::new("toggle"))
                {
                    self.on = !self.on;
                    return Reaction::Redraw;
                }
            }
            Reaction::Continue
        }
    }

    /// GD-2 acceptance test: `find` locates the control (no hardcoded
    /// coords), `click` activates it, and both a pixel-colour probe and a
    /// geometry (bounds) assertion observe the resulting change.
    #[test]
    fn find_click_asserts_pixel_and_geometry_change() {
        let mut driver = GtkDriver::new(ToggleStatusBarApp { on: false }, W, H);

        let (x, y) = driver
            .find("Toggle")
            .expect("find should locate the toggle segment before any click");
        let bounds_before = driver.find_bounds("Toggle").expect("bounds before click");
        // The segment's bounds are text-tight (clickable segments aren't
        // padded out to fill the bar, unlike the trailing non-clickable
        // segment `renders_offscreen_and_reads_back_known_pixel` reads
        // from), so no single fixed pixel is guaranteed to dodge the
        // label's anti-aliased glyphs. Sample the whole bounds rect and
        // take the most common colour — the background, since it covers
        // far more area than the thin glyph strokes.
        let pixel_before = dominant_pixel(&mut driver, bounds_before);
        assert_eq!(
            pixel_before,
            (
                ToggleStatusBarApp::OFF_BG.r,
                ToggleStatusBarApp::OFF_BG.g,
                ToggleStatusBarApp::OFF_BG.b
            ),
            "segment should start OFF-coloured"
        );

        let reaction = driver.click(x, y);
        assert_eq!(reaction, Reaction::Redraw, "click should trigger a redraw");
        assert!(
            driver.app().on,
            "click should have flipped the toggle state"
        );

        // Pixel assertion: same bounds (segment didn't move — the bar
        // layout is unchanged), different dominant colour.
        let pixel_after = dominant_pixel(&mut driver, bounds_before);
        assert_eq!(
            pixel_after,
            (
                ToggleStatusBarApp::ON_BG.r,
                ToggleStatusBarApp::ON_BG.g,
                ToggleStatusBarApp::ON_BG.b
            ),
            "segment should be ON-coloured after the click toggled state"
        );
        assert_ne!(
            pixel_before, pixel_after,
            "click should change the painted pixel"
        );

        // Geometry assertion: re-`find` after the click (the label text
        // is unchanged, so this proves the API works post-redraw too) and
        // confirm the bounds are stable across the repaint.
        let bounds_after = driver
            .find_bounds("Toggle")
            .expect("bounds after click should still resolve");
        assert_eq!(
            bounds_before, bounds_after,
            "segment geometry should be unchanged by a colour-only redraw"
        );
    }

    /// `setup()` must observe the driver's real surface dimensions, not
    /// a zeroed default — regression guard for initial-layout bugs.
    #[test]
    fn setup_sees_real_viewport_not_default() {
        use std::cell::Cell;
        use std::rc::Rc;

        struct ViewportRecorder {
            seen: Rc<Cell<Option<crate::Viewport>>>,
        }

        impl AppLogic for ViewportRecorder {
            type AreaId = ();

            fn setup(&mut self, backend: &mut dyn Backend) {
                self.seen.set(Some(backend.viewport()));
            }

            fn render(&self, _backend: &mut dyn Backend, _area: ()) {}

            fn handle(&mut self, _event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
                Reaction::Continue
            }
        }

        let seen = Rc::new(Cell::new(None));
        let app = ViewportRecorder { seen: seen.clone() };
        let _driver = GtkDriver::new(app, 200, 60);

        let vp = seen.get().expect("setup() should have run");
        assert_eq!(
            (vp.width, vp.height),
            (200.0, 60.0),
            "setup() must see the driver's real size, not a zeroed default"
        );
    }

    const STACKED_ROW_H: f32 = 20.0;

    /// Two `StatusBar`s stacked vertically at different `rect.y` offsets —
    /// the shape `examples/common/panel_app.rs`'s per-line content
    /// rendering uses, and the one that exposed the `draw_status_bar` bug
    /// this regression test guards.
    struct StackedRowsApp;

    impl AppLogic for StackedRowsApp {
        type AreaId = ();

        fn render(&self, backend: &mut dyn Backend, _area: ()) {
            for (i, label) in ["row zero", "row one"].into_iter().enumerate() {
                backend.draw_status_bar_interactive(
                    Rect::new(0.0, i as f32 * STACKED_ROW_H, 200.0, STACKED_ROW_H),
                    &StatusBar {
                        id: WidgetId::new(format!("row-{i}")),
                        left_segments: vec![StatusBarSegment {
                            text: label.to_string(),
                            fg: Color::rgb(255, 255, 255),
                            bg: Color::rgb(20, 20, 20),
                            bold: false,
                            action_id: None,
                        }],
                        right_segments: vec![],
                    },
                    &crate::InteractionState::new(),
                );
            }
        }

        fn handle(&mut self, _event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
            Reaction::Continue
        }
    }

    /// Regression guard: each row's painted text must record its *own*
    /// absolute `y`, not a shared bar-local `y = 0`, so that
    /// `find`/`find_bounds` reports the correct row's geometry.
    #[test]
    fn find_bounds_reports_each_stacked_rows_own_absolute_y() {
        let driver = GtkDriver::new(StackedRowsApp, 200, 60);

        let row0 = driver
            .find_bounds("row zero")
            .expect("row zero should be painted");
        let row1 = driver
            .find_bounds("row one")
            .expect("row one should be painted");

        assert_eq!(row0.y, 0.0, "row 0 should record at its own rect's y");
        assert_eq!(
            row1.y, STACKED_ROW_H,
            "row 1 should record at its own rect's y, not row 0's"
        );
    }

    /// `app_mut` mirrors `TuiDriver::app_mut`: tests can
    /// poke app state directly rather than only through a scripted
    /// `UiEvent`.
    #[test]
    fn app_mut_allows_direct_state_mutation() {
        let mut driver = GtkDriver::new(ToggleStatusBarApp { on: false }, W, H);
        assert!(!driver.app().on);

        driver.app_mut().on = true;

        assert!(
            driver.app().on,
            "app_mut should mutate the wrapped app in place"
        );
    }

    /// `ConformanceDriver` smoke test for the GTK impl: `new_fixture`
    /// (the `LogicalViewport`-aligned constructor), `click_text_at` with
    /// each `Anchor`, and `screen_has`/`exited` all round-trip through
    /// the promoted trait, not just the inherent methods the other tests
    /// in this module exercise directly.
    #[test]
    fn conformance_driver_new_fixture_and_click_text_at_round_trip() {
        use crate::testing::{Anchor, ConformanceDriver, LogicalViewport};

        let mut driver: GtkDriver<ToggleStatusBarApp> = GtkDriver::new_fixture(
            ToggleStatusBarApp { on: false },
            LogicalViewport::new(30, 5),
        );
        assert!(!ConformanceDriver::exited(&driver));
        assert!(ConformanceDriver::screen_has(&driver, "Toggle"));

        ConformanceDriver::click_text_at(&mut driver, "Toggle", Anchor::Center);

        assert!(
            driver.app().on,
            "click_text_at(Anchor::Center) should activate the toggle segment \
             exactly like the existing find()+click() path does"
        );
    }

    use crate::primitives::tab_bar::{TabBar, TabItem};

    const TAB_BAR_W: i32 = 300;
    const TAB_BAR_H: i32 = 30;

    /// Three closable tabs on a wide bar. `handle()` hit-tests raw
    /// `MouseDown` clicks against the *live*, non-painting
    /// [`crate::Backend::tab_bar_layout`] query (mirrors the "cached
    /// layout hit-test pattern" [`ToggleStatusBarApp`] above uses) — close
    /// regions win over tab bodies, matching `TabBarLayout::hit_regions`'
    /// close-before-body ordering. Exercises `GtkDriver::tab_center`/
    /// `tab_close_center` end-to-end: the driver locates a specific tab's
    /// click target with no hardcoded coordinates, and the resulting
    /// click reaches the app through the ordinary event path.
    struct InteractiveTabBarApp {
        active: usize,
        closed_idx: Option<usize>,
        /// UI font the app installs in `setup`, or `None` to keep the
        /// backend default. Lets a test paint the same bar at a
        /// deliberately narrow / wide font and prove the driver's click
        /// targets still land where the tabs were painted, whatever the
        /// host's default font happens to measure.
        ui_font: Option<&'static str>,
    }

    impl InteractiveTabBarApp {
        const RECT: Rect = Rect::new(0.0, 0.0, TAB_BAR_W as f32, TAB_BAR_H as f32);

        fn new(active: usize) -> Self {
            Self {
                active,
                closed_idx: None,
                ui_font: None,
            }
        }

        fn with_ui_font(font: &'static str) -> Self {
            Self {
                ui_font: Some(font),
                ..Self::new(0)
            }
        }

        fn bar(&self) -> TabBar {
            TabBar {
                id: WidgetId::new("tabs"),
                tabs: (0..3)
                    .map(|i| TabItem {
                        label: format!("tab{i}"),
                        is_active: i == self.active,
                        is_dirty: false,
                        is_preview: false,
                        is_closable: true,
                    })
                    .collect(),
                scroll_offset: 0,
                right_segments: vec![],
                active_accent: None,
                show_tab_close: true,
                compact: false,
            }
        }
    }

    impl AppLogic for InteractiveTabBarApp {
        type AreaId = ();

        fn setup(&mut self, backend: &mut dyn Backend) {
            if let Some(font) = self.ui_font {
                backend.set_ui_font(font);
            }
        }

        #[allow(deprecated)] // `Backend::draw_tab_bar` returns `TabBarHits` — issue #823
        fn render(&self, backend: &mut dyn Backend, _area: ()) {
            backend.draw_tab_bar(Self::RECT, &self.bar(), None);
        }

        #[allow(deprecated)] // `Backend::tab_bar_layout` returns `TabBarHits` — issue #823
        fn handle(&mut self, event: UiEvent, backend: &mut dyn Backend) -> Reaction {
            let UiEvent::MouseDown { position, .. } = event else {
                return Reaction::Continue;
            };
            let hits = backend.tab_bar_layout(Self::RECT, &self.bar());
            let x = position.x as f64;
            // Close regions before tab bodies — mirrors
            // `TabBarLayout::hit_regions`' ordering (close-before-body).
            for (i, close) in hits.close_bounds.iter().enumerate() {
                if let Some((sx, ex)) = close {
                    if x >= *sx && x < *ex {
                        self.closed_idx = Some(i);
                        return Reaction::Redraw;
                    }
                }
            }
            for (i, (sx, ex)) in hits.slot_positions.iter().enumerate() {
                if x >= *sx && x < *ex {
                    self.active = i;
                    return Reaction::Redraw;
                }
            }
            Reaction::Continue
        }
    }

    /// Acceptance criterion: with a 3-tab bar rendered,
    /// `driver.click(tab_center(&bar, 1))` activates tab 1.
    #[test]
    fn tab_center_click_activates_target_tab() {
        let app = InteractiveTabBarApp::new(0);
        let mut driver = GtkDriver::new(app, TAB_BAR_W, TAB_BAR_H);
        let bar_id = WidgetId::new("tabs");

        assert_eq!(driver.app().active, 0);
        let (x, y) = driver
            .tab_center(&bar_id, 1)
            .expect("tab 1 should be visible on a wide bar with 3 short tabs");
        driver.click(x, y);

        assert_eq!(
            driver.app().active,
            1,
            "clicking tab 1's center should activate it"
        );
    }

    /// The no-paint [`Backend::tab_bar_layout`] twin an app hit-tests
    /// clicks against must report the geometry the bar was *painted*
    /// with — not an independent estimate. In headless testing there is
    /// no Pango handle outside the frame scope, so both the paint path
    /// and the layout twin must measure the same fonts identically;
    /// this test pins them as exact equality so the two paths can't
    /// drift apart on any font.
    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` — issue #823
    fn tab_bar_layout_twin_matches_painted_geometry_headless() {
        let app = InteractiveTabBarApp::new(0);
        let mut driver = GtkDriver::new(app, TAB_BAR_W, TAB_BAR_H);
        let bar = driver.app().bar();

        let (rect, painted) = driver
            .core
            .backend()
            .cached_tab_bar_layout(&bar.id)
            .map(|(r, l)| (r, l.clone()))
            .expect("the first frame painted the tab bar");
        let hits = crate::Backend::tab_bar_layout(driver.core.backend_mut(), rect, &bar);

        for vt in &painted.visible_tabs {
            let painted_slot = (
                (rect.x + vt.bounds.x) as f64,
                (rect.x + vt.bounds.x + vt.bounds.width) as f64,
            );
            assert_eq!(
                hits.slot_positions[vt.tab_idx], painted_slot,
                "tab {} body: click-time region must equal the painted one",
                vt.tab_idx
            );
            let painted_close = vt
                .close_bounds
                .map(|cb| ((rect.x + cb.x) as f64, (rect.x + cb.x + cb.width) as f64));
            assert_eq!(
                hits.close_bounds[vt.tab_idx], painted_close,
                "tab {} close button: click-time region must equal the painted one",
                vt.tab_idx
            );
        }
    }

    /// [`Backend::resolve_tab_bar_layout`] must report the exact
    /// geometry the bar was painted with, headless and all.
    /// Both the paint cache and this accessor deal in [`TabBarLayout`]
    /// directly.
    #[test]
    fn resolve_tab_bar_layout_matches_painted_geometry_headless() {
        let app = InteractiveTabBarApp::new(0);
        let mut driver = GtkDriver::new(app, TAB_BAR_W, TAB_BAR_H);
        let bar = driver.app().bar();

        let (rect, painted) = driver
            .core
            .backend()
            .cached_tab_bar_layout(&bar.id)
            .map(|(r, l)| (r, l.clone()))
            .expect("the first frame painted the tab bar");
        let resolved =
            crate::Backend::resolve_tab_bar_layout(driver.core.backend_mut(), rect, &bar);

        assert_eq!(
            resolved, painted,
            "`resolve_tab_bar_layout` must report exactly the `TabBarLayout` \
             the bar was last painted with"
        );
    }

    /// Acceptance criterion: `driver.click(tab_close_center(&bar, 1))`
    /// closes tab 1 and does **not** merely activate it.
    #[test]
    fn tab_close_center_click_closes_target_tab_not_just_activates() {
        let app = InteractiveTabBarApp::new(0);
        let mut driver = GtkDriver::new(app, TAB_BAR_W, TAB_BAR_H);
        let bar_id = WidgetId::new("tabs");

        let (x, y) = driver
            .tab_close_center(&bar_id, 1)
            .expect("tab 1 is closable and should have a close button");
        driver.click(x, y);

        assert_eq!(
            driver.app().closed_idx,
            Some(1),
            "clicking tab 1's close button should close it"
        );
        assert_ne!(
            driver.app().active,
            1,
            "closing tab 1 must not merely activate it — active should stay at its prior value"
        );
    }

    /// The close-button click must hold at *any* UI font, not just
    /// whatever the host's default `Sans` happens to measure. Painting
    /// the same bar at a deliberately narrow and a deliberately wide font
    /// moves every tab boundary, and the driver's click target has to
    /// move with it.
    #[test]
    fn tab_close_center_click_closes_target_tab_at_any_ui_font() {
        for font in ["Sans 6", "Sans 20"] {
            let mut driver = GtkDriver::new(
                InteractiveTabBarApp::with_ui_font(font),
                TAB_BAR_W,
                TAB_BAR_H,
            );
            let bar_id = WidgetId::new("tabs");

            let (x, y) = driver
                .tab_close_center(&bar_id, 1)
                .unwrap_or_else(|| panic!("tab 1 should have a close button at {font:?}"));
            driver.click(x, y);

            assert_eq!(
                driver.app().closed_idx,
                Some(1),
                "at ui_font {font:?}, clicking tab 1's close button should close it"
            );
            assert_ne!(
                driver.app().active,
                1,
                "at ui_font {font:?}, closing tab 1 must not merely activate it"
            );
        }
    }

    /// Acceptance criterion: `tab_close_center` returns `None` for a tab
    /// rendered with `is_closable: false`.
    #[test]
    fn tab_close_center_none_when_tab_not_closable() {
        struct NonClosableTabBarApp;

        impl AppLogic for NonClosableTabBarApp {
            type AreaId = ();

            fn render(&self, backend: &mut dyn Backend, _area: ()) {
                backend.draw_tab_bar(
                    Rect::new(0.0, 0.0, TAB_BAR_W as f32, TAB_BAR_H as f32),
                    &TabBar {
                        id: WidgetId::new("tabs"),
                        tabs: vec![TabItem {
                            label: "a".to_string(),
                            is_active: true,
                            is_dirty: false,
                            is_preview: false,
                            is_closable: false,
                        }],
                        scroll_offset: 0,
                        right_segments: vec![],
                        active_accent: None,
                        show_tab_close: true,
                        compact: false,
                    },
                    None,
                );
            }

            fn handle(&mut self, _event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
                Reaction::Continue
            }
        }

        let driver = GtkDriver::new(NonClosableTabBarApp, TAB_BAR_W, TAB_BAR_H);
        let bar_id = WidgetId::new("tabs");

        assert!(
            driver.tab_center(&bar_id, 0).is_some(),
            "the tab itself is visible"
        );
        assert!(
            driver.tab_close_center(&bar_id, 0).is_none(),
            "a non-closable tab drew no close button, so its center must be None"
        );
    }

    /// Acceptance criterion: `tab_center` returns `None` for a tab hidden
    /// behind the bar's `scroll_offset`.
    #[test]
    fn tab_center_none_when_scrolled_out_of_view() {
        struct ScrolledTabBarApp;

        impl AppLogic for ScrolledTabBarApp {
            type AreaId = ();

            fn render(&self, backend: &mut dyn Backend, _area: ()) {
                backend.draw_tab_bar(
                    // Tab 0's 80-char label alone vastly exceeds this
                    // width, so the full set can never fit — guarantees
                    // the "everything fits" layout branch (which would
                    // ignore `scroll_offset` and reset it to 0) never
                    // triggers, regardless of the host's exact font
                    // metrics. Tabs 1/2 are short, so once `scroll_offset`
                    // skips tab 0 they comfortably fit inside this same
                    // width.
                    Rect::new(0.0, 0.0, TAB_BAR_W as f32, TAB_BAR_H as f32),
                    &TabBar {
                        id: WidgetId::new("tabs"),
                        tabs: vec![
                            TabItem {
                                label: "a".repeat(80),
                                is_active: false,
                                is_dirty: false,
                                is_preview: false,
                                is_closable: true,
                            },
                            TabItem {
                                label: "b".to_string(),
                                is_active: true,
                                is_dirty: false,
                                is_preview: false,
                                is_closable: true,
                            },
                            TabItem {
                                label: "c".to_string(),
                                is_active: false,
                                is_dirty: false,
                                is_preview: false,
                                is_closable: true,
                            },
                        ],
                        // GTK, like TUI, honours this caller-supplied
                        // offset directly when the full set doesn't fit
                        // (no scroll arrows computed internally here).
                        scroll_offset: 1,
                        right_segments: vec![],
                        active_accent: None,
                        show_tab_close: true,
                        compact: false,
                    },
                    None,
                );
            }

            fn handle(&mut self, _event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
                Reaction::Continue
            }
        }

        let driver = GtkDriver::new(ScrolledTabBarApp, TAB_BAR_W, TAB_BAR_H);
        let bar_id = WidgetId::new("tabs");

        assert!(
            driver.tab_center(&bar_id, 0).is_none(),
            "tab 0 is scrolled out of view behind scroll_offset=1"
        );
        assert!(driver.tab_close_center(&bar_id, 0).is_none());
        assert!(
            driver.tab_center(&bar_id, 1).is_some(),
            "tab 1 (the scroll target) should still be visible"
        );
    }
}