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
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
//! Backend-agnostic conformance-test surface.
//!
//! [`ConformanceDriver`] promotes the `ExampleDriver` trait sketched in
//! `docs/TESTING.md` into a real, feature-independent module every backend
//! driver can implement.
//!
//! This module has **no `tui`/`gtk`/`macos`/`win` feature gate** — the
//! trait and its supporting types (`LogicalViewport`, `Anchor`,
//! `TextRun`, `ZoneRec`, `FrameInventory`) compile unconditionally so a
//! shared test body can be written against `ConformanceDriver` without
//! pulling in any backend. The `impl ConformanceDriver for {Tui,Gtk}Driver`
//! blocks live in `quadraui::tui::testing` / `quadraui::gtk::testing`,
//! each behind its own backend feature flag.
//!
//! ## Why a promoted trait, not test-local
//!
//! A module-level trait reaches into driver modules to fix API divergences
//! (constructor units, `screen()` return type, missing `GtkDriver::app_mut`,
//! TUI `find()` assumptions) and include all methods — a test-local trait
//! cannot. It also enables shared drag scenarios.
//!
//! ## Rules for shared bodies
//!
//! 1. **Locate by semantics, never literal coordinates.** Use
//!    `click_text`/`click_text_at`/`drag_text`, not a hardcoded
//!    `click(12.0, 3.0)` — TUI cells and GTK pixels are different units,
//!    so a literal in a shared body would silently be wrong on one side.
//! 2. **Assert on logic/text, not pixels, in shared bodies.** `screen_has`
//!    works identically on every backend.
//!
//! ## `driver_core`
//!
//! [`driver_core::DriverCore`] is the shared `app`/`backend`/`exited`
//! state every concrete backend driver (`TuiDriver`, `GtkDriver`,
//! `MacDriver`, `WinDriver`) wraps. `pub(crate)`, not re-exported here:
//! it's an implementation detail of the four driver structs, not part of
//! this module's own `ConformanceDriver`/`DriverInput` public surface.
//!
//! Gated to the same predicate as those four driver modules' own
//! existence, not left unconditional: `crate::testing` itself has no
//! backend feature gate (see this module's own top doc), but
//! `DriverCore` has no consumer at all unless at least one concrete
//! driver — `TuiDriver` (`feature = "tui"`), `GtkDriver`
//! (`feature = "gtk"`), `MacDriver`
//! (`all(feature = "macos", target_os = "macos")`), or `WinDriver`
//! (`feature = "win"`) — is actually being compiled. Without this,
//! `cargo check -p quadraui --features win` on a non-Windows host would
//! trip `dead_code` under this crate's workflow-wide `-D warnings`.
#[cfg(any(
    feature = "tui",
    feature = "gtk",
    all(feature = "macos", target_os = "macos"),
    feature = "win"
))]
pub(crate) mod driver_core;

/// Headless accessibility-tree scenarios — see [`a11y::A11yScenario`].
///
/// Ungated, like this module itself: the tree builder it drives is a pure
/// function of an owned [`crate::OwnedFrame`], so a scenario needs no
/// backend and no `a11y` feature to produce an assertable snapshot.
pub mod a11y;

// Only pulled in by the paint-time text-run recording sink below, which
// is itself gated to the pixel backends that need it (`gtk`/`win`/`macos`
// — see that section's doc) — TUI has no analogous need (its `find` scans
// a character grid instead), so this import must be gated in lock-step or
// a `--features tui` build (no pixel backend) flags it unused under
// `-D warnings`.
//
// The macOS arm must carry `target_os = "macos"` here too, exactly as the
// sink's own cfg below does: `--features macos` on a Linux host turns the
// feature on but compiles none of `macos::text`, so a bare
// `feature = "macos"` arm imports `RefCell` for a `thread_local!` that
// isn't there and warns `unused_imports`.
#[cfg(any(
    feature = "gtk",
    feature = "win",
    all(feature = "macos", target_os = "macos")
))]
use std::cell::RefCell;

use crate::runner::{AppLogic, Reaction};
use crate::{Key, Modifiers, NamedKey, Point, Rect, ScrollDelta, UiEvent, WidgetId};

/// Backend-neutral viewport size for [`ConformanceDriver::new_fixture`].
///
/// Interpreted per backend: TUI treats `cols`/`rows` as terminal cells
/// directly; pixel backends (GTK, Win-GUI, macOS) scale by a nominal
/// `char_width`/`line_height` to get a device-unit surface size. Either
/// way, a shared test body never writes a pixel or cell number itself —
/// it only ever picks a `LogicalViewport`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LogicalViewport {
    pub cols: u32,
    pub rows: u32,
}

impl LogicalViewport {
    pub const fn new(cols: u32, rows: u32) -> Self {
        Self { cols, rows }
    }
}

/// Where within a located text run's bounds a click should land.
///
/// `click_text`/[`ConformanceDriver::click_text`] is `click_text_at(needle,
/// Anchor::Center)`; `LeftEdge`/`RightEdge` exist for widgets whose hit
/// regions are sensitive to which end of a label was clicked (e.g. a
/// divider immediately to the right of a column header).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Anchor {
    Center,
    LeftEdge,
    RightEdge,
}

/// One run of text painted during a frame, and where — the portable
/// equivalent of `TuiDriver::find`'s cell scan or `GtkDriver`'s
/// `(text, bounds)` map, per `docs/SMELL_AUDIT_2026-07.md` §6.2.
#[derive(Debug, Clone, PartialEq)]
pub struct TextRun {
    pub text: String,
    pub bounds: Rect,
}

// GTK (`gtk::painted_text::show_layout`) and macOS (`macos::text::draw_text`)
// each need to record a `(text, bounds)` run at the exact point their backend
// paints text, so `find`/`find_bounds`/`inventory`/`screen_has` can locate
// any text-bearing primitive without a per-primitive opt-in. Neither call
// site has a `&mut Backend` in scope to push the run onto — GTK's rasterisers
// are free functions handed only a `&cairo::Context`, macOS's `draw_text` is
// handed only a borrowed `CGContextRef`, Win-GUI's `DWrite::draw_text` is
// a `&ID2D1RenderTarget` — so both back onto a thread-local sink instead.
//
// This is a thread-local shared implementation every backend's paint-time
// recorder now wraps, per `docs/PRIMITIVE_RULES.md`'s primitive-first rule.
//
// Thread-local rather than a static: each headless driver lives on its own
// test thread, so one sink per thread pairs exactly with `cargo test`'s
// one-thread-per-test model and needs no locking.
//
// Two distinct cfg predicates gate this section, not one, because the
// three backends reach it through call sites with different OS gating:
//
// - `WinBackend::begin_frame`/`end_frame` call `install_text_run_sink`/
//   `take_text_run_sink` unconditionally under `feature = "win"` — those two
//   methods are never `cfg(target_os)`-gated themselves (only the real
//   Direct2D calls inside are), so `--features win` alone reaches them on
//   any host, including Linux.
// - `gtk::painted_text::show_layout` / `macos::text::draw_text` /
//   `win::text::draw_text` call `text_run_sink_active`/`record_text_run`,
//   but `win::text` is itself `cfg(target_os = "windows")`-gated (see its
//   module doc), so under `--features win` on a non-Windows host those two
//   calls don't exist anywhere in the crate.
//
// A single shared predicate would leave `text_run_sink_active`/
// `record_text_run` `dead_code` on that ubuntu leg specifically, even
// though `install_text_run_sink`/`take_text_run_sink` are genuinely used
// there. TUI needs neither group at all — its `find` scans a character
// grid instead of a sink.
#[cfg(any(
    feature = "gtk",
    feature = "win",
    all(feature = "macos", target_os = "macos")
))]
thread_local! {
    static TEXT_RUN_SINK: RefCell<Option<Vec<TextRun>>> = const { RefCell::new(None) };
}

/// Install a fresh recording sink, returning the previous one so a
/// (theoretically) nested paint scope can restore it. Pair with
/// [`take_text_run_sink`]. `pub(crate)`: each backend's own paint-time
/// recording module (`gtk::painted_text`, `macos::text`, `win::text`)
/// wraps this rather than exposing the raw sink outside the crate.
#[cfg(any(
    feature = "gtk",
    feature = "win",
    all(feature = "macos", target_os = "macos")
))]
pub(crate) fn install_text_run_sink() -> Option<Vec<TextRun>> {
    TEXT_RUN_SINK.with(|s| s.borrow_mut().replace(Vec::new()))
}

/// Take everything recorded since [`install_text_run_sink`] and restore
/// `previous` as the active sink (`None` = recording off again).
#[cfg(any(
    feature = "gtk",
    feature = "win",
    all(feature = "macos", target_os = "macos")
))]
pub(crate) fn take_text_run_sink(previous: Option<Vec<TextRun>>) -> Vec<TextRun> {
    TEXT_RUN_SINK.with(|s| {
        let mut slot = s.borrow_mut();
        let recorded = slot.take().unwrap_or_default();
        *slot = previous;
        recorded
    })
}

/// Whether a sink is currently installed. Backends that would otherwise
/// do real measurement work before recording a run (GTK: converting
/// Cairo's current point + Pango pixel size to device coordinates; macOS:
/// `measure_text`) check this first so that work is skipped entirely
/// when recording is off — Win-GUI does too (its bounds are already in
/// hand, but the check keeps this function's reachability, and therefore
/// its `cfg`, identical to [`record_text_run`]'s — see this section's
/// top-level comment for why that has to match exactly).
#[cfg(any(
    feature = "gtk",
    all(feature = "macos", target_os = "macos"),
    all(feature = "win", target_os = "windows")
))]
pub(crate) fn text_run_sink_active() -> bool {
    TEXT_RUN_SINK.with(|s| s.borrow().is_some())
}

/// Append one run to the active sink. No-op when recording is off.
///
/// Skips whitespace-only `text` (alignment pads, blank rows, selection
/// prefixes): those can never be a useful `find` needle and would bury
/// the real labels in `painted_texts()` output.
#[cfg(any(
    feature = "gtk",
    all(feature = "macos", target_os = "macos"),
    all(feature = "win", target_os = "windows")
))]
pub(crate) fn record_text_run(text: &str, bounds: Rect) {
    if text.trim().is_empty() {
        return;
    }
    TEXT_RUN_SINK.with(|s| {
        if let Some(sink) = s.borrow_mut().as_mut() {
            sink.push(TextRun {
                text: text.to_string(),
                bounds,
            });
        }
    });
}

/// One registered widget zone (a hit-testable region) painted during a
/// frame.
#[derive(Debug, Clone, PartialEq)]
pub struct ZoneRec {
    pub id: WidgetId,
    pub bounds: Rect,
}

/// Semantic paint inventory for one rendered frame — the cross-backend
/// observable contract describing what was painted.
///
/// `text_runs` is populated from each backend's existing text search
/// (TUI's cell-grid scan, GTK's `painted_text` map) — this covers every
/// text-bearing primitive with no per-widget opt-in required.
///
/// `zones` is populated from [`crate::Backend::register_zone`] calls made
/// during the frame, and **coverage is opt-in per paint site**. Exactly
/// one composer registers zones today —
/// [`crate::compose::app_shell::AppShell::render`], via its
/// `register_chrome_zones` helper — and it contributes:
///
/// - one `app-shell:`-prefixed zone per chrome region it lays out:
///   `window`, `activity-bar`, `main-content`, and (when that region
///   exists this frame) `title-bar`, `sidebar-header`, `sidebar-content`,
///   `divider`, `bottom-panel`, `command-line`, `status-bar`;
/// - one zone per activity-bar item, keyed by that panel's own
///   `WidgetId` (e.g. `panel:explorer`) rather than an `app-shell:` name.
///
/// Every other primitive contributes **no** zone until it is wired to
/// call `register_zone` — no zone, rather than a wrong one. Because
/// [`Self::inside`] answers `false` for an unregistered zone exactly as
/// it does for a run that landed outside a registered one, a caller
/// asserting against a zone id no paint site produces gets an
/// unsatisfiable assertion, not a flaky one.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct FrameInventory {
    pub text_runs: Vec<TextRun>,
    pub zones: Vec<ZoneRec>,
}

impl FrameInventory {
    pub fn text_runs(&self) -> &[TextRun] {
        &self.text_runs
    }

    pub fn zones(&self) -> &[ZoneRec] {
        &self.zones
    }

    // ── Relational assertion vocabulary ─────────────────────────────────
    //
    // These are the "no hardcoded coordinates" assertions the issue calls
    // for: every one of them is computed from `Rect`s this same
    // `FrameInventory` already reports, in whichever unit the backend
    // that produced it uses (cells for TUI, pixels for GTK) — a shared
    // test body never writes a literal coordinate itself, it only ever
    // names two painted things and asks how they relate.

    /// True if any painted text run contains `needle`.
    pub fn screen_has(&self, needle: &str) -> bool {
        self.text_runs.iter().any(|r| r.text.contains(needle))
    }

    /// True if no painted text run contains `needle` — the negative
    /// counterpart to [`Self::screen_has`], for asserting something was
    /// *not* painted this frame (e.g. a closed panel's content).
    pub fn absent(&self, needle: &str) -> bool {
        !self.screen_has(needle)
    }

    /// Number of painted text runs containing `needle`. Useful for
    /// asserting a repeated element's cardinality (e.g. "3 rows contain
    /// this label") without caring where each instance landed.
    pub fn count(&self, needle: &str) -> usize {
        self.text_runs
            .iter()
            .filter(|r| r.text.contains(needle))
            .count()
    }

    /// Bounds of the first text run containing `needle`, in this frame's
    /// paint order. `None` if nothing painted matched.
    fn locate(&self, needle: &str) -> Option<Rect> {
        self.text_runs
            .iter()
            .find(|r| r.text.contains(needle))
            .map(|r| r.bounds)
    }

    /// Bounds of the zone registered under `id` via
    /// [`crate::Backend::register_zone`], if any.
    fn zone_bounds(&self, id: &WidgetId) -> Option<Rect> {
        self.zones.iter().find(|z| &z.id == id).map(|z| z.bounds)
    }

    /// True if `a`'s painted bounds lie entirely to the left of `b`'s —
    /// `a`'s right edge at or before `b`'s left edge. Panics-free: if
    /// either needle wasn't painted this frame, returns `false` (the
    /// same "didn't happen" answer a missing needle gets everywhere else
    /// in this vocabulary — callers that need to know *why* should pair
    /// this with [`Self::screen_has`]).
    pub fn left_of(&self, a: &str, b: &str) -> bool {
        match (self.locate(a), self.locate(b)) {
            (Some(ra), Some(rb)) => ra.x + ra.width <= rb.x,
            _ => false,
        }
    }

    /// True if `a`'s painted bounds lie entirely above `b`'s — `a`'s
    /// bottom edge at or before `b`'s top edge.
    pub fn above(&self, a: &str, b: &str) -> bool {
        match (self.locate(a), self.locate(b)) {
            (Some(ra), Some(rb)) => ra.y + ra.height <= rb.y,
            _ => false,
        }
    }

    /// True if `a` and `b`'s painted bounds vertically overlap — the
    /// same logical text row, even across backends whose native units
    /// (TUI cell rows vs GTK sub-pixel baselines) never line up on exact
    /// equality.
    pub fn same_row(&self, a: &str, b: &str) -> bool {
        match (self.locate(a), self.locate(b)) {
            (Some(ra), Some(rb)) => ra.y < rb.y + rb.height && rb.y < ra.y + ra.height,
            _ => false,
        }
    }

    /// True if `needle`'s painted bounds lie entirely within the zone
    /// registered under `zone_id`. `false` if either the needle wasn't
    /// painted or the zone wasn't registered this frame.
    pub fn inside(&self, needle: &str, zone_id: &WidgetId) -> bool {
        match (self.locate(needle), self.zone_bounds(zone_id)) {
            (Some(r), Some(z)) => {
                r.x >= z.x
                    && r.y >= z.y
                    && r.x + r.width <= z.x + z.width
                    && r.y + r.height <= z.y + z.height
            }
            _ => false,
        }
    }
}

/// Shared "act" surface for headless [`AppLogic`] test drivers.
///
/// `press`/`type_char`/`press_named`/`ctrl_char`/`click`/`drag` reduce to
/// the exact same body on every backend driver once [`Self::dispatch`]
/// and the three raw mouse primitives exist — only the *how* of
/// `dispatch`/`mouse_down`/`mouse_move`/`mouse_up` differs per backend
/// (compare `GtkDriver::mouse_down`, which routes through
/// `crate::dispatch::dispatch_click` and drag-state tracking, against
/// `TuiDriver::mouse_down`, a bare `UiEvent::MouseDown` dispatch).
/// Before this trait existed, every method built *on top of* those four
/// primitives was transcribed into each of `GtkDriver`'s, `MacDriver`'s,
/// and `TuiDriver`'s own inherent impl blocks.
///
/// Each driver keeps its own same-named **inherent** method (so no
/// caller needs to import this trait to call `driver.press(..)` — see
/// e.g. `GtkDriver::press`), whose body now just forwards to
/// `DriverInput::method(self, …)`.
pub trait DriverInput: Sized {
    /// Feed one synthetic event through this driver's production
    /// dispatch path. See the concrete driver's own `dispatch` doc for
    /// what "production" means there — it's the one genuinely
    /// per-backend piece (extra macOS caret-blink handles, TUI's
    /// `translate_injected` preprocessing, …), which is exactly why it's
    /// `dispatch` itself that's the required method here and not shared.
    fn dispatch(&mut self, event: UiEvent) -> Reaction;

    /// Press the left mouse button down at `(x, y)`.
    fn mouse_down(&mut self, x: f32, y: f32) -> Reaction;
    /// Move the cursor to `(x, y)` with the left button held.
    fn mouse_move(&mut self, x: f32, y: f32) -> Reaction;
    /// Release the left mouse button at `(x, y)`.
    fn mouse_up(&mut self, x: f32, y: f32) -> Reaction;

    /// Press a key (no modifiers).
    fn press(&mut self, key: Key) -> Reaction {
        self.dispatch(UiEvent::KeyPressed {
            key,
            modifiers: Modifiers::default(),
            repeat: false,
        })
    }

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

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

    /// Press a character key with Ctrl held (e.g. `ctrl_char('c')` to
    /// trigger the runner's copy-on-selection path).
    fn ctrl_char(&mut self, c: char) -> Reaction {
        self.dispatch(UiEvent::KeyPressed {
            key: Key::Char(c),
            modifiers: Modifiers {
                ctrl: true,
                ..Modifiers::default()
            },
            repeat: false,
        })
    }

    /// Left-click at `(x, y)`. The default is a bare press-down with no
    /// release — the behaviour `GtkDriver`, `MacDriver`, and `TuiDriver`
    /// all already shared before this trait existed. Override this (as
    /// `WinDriver` does) if a backend's real `click` needs a release too.
    fn click(&mut self, x: f32, y: f32) -> Reaction {
        self.mouse_down(x, y)
    }

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

/// Shared [`ConformanceDriver::click_text_at`] /
/// [`ConformanceDriver::drag_text`] / [`ConformanceDriver::scroll_at`]
/// bodies for pixel-unit backends.
///
/// GTK, macOS, and Win-GUI all locate a painted run's bounds and click
/// `bounds.x + 1.0` / `bounds.x + bounds.width - 1.0` for
/// `LeftEdge`/`RightEdge`; only TUI (cell-unit, `+0.5`/`-0.5`, and a
/// `self.screen()` dump folded into its panic messages) diverges enough
/// to keep its own bespoke `ConformanceDriver` impl rather than adopt
/// this trait. The 2026-09-03 duplication audit measured this block at 8
/// duplicated lines between `GtkDriver` and `MacDriver` alone.
pub trait PixelClickConformance: DriverInput {
    /// This driver's type name, for panic messages (`"GtkDriver"`, …).
    const NAME: &'static str;

    /// Pixel bounds of the first painted run containing `needle`.
    fn find_bounds(&self, needle: &str) -> Option<Rect>;
    /// Center pixel coordinates of the first painted run containing
    /// `needle`.
    fn find(&self, needle: &str) -> Option<(f32, f32)>;
    /// This backend's current line height, for [`Self::scroll_at`]'s
    /// `ScrollDelta`.
    fn conformance_line_height(&self) -> f32;

    fn click_text_at(&mut self, needle: &str, at: Anchor) {
        let bounds = self
            .find_bounds(needle)
            .unwrap_or_else(|| panic!("{}: {needle:?} not painted", Self::NAME));
        let y = bounds.y + bounds.height / 2.0;
        let x = match at {
            Anchor::Center => bounds.x + bounds.width / 2.0,
            Anchor::LeftEdge => bounds.x + 1.0,
            Anchor::RightEdge => bounds.x + bounds.width - 1.0,
        };
        self.click(x, y);
    }

    fn drag_text(&mut self, from: &str, to: &str) {
        let (x0, y0) = self
            .find(from)
            .unwrap_or_else(|| panic!("{}: {from:?} not painted", Self::NAME));
        let (x1, y1) = self
            .find(to)
            .unwrap_or_else(|| panic!("{}: {to:?} not painted", Self::NAME));
        self.drag(x0, y0, x1, y1);
    }

    fn scroll_at(&mut self, needle: &str, lines: i32) {
        let (x, y) = self
            .find(needle)
            .unwrap_or_else(|| panic!("{}: {needle:?} not painted", Self::NAME));
        let line_height = self.conformance_line_height();
        self.dispatch(UiEvent::Scroll {
            widget: None,
            delta: ScrollDelta::new(0.0, lines as f32 * line_height),
            position: Point::new(x, y),
        });
    }
}

/// Backend-agnostic driver surface a shared conformance-test body needs.
///
/// Implemented once per backend, behind that backend's feature flag
/// (`quadraui::tui::testing::TuiDriver`, `quadraui::gtk::testing::GtkDriver`).
/// A test body written generically over `D: ConformanceDriver` runs
/// unmodified against every backend that implements it.
pub trait ConformanceDriver: Sized {
    /// The [`AppLogic`] this driver instance wraps.
    type App: AppLogic;

    /// Build a driver for `app` on a `viewport`-sized surface, running the
    /// app's `setup` hook and painting the first frame — the
    /// [`LogicalViewport`]-aligned constructor `docs/SMELL_AUDIT_2026-07.md`
    /// §6.3 calls for, sitting alongside (not replacing) each backend's
    /// existing native-unit `new`.
    fn new_fixture(app: Self::App, viewport: LogicalViewport) -> Self;

    /// Press a named (non-printable) key, e.g. [`NamedKey::Enter`].
    fn press_named(&mut self, key: NamedKey);

    /// Type a single character key (no modifiers).
    fn type_char(&mut self, c: char);

    /// Press a character key with Ctrl held — the runner-level path that
    /// turns `Ctrl-C` over an active selection into
    /// [`crate::UiEvent::TextCopied`] rather than a raw key press. Needed
    /// by any scenario that exercises copy (audit §6.5 example 3), which
    /// is why it sits on the trait rather than only on each concrete
    /// driver.
    fn ctrl_char(&mut self, c: char);

    /// Type each character of `s` in turn (no modifiers).
    fn type_text(&mut self, s: &str) {
        for c in s.chars() {
            self.type_char(c);
        }
    }

    /// Locate `needle`'s painted bounds and click its center. Equivalent
    /// to `click_text_at(needle, Anchor::Center)`.
    fn click_text(&mut self, needle: &str) {
        self.click_text_at(needle, Anchor::Center);
    }

    /// Locate `needle`'s painted bounds and click the point `at` picks out
    /// within them.
    fn click_text_at(&mut self, needle: &str, at: Anchor);

    /// Locate `from` and `to`'s painted bounds and drag from the center of
    /// one to the center of the other (down → move → up) — the method
    /// `docs/TESTING.md`'s canonical `ExampleDriver` sketch included and
    /// the test-local copy in `tests/cross_backend_parity.rs` dropped.
    fn drag_text(&mut self, from: &str, to: &str);

    /// Locate `needle`'s painted bounds and dispatch a scroll-wheel event
    /// there, `lines` deep (in this backend's `line_height` multiples;
    /// positive = scroll up, matching [`crate::ScrollDelta`]'s convention).
    fn scroll_at(&mut self, needle: &str, lines: i32);

    /// The [`crate::BackendCaps`] the backend under this driver declares
    /// — i.e. `Backend::backend_caps` on the *real* backend instance the
    /// driver wraps.
    ///
    /// Capability names are now literally from what the backend declares,
    /// so a scenario's `requires` gate can only ever match against what the
    /// backend really said. Required (no default) on purpose: there is no
    /// honest answer to guess.
    fn backend_caps(&self) -> crate::BackendCaps;

    /// Semantic paint inventory for the last rendered frame.
    fn inventory(&self) -> FrameInventory;

    /// True if any painted text contains `needle`.
    fn screen_has(&self, needle: &str) -> bool;

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

// ── RecordingBackend ────────────────────────────────────────────────────
//
// Before this, an external developer who wanted to unit-test their own
// `compose`-style controller (something that takes `&mut dyn Backend`,
// the way `TreeController`/`ChatController`/`AppShell` do) had nothing to
// test against: the only full `impl Backend` mocks in this crate were
// three near-identical private `MockBackend` copies, one each in
// `compose::{tree_controller, chat_controller, app_shell}`'s own
// `#[cfg(test)] mod tests`, invisible outside the crate. `RecordingBackend`
// is that mock, promoted to a public, crate-external-friendly type, and
// those three private copies delegate to (rather than duplicate) it.
//
// Behaviour merges the most functional method body wherever the three
// originals disagreed (documented per-method below); every other method
// was byte-for-byte identical across all three, so there was only one
// reasonable choice.

// Crate-internal test switch for `Backend::tree_paints_own_scrollbar`, kept
// off `RecordingBackend`'s public fields: that struct is exhaustively
// constructible, so any new field is a semver break (cargo-semver-checks).
#[cfg(test)]
thread_local! {
    static TREE_PAINTS_OWN_SCROLLBAR: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Makes every `RecordingBackend` on this thread report
/// `tree_paints_own_scrollbar() == value` until the guard drops.
#[cfg(test)]
pub(crate) struct TreePaintsOwnScrollbar(bool);

#[cfg(test)]
impl TreePaintsOwnScrollbar {
    pub(crate) fn set(value: bool) -> Self {
        Self(TREE_PAINTS_OWN_SCROLLBAR.with(|c| c.replace(value)))
    }
}

#[cfg(test)]
impl Drop for TreePaintsOwnScrollbar {
    fn drop(&mut self) {
        TREE_PAINTS_OWN_SCROLLBAR.with(|c| c.set(self.0));
    }
}

/// A batteries-included, fully-implemented [`Backend`] for unit tests
/// that need *some* backend to hand a controller — not a specific
/// backend's real rendering. Reports an 80×24, TUI-cell-shaped viewport
/// (`line_height`/`char_width` both `1.0`) by default; construct with
/// [`Self::with_viewport`] for a pixel-backend-shaped fixture instead.
///
/// Every `draw_*` call appends its method name to [`Self::calls`] — the
/// "recording" in the name — so a test can assert *what* got painted
/// (`backend.calls.contains(&"draw_status_bar")`) without a real
/// rasteriser. Layout getters (`tree_layout`, `status_bar_layout`, …)
/// are not recorded: they're queries, not paint events, and controllers
/// call them freely (sometimes more than once a frame) as part of
/// ordinary hit-testing.
///
/// Most `draw_*`/`*_layout` pairs return an inert-but-real default
/// (`StatusBarLayout` with zeroed geometry, `TabBarHits::default()`, …)
/// rather than panicking, so a controller under test can call them
/// without the test needing to know it did. A handful of primitives this
/// crate's own controllers never exercise through a bare `Backend` still
/// `unimplemented!()` — most notably `modal_stack_handle`,
/// `drag_state_handle`, and `services()`, which real backends back with
/// actual shared state / platform services that a headless mock cannot
/// honestly fabricate. If your test needs one of those, `RecordingBackend`
/// is the wrong tool — drive a real backend (`quadraui::tui::testing::
/// TuiDriver`) instead.
#[derive(Debug, Clone, PartialEq)]
pub struct RecordingBackend {
    /// Method name of every `draw_*` call made against this backend, in
    /// call order. Cleared by nothing — construct a fresh
    /// `RecordingBackend` per test (or per frame) if you need a clean
    /// slate.
    pub calls: Vec<&'static str>,
    /// Viewport reported by [`Backend::viewport`]. `80x24x1.0` by
    /// default — see [`Self::with_viewport`].
    pub viewport: crate::Viewport,
    /// Reported by [`Backend::line_height`]. `1.0` by default.
    pub line_height: f32,
    /// Reported by [`Backend::char_width`]. `1.0` by default.
    pub char_width: f32,
    /// Reported by [`Backend::chrome_line_height`]. `None` means fall
    /// through to [`Self::line_height`] (matching the trait default).
    /// Set to `Some(h)` to simulate a backend whose chrome font has a
    /// different line height than the editor font.
    pub chrome_line_height: Option<f32>,
    /// Backs [`Backend::focus_manager`] — unlike `modal_stack_handle`/
    /// `drag_state_handle`, this one *is* real state a headless mock can
    /// honestly fabricate, so it's included rather than
    /// `unimplemented!()`.
    pub focus: crate::focus::FocusManager,
    /// Backs [`Backend::invalidate_rect`]/[`Backend::invalidation_log`] —
    /// pure bookkeeping, same shape every real backend's `BackendCore`
    /// delegates to.
    pub invalidation_log: crate::backend::InvalidationLog,
}

impl Default for RecordingBackend {
    fn default() -> Self {
        Self {
            calls: Vec::new(),
            viewport: crate::Viewport {
                width: 80.0,
                height: 24.0,
                scale: 1.0,
            },
            line_height: 1.0,
            char_width: 1.0,
            chrome_line_height: None,
            focus: crate::focus::FocusManager::new(),
            invalidation_log: crate::backend::InvalidationLog::new(),
        }
    }
}

impl RecordingBackend {
    /// A fresh recorder with the default 80×24 TUI-cell-shaped viewport.
    pub fn new() -> Self {
        Self::default()
    }

    /// A fresh recorder reporting `viewport`/`line_height`/`char_width`
    /// instead of the TUI-cell-shaped default — e.g. to fake a pixel
    /// backend's geometry.
    pub fn with_viewport(viewport: crate::Viewport, line_height: f32, char_width: f32) -> Self {
        Self {
            viewport,
            line_height,
            char_width,
            ..Self::default()
        }
    }

    fn record(&mut self, name: &'static str) {
        self.calls.push(name);
    }
}

/// An empty [`crate::TabBarLayout`] — no tabs, no segments, no hit
/// regions. `TabBarLayout` has no `Default` impl of its own (unlike
/// `TabBarHits`), so the inert-but-real stub every other `*_layout`
/// getter on this mock returns needs a literal instead.
fn empty_tab_bar_layout() -> crate::TabBarLayout {
    crate::TabBarLayout {
        bar_width: 0.0,
        bar_height: 0.0,
        visible_tabs: Vec::new(),
        visible_segments: Vec::new(),
        scroll_left: None,
        scroll_right: None,
        hit_regions: Vec::new(),
        resolved_scroll_offset: 0,
    }
}

impl crate::backend::sealed::Sealed for RecordingBackend {}

impl crate::Backend for RecordingBackend {
    fn viewport(&self) -> crate::Viewport {
        self.viewport
    }
    fn begin_frame(&mut self, _v: crate::Viewport) {}
    fn end_frame(&mut self) {}
    fn poll_events(&mut self) -> Vec<UiEvent> {
        Vec::new()
    }
    fn wait_events(&mut self, _t: std::time::Duration) -> Vec<UiEvent> {
        Vec::new()
    }
    fn waker(&self) -> std::sync::Arc<dyn Fn(crate::UserPayload) + Send + Sync> {
        // `RecordingBackend` never runs an event loop for a `waker` call to
        // wake — it's a synchronous call recorder for unit tests, not a
        // live runner. No-op, matching `poll_events`/`wait_events` above.
        std::sync::Arc::new(|_payload| {})
    }
    fn request_frame_in(&self, _delay: std::time::Duration) {
        // No event loop to wake, same rationale as `waker` above — a
        // scheduled-frame request has nothing to arm against.
    }
    fn register_accelerator(&mut self, _a: &crate::Accelerator) {}
    fn unregister_accelerator(&mut self, _id: &crate::AcceleratorId) {}
    fn invalidate_rect(&mut self, rect: crate::event::Rect) {
        self.invalidation_log.push(rect);
    }
    fn invalidation_log(&self) -> &crate::backend::InvalidationLog {
        &self.invalidation_log
    }
    fn modal_stack_handle(&self) -> std::rc::Rc<std::cell::RefCell<crate::ModalStack>> {
        unimplemented!(
            "RecordingBackend has no shared ModalStack — drive a real backend \
             (quadraui::tui::testing::TuiDriver) if your test needs one"
        )
    }
    fn focus_manager(&self) -> &crate::focus::FocusManager {
        &self.focus
    }
    fn draw_focus_ring(&mut self, _r: Rect) {
        self.record("draw_focus_ring");
    }
    fn drag_state_handle(&self) -> std::rc::Rc<std::cell::RefCell<crate::DragState>> {
        unimplemented!(
            "RecordingBackend has no shared DragState — drive a real backend \
             (quadraui::tui::testing::TuiDriver) if your test needs one"
        )
    }
    fn services(&self) -> &dyn crate::backend::PlatformServices {
        unimplemented!(
            "RecordingBackend has no PlatformServices — drive a real backend \
             (quadraui::tui::testing::TuiDriver) if your test needs one"
        )
    }
    fn backend_caps(&self) -> crate::backend::BackendCaps {
        crate::backend::BackendCaps::empty()
    }
    fn line_height(&self) -> f32 {
        self.line_height
    }
    fn chrome_line_height(&self) -> f32 {
        self.chrome_line_height.unwrap_or(self.line_height)
    }
    fn char_width(&self) -> f32 {
        self.char_width
    }
    fn list_char_width(&self) -> f32 {
        // `RecordingBackend` only records call shape, not real font
        // metrics (see `char_width`/`line_height` above) — no separate
        // chrome-font notion to model, so this just aliases `char_width`
        // like TUI's real backend does.
        self.char_width
    }
    fn measure_text(&self, text: &str, _role: crate::FontRole) -> (f32, f32) {
        // Same rationale as `list_char_width` above: no real font to
        // measure against, just the same char-cell arithmetic every
        // caller used before `Backend::measure_text` existed.
        (
            text.chars().count() as f32 * self.char_width,
            self.line_height,
        )
    }
    fn default_fonts(&self) -> crate::backend::PlatformFontDefaults {
        // `RecordingBackend` only records call shape, not real font
        // metrics — same rationale as `list_char_width` above. No
        // platform to default fonts against, so this is the same
        // all-sentinel value TUI's real backend returns.
        crate::backend::PlatformFontDefaults {
            editor_family: String::new(),
            editor_size_pt: 0.0,
            ui_family: String::new(),
            ui_size_pt: 0.0,
        }
    }
    fn draw_tree(&mut self, _r: Rect, _t: &crate::TreeView) {
        self.record("draw_tree");
    }
    fn draw_list(&mut self, _r: Rect, _l: &crate::ListView) {
        self.record("draw_list");
    }
    fn draw_data_table(
        &mut self,
        _r: Rect,
        _t: &crate::DataTable,
        _h: Option<usize>,
    ) -> crate::DataTableLayout {
        self.record("draw_data_table");
        unimplemented!("RecordingBackend has no DataTable layout algorithm")
    }
    fn data_table_layout(&self, _r: Rect, _t: &crate::DataTable) -> crate::DataTableLayout {
        unimplemented!("RecordingBackend has no DataTable layout algorithm")
    }
    fn list_hscrollbar(&self, _r: Rect, _l: &crate::ListView) -> Option<crate::Scrollbar> {
        None
    }
    fn list_vscrollbar(&self, _r: Rect, _l: &crate::ListView) -> Option<crate::Scrollbar> {
        None
    }
    fn list_layout(&self, r: Rect, l: &crate::ListView) -> crate::ListViewLayout {
        l.layout(r.width, r.height, 0.0, |_| {
            crate::primitives::list::ListItemMeasure::new(1.0)
        })
    }
    fn draw_form(&mut self, _r: Rect, _f: &crate::Form) {
        self.record("draw_form");
    }
    fn draw_palette(&mut self, _r: Rect, _p: &crate::Palette) {
        self.record("draw_palette");
    }
    fn palette_layout(&self, r: Rect, p: &crate::Palette) -> crate::PaletteLayout {
        let lh = self.line_height;
        let title_h = lh;
        let query_h = if p.show_query { lh } else { 0.0 };
        p.layout(r.width, r.height, title_h, query_h, 0.0, 1.0, |_| {
            crate::PaletteItemMeasure::new(lh)
        })
    }
    fn draw_settings_chrome(
        &mut self,
        _r: Rect,
        _header_text: &str,
        _query: &str,
        _placeholder: &str,
        _active: bool,
    ) {
        self.record("draw_settings_chrome");
    }
    /// Computes a real [`crate::StatusBarLayout`] via [`crate::StatusBar::layout`]
    /// with a char-cell measurer (`self.char_width` per character,
    /// mirroring `TuiBackend`'s own measurer) rather than a hardcoded
    /// empty layout — `SidebarPanelBody`'s `StatusBars` chrome surfaces real
    /// hit regions from it, and a recorder that always returns empty can
    /// never exercise that translation.
    fn draw_status_bar_interactive(
        &mut self,
        r: Rect,
        b: &crate::primitives::status_bar::StatusBar,
        _interaction: &crate::interaction::InteractionState,
    ) -> crate::StatusBarLayout {
        self.record("draw_status_bar");
        let cw = self.char_width.max(0.0);
        b.layout(r.width, r.height, 2.0 * cw, |seg| {
            crate::StatusSegmentMeasure::new(seg.text.chars().count() as f32 * cw)
        })
    }
    /// Union note: see `draw_status_bar` above — `app_shell::MockBackend`'s
    /// real body wins for the same reason.
    ///
    /// `TabBarHits` is `#[deprecated]`; this mock still
    /// implements the trait method as declared.
    #[allow(deprecated)]
    fn draw_tab_bar(
        &mut self,
        _r: Rect,
        _b: &crate::TabBar,
        _h: Option<usize>,
    ) -> crate::TabBarHits {
        self.record("draw_tab_bar");
        crate::TabBarHits::default()
    }
    #[allow(deprecated)] // `TabBarHits` is `#[deprecated]`
    fn draw_tab_bar_icons(
        &mut self,
        _r: Rect,
        _b: &crate::TabBar,
        _icons: &[Option<crate::TabIcon>],
        _h: Option<usize>,
    ) -> crate::TabBarHits {
        self.record("draw_tab_bar_icons");
        crate::TabBarHits::default()
    }
    /// `TabBarLayout`-returning counterpart to `draw_tab_bar` above.
    fn draw_tab_bar_layout(
        &mut self,
        _r: Rect,
        _b: &crate::TabBar,
        _h: Option<usize>,
    ) -> crate::TabBarLayout {
        self.record("draw_tab_bar_layout");
        empty_tab_bar_layout()
    }
    /// `TabBarLayout`-returning counterpart to `draw_tab_bar_icons` above.
    fn draw_tab_bar_icons_layout(
        &mut self,
        _r: Rect,
        _b: &crate::TabBar,
        _icons: &[Option<crate::TabIcon>],
        _h: Option<usize>,
    ) -> crate::TabBarLayout {
        self.record("draw_tab_bar_icons_layout");
        empty_tab_bar_layout()
    }
    /// Union note: see `draw_status_bar` above — `app_shell::MockBackend`'s
    /// real body (`Vec::new()`) wins for the same reason;
    /// `AppShell::render` calls this for real.
    fn draw_activity_bar(
        &mut self,
        _r: Rect,
        _b: &crate::primitives::activity_bar::ActivityBar,
        _h: Option<usize>,
    ) -> Vec<crate::primitives::activity_bar::ActivityBarRowHit> {
        self.record("draw_activity_bar");
        Vec::new()
    }
    fn draw_terminal(&mut self, _r: Rect, _t: &crate::Terminal) {
        self.record("draw_terminal");
    }
    fn draw_terminal_divider(&mut self, _r: Rect) {
        self.record("draw_terminal_divider");
    }
    fn draw_solid_fill(&mut self, _r: Rect, _c: crate::Color) {
        self.record("draw_solid_fill");
    }
    fn draw_text_display(&mut self, _r: Rect, _t: &crate::TextDisplay) {
        self.record("draw_text_display");
    }
    fn draw_command_line(&mut self, _r: Rect, _c: &crate::CommandLine) {
        self.record("draw_command_line");
    }
    fn draw_command_line_selection(
        &mut self,
        _r: Rect,
        _c: &crate::CommandLine,
        _s: Option<(usize, usize)>,
    ) {
        self.record("draw_command_line_selection");
    }
    fn command_line_layout(
        &self,
        _r: Rect,
        _c: &crate::CommandLine,
    ) -> crate::primitives::command_line::CommandLineLayout {
        Default::default()
    }
    fn status_bar_layout(&self, _r: Rect, _b: &crate::StatusBar) -> crate::StatusBarLayout {
        crate::StatusBarLayout {
            bar_width: 0.0,
            bar_height: 0.0,
            visible_segments: Vec::new(),
            hit_regions: Vec::new(),
            resolved_right_start: 0,
        }
    }
    #[allow(deprecated)] // `TabBarHits` is `#[deprecated]`
    fn tab_bar_layout(&self, _r: Rect, _b: &crate::TabBar) -> crate::TabBarHits {
        crate::TabBarHits::default()
    }
    #[allow(deprecated)] // `TabBarHits` is `#[deprecated]`
    fn tab_bar_layout_icons(
        &self,
        _r: Rect,
        _b: &crate::TabBar,
        _icons: &[Option<crate::TabIcon>],
    ) -> crate::TabBarHits {
        crate::TabBarHits::default()
    }
    /// `TabBarLayout`-returning counterpart to `tab_bar_layout` above.
    fn resolve_tab_bar_layout(&self, _r: Rect, _b: &crate::TabBar) -> crate::TabBarLayout {
        empty_tab_bar_layout()
    }
    /// `TabBarLayout`-returning counterpart to `tab_bar_layout_icons` above.
    fn resolve_tab_bar_layout_icons(
        &self,
        _r: Rect,
        _b: &crate::TabBar,
        _icons: &[Option<crate::TabIcon>],
    ) -> crate::TabBarLayout {
        empty_tab_bar_layout()
    }
    fn activity_bar_layout(
        &self,
        _r: Rect,
        _b: &crate::primitives::activity_bar::ActivityBar,
    ) -> Vec<crate::ActivityBarRowHit> {
        Vec::new()
    }
    fn text_display_layout(&self, _r: Rect, _t: &crate::TextDisplay) -> crate::TextDisplayLayout {
        unimplemented!("RecordingBackend has no TextDisplay layout algorithm")
    }
    /// Union note: `chat_controller::MockBackend` was the only one with a
    /// real body (the other two `unimplemented!()`d, safe only because
    /// neither `TreeController` nor `AppShell` ever calls
    /// `draw_text_input`) — `ChatController`'s click-routing tests need a
    /// real layout, so its behaviour wins.
    fn draw_text_input(&mut self, r: Rect, ti: &crate::TextInput) -> crate::TextInputLayout {
        self.record("draw_text_input");
        ti.layout(r, crate::TextInputMeasure::from_metrics(&self.measure()))
    }
    /// Union note: see `draw_text_input` above.
    fn text_input_layout(&self, r: Rect, ti: &crate::TextInput) -> crate::TextInputLayout {
        ti.layout(r, crate::TextInputMeasure::from_metrics(&self.measure()))
    }
    fn draw_number_input(&mut self, _n: &crate::NumberInput, _l: &crate::NumberInputLayout) {
        self.record("draw_number_input");
    }
    fn draw_combo_box(&mut self, _c: &crate::ComboBox, _l: &crate::ComboBoxLayout) {
        self.record("draw_combo_box");
    }
    fn draw_date_picker(&mut self, _d: &crate::DatePicker, _l: &crate::DatePickerLayout) {
        self.record("draw_date_picker");
    }
    fn draw_tooltip(&mut self, _t: &crate::Tooltip, _l: &crate::TooltipLayout) {
        self.record("draw_tooltip");
    }
    /// Union note: `app_shell::MockBackend` was the only one with a real
    /// body (`Vec::new()`); the other two `unimplemented!()`d.
    fn draw_context_menu(
        &mut self,
        _m: &crate::ContextMenu,
        _l: &crate::ContextMenuLayout,
    ) -> Vec<(Rect, WidgetId)> {
        self.record("draw_context_menu");
        Vec::new()
    }
    /// Union note: see `draw_context_menu` above.
    fn draw_dialog(&mut self, _d: &crate::Dialog, _l: &crate::DialogLayout) -> Vec<Rect> {
        self.record("draw_dialog");
        Vec::new()
    }
    fn draw_float(&mut self, _f: &crate::Float, _l: &crate::FloatLayout) {
        self.record("draw_float");
    }
    fn draw_multi_section_view(&mut self, _r: Rect, _v: &crate::MultiSectionView) {
        self.record("draw_multi_section_view");
    }
    fn msv_layout(&self, _r: Rect, _v: &crate::MultiSectionView) -> crate::MultiSectionViewLayout {
        unimplemented!("RecordingBackend has no MultiSectionView layout algorithm")
    }
    fn msv_metrics(&self) -> crate::primitives::multi_section_view::MsvLayoutMetrics {
        unimplemented!("RecordingBackend has no MultiSectionView metrics")
    }
    /// Union note: `tree_controller::MockBackend`'s body wins —
    /// `chat_controller::MockBackend` also had a real (but simpler,
    /// hit-region-free) body, but `ChatController` never calls
    /// `tree_layout`, so the more complete chevron-aware algorithm
    /// `TreeController`'s own click-routing tests depend on is safe to
    /// use everywhere. Delegates to [`crate::TreeView::layout`] so
    /// chevron hit regions come out identical to a real backend's.
    fn tree_layout(
        &self,
        rect: Rect,
        tree: &crate::TreeView,
    ) -> crate::primitives::tree::TreeViewLayout {
        let lh = self.line_height();
        let indent_cells = tree.style.indent as f32;
        let chevron_w = if tree.style.show_chevrons {
            tree.style.chevron_expanded.chars().count() as f32 + 1.0
        } else {
            0.0
        };
        tree.layout(rect.width, rect.height, |i| {
            let row = &tree.rows[i];
            let chevron_end_x = if row.is_expanded.is_some() && chevron_w > 0.0 {
                Some(row.indent as f32 * indent_cells + chevron_w)
            } else {
                None
            };
            crate::primitives::tree::TreeRowMeasure {
                height: lh,
                chevron_end_x,
            }
        })
    }
    fn tree_vscrollbar(&self, rect: Rect, tree: &crate::TreeView) -> Option<crate::Scrollbar> {
        // Reached only when `tree_paints_own_scrollbar()` is true (see
        // `TreeController::split_rect`), i.e. only when a test is
        // simulating a pixel backend — so the track width matches the
        // real pixel backends' fixed column, not `line_height`.
        tree.vscrollbar_with_track_width(
            rect,
            self.line_height(),
            crate::primitives::layout_metrics::pixel::TREE_VSCROLLBAR_WIDTH,
        )
    }
    fn tree_paints_own_scrollbar(&self) -> bool {
        #[cfg(test)]
        {
            TREE_PAINTS_OWN_SCROLLBAR.with(std::cell::Cell::get)
        }
        #[cfg(not(test))]
        {
            false
        }
    }
    fn form_layout(&self, _r: Rect, _f: &crate::Form) -> crate::primitives::form::FormLayout {
        unimplemented!("RecordingBackend has no Form layout algorithm")
    }
    fn draw_editor(
        &mut self,
        _r: Rect,
        _e: &crate::primitives::editor::Editor,
    ) -> crate::backend::EditorPaintResult {
        self.record("draw_editor");
        Default::default()
    }
    fn draw_message_list(&mut self, _r: Rect, _l: &crate::primitives::message_list::MessageList) {
        self.record("draw_message_list");
    }
    fn draw_rich_text_popup(
        &mut self,
        _p: &crate::RichTextPopup,
        _l: &crate::primitives::rich_text_popup::RichTextPopupLayout,
    ) {
        self.record("draw_rich_text_popup");
    }
    fn draw_find_replace(
        &mut self,
        _r: Rect,
        _p: &crate::primitives::find_replace::FindReplacePanel,
    ) {
        self.record("draw_find_replace");
    }
    fn draw_completions(
        &mut self,
        _c: &crate::Completions,
        _l: &crate::primitives::completions::CompletionsLayout,
    ) {
        self.record("draw_completions");
    }
    fn draw_scrollbar(&mut self, _r: Rect, _s: &crate::Scrollbar) {
        self.record("draw_scrollbar");
    }
    fn draw_drop_overlay(&mut self, _o: &crate::primitives::drop_zone::DropOverlay) {
        self.record("draw_drop_overlay");
    }
    fn draw_menu_bar(&mut self, _r: Rect, _b: &crate::MenuBar) -> crate::MenuBarLayout {
        self.record("draw_menu_bar");
        unimplemented!("RecordingBackend has no MenuBar layout algorithm")
    }
    fn menu_bar_layout(&self, _r: Rect, _b: &crate::MenuBar) -> crate::MenuBarLayout {
        unimplemented!("RecordingBackend has no MenuBar layout algorithm")
    }
    fn draw_split(&mut self, _r: Rect, _s: &crate::Split) -> crate::SplitLayout {
        self.record("draw_split");
        unimplemented!("RecordingBackend has no Split layout algorithm")
    }
    fn split_layout(&self, _r: Rect, _s: &crate::Split) -> crate::SplitLayout {
        unimplemented!("RecordingBackend has no Split layout algorithm")
    }
    fn draw_split_tree(&mut self, _r: Rect, _t: &crate::SplitTree) -> crate::SplitTreeLayout {
        self.record("draw_split_tree");
        unimplemented!("RecordingBackend has no SplitTree layout algorithm")
    }
    fn split_tree_layout(&self, _r: Rect, _t: &crate::SplitTree) -> crate::SplitTreeLayout {
        unimplemented!("RecordingBackend has no SplitTree layout algorithm")
    }
    fn draw_panel(&mut self, _r: Rect, _p: &crate::Panel) -> crate::PanelLayout {
        self.record("draw_panel");
        unimplemented!("RecordingBackend has no Panel layout algorithm")
    }
    fn panel_layout(&self, _r: Rect, _p: &crate::Panel) -> crate::PanelLayout {
        unimplemented!("RecordingBackend has no Panel layout algorithm")
    }
    fn draw_canvas(&mut self, _r: Rect, _c: &crate::Canvas) -> crate::CanvasLayout {
        self.record("draw_canvas");
        unimplemented!("RecordingBackend has no Canvas paint algorithm")
    }
    fn draw_toast_overlay(
        &mut self,
        _r: Rect,
        _s: &crate::ToastOverlay,
    ) -> crate::ToastStackLayout {
        self.record("draw_toast_stack");
        unimplemented!("RecordingBackend has no ToastOverlay layout algorithm")
    }
    fn toast_stack_layout(&self, _r: Rect, _s: &crate::ToastOverlay) -> crate::ToastStackLayout {
        unimplemented!("RecordingBackend has no ToastOverlay layout algorithm")
    }
    fn draw_pipeline_view(
        &mut self,
        _r: Rect,
        _v: &crate::PipelineView,
    ) -> crate::PipelineViewLayout {
        self.record("draw_pipeline_view");
        unimplemented!("RecordingBackend has no PipelineView layout algorithm")
    }
    fn pipeline_view_layout(
        &self,
        _r: Rect,
        _v: &crate::PipelineView,
    ) -> crate::PipelineViewLayout {
        unimplemented!("RecordingBackend has no PipelineView layout algorithm")
    }
    fn draw_progress(&mut self, _r: Rect, _b: &crate::ProgressBar) -> crate::ProgressBarLayout {
        self.record("draw_progress");
        unimplemented!("RecordingBackend has no ProgressBar layout algorithm")
    }
    fn progress_layout(&self, _r: Rect, _b: &crate::ProgressBar) -> crate::ProgressBarLayout {
        unimplemented!("RecordingBackend has no ProgressBar layout algorithm")
    }
    /// Union note: `chat_controller::MockBackend` was the only one with a
    /// real body (trivial `SpinnerLayout { bounds: r }`, needed so its
    /// render tests don't panic); the other two `unimplemented!()`d.
    fn draw_spinner(&mut self, r: Rect, _s: &crate::Spinner) -> crate::SpinnerLayout {
        self.record("draw_spinner");
        crate::SpinnerLayout { bounds: r }
    }
    /// Union note: see `draw_spinner` above.
    fn spinner_layout(&self, r: Rect, _s: &crate::Spinner) -> crate::SpinnerLayout {
        crate::SpinnerLayout { bounds: r }
    }
    fn draw_button(&mut self, _r: Rect, _b: &crate::Button) -> crate::ButtonLayout {
        self.record("draw_button");
        unimplemented!("RecordingBackend has no Button layout algorithm")
    }
    fn button_layout(&self, _r: Rect, _b: &crate::Button) -> crate::ButtonLayout {
        unimplemented!("RecordingBackend has no Button layout algorithm")
    }
    fn draw_radio_group(&mut self, _r: Rect, _g: &crate::RadioGroup) -> crate::RadioGroupLayout {
        self.record("draw_radio_group");
        unimplemented!("RecordingBackend has no RadioGroup layout algorithm")
    }
    fn radio_group_layout(&self, _r: Rect, _g: &crate::RadioGroup) -> crate::RadioGroupLayout {
        unimplemented!("RecordingBackend has no RadioGroup layout algorithm")
    }
    fn draw_switch(&mut self, _r: Rect, _s: &crate::Switch) -> crate::SwitchLayout {
        self.record("draw_switch");
        unimplemented!("RecordingBackend has no Switch layout algorithm")
    }
    fn switch_layout(&self, _r: Rect, _s: &crate::Switch) -> crate::SwitchLayout {
        unimplemented!("RecordingBackend has no Switch layout algorithm")
    }
    fn draw_command_center(
        &mut self,
        _r: Rect,
        _c: &crate::CommandCenter,
    ) -> crate::CommandCenterLayout {
        self.record("draw_command_center");
        unimplemented!("RecordingBackend has no CommandCenter layout algorithm")
    }
    fn command_center_layout(
        &self,
        _r: Rect,
        _c: &crate::CommandCenter,
    ) -> crate::CommandCenterLayout {
        unimplemented!("RecordingBackend has no CommandCenter layout algorithm")
    }
    fn draw_chart(
        &mut self,
        _r: Rect,
        _c: &crate::primitives::chart::Chart,
        _h: Option<(usize, usize)>,
        _x: Option<f64>,
    ) -> crate::primitives::chart::ChartLayout {
        self.record("draw_chart");
        unimplemented!("RecordingBackend has no Chart layout algorithm")
    }
    fn chart_layout(
        &self,
        _r: Rect,
        _c: &crate::primitives::chart::Chart,
    ) -> crate::primitives::chart::ChartLayout {
        unimplemented!("RecordingBackend has no Chart layout algorithm")
    }
    fn draw_toolbar_with_options(
        &mut self,
        _r: Rect,
        _b: &crate::primitives::toolbar::Toolbar,
        _interaction: &crate::interaction::InteractionState,
        _options: crate::primitives::toolbar::ToolbarPaintOptions,
    ) -> crate::primitives::toolbar::ToolbarLayout {
        self.record("draw_toolbar");
        unimplemented!("RecordingBackend has no Toolbar layout algorithm")
    }
    fn toolbar_layout(
        &self,
        _r: Rect,
        _b: &crate::primitives::toolbar::Toolbar,
    ) -> crate::primitives::toolbar::ToolbarLayout {
        unimplemented!("RecordingBackend has no Toolbar layout algorithm")
    }
    fn draw_sidebar_panel_interactive(
        &mut self,
        _r: Rect,
        _p: &crate::primitives::sidebar_panel::SidebarPanel,
        _interaction: &crate::interaction::InteractionState,
    ) -> crate::primitives::sidebar_panel::SidebarPanelLayout {
        self.record("draw_sidebar_panel");
        unimplemented!("RecordingBackend has no SidebarPanel layout algorithm")
    }
    fn sidebar_panel_layout(
        &self,
        _r: Rect,
        _p: &crate::primitives::sidebar_panel::SidebarPanel,
    ) -> crate::primitives::sidebar_panel::SidebarPanelLayout {
        unimplemented!("RecordingBackend has no SidebarPanel layout algorithm")
    }
    fn draw_diff_view(
        &mut self,
        _r: Rect,
        view: &crate::primitives::diff_view::DiffView,
    ) -> crate::primitives::diff_view::DiffViewLayout {
        self.record("draw_diff_view");
        crate::primitives::diff_view::DiffViewLayout {
            visible_rows: 0,
            total_rows: view.total_rows(),
        }
    }
    fn draw_board(
        &mut self,
        _r: Rect,
        _m: &crate::primitives::board::BoardModel,
    ) -> crate::primitives::board::BoardLayout {
        self.record("draw_board");
        crate::primitives::board::BoardLayout {
            bounds: crate::event::Rect::new(_r.x, _r.y, _r.width, _r.height),
            columns: vec![],
        }
    }
    fn board_layout(
        &self,
        _r: Rect,
        _m: &crate::primitives::board::BoardModel,
    ) -> crate::primitives::board::BoardLayout {
        crate::primitives::board::BoardLayout {
            bounds: crate::event::Rect::new(_r.x, _r.y, _r.width, _r.height),
            columns: vec![],
        }
    }
    fn draw_minimap(
        &mut self,
        _r: Rect,
        _m: &crate::primitives::minimap::Minimap,
    ) -> crate::backend::MinimapPaintResult {
        self.record("draw_minimap");
        crate::backend::MinimapPaintResult::default()
    }
    fn minimap_layout(
        &self,
        _r: Rect,
        _m: &crate::primitives::minimap::Minimap,
    ) -> crate::primitives::minimap::MinimapLayout {
        crate::primitives::minimap::MinimapLayout::default()
    }
    fn draw_image(
        &mut self,
        _r: Rect,
        _i: &crate::primitives::image::Image,
    ) -> crate::backend::ImagePaintResult {
        self.record("draw_image");
        crate::backend::ImagePaintResult::Unsupported
    }
}

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

    // ─── Shared text-run recording sink ───────────────────────────────────
    //
    // Gated to match `record_text_run`/`text_run_sink_active`'s own cfg
    // (the narrower of the sink module's two predicates — see its
    // top-level comment): every function this sub-module exercises must
    // actually exist under whichever single-backend feature combination
    // is compiling it, and `install_text_run_sink`/`take_text_run_sink`
    // are available under strictly more feature combinations than that
    // (`--features win` alone on a non-Windows host, in particular) — so
    // gating on the narrower predicate is what guarantees all four names
    // resolve together.
    #[cfg(any(
        feature = "gtk",
        all(feature = "macos", target_os = "macos"),
        all(feature = "win", target_os = "windows")
    ))]
    mod text_run_sink {
        use super::*;

        /// Recording is off by default: [`record_text_run`] must be a
        /// no-op until [`install_text_run_sink`] has been called — the "a
        /// live app never pays for this" contract every backend's own
        /// recording toggle (`GtkBackend::set_painted_text_recording`,
        /// etc.) relies on.
        #[test]
        fn record_is_a_no_op_with_no_sink_installed() {
            // No `install_text_run_sink()` call — proves recording
            // doesn't leak across tests via some global default, and
            // that a run painted with nothing installed is silently
            // dropped, not buffered somewhere it could resurface later.
            record_text_run("stray", Rect::new(0.0, 0.0, 1.0, 1.0));
            let prev = install_text_run_sink();
            let runs = take_text_run_sink(prev);
            assert!(
                runs.is_empty(),
                "a run recorded before any sink existed must not appear once one is installed: {runs:?}"
            );
        }

        #[test]
        fn install_then_record_then_take_round_trips_one_run() {
            assert!(!text_run_sink_active());
            let prev = install_text_run_sink();
            assert!(text_run_sink_active());

            record_text_run("hello", Rect::new(1.0, 2.0, 3.0, 4.0));

            let runs = take_text_run_sink(prev);
            assert_eq!(
                runs,
                vec![TextRun {
                    text: "hello".into(),
                    bounds: Rect::new(1.0, 2.0, 3.0, 4.0),
                }]
            );
            assert!(
                !text_run_sink_active(),
                "take_text_run_sink(None) must leave recording off again"
            );
        }

        /// Whitespace-only runs (alignment pads, blank rows, selection
        /// prefixes) are dropped — they can never be a useful `find`
        /// needle.
        #[test]
        fn whitespace_only_runs_are_not_recorded() {
            let prev = install_text_run_sink();
            for text in ["", "   ", "real"] {
                record_text_run(text, Rect::new(0.0, 0.0, 1.0, 1.0));
            }
            let runs = take_text_run_sink(prev);
            assert_eq!(
                runs.len(),
                1,
                "only the non-blank run should record: {runs:?}"
            );
            assert_eq!(runs[0].text, "real");
        }

        /// [`install_text_run_sink`] returns the previous sink so a
        /// (theoretically) nested paint scope can restore it exactly —
        /// [`take_text_run_sink`]'s `previous` parameter — rather than
        /// clobbering an outer scope's in-flight recording.
        #[test]
        fn nested_install_restores_the_outer_sink_on_take() {
            let outer_prev = install_text_run_sink();
            record_text_run("outer-before", Rect::new(0.0, 0.0, 1.0, 1.0));

            let inner_prev = install_text_run_sink();
            record_text_run("inner", Rect::new(0.0, 0.0, 1.0, 1.0));
            let inner_runs = take_text_run_sink(inner_prev);
            assert_eq!(inner_runs.len(), 1);
            assert_eq!(inner_runs[0].text, "inner");

            // The outer sink is active again and still carries its own
            // earlier run — the inner scope's recording didn't bleed
            // into it.
            assert!(text_run_sink_active());
            record_text_run("outer-after", Rect::new(0.0, 0.0, 1.0, 1.0));
            let outer_runs = take_text_run_sink(outer_prev);
            assert_eq!(
                outer_runs
                    .iter()
                    .map(|r| r.text.as_str())
                    .collect::<Vec<_>>(),
                vec!["outer-before", "outer-after"]
            );
        }
    }

    /// A small hand-built inventory: an activity-bar-style icon column
    /// (`"E"`, `"S"`, `"G"` stacked at x=0..2) to the left of a sidebar
    /// header/content pair (`"SOURCE CONTROL"` above `"content"` at
    /// x=10..40), plus one registered zone around the sidebar content
    /// run. Exercises the relational vocabulary with no backend at all —
    /// the cross-backend agreement itself is proven separately in
    /// `tests/cross_backend_parity.rs::frame_inventory_relations_agree_tui_and_gtk`.
    fn fixture() -> FrameInventory {
        FrameInventory {
            text_runs: vec![
                TextRun {
                    text: "E".into(),
                    bounds: Rect::new(0.0, 0.0, 1.0, 1.0),
                },
                TextRun {
                    text: "S".into(),
                    bounds: Rect::new(0.0, 1.0, 1.0, 1.0),
                },
                TextRun {
                    text: "G".into(),
                    bounds: Rect::new(0.0, 2.0, 1.0, 1.0),
                },
                TextRun {
                    text: "SOURCE CONTROL".into(),
                    bounds: Rect::new(10.0, 0.0, 14.0, 1.0),
                },
                TextRun {
                    text: "content".into(),
                    bounds: Rect::new(10.0, 1.0, 7.0, 1.0),
                },
            ],
            zones: vec![ZoneRec {
                id: WidgetId::new("sidebar-content"),
                bounds: Rect::new(10.0, 1.0, 30.0, 1.0),
            }],
        }
    }

    #[test]
    fn screen_has_and_absent() {
        let inv = fixture();
        assert!(inv.screen_has("SOURCE"));
        assert!(inv.screen_has("CONTROL"));
        assert!(inv.absent("git"));
        assert!(!inv.screen_has("git"));
    }

    #[test]
    fn count_matches_every_run_containing_needle() {
        let inv = fixture();
        // "S" appears in the "S" icon run and inside "SOURCE CONTROL".
        assert_eq!(inv.count("S"), 2);
        assert_eq!(inv.count("G"), 1);
        assert_eq!(inv.count("nope"), 0);
    }

    #[test]
    fn left_of_is_true_for_the_icon_column_vs_the_sidebar() {
        let inv = fixture();
        assert!(inv.left_of("G", "SOURCE CONTROL"));
        assert!(inv.left_of("G", "content"));
        assert!(!inv.left_of("SOURCE CONTROL", "G"), "reverse must not hold");
    }

    #[test]
    fn above_is_true_for_header_vs_content() {
        let inv = fixture();
        assert!(inv.above("SOURCE CONTROL", "content"));
        assert!(
            !inv.above("content", "SOURCE CONTROL"),
            "reverse must not hold"
        );
        // Same-column icons stack top to bottom too.
        assert!(inv.above("E", "S"));
        assert!(inv.above("S", "G"));
    }

    #[test]
    fn same_row_true_for_overlapping_ranges_false_across_rows() {
        let inv = fixture();
        assert!(inv.same_row("E", "SOURCE CONTROL"));
        assert!(inv.same_row("S", "content"));
        assert!(!inv.same_row("E", "content"));
    }

    #[test]
    fn inside_checks_containment_within_a_registered_zone() {
        let inv = fixture();
        let zone = WidgetId::new("sidebar-content");
        assert!(inv.inside("content", &zone));
        assert!(
            !inv.inside("SOURCE CONTROL", &zone),
            "the header run sits above the zone's y range, not inside it"
        );
        assert!(
            !inv.inside("content", &WidgetId::new("no-such-zone")),
            "an unregistered zone id must never report containment"
        );
    }

    #[test]
    fn relations_are_false_not_panicking_when_a_needle_never_painted() {
        let inv = fixture();
        assert!(!inv.left_of("nope", "G"));
        assert!(!inv.above("G", "nope"));
        assert!(!inv.same_row("nope", "G"));
        assert!(!inv.inside("nope", &WidgetId::new("sidebar-content")));
    }

    // Every real backend driver now delegates `press`/`type_char`/
    // `press_named`/`ctrl_char`/`click`/`drag` (and, for the pixel-unit
    // backends, `click_text_at`/`drag_text`/`scroll_at`) to these traits'
    // default method bodies. This fixture exercises the default bodies
    // *directly*, with no backend feature at all, so a future edit to a
    // default has a test right beside it.

    use crate::MouseButton;

    /// Minimal fake driver recording every dispatched [`UiEvent`] plus a
    /// hand-built `needle -> bounds` map.
    struct FakeDriver {
        events: Vec<UiEvent>,
        painted: Vec<(&'static str, Rect)>,
        line_height: f32,
    }

    impl FakeDriver {
        fn new() -> Self {
            Self {
                events: Vec::new(),
                painted: vec![("Toggle", Rect::new(10.0, 20.0, 40.0, 8.0))],
                line_height: 16.0,
            }
        }
    }

    impl DriverInput for FakeDriver {
        fn dispatch(&mut self, event: UiEvent) -> Reaction {
            self.events.push(event);
            Reaction::Redraw
        }

        fn mouse_down(&mut self, x: f32, y: f32) -> Reaction {
            self.dispatch(UiEvent::MouseDown {
                widget: None,
                button: MouseButton::Left,
                position: Point::new(x, y),
                modifiers: Modifiers::default(),
            })
        }

        fn mouse_move(&mut self, x: f32, y: f32) -> Reaction {
            self.dispatch(UiEvent::MouseMoved {
                position: Point::new(x, y),
                buttons: crate::ButtonMask {
                    left: true,
                    ..crate::ButtonMask::default()
                },
            })
        }

        fn mouse_up(&mut self, x: f32, y: f32) -> Reaction {
            self.dispatch(UiEvent::MouseUp {
                widget: None,
                button: MouseButton::Left,
                position: Point::new(x, y),
            })
        }
    }

    impl PixelClickConformance for FakeDriver {
        const NAME: &'static str = "FakeDriver";

        fn find_bounds(&self, needle: &str) -> Option<Rect> {
            self.painted
                .iter()
                .find(|(t, _)| *t == needle)
                .map(|(_, b)| *b)
        }

        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))
        }

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

    #[test]
    fn driver_input_press_family_dispatches_expected_key_events() {
        let mut d = FakeDriver::new();
        d.press(Key::Char('a'));
        d.type_char('b');
        d.press_named(NamedKey::Enter);
        d.ctrl_char('c');

        assert_eq!(
            d.events,
            vec![
                UiEvent::KeyPressed {
                    key: Key::Char('a'),
                    modifiers: Modifiers::default(),
                    repeat: false,
                },
                UiEvent::KeyPressed {
                    key: Key::Char('b'),
                    modifiers: Modifiers::default(),
                    repeat: false,
                },
                UiEvent::KeyPressed {
                    key: Key::Named(NamedKey::Enter),
                    modifiers: Modifiers::default(),
                    repeat: false,
                },
                UiEvent::KeyPressed {
                    key: Key::Char('c'),
                    modifiers: Modifiers {
                        ctrl: true,
                        ..Modifiers::default()
                    },
                    repeat: false,
                },
            ]
        );
    }

    #[test]
    fn driver_input_click_is_a_bare_mouse_down_by_default() {
        let mut d = FakeDriver::new();
        d.click(3.0, 4.0);
        assert_eq!(
            d.events,
            vec![UiEvent::MouseDown {
                widget: None,
                button: MouseButton::Left,
                position: Point::new(3.0, 4.0),
                modifiers: Modifiers::default(),
            }],
            "the default `click` is a bare press-down — WinDriver overrides \
             this to add a release, everyone else keeps the default"
        );
    }

    #[test]
    fn driver_input_drag_is_down_then_move_then_up() {
        let mut d = FakeDriver::new();
        d.drag(1.0, 2.0, 5.0, 6.0);
        assert_eq!(d.events.len(), 3);
        assert!(matches!(d.events[0], UiEvent::MouseDown { .. }));
        assert!(matches!(d.events[1], UiEvent::MouseMoved { .. }));
        assert!(matches!(d.events[2], UiEvent::MouseUp { .. }));
    }

    #[test]
    fn pixel_click_conformance_click_text_at_resolves_each_anchor() {
        // "Toggle" bounds: x=10, y=20, w=40, h=8 → center (30, 24),
        // left-edge (11, 24), right-edge (49, 24).
        let mut d = FakeDriver::new();
        PixelClickConformance::click_text_at(&mut d, "Toggle", Anchor::Center);
        PixelClickConformance::click_text_at(&mut d, "Toggle", Anchor::LeftEdge);
        PixelClickConformance::click_text_at(&mut d, "Toggle", Anchor::RightEdge);

        let positions: Vec<(f32, f32)> = d
            .events
            .iter()
            .map(|e| match e {
                UiEvent::MouseDown { position, .. } => (position.x, position.y),
                other => panic!("expected MouseDown, got {other:?}"),
            })
            .collect();
        assert_eq!(positions, vec![(30.0, 24.0), (11.0, 24.0), (49.0, 24.0)]);
    }

    #[test]
    #[should_panic(expected = "FakeDriver: \"nope\" not painted")]
    fn pixel_click_conformance_click_text_at_panics_naming_the_driver_when_not_painted() {
        let mut d = FakeDriver::new();
        PixelClickConformance::click_text_at(&mut d, "nope", Anchor::Center);
    }

    #[test]
    fn pixel_click_conformance_scroll_at_dispatches_scroll_scaled_by_line_height() {
        let mut d = FakeDriver::new();
        PixelClickConformance::scroll_at(&mut d, "Toggle", 2);
        assert_eq!(d.events.len(), 1);
        match &d.events[0] {
            UiEvent::Scroll { delta, .. } => assert_eq!(delta.y, 2.0 * 16.0),
            other => panic!("expected Scroll, got {other:?}"),
        }
    }
}