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
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
//! macOS rasteriser for [`crate::TabBar`].
//!
//! Mirrors [`crate::gtk::tab_bar::draw_tab_bar`]: measures tab widths
//! via Core Text, lays out left-to-right with active-tab highlighting,
//! close glyphs (a codicon close mark, or a filled circle for dirty —
//! see [`crate::codicon`]), and right-aligned segments.
//! Returns a [`TabBarHits`] carrying per-tab + per-segment screen
//! bounds for the caller's click dispatch.
//!
//! ## Scope omissions
//!
//! - **Italic preview tabs** — needs an italic-variant `CTFont` via
//!   `CTFontCreateCopyWithSymbolicTraits`. Same dependency as bold
//!   support in [`super::status_bar`]; pairs naturally with that
//!   future change. Until it lands, preview tabs render in the
//!   active font.
//! - **Rounded close-button hover background** — the GTK rasteriser
//!   draws a 3 px rounded rect under the close glyph on hover. macOS
//!   uses a simpler approach: tint the close glyph itself
//!   (`theme.foreground`) when hovered.
//!
//! ## Per-backend paint loop
//!
//! Unlike `macos::menu_bar` / `macos::toolbar` / `macos::activity_bar`,
//! every pixel this module paints is still Core Graphics-specific and
//! still triplicated with `gtk::tab_bar` / `win::tab_bar`. Of the five
//! rows in the drift table, macOS matches GTK on two — active-tab
//! background and active-tab top accent (rounded, y-inset chip; 1 px
//! accent on the chip's own inset top edge) — and drifts on three:
//! the two "Scope omissions" above plus
//! [`crate::primitives::tab_bar::TabFrame::Brackets`] framing. Windows
//! drifts on all five rows. **This backend is the blocker**:
//! `mac_tab_bar_layout_icons` / `mac_tab_bar_native_layout_icons`
//! below still derive geometry themselves instead of going through the
//! shared [`crate::primitives::layout_metrics::pixel_tab_bar_layout`]
//! that `gtk::tab_bar` and `win::tab_bar` already use, and they size
//! `close_bounds` by a different convention (`CLOSE_PAD` around the
//! glyph, rather than `tab_inner_gap + close_glyph_w` before it). See
//! [`crate::primitives::tab_bar`]'s drift documentation for the full
//! table and remaining work.

use core_graphics::sys::CGContextRef;
use core_text::font::CTFont;

use super::cg::*;

use super::backend::ns_fill_rounded_rect;
use super::text::{draw_text, measure_text};
// `TabBarHits` is `#[deprecated]` — this module converts a computed
// `TabBarLayout` into one per paint/no-paint call, so the import needs
// the same allow every use site below does.
use crate::event::Rect;
use crate::primitives::tab_bar::{
    tab_icon_at, TabBarGlyphs, TabBarHit, TabBarLayout, TabIcon, VisibleSegment, VisibleTab,
};
#[allow(deprecated)]
use crate::primitives::tab_bar::{TabBar, TabBarHits};
use crate::theme::Theme;

/// Per-tab horizontal padding (left + right) inside the tab background fill.
const TAB_PAD: f64 = 14.0;
/// Gap between the tab label and the close glyph.
const TAB_INNER_GAP: f64 = 10.0;
/// Gap between adjacent tabs.
const TAB_OUTER_GAP: f64 = 1.0;
/// Top-edge accent strip height for the active tab (when `active_accent`
/// is set) — same value as [`crate::gtk::tab_bar`]'s
/// `TAB_ACTIVE_BORDER_TOP_PX`, so the accent is the same thickness on
/// both pixel backends, not just the same position on the chip.
const ACCENT_HEIGHT: f64 = 1.0;
/// 15-char sample used to estimate cell width for `available_cols`.
/// Same string the GTK rasteriser uses, so app-level cell budgets
/// remain comparable between backends.
const CELL_WIDTH_SAMPLE: &str = "ABCDabcd0123.:_";
/// Slack added either side of the close glyph when building its hit box.
const CLOSE_PAD: f64 = 2.0;
/// Gap between a tab's icon glyph (see [`TabIcon`]) and its label.
/// Same value as [`crate::gtk::tab_bar`]'s `TAB_ICON_GAP`, so a decorated
/// tab is the same shape on both pixel backends.
const TAB_ICON_GAP: f64 = 6.0;
/// Vertical margin (px) above and below the active-tab chip fill — same
/// value as [`crate::gtk::tab_bar`]'s `TAB_CHIP_INSET_Y`. VS Code insets
/// its active-tab pill inside the tab strip rather than filling the full
/// row height edge to edge, and this backend matches that shape.
const TAB_CHIP_INSET_Y: f64 = 4.0;
/// Corner radius (px) of the active-tab chip, all four corners — same
/// value as [`crate::gtk::tab_bar`]'s `TAB_CHIP_RADIUS`.
const TAB_CHIP_RADIUS: f64 = 4.0;

/// Per-tab extra width (points) reserved for an icon glyph plus
/// [`TAB_ICON_GAP`], indexed like `bar.tabs`. `0.0` for every tab without
/// an icon, so an icon-less tab keeps byte-identical width and hit-test
/// geometry to the pre-#926 rasteriser (and `&[]` — what [`draw_tab_bar`]
/// and the other icon-less wrappers pass — reproduces it exactly for
/// every tab).
///
/// This is the CoreText icon-width pass #926 was opened for. Every
/// geometry consumer goes through it — [`mac_tab_bar_layout_icons`],
/// [`mac_tab_bar_native_layout_icons`] and [`draw_tab_bar_icons`]'s paint
/// loop — which is what keeps a tab's close-button hit box on the glyph
/// it draws once an icon shifts the label right.
///
/// # Font choice — the current font, not a swapped-in icon family
///
/// Unlike GTK (`gtk::tab_bar::tab_icon_font`, which replaces the family
/// with `Symbols Nerd Font`), macOS measures and paints the glyph with
/// whatever font [`crate::Backend::set_current_font`] installed. That is
/// this backend's established convention for every other glyph it draws —
/// see [`super::activity_bar::draw_activity_bar`]'s doc, which makes the
/// same choice for [`crate::Icon`] — and it is what keeps measure and
/// paint using one font by construction: a family swap here would need
/// the same swap in the paint loop or the reservation would not match the
/// ink. A caller whose font carries no icon codepoints gets tofu of the
/// measured width, not misplaced hit boxes.
pub(crate) fn mac_tab_icon_extras(
    font: &CTFont,
    tab_count: usize,
    icons: &[Option<TabIcon>],
) -> Vec<f64> {
    (0..tab_count)
        .map(|i| match tab_icon_at(icons, i) {
            Some(icon) => measure_text(font, &icon.glyph).0 + TAB_ICON_GAP,
            None => 0.0,
        })
        .collect()
}

/// Per-tab extra width (points) reserved for an icon glyph plus
/// [`TAB_ICON_GAP`], indexed like `bar.tabs`. `0.0` for every tab without
/// an icon, so an icon-less tab keeps byte-identical width and hit-test
/// geometry to the pre-#926 rasteriser (and `&[]` reproduces it exactly).
///
/// This is the CoreText icon-width pass. Every geometry consumer goes
/// through it — [`mac_tab_bar_layout_icons`],
/// [`mac_tab_bar_native_layout_icons`] and [`draw_tab_bar_icons`]'s paint
/// loop — which keeps a tab's close-button hit box on the glyph it draws
/// once an icon shifts the label right.
///
/// # Font choice — the current font, not a swapped-in icon family
///
/// Unlike GTK (`gtk::tab_bar::tab_icon_font`, which replaces the family
/// with `Symbols Nerd Font`), macOS measures and paints the glyph with
/// whatever font [`crate::Backend::set_current_font`] installed. That is
/// this backend's established convention for every other glyph it draws —
/// see [`super::activity_bar::draw_activity_bar`]'s doc, which makes the
/// same choice for [`crate::Icon`] — and it is what keeps measure and
/// paint using one font by construction: a family swap here would need
/// the same swap in the paint loop or the reservation would not match the
/// ink. A caller whose font carries no icon codepoints gets tofu of the
/// measured width, not misplaced hit boxes.
#[allow(deprecated)]
pub fn mac_tab_bar_layout(font: &CTFont, width: f64, bar: &TabBar) -> TabBarHits {
    mac_tab_bar_layout_icons(font, width, bar, &[])
}

/// Compute the [`TabBarHits`] [`draw_tab_bar`] would produce for `bar` at
/// `width`, without painting.
///
/// This is the single measurement path: [`draw_tab_bar`] calls it too and
/// paints from its output, so the no-paint twin backing
/// [`crate::Backend::tab_bar_layout`] cannot drift from what was painted.
/// Both spellings go through [`mac_tab_bar_layout_icons`] with an empty
/// icon sidecar, which is equivalent point for point — pass a real sidecar
/// to that function to decorate tabs.
///
/// # Coordinate space — bar-relative here; callers shift to absolute
///
/// This function itself returns **bar-relative** `x` (slots start at
/// `0.0`) and is never handed `rect.x` — same shape as
/// [`mac_tab_bar_native_layout_icons`] below. The
/// [`crate::Backend::tab_bar_layout`] doc pins the `TabBarHits` *contract*
/// at target-surface (absolute) coordinates though, so every caller that
/// owes it — [`crate::macos::MacBackend::draw_tab_bar_icons`]'s paint path
/// and [`crate::macos::MacBackend::tab_bar_layout_icons`]'s no-paint twin —
/// runs this function's output through
/// [`crate::backend::shift_tab_bar_hits`] with `rect.x`, the same TUI /
/// GTK convention. `MacBackend::draw_tab_bar_icons` additionally wraps its
/// CGContext in `CGContextTranslateCTM(ctx, rect.x, rect.y)` before calling
/// [`draw_tab_bar_icons`] below, so the ink lands at the shifted hits'
/// position too — mirroring `GtkBackend::draw_activity_bar`'s `cr.translate`
/// and this crate's own `MacBackend::draw_activity_bar`. What this function
/// guarantees is the invariant that is actually load-bearing: `tab_bar_layout`
/// returns exactly what `draw_tab_bar` painted, once both are shifted the same way.
#[allow(deprecated)]
pub fn mac_tab_bar_layout_icons(
    font: &CTFont,
    width: f64,
    bar: &TabBar,
    icons: &[Option<TabIcon>],
) -> TabBarHits {
    let native = mac_tab_bar_native_layout_icons(font, width, 1.0, bar, icons);
    let mut hits = crate::backend::tab_bar_hits_from_layout(&native, bar);
    // `mac_tab_bar_native_layout_icons`'s `resolved_scroll_offset` is the
    // scroll-offset value this function reports back as engine feedback.
    hits.correct_scroll_offset = native.resolved_scroll_offset;

    // Cell-width estimation: 15-char sample width / 15 → average glyph
    // advance. Matches the GTK/Windows convention so app-level char-col
    // math doesn't diverge across backends.
    let right_widths: f64 = bar
        .right_segments
        .iter()
        .map(|seg| measure_text(font, &seg.text).0)
        .sum();
    let effective_tab_area = (width - right_widths).max(0.0);
    let (sample_px, _) = measure_text(font, CELL_WIDTH_SAMPLE);
    let char_w = (sample_px / CELL_WIDTH_SAMPLE.chars().count() as f64).max(1.0);
    hits.available_cols = (effective_tab_area / char_w).floor().max(0.0) as usize;

    hits
}

/// Compute the [`TabBarLayout`] [`draw_tab_bar`] paints, without painting.
///
/// # This is the canonical composition — `mac_tab_bar_layout` derives from it
///
/// Every other backend derives its `TabBarHits` by calling
/// [`crate::TabBar::layout`] (the shared D6 layout API) and narrowing the
/// resulting `TabBarLayout` down via
/// [`crate::backend::tab_bar_hits_from_layout`]. macOS measures and
/// positions tabs by hand, one `f64` tuple at a time, but as of now
/// [`mac_tab_bar_layout_icons`] calls this function and narrows the result
/// via [`crate::backend::tab_bar_hits_from_layout`], the same pattern
/// `gtk`/`win` use.
///
/// # Coordinate space — bar-relative, matching `mac_tab_bar_layout`
///
/// Same x-axis convention as `mac_tab_bar_layout` (see its doc): macOS
/// paints tabs from `x = 0`, never shifted by `rect.x`, so both this
/// and that function are already bar-relative in x — no `TabBarHits`
/// absolute-coordinate divergence to account for. `height` (the caller's
/// `rect.height`) becomes every tab's `bounds.height`, and every
/// `bounds.y` is `0.0` — [`TabBarLayout`]'s own documented convention
/// (origin at the bar's top-left).
pub fn mac_tab_bar_native_layout(
    font: &CTFont,
    width: f64,
    height: f64,
    bar: &TabBar,
) -> TabBarLayout {
    mac_tab_bar_native_layout_icons(font, width, height, bar, &[])
}

/// [`mac_tab_bar_native_layout`] with a per-tab icon sidecar — the
/// `TabBarLayout`-returning twin of [`mac_tab_bar_layout_icons`], backing
/// [`crate::Backend::resolve_tab_bar_layout_icons`].
///
/// `icons` follows the same convention as [`mac_tab_bar_layout_icons`]'
/// (`&[]` reproduces the icon-less geometry point for point), and both
/// functions source their reservation from the same
/// [`mac_tab_icon_extras`] pass, so `native_layout_agrees_with_hits_layout`
/// keeps holding with icons present.
pub fn mac_tab_bar_native_layout_icons(
    font: &CTFont,
    width: f64,
    height: f64,
    bar: &TabBar,
    icons: &[Option<TabIcon>],
) -> TabBarLayout {
    let tab_pad = if bar.compact { 2.0 } else { TAB_PAD };
    let tab_inner_gap = if bar.compact { 4.0 } else { TAB_INNER_GAP };
    let tab_outer_gap = if bar.compact { 0.0 } else { TAB_OUTER_GAP };

    // ── Right-segment widths (reserved before tabs get their budget) ──
    let right_widths: Vec<f64> = bar
        .right_segments
        .iter()
        .map(|seg| measure_text(font, &seg.text).0)
        .collect();
    let reserved_px: f64 = right_widths.iter().sum();
    let effective_tab_area = (width - reserved_px).max(0.0);

    // Measure the codicon close glyph actually painted — `font`
    // already carries the bundled codicon cascade unconditionally
    // (`chrome_font` is wrapped via `font_with_builtin_fallback`), so
    // this resolves the real glyph's advance width.
    let close_w = if bar.show_tab_close {
        measure_text(font, &crate::codicon::CLOSE.to_string()).0
    } else {
        0.0
    };
    let close_extra_for = |tab_idx: usize| -> f64 {
        if bar.show_tab_close && bar.tabs[tab_idx].is_closable {
            tab_inner_gap + close_w
        } else {
            0.0
        }
    };

    // Icon-width pass — same call, same values as `mac_tab_bar_layout_icons`'.
    let icon_extras = mac_tab_icon_extras(font, bar.tabs.len(), icons);

    // Pre-measure every tab's full slot width — used for scroll-offset
    // resolution, exactly as `mac_tab_bar_layout` does.
    let tab_slot_widths: Vec<f64> = bar
        .tabs
        .iter()
        .enumerate()
        .map(|(i, tab)| {
            let (name_w, _) = measure_text(font, &tab.label);
            tab_pad + icon_extras[i] + name_w + close_extra_for(i) + tab_pad + tab_outer_gap
        })
        .collect();

    let active_idx = bar.tabs.iter().position(|t| t.is_active);
    let resolved_scroll_offset = if let Some(active) = active_idx {
        TabBar::fit_active_scroll_offset(active, bar.tabs.len(), effective_tab_area as usize, |i| {
            tab_slot_widths[i] as usize
        })
    } else {
        bar.scroll_offset
    };

    // ── Visible tabs ─────────────────────────────────────────────────
    // Painted from `bar.scroll_offset` (the caller's value), not the
    // freshly-resolved `resolved_scroll_offset` above — exactly what
    // `mac_tab_bar_layout` does: the "engine feedback" correction is
    // reported back for the *next* frame's caller to apply, not applied
    // to this one. Unlike `TabBarHits`, there is no `(0.0, 0.0)`
    // sentinel padding to keep vector indices aligned — `visible_tabs`
    // is sparse and carries its own `tab_idx`, matching every other
    // backend's `TabBarLayout`.
    let mut visible_tabs: Vec<VisibleTab> = Vec::new();
    let mut close_regions: Vec<(Rect, TabBarHit)> = Vec::new();
    let mut body_regions: Vec<(Rect, TabBarHit)> = Vec::new();

    let mut x = 0.0_f64;
    for (tab_idx, tab) in bar.tabs.iter().enumerate().skip(bar.scroll_offset) {
        let (tab_name_w, _) = measure_text(font, &tab.label);
        let icon_extra = icon_extras[tab_idx];
        let tab_content_w = tab_pad + icon_extra + tab_name_w + close_extra_for(tab_idx) + tab_pad;
        let slot_w = tab_content_w + tab_outer_gap;
        if x + slot_w > effective_tab_area {
            break;
        }
        let bounds = Rect::new(x as f32, 0.0, slot_w as f32, height as f32);

        let close_bounds = if bar.show_tab_close && tab.is_closable {
            let close_x = x + tab_pad + icon_extra + tab_name_w + tab_inner_gap;
            let cb = Rect::new(
                (close_x - CLOSE_PAD) as f32,
                0.0,
                (close_w + 2.0 * CLOSE_PAD) as f32,
                height as f32,
            );
            close_regions.push((cb, TabBarHit::TabClose(tab_idx)));
            Some(cb)
        } else {
            None
        };

        body_regions.push((bounds, TabBarHit::Tab(tab_idx)));
        visible_tabs.push(VisibleTab {
            tab_idx,
            bounds,
            close_bounds,
        });

        x += slot_w;
    }

    // Close regions before body regions — matches `TabBar::layout`'s own
    // hit-region ordering (close-before-body) so `hit_test` returns the
    // more-specific close hit when the pointer is on the × glyph.
    let mut hit_regions: Vec<(Rect, TabBarHit)> =
        Vec::with_capacity(close_regions.len() + body_regions.len());
    hit_regions.extend(close_regions);
    hit_regions.extend(body_regions);

    // ── Right segments ───────────────────────────────────────────────
    let mut visible_segments: Vec<VisibleSegment> = Vec::with_capacity(right_widths.len());
    let mut sx = width - reserved_px;
    for (segment_idx, seg_w) in right_widths.iter().enumerate() {
        let bounds = Rect::new(sx as f32, 0.0, *seg_w as f32, height as f32);
        let seg = &bar.right_segments[segment_idx];
        let clickable = seg.id.is_some();
        if let Some(id) = &seg.id {
            hit_regions.push((bounds, TabBarHit::RightSegment(*id)));
        }
        visible_segments.push(VisibleSegment {
            segment_idx,
            bounds,
            clickable,
        });
        sx += seg_w;
    }

    TabBarLayout {
        bar_width: width as f32,
        bar_height: height as f32,
        visible_tabs,
        visible_segments,
        scroll_left: None,
        scroll_right: None,
        hit_regions,
        resolved_scroll_offset,
    }
}

/// Paint `bar` into the rect `(0, y_offset, width, row_height)` on
/// `ctx`. `line_height` is the *text* line height; `row_height` may be
/// larger (callers pad file-tab bars). Returns per-tab + per-segment
/// hit bounds plus the resolved scroll offset.
///
/// # Safety
///
/// `ctx` must be a valid `CGContextRef` borrowed for the duration of
/// the call (typical: the frame-scope pointer stashed on
/// [`super::MacBackend`]). Calling with a freed or null pointer is UB.
#[allow(clippy::too_many_arguments)]
#[allow(deprecated)]
pub unsafe fn draw_tab_bar(
    ctx: CGContextRef,
    font: &CTFont,
    width: f64,
    line_height: f64,
    y_offset: f64,
    row_height: f64,
    bar: &TabBar,
    theme: &Theme,
    hovered_close_tab: Option<usize>,
) -> TabBarHits {
    draw_tab_bar_icons(
        ctx,
        font,
        width,
        line_height,
        y_offset,
        row_height,
        bar,
        theme,
        hovered_close_tab,
        &[],
    )
}

/// Resolve a [`TabBarGlyphs`] slot (the close or dirty override) to the
/// text this rasteriser paints via `draw_text`, falling back to `default`
/// when the slot is unset.
fn tab_glyph_text(
    icon: Option<&crate::types::Icon>,
    nerd_fonts_enabled: bool,
    default: char,
) -> String {
    icon.map(|icon| icon.resolve(nerd_fonts_enabled).to_string())
        .unwrap_or_else(|| default.to_string())
}

/// [`draw_tab_bar`] plus per-tab icon glyphs.
///
/// `icons` is a sidecar slice parallel to `bar.tabs` (see
/// [`crate::Backend::draw_tab_bar_icons`]) — entry `i` decorates tab `i`,
/// a `None` or missing entry means "no icon", and `&[]` reproduces
/// [`draw_tab_bar`] pixel for pixel. The glyph paints at the tab's leading
/// edge, just inside the tab padding, in its own [`TabIcon::color`] (an
/// icon keeps its language/identity colour rather than inheriting the
/// tab's active/inactive foreground, matching the TUI and GTK
/// rasterisers); the label and close glyph shift right by exactly the
/// width [`mac_tab_icon_extras`] reserved for it, which is why the
/// returned close-button hit boxes still land on the × the user sees.
///
/// # Coordinate space — paints bar-relative; caller supplies the origin
///
/// Like [`mac_tab_bar_layout_icons`] above, this paints into
/// `(0, y_offset, width, row_height)` in `ctx`'s *current* coordinate
/// space and returns bar-relative `TabBarHits`. It does not take an
/// `x_offset` — [`crate::macos::MacBackend::draw_tab_bar_icons`] instead
/// wraps this call in `CGContextTranslateCTM(ctx, rect.x, rect.y)` so the
/// ink lands at the bar's real screen position, and separately shifts the
/// returned hits by `rect.x` via [`crate::backend::shift_tab_bar_hits`] so
/// they still describe exactly what was painted. Mirrors
/// `MacBackend::draw_activity_bar`'s identical CTM-translate treatment of
/// the (also bar-relative) `super::activity_bar::draw_activity_bar`.
///
/// # Safety
///
/// `ctx` must be a valid `CGContextRef` borrowed for the duration of the
/// call (typical: the frame-scope pointer stashed on [`super::MacBackend`]).
/// Calling with a freed or null pointer is UB.
#[allow(clippy::too_many_arguments)]
#[allow(deprecated)]
pub unsafe fn draw_tab_bar_icons(
    ctx: CGContextRef,
    font: &CTFont,
    width: f64,
    line_height: f64,
    y_offset: f64,
    row_height: f64,
    bar: &TabBar,
    theme: &Theme,
    hovered_close_tab: Option<usize>,
    icons: &[Option<TabIcon>],
) -> TabBarHits {
    draw_tab_bar_icons_with_glyphs(
        ctx,
        font,
        width,
        line_height,
        y_offset,
        row_height,
        bar,
        theme,
        hovered_close_tab,
        icons,
        None,
        false,
    )
}

/// [`draw_tab_bar_icons`], but honouring an optional [`TabBarGlyphs`]
/// override for the close/dirty mark — `glyphs: None` reproduces
/// [`draw_tab_bar_icons`] exactly.
///
/// # Safety
///
/// `ctx` must be a valid `CGContextRef` borrowed for the duration of the
/// call (typical: the frame-scope pointer stashed on [`super::MacBackend`]).
/// Calling with a freed or null pointer is UB.
#[allow(clippy::too_many_arguments)]
#[allow(deprecated)]
pub unsafe fn draw_tab_bar_icons_with_glyphs(
    ctx: CGContextRef,
    font: &CTFont,
    width: f64,
    line_height: f64,
    y_offset: f64,
    row_height: f64,
    bar: &TabBar,
    theme: &Theme,
    hovered_close_tab: Option<usize>,
    icons: &[Option<TabIcon>],
    glyphs: Option<&TabBarGlyphs>,
    nerd_fonts_enabled: bool,
) -> TabBarHits {
    let text_y_offset = y_offset + (row_height - line_height) / 2.0;
    let tab_pad = if bar.compact { 2.0 } else { TAB_PAD };
    let tab_outer_gap = if bar.compact { 0.0 } else { TAB_OUTER_GAP };

    // Single source of truth for geometry — `Backend::tab_bar_layout_icons`
    // calls the same function with the same sidecar, so the no-paint twin
    // can never drift from what this loop actually paints.
    let hits = mac_tab_bar_layout_icons(font, width, bar, icons);
    // Re-derived rather than threaded out of `mac_tab_bar_layout_icons`:
    // the same pure function of (font, icons), so the label x below is
    // offset by exactly the width the hit boxes were built around.
    let icon_extras = mac_tab_icon_extras(font, bar.tabs.len(), icons);

    CGContextSaveGState(ctx);

    // Tab-bar background.
    fill_rect(ctx, 0.0, y_offset, width, row_height, theme.tab_bar_bg);

    // The active tab's chip is inset from the row by `TAB_CHIP_INSET_Y`
    // on top and bottom — VS Code's pill, not a square block filling the
    // row edge to edge. That fixed inset is only safe when the row has
    // slack beyond the label's own line height; `text_y_offset` above
    // centers the label within the *row*, so a row barely taller than
    // `line_height` (a caller that reuses its editor line height as the
    // tab bar's row height, e.g. `tui_tab_icons`/`macos_tab_icons`'s
    // `backend.line_height()`) leaves less than `TAB_CHIP_INSET_Y` of
    // slack per side above and below the label text — not enough for the
    // fixed inset, so the chip would paint narrower than the label and a
    // descender like "Cargo.toml"'s "g" would ink past the chip's edge.
    // Shrinking the inset (down to 0, at the limit) whenever the row is
    // that tight keeps the chip at least `line_height` tall, which is
    // exactly the height `text_y_offset` already centers the label
    // within — so the chip encloses the label whenever the row is tall
    // enough to hold the label at all.
    let max_chip_inset_y = ((row_height - line_height) / 2.0).max(0.0);
    let chip_inset_y = TAB_CHIP_INSET_Y.min(max_chip_inset_y);
    let chip_y = y_offset + chip_inset_y;
    let chip_h = (row_height - 2.0 * chip_inset_y).max(0.0);

    // ── Tabs paint loop ──────────────────────────────────────────────
    // `slot_positions` is padded with `(0.0, 0.0)` for the scrolled-past
    // tabs, so start after them and stop where the layout stopped.
    for (tab_idx, tab) in bar
        .tabs
        .iter()
        .enumerate()
        .skip(bar.scroll_offset)
        .take(hits.slot_positions.len().saturating_sub(bar.scroll_offset))
    {
        let (slot_x, slot_end) = hits.slot_positions[tab_idx];
        let tab_content_w = slot_end - slot_x - tab_outer_gap;

        // Tab background. The active tab paints the inset, rounded chip
        // computed above (VS Code's pill, matching `gtk::tab_bar`'s
        // `TAB_CHIP_INSET_Y` / `TAB_CHIP_RADIUS` — the same active-tab
        // shape on both pixel backends) rather than a square block
        // filling the full row height edge to edge. Inactive tabs are
        // unchanged: a full-height rectangle in the bar's own
        // background colour.
        if tab.is_active {
            // SAFETY: `ctx` is a valid `CGContextRef` for the duration of
            // this paint call — see this fn's own `# Safety` doc.
            unsafe {
                ns_fill_rounded_rect(
                    ctx,
                    Rect::new(
                        slot_x as f32,
                        chip_y as f32,
                        tab_content_w as f32,
                        chip_h as f32,
                    ),
                    TAB_CHIP_RADIUS as f32,
                    theme.tab_active_bg,
                );
            }
        } else {
            fill_rect(
                ctx,
                slot_x,
                y_offset,
                tab_content_w,
                row_height,
                theme.tab_bar_bg,
            );
        }

        // Top accent line for the active tab, painted on the chip's own
        // inset top edge rather than the strip's top edge, so it stays
        // attached to the pill instead of floating above it.
        if tab.is_active {
            if let Some(accent) = bar.active_accent {
                fill_rect(ctx, slot_x, chip_y, tab_content_w, ACCENT_HEIGHT, accent);
            }
        }

        // Icon glyph, at the tab's leading edge in its own colour.
        // `icon_extras[tab_idx]` is the glyph's measured width plus
        // `TAB_ICON_GAP`, so the label below starts one gap past the ink.
        let icon_extra = icon_extras[tab_idx];
        if let Some(icon) = tab_icon_at(icons, tab_idx) {
            draw_text(
                ctx,
                font,
                &icon.glyph,
                slot_x + tab_pad,
                text_y_offset,
                color_to_cg(icon.color),
            );
        }

        // Tab label.
        let fg_col = match (tab.is_active, tab.is_preview) {
            (true, true) => theme.tab_preview_active_fg,
            (true, false) => theme.tab_active_fg,
            (false, true) => theme.tab_preview_inactive_fg,
            (false, false) => theme.tab_inactive_fg,
        };
        draw_text(
            ctx,
            font,
            &tab.label,
            slot_x + tab_pad + icon_extra,
            text_y_offset,
            color_to_cg(fg_col),
        );

        // Close glyph (× or ● for dirty), tinted on hover. Painted at the
        // exact x the hit box was built around, so a click that lands in
        // `close_bounds` lands on the glyph the user saw.
        if let Some((close_lo, _)) = hits.close_bounds[tab_idx] {
            let close_x = close_lo + CLOSE_PAD;
            let is_close_hovered = hovered_close_tab == Some(tab_idx);
            // Codicon glyphs by default, painted through the same `font`
            // the label/icon above already use, since
            // `MacBackend::set_chrome_font` wraps it with the bundled
            // codicon cascade unconditionally (see
            // `font_with_builtin_fallback`'s doc). An app-supplied
            // `glyphs` override replaces either mark.
            let close_glyph = if tab.is_dirty && !is_close_hovered {
                tab_glyph_text(
                    glyphs.and_then(TabBarGlyphs::dirty_glyph),
                    nerd_fonts_enabled,
                    crate::codicon::DIRTY,
                )
            } else {
                tab_glyph_text(
                    glyphs.and_then(TabBarGlyphs::close_glyph),
                    nerd_fonts_enabled,
                    crate::codicon::CLOSE,
                )
            };
            let close_fg = if tab.is_dirty || is_close_hovered {
                theme.foreground
            } else if tab.is_active {
                theme.tab_inactive_fg
            } else {
                theme.separator
            };
            draw_text(
                ctx,
                font,
                &close_glyph,
                close_x,
                text_y_offset,
                color_to_cg(close_fg),
            );
        }
    }

    // ── Right segments paint loop ────────────────────────────────────
    for (i, seg) in bar.right_segments.iter().enumerate() {
        let (sx, _) = hits.right_segment_bounds[i];
        let fg_col = if seg.is_active {
            theme.tab_active_fg
        } else {
            theme.tab_inactive_fg
        };
        draw_text(ctx, font, &seg.text, sx, text_y_offset, color_to_cg(fg_col));
    }

    CGContextRestoreGState(ctx);

    hits
}

#[cfg(test)]
mod tests {
    use super::super::headless::BitmapSurface;
    use super::super::text::make_font;
    use super::super::MacBackend;
    use super::*;
    use crate::event::{Rect as QRect, Viewport};
    use crate::primitives::tab_bar::{TabBar, TabBarSegment, TabIcon, TabItem};
    use crate::theme::Theme;
    use crate::types::{Color, WidgetId};
    use crate::Backend;

    const W: u32 = 480;
    const H: u32 = 28;
    const FONT_SIZE: f64 = 14.0;

    fn font() -> CTFont {
        make_font("Menlo", FONT_SIZE).expect("Menlo installed")
    }

    /// A backend whose *editor* and *chrome* fonts are both this module's
    /// `font()`.
    ///
    /// The tab bar now uses the chrome font (`ChromePrimitive::TabBar`):
    /// `draw_tab_bar`/`draw_tab_bar_icons` and their no-paint `tab_bar_layout*`
    /// twins now measure and paint through `MacBackend::chrome_font`, which
    /// `MacBackend::new` seeds with the ~11pt **system UI** font. A harness
    /// that set only the editor font would therefore paint at a size no
    /// assertion here knows about, while the `mac_tab_bar_layout*`/
    /// `mac_tab_icon_extras` expectations several tests compute directly
    /// still used `font()` — the two would disagree about every slot boundary
    /// and glyph position. Setting both keeps every assertion in this module
    /// about tab-bar geometry at a known `FONT_SIZE`, rather than about
    /// whichever metrics the system UI font happens to have on the running host.
    fn backend_with_test_fonts() -> MacBackend {
        let mut backend = MacBackend::new();
        backend.set_current_font(font());
        backend.set_chrome_font(font());
        backend
    }

    fn sample_bar() -> TabBar {
        TabBar {
            id: WidgetId::new("tabs"),
            tabs: vec![
                TabItem {
                    label: "main.rs".into(),
                    is_active: true,
                    is_dirty: false,
                    is_preview: false,
                    is_closable: true,
                },
                TabItem {
                    label: "lib.rs".into(),
                    is_active: false,
                    is_dirty: true,
                    is_preview: false,
                    is_closable: true,
                },
            ],
            scroll_offset: 0,
            right_segments: vec![],
            active_accent: Some(Color::rgb(80, 140, 255)),
            show_tab_close: true,
            compact: false,
        }
    }

    /// Drive a paint through the full `MacBackend::draw_tab_bar` path
    /// and return `(surface, hits)` for inspection. Mirrors the
    /// status_bar harness so future chrome tests follow the same
    /// shape.
    #[allow(deprecated)]
    fn paint_via_backend(
        bar: &TabBar,
        hovered_close: Option<usize>,
    ) -> (BitmapSurface, TabBarHits) {
        let surface = BitmapSurface::new(W, H);
        surface.fill(0.0, 0.0, 0.0, 0.0);

        let mut backend = backend_with_test_fonts();
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        let hits = std::cell::RefCell::new(None);
        backend.enter_frame_scope(surface.context_ptr(), |b| {
            let h = b.draw_tab_bar(QRect::new(0.0, 0.0, W as f32, H as f32), bar, hovered_close);
            *hits.borrow_mut() = Some(h);
        });
        backend.end_frame();
        (surface, hits.into_inner().unwrap())
    }

    #[test]
    #[allow(deprecated)]
    fn active_tab_paints_active_bg() {
        // The active tab's bg differs from `tab_bar_bg`. Probe the
        // vertical middle of the row, past the leading padding — safely
        // inside the inset chip regardless of `TAB_CHIP_INSET_Y`'s exact
        // value, unlike a bottom-edge probe, which the inset excludes.
        let bar = sample_bar();
        let (surface, hits) = paint_via_backend(&bar, None);
        let theme = Theme::default();

        let (start, end) = hits.slot_positions[0];
        assert!(end > start, "active tab slot must have non-zero width");

        let probe_x = (start + 2.0) as u32;
        let probe_y = H / 2;
        let (r, g, b, _) = surface.pixel(probe_x, probe_y);
        let expected = theme.tab_active_bg;
        assert_eq!(
            (r, g, b),
            (expected.r, expected.g, expected.b),
            "active tab bg at ({}, {}) should be tab_active_bg",
            probe_x,
            probe_y,
        );
    }

    /// The active tab's chip is inset by `TAB_CHIP_INSET_Y` from
    /// both the top and bottom of the row — matching
    /// `gtk::tab_bar::active_chip_inset_is_symmetric_around_a_nonzero_y_offset`'s
    /// GTK twin. The very top and bottom scanlines of the row must *not*
    /// be the active fill (a square, edge-to-edge chip would paint them).
    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits`
    fn active_chip_is_inset_from_top_and_bottom_of_the_row() {
        let bar = sample_bar();
        let (surface, hits) = paint_via_backend(&bar, None);
        let theme = Theme::default();
        let active_bg = theme.tab_active_bg;

        let (start, _) = hits.slot_positions[0];
        // Past the left padding and inset radius, so corner rounding
        // doesn't also explain a non-active-bg top/bottom pixel.
        let probe_x = (start + TAB_CHIP_RADIUS + 4.0) as u32;

        let is_active = |y: u32| {
            let (r, g, b, _) = surface.pixel(probe_x, y);
            (r, g, b) == (active_bg.r, active_bg.g, active_bg.b)
        };
        assert!(
            !is_active(0),
            "top scanline of the row must be outside the inset chip"
        );
        assert!(
            !is_active(H - 1),
            "bottom scanline of the row must be outside the inset chip"
        );
        // But somewhere in the middle, the chip must actually paint.
        assert!(
            is_active(H / 2),
            "chip must paint the active fill in the middle of the row"
        );
    }

    /// The active-tab chip is *rounded*, not just inset — mirrors
    /// `gtk::tab_bar::active_chip_corners_are_bar_background_not_active_fill`.
    /// `active_chip_is_inset_from_top_and_bottom_of_the_row` above only
    /// probes a point well clear of the corners (`TAB_CHIP_RADIUS + 4.0`
    /// in from the left edge), so a regression that swapped
    /// `ns_fill_rounded_rect` for a plain rectangular fill at the same
    /// inset would still pass it. Probe all four corners of the chip's
    /// bounding rect instead: a rounded corner leaves them painted the
    /// bar background, not the active fill.
    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits`
    fn active_chip_corners_are_bar_background_not_active_fill() {
        // No `active_accent` here, unlike `sample_bar()` — the accent
        // strip paints the chip's full inset top edge including its top
        // corners (square "ears" over the rounded chip, same as
        // `gtk::tab_bar`), which would otherwise overwrite exactly the
        // pixels this test probes with the accent colour instead of the
        // bar background it's checking for.
        let mut bar = sample_bar();
        bar.active_accent = None;
        let (surface, hits) = paint_via_backend(&bar, None);
        let theme = Theme::default();
        let bar_bg = theme.tab_bar_bg;

        let (slot_x, slot_end) = hits.slot_positions[0];
        let tab_content_w = slot_end - slot_x - TAB_OUTER_GAP;
        let chip_x0 = slot_x as u32;
        let chip_x1 = (slot_x + tab_content_w) as u32 - 1;
        let chip_y0 = TAB_CHIP_INSET_Y as u32;
        let chip_y1 = H - TAB_CHIP_INSET_Y as u32 - 1;

        for (x, y) in [
            (chip_x0, chip_y0),
            (chip_x1, chip_y0),
            (chip_x0, chip_y1),
            (chip_x1, chip_y1),
        ] {
            let (r, g, b, _) = surface.pixel(x, y);
            assert_eq!(
                (r, g, b),
                (bar_bg.r, bar_bg.g, bar_bg.b),
                "chip bounding-rect corner ({x},{y}) should be bar background \
                 (rounded off by TAB_CHIP_RADIUS), not the active fill",
            );
        }
    }

    #[test]
    #[allow(deprecated)]
    fn active_accent_paints_at_top_of_active_tab_chip() {
        // The accent strip paints on the chip's own inset top edge,
        // mirroring `gtk::tab_bar`'s treatment, rather than the strip's
        // top edge — so it stays attached to the pill.
        let bar = sample_bar();
        let (surface, hits) = paint_via_backend(&bar, None);

        let (start, _) = hits.slot_positions[0];
        // Past leading padding so we don't overlap the second tab.
        let probe_x = (start + 4.0) as u32;
        let probe_y = TAB_CHIP_INSET_Y as u32;
        let (r, g, b, _) = surface.pixel(probe_x, probe_y);
        let accent = bar.active_accent.unwrap();
        assert_eq!(
            (r, g, b),
            (accent.r, accent.g, accent.b),
            "accent strip at the chip's inset top edge should match TabBar.active_accent",
        );

        // The strip's own top edge (y=0, above the inset) must not be
        // the accent colour — otherwise this would pass even if the
        // accent painted at the old, non-inset position.
        let (r0, g0, b0, _) = surface.pixel(probe_x, 0);
        assert_ne!(
            (r0, g0, b0),
            (accent.r, accent.g, accent.b),
            "accent strip must not paint at the strip's own top edge once inset"
        );
    }

    #[test]
    #[allow(deprecated)]
    fn close_bounds_round_trip_via_hits_struct() {
        // Round-trip: paint, then sample a coordinate inside the
        // reported close-bounds and assert the hits struct's bounds
        // contain it. This is the "paint and click agree on close
        // button location" gate.
        let bar = sample_bar();
        let (_surface, hits) = paint_via_backend(&bar, None);

        let close = hits.close_bounds[0].expect("active tab has close bounds");
        let mid_x = (close.0 + close.1) / 2.0;
        assert!(
            mid_x >= close.0 && mid_x < close.1,
            "midpoint must be inside close bounds [{}, {})",
            close.0,
            close.1,
        );
        // The reported bounds must sit inside the tab slot — a paint
        // shift on the close glyph would land outside the slot and
        // catch the drift here.
        let (slot_start, slot_end) = hits.slot_positions[0];
        assert!(
            close.0 >= slot_start && close.1 <= slot_end,
            "close bounds [{}, {}) must be inside tab slot [{}, {})",
            close.0,
            close.1,
            slot_start,
            slot_end,
        );
    }

    #[test]
    #[allow(deprecated)]
    fn dirty_tab_uses_filled_circle_glyph() {
        // `is_dirty` swaps the close glyph for a codicon filled circle
        // (`crate::codicon::DIRTY`). We can't easily compare glyph
        // shape pixel-by-pixel, but a row-wise ink ratio differs
        // noticeably: a filled circle is mostly filled, the codicon
        // close mark (`crate::codicon::CLOSE`) is thin strokes.
        // Compare the dirty tab's close column against the active
        // tab's: dirty should be visibly denser.
        let bar = sample_bar();
        let (surface, hits) = paint_via_backend(&bar, None);

        let active_close = hits.close_bounds[0].unwrap();
        let dirty_close = hits.close_bounds[1].unwrap();

        // Count non-bg pixels in a 1-column `[y0, y1)` strip for each
        // close glyph. The dirty (filled circle) column should have more
        // inked pixels than the close-mark column.
        fn ink_density(surface: &BitmapSurface, x: u32, y0: u32, y1: u32, bg: Color) -> u32 {
            (y0..y1)
                .filter(|&y| {
                    let (r, g, b, _) = surface.pixel(x, y);
                    !(r == bg.r && g == bg.g && b == bg.b)
                })
                .count() as u32
        }
        let theme = Theme::default();
        // The active tab's close glyph sits over the inset chip, so only
        // its `[chip_y, chip_y + chip_h)` band is actually painted
        // `tab_active_bg` — the inset margin above/below it is
        // `tab_bar_bg` and would otherwise be miscounted as glyph ink.
        let chip_y0 = TAB_CHIP_INSET_Y as u32;
        let chip_y1 = H - TAB_CHIP_INSET_Y as u32;
        let active_ink = ink_density(
            &surface,
            ((active_close.0 + active_close.1) / 2.0) as u32,
            chip_y0,
            chip_y1,
            theme.tab_active_bg,
        );
        // Same `[chip_y0, chip_y1)` band as `active_ink` — scanning both
        // columns over the same window keeps the comparison about glyph
        // shape, not about one column getting a taller scan range than
        // the other.
        let dirty_ink = ink_density(
            &surface,
            ((dirty_close.0 + dirty_close.1) / 2.0) as u32,
            chip_y0,
            chip_y1,
            theme.tab_bar_bg,
        );
        assert!(
            dirty_ink > active_ink,
            "dirty glyph should ink more rows ({}) than the active close glyph ({})",
            dirty_ink,
            active_ink,
        );
    }

    #[test]
    #[allow(deprecated)]
    fn non_closable_tab_has_no_close_bounds_even_when_bar_show_close_is_true() {
        // Regression: `bar.show_tab_close = true` is a bar-level flag, but
        // individual tabs may opt out via `is_closable = false`. The macOS
        // rasteriser must consult both — otherwise non-closable tabs render
        // a phantom × that triggers no action when clicked.
        // Use identical labels so the *only* width difference between the
        // two slots is the close-glyph reservation, isolating the regression.
        let bar = TabBar {
            id: WidgetId::new("tabs"),
            tabs: vec![
                TabItem {
                    label: "tab.rs".into(),
                    is_active: true,
                    is_dirty: false,
                    is_preview: false,
                    is_closable: true,
                },
                TabItem {
                    label: "tab.rs".into(),
                    is_active: false,
                    is_dirty: false,
                    is_preview: false,
                    is_closable: false,
                },
            ],
            scroll_offset: 0,
            right_segments: vec![],
            active_accent: None,
            show_tab_close: true,
            compact: false,
        };
        let (_surface, hits) = paint_via_backend(&bar, None);
        assert!(
            hits.close_bounds[0].is_some(),
            "closable tab must have close bounds",
        );
        assert!(
            hits.close_bounds[1].is_none(),
            "non-closable tab must have no close bounds even when bar.show_tab_close is true",
        );
        // The non-closable tab's slot must also be narrower (no close-glyph
        // reservation), so the two slot widths differ in proportion to the
        // close glyph + inner gap.
        let (s0, e0) = hits.slot_positions[0];
        let (s1, e1) = hits.slot_positions[1];
        let closable_slot = e0 - s0;
        let pinned_slot = e1 - s1;
        assert!(
            closable_slot > pinned_slot,
            "closable tab slot ({closable_slot}) should reserve more width than pinned slot ({pinned_slot})",
        );
    }

    #[test]
    #[allow(deprecated)]
    fn empty_bar_paints_only_tab_bar_bg() {
        let bar = TabBar {
            id: WidgetId::new("empty"),
            tabs: vec![],
            scroll_offset: 0,
            right_segments: vec![],
            active_accent: None,
            show_tab_close: true,
            compact: false,
        };
        let (surface, hits) = paint_via_backend(&bar, None);
        let theme = Theme::default();

        // Whole row should be tab_bar_bg.
        let (r, g, b, _) = surface.pixel(W / 2, H / 2);
        assert_eq!(
            (r, g, b),
            (theme.tab_bar_bg.r, theme.tab_bar_bg.g, theme.tab_bar_bg.b)
        );
        assert!(hits.slot_positions.is_empty());
        assert!(hits.close_bounds.is_empty());
    }

    /// `Backend::tab_bar_layout` must return exactly what
    /// `draw_tab_bar` painted — both route through `mac_tab_bar_layout`,
    /// and this pins that. See that function's docs for
    /// the known bar-relative-vs-absolute divergence; what is
    /// guaranteed here is that layout == paint.
    #[test]
    #[allow(deprecated)]
    fn layout_twin_matches_the_painted_hits() {
        let bar = sample_bar();
        let (_surface, painted) = paint_via_backend(&bar, None);

        let backend = backend_with_test_fonts();
        let computed = backend.tab_bar_layout(QRect::new(0.0, 0.0, W as f32, H as f32), &bar);

        assert_eq!(painted.slot_positions, computed.slot_positions);
        assert_eq!(painted.close_bounds, computed.close_bounds);
        assert_eq!(painted.right_segment_bounds, computed.right_segment_bounds);
        assert_eq!(painted.available_cols, computed.available_cols);
        assert_eq!(
            painted.correct_scroll_offset,
            computed.correct_scroll_offset
        );
    }

    /// `mac_tab_bar_native_layout` — the `TabBarLayout`-returning function
    /// backing `Backend::resolve_tab_bar_layout` — must report exactly the
    /// same geometry `mac_tab_bar_layout` (the deprecated `TabBarHits`-returning
    /// one) does, since the two duplicate rather than share their measurement
    /// code. Converting the new function's `TabBarLayout` through the shared
    /// `tab_bar_hits_from_layout` helper and comparing field-by-field against
    /// the old function's direct output pins the two together.
    #[test]
    #[allow(deprecated)]
    fn native_layout_agrees_with_hits_layout() {
        let bar = sample_bar();
        let f = font();

        let hits = mac_tab_bar_layout(&f, W as f64, &bar);
        let native = mac_tab_bar_native_layout(&f, W as f64, H as f64, &bar);
        let native_as_hits = crate::backend::tab_bar_hits_from_layout(&native, &bar);

        assert_eq!(
            hits.slot_positions, native_as_hits.slot_positions,
            "tab slots must agree between the two independently-computed layouts"
        );
        assert_eq!(
            hits.close_bounds, native_as_hits.close_bounds,
            "close-button spans must agree too"
        );
        assert_eq!(
            hits.right_segment_bounds, native_as_hits.right_segment_bounds,
            "right-segment spans must agree too"
        );
        assert_eq!(
            hits.correct_scroll_offset, native.resolved_scroll_offset,
            "the \"fit active tab\" scroll correction must agree"
        );
    }

    /// A click at the centre of a reported close box lands on the close
    /// glyph the rasteriser actually drew — the paint↔click round trip
    /// the shared `mac_tab_bar_layout` exists to guarantee.
    #[test]
    #[allow(deprecated)]
    fn close_box_centre_is_where_the_glyph_was_painted() {
        let bar = sample_bar();
        let (surface, hits) = paint_via_backend(&bar, None);
        let theme = Theme::default();
        let (lo, hi) = hits.close_bounds[0].expect("tab 0 is closable");
        let bg = theme.tab_active_bg;
        // Tab 0 is active, so its close glyph sits over the inset chip
        // — restrict the scan to the chip's own vertical band. Outside
        // it the row is `tab_bar_bg` by design, which would
        // otherwise register as "inked" against `tab_active_bg` even
        // with no glyph drawn there, making this assertion pass
        // vacuously instead of actually proving the glyph painted.
        let chip_y0 = TAB_CHIP_INSET_Y as u32;
        let chip_y1 = H - TAB_CHIP_INSET_Y as u32;

        // Somewhere in the close box's x-span, some row differs from the
        // tab background: that is the glyph.
        let inked = (lo.ceil() as u32..hi.floor() as u32).any(|x| {
            (chip_y0..chip_y1).any(|y| {
                let (r, g, b, _) = surface.pixel(x.min(W - 1), y);
                (r, g, b) != (bg.r, bg.g, bg.b)
            })
        });
        assert!(
            inked,
            "close box [{lo}, {hi}] contains no painted glyph — hits and paint have drifted",
        );
    }

    /// A helper for icon tests: drive a paint through the full
    /// `MacBackend::draw_tab_bar_icons` path with a real sidecar and return
    /// `(surface, hits)`. Deliberately the icon-carrying twin of
    /// [`paint_via_backend`], so a test can compare the two outputs and
    /// attribute every delta to the icon reservation.
    #[allow(deprecated)]
    fn paint_icons_via_backend(
        bar: &TabBar,
        icons: &[Option<TabIcon>],
        hovered_close: Option<usize>,
    ) -> (BitmapSurface, TabBarHits) {
        let surface = BitmapSurface::new(W, H);
        surface.fill(0.0, 0.0, 0.0, 0.0);

        let mut backend = backend_with_test_fonts();
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        let hits = std::cell::RefCell::new(None);
        backend.enter_frame_scope(surface.context_ptr(), |b| {
            let h = b.draw_tab_bar_icons(
                QRect::new(0.0, 0.0, W as f32, H as f32),
                bar,
                icons,
                hovered_close,
            );
            *hits.borrow_mut() = Some(h);
        });
        backend.end_frame();
        (surface, hits.into_inner().unwrap())
    }

    /// An ASCII icon on tab 0 only. ASCII on purpose — a Nerd Font
    /// codepoint measures as tofu (or nothing) under Menlo, which would
    /// make `icon_extra` uninformative; `examples/common/tab_icons_demo.rs`
    /// makes the same choice for the same reason. Tab 1 is left `None` so
    /// every test below also covers the mixed-sidecar case: a decorated
    /// tab must not change an undecorated one's *width*, only its origin.
    fn sample_icons() -> Vec<Option<TabIcon>> {
        vec![
            Some(TabIcon {
                glyph: "R".into(),
                color: Color::rgb(220, 120, 60),
            }),
            None,
        ]
    }

    /// `draw_tab_bar_icons` with a non-empty icon sidecar must not abort;
    /// reaching the assertions below at all is that regression test. The width
    /// assertions pin that the sidecar actually does something: the decorated
    /// tab is wider than its icon-less self.
    #[test]
    #[allow(deprecated)]
    fn draw_tab_bar_icons_with_non_empty_sidecar_does_not_abort() {
        let bar = sample_bar();
        let icons = sample_icons();

        let (_surface, hits) = paint_icons_via_backend(&bar, &icons, None);
        let (_icon_less_surface, icon_less_hits) = paint_via_backend(&bar, None);

        // The decorated tab is wider than its icon-less self by
        // exactly the CoreText-measured glyph width plus `TAB_ICON_GAP`.
        let expected_extra = mac_tab_icon_extras(&font(), bar.tabs.len(), &icons)[0];
        assert!(
            expected_extra > TAB_ICON_GAP,
            "an ASCII icon glyph must measure non-zero under Menlo (got \
             {expected_extra} including a {TAB_ICON_GAP}pt gap)",
        );
        let (lo, hi) = hits.slot_positions[0];
        let (plain_lo, plain_hi) = icon_less_hits.slot_positions[0];
        assert_eq!(lo, plain_lo, "the first tab still starts at the bar origin");
        assert!(
            ((hi - lo) - ((plain_hi - plain_lo) + expected_extra)).abs() < 0.01,
            "decorated slot width {} should be the icon-less width {} plus the \
             reservation {expected_extra}",
            hi - lo,
            plain_hi - plain_lo,
        );

        // Tab 1 carries no icon, so its own width is unchanged — it is
        // only pushed right by tab 0's reservation.
        let (t1_lo, t1_hi) = hits.slot_positions[1];
        let (p1_lo, p1_hi) = icon_less_hits.slot_positions[1];
        assert!(
            ((t1_hi - t1_lo) - (p1_hi - p1_lo)).abs() < 0.01,
            "an undecorated tab must keep its icon-less width",
        );
        assert!(
            ((t1_lo - p1_lo) - expected_extra).abs() < 0.01,
            "an undecorated tab shifts right by exactly the preceding tab's \
             icon reservation",
        );
    }

    /// The layout-only twins (`draw_tab_bar_icons_layout`, `tab_bar_layout_icons`,
    /// `resolve_tab_bar_layout_icons`) must not abort, and all four must agree
    /// with the *painted* geometry once a sidecar is present, not merely with
    /// each other.
    #[test]
    #[allow(deprecated)]
    fn layout_only_icon_twins_agree_with_the_icon_paint() {
        let bar = sample_bar();
        let icons = sample_icons();
        let rect = QRect::new(0.0, 0.0, W as f32, H as f32);
        let (_surface, painted) = paint_icons_via_backend(&bar, &icons, None);

        let mut backend = backend_with_test_fonts();

        // `tab_bar_layout_icons` is the no-paint twin: it must report
        // exactly what `draw_tab_bar_icons` painted (the load-bearing
        // macOS invariant), and must differ from the icon-less twin.
        let icon_hits = backend.tab_bar_layout_icons(rect, &bar, &icons);
        assert_eq!(icon_hits.slot_positions, painted.slot_positions);
        assert_eq!(icon_hits.close_bounds, painted.close_bounds);
        let plain_hits = backend.tab_bar_layout(rect, &bar);
        assert_ne!(
            icon_hits.slot_positions, plain_hits.slot_positions,
            "#926: a non-empty sidecar must change the reported geometry",
        );

        // `resolve_tab_bar_layout_icons` is the `TabBarLayout` spelling of
        // the same measurement — independently computed (see
        // `mac_tab_bar_native_layout_icons`' doc), so pin it against the
        // painted hits through the shared converter.
        let icon_layout = backend.resolve_tab_bar_layout_icons(rect, &bar, &icons);
        let as_hits = crate::backend::tab_bar_hits_from_layout(&icon_layout, &bar);
        assert_eq!(
            as_hits.slot_positions, painted.slot_positions,
            "the two independently-computed icon layouts must agree",
        );
        assert_eq!(as_hits.close_bounds, painted.close_bounds);

        // And the painting `TabBarLayout` variant must match it too.
        let surface = BitmapSurface::new(W, H);
        surface.fill(0.0, 0.0, 0.0, 0.0);
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        let drawn = std::cell::RefCell::new(None);
        backend.enter_frame_scope(surface.context_ptr(), |b| {
            *drawn.borrow_mut() = Some(b.draw_tab_bar_icons_layout(rect, &bar, &icons, None));
        });
        backend.end_frame();
        assert_eq!(
            drawn.into_inner().unwrap().visible_tabs,
            icon_layout.visible_tabs,
        );
    }

    /// With an icon present, a click at the centre of the reported close box
    /// still lands on the `×` the rasteriser drew. This is precisely what a
    /// *paint-only* icon fix would break — the glyph shifts right while the hit
    /// box stays put — and why the reservation has to live in the shared
    /// measurement pass.
    #[test]
    #[allow(deprecated)]
    fn close_box_still_lands_on_the_close_glyph_with_an_icon_present() {
        let bar = sample_bar();
        let icons = sample_icons();
        let (surface, hits) = paint_icons_via_backend(&bar, &icons, None);
        let (_plain_surface, plain_hits) = paint_via_backend(&bar, None);
        let theme = Theme::default();

        let (lo, hi) = hits.close_bounds[0].expect("tab 0 is closable");
        let (plain_lo, _) = plain_hits.close_bounds[0].expect("tab 0 is closable");
        assert!(
            lo > plain_lo,
            "the icon must push the close box right (icon {lo} vs icon-less {plain_lo})",
        );

        // The close box must still sit inside its own slot…
        let (slot_lo, slot_hi) = hits.slot_positions[0];
        assert!(
            lo >= slot_lo && hi <= slot_hi,
            "close box [{lo}, {hi}) must stay inside tab slot [{slot_lo}, {slot_hi})",
        );

        // …and there must be ink in it: the `×` the user clicks. Tab 0 is
        // active, so restrict the scan to the inset chip's own vertical
        // band — outside it the row is `tab_bar_bg` by design, which
        // would otherwise register as "inked" against `tab_active_bg`
        // with no glyph drawn there at all.
        let bg = theme.tab_active_bg;
        let chip_y0 = TAB_CHIP_INSET_Y as u32;
        let chip_y1 = H - TAB_CHIP_INSET_Y as u32;
        let inked = (lo.ceil() as u32..hi.floor() as u32).any(|x| {
            (chip_y0..chip_y1).any(|y| {
                let (r, g, b, _) = surface.pixel(x.min(W - 1), y);
                (r, g, b) != (bg.r, bg.g, bg.b)
            })
        });
        assert!(
            inked,
            "close box [{lo}, {hi}) contains no painted glyph — the icon \
             reservation moved the hit box off the × it draws",
        );
    }

    /// The icon glyph paints at the tab's leading edge, ahead of the label, in
    /// its own [`TabIcon::color`] rather than the tab foreground — the
    /// "identity colour survives an inactive tab" half of the `TabIcon`
    /// contract the TUI and GTK rasterisers already honour.
    #[test]
    #[allow(deprecated)]
    fn icon_glyph_paints_before_the_label_in_its_own_colour() {
        let bar = sample_bar();
        let icons = sample_icons();
        let icon_color = icons[0].as_ref().unwrap().color;
        let (surface, hits) = paint_icons_via_backend(&bar, &icons, None);

        let (slot_lo, _) = hits.slot_positions[0];
        let icon_extra = mac_tab_icon_extras(&font(), bar.tabs.len(), &icons)[0];
        // The glyph occupies `[slot_lo + TAB_PAD, slot_lo + TAB_PAD +
        // icon_extra - TAB_ICON_GAP)`; the gap after it is bare
        // background, which is what separates icon ink from label ink.
        let glyph_lo = slot_lo + TAB_PAD;
        let glyph_hi = glyph_lo + icon_extra - TAB_ICON_GAP;
        assert!(glyph_hi > glyph_lo, "icon span must be non-empty");

        // Some pixel in the glyph span leans towards the icon colour.
        // Exact equality would be wrong to assert — CoreText antialiases
        // the glyph against `tab_active_bg` — so look for a pixel closer
        // to the icon colour than to the background.
        let bg = Theme::default().tab_active_bg;
        let dist = |a: (u8, u8, u8), c: Color| {
            let d = |x: u8, y: u8| (x as i32 - y as i32).pow(2);
            d(a.0, c.r) + d(a.1, c.g) + d(a.2, c.b)
        };
        // Tab 0 is active, so restrict the scan to the inset chip's own
        // vertical band — outside it the row is `tab_bar_bg`, not
        // `bg` (`tab_active_bg`), and comparing against the wrong
        // background there could pass or fail for reasons unrelated to
        // the icon glyph.
        let chip_y0 = TAB_CHIP_INSET_Y as u32;
        let chip_y1 = H - TAB_CHIP_INSET_Y as u32;
        let found = (glyph_lo.floor() as u32..glyph_hi.ceil() as u32).any(|x| {
            (chip_y0..chip_y1).any(|y| {
                let (r, g, b, _) = surface.pixel(x.min(W - 1), y);
                dist((r, g, b), icon_color) < dist((r, g, b), bg)
            })
        });
        assert!(
            found,
            "no pixel in the icon span [{glyph_lo}, {glyph_hi}) leans towards \
             TabIcon::color {icon_color:?} — the glyph was not painted, or was \
             painted in the tab foreground",
        );
    }

    /// An empty sidecar must reproduce the icon-less rasteriser *pixel for
    /// pixel* — `draw_tab_bar` is now literally `draw_tab_bar_icons(.., &[])`.
    #[test]
    #[allow(deprecated)]
    fn empty_sidecar_is_pixel_identical_to_the_icon_less_paint() {
        let bar = sample_bar();
        let (icon_surface, icon_hits) = paint_icons_via_backend(&bar, &[], None);
        let (plain_surface, plain_hits) = paint_via_backend(&bar, None);

        assert_eq!(icon_hits.slot_positions, plain_hits.slot_positions);
        assert_eq!(icon_hits.close_bounds, plain_hits.close_bounds);
        assert_eq!(icon_hits.available_cols, plain_hits.available_cols);
        for y in 0..H {
            for x in 0..W {
                assert_eq!(
                    icon_surface.pixel(x, y),
                    plain_surface.pixel(x, y),
                    "pixel ({x}, {y}) differs with an empty sidecar",
                );
            }
        }
    }

    /// A sidecar shorter (or longer) than `bar.tabs` must not panic —
    /// `tab_icon_at` treats a missing entry as "no icon", the convention
    /// every backend's sidecar handling shares.
    #[test]
    #[allow(deprecated)]
    fn short_and_overlong_sidecars_are_tolerated() {
        let bar = sample_bar();
        let f = font();

        // One entry for a two-tab bar: tab 1 behaves as `None`.
        let short = vec![Some(TabIcon {
            glyph: "R".into(),
            color: Color::rgb(220, 120, 60),
        })];
        let hits = mac_tab_bar_layout_icons(&f, W as f64, &bar, &short);
        assert_eq!(hits.slot_positions.len(), bar.tabs.len());
        assert_eq!(
            hits.slot_positions[0],
            mac_tab_bar_layout_icons(&f, W as f64, &bar, &sample_icons()).slot_positions[0],
            "a short sidecar decorates the entries it does have",
        );

        // Three entries for a two-tab bar: the extra is ignored.
        let long = vec![
            None,
            None,
            Some(TabIcon {
                glyph: "R".into(),
                color: Color::rgb(220, 120, 60),
            }),
        ];
        let long_hits = mac_tab_bar_layout_icons(&f, W as f64, &bar, &long);
        let plain = mac_tab_bar_layout(&f, W as f64, &bar);
        assert_eq!(
            long_hits.slot_positions, plain.slot_positions,
            "an overlong sidecar whose in-range entries are all None must \
             reproduce the icon-less geometry",
        );
    }

    /// The scroll-offset correction (`fit_active_scroll_offset`) has to see
    /// the icon reservation too — a decorated tab is wider, so fewer tabs
    /// fit and the offset that keeps the active tab visible can differ.
    /// Pins that `mac_tab_bar_layout_icons` feeds the *widened* slot widths
    /// into that correction rather than the icon-less ones.
    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` — issue #823
    fn icon_reservation_feeds_the_scroll_offset_correction() {
        // Wide labels + the narrow test bar so the active tab can't fit
        // without scrolling, and every tab decorated so the reservation is
        // what tips it over.
        let bar = TabBar {
            id: WidgetId::new("tabs"),
            tabs: (0..6)
                .map(|i| TabItem {
                    label: format!(" a_rather_long_file_name_{i}.rs "),
                    is_active: i == 5,
                    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,
        };
        let icons: Vec<Option<TabIcon>> = (0..6)
            .map(|_| {
                Some(TabIcon {
                    glyph: "RR".into(),
                    color: Color::rgb(220, 120, 60),
                })
            })
            .collect();
        let f = font();

        let plain = mac_tab_bar_layout(&f, W as f64, &bar);
        let decorated = mac_tab_bar_layout_icons(&f, W as f64, &bar, &icons);
        // Guard the premise: the reservation must actually have widened
        // the slots this correction is computed from, otherwise the
        // assertions below would hold vacuously.
        // `bar.scroll_offset` is 0, so slot 0 is the first *painted* tab.
        let slot_w = |h: &TabBarHits| {
            let (lo, hi) = h.slot_positions[0];
            hi - lo
        };
        assert!(
            slot_w(&decorated) > slot_w(&plain),
            "decorated slots must be wider than icon-less ones \
             ({} vs {})",
            slot_w(&decorated),
            slot_w(&plain),
        );
        assert!(
            decorated.correct_scroll_offset >= plain.correct_scroll_offset,
            "wider tabs can only need the same or a later scroll offset \
             (icon-less {}, decorated {})",
            plain.correct_scroll_offset,
            decorated.correct_scroll_offset,
        );
        // Fewer decorated tabs fit in the same bar, so the visible slot
        // count can only shrink or hold.
        let visible = |h: &TabBarHits| h.slot_positions.len();
        assert!(
            visible(&decorated) <= visible(&plain),
            "decorated tabs are wider, so no more of them can fit \
             (icon-less {}, decorated {})",
            visible(&plain),
            visible(&decorated),
        );
    }

    /// `mac_tab_bar_native_layout_icons` and `mac_tab_bar_layout_icons`
    /// duplicate their measurement code, so this test verifies they agree
    /// with a sidecar present — the reservation must be applied in both places
    /// to keep the implementations from drifting.
    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` — issue #823
    fn native_layout_agrees_with_hits_layout_with_icons() {
        let bar = sample_bar();
        let icons = sample_icons();
        let f = font();

        let hits = mac_tab_bar_layout_icons(&f, W as f64, &bar, &icons);
        let native = mac_tab_bar_native_layout_icons(&f, W as f64, H as f64, &bar, &icons);
        let native_as_hits = crate::backend::tab_bar_hits_from_layout(&native, &bar);

        assert_eq!(hits.slot_positions, native_as_hits.slot_positions);
        assert_eq!(hits.close_bounds, native_as_hits.close_bounds);
        assert_eq!(
            hits.right_segment_bounds,
            native_as_hits.right_segment_bounds
        );
        assert_eq!(hits.correct_scroll_offset, native.resolved_scroll_offset);
    }

    /// `MacBackend::draw_tab_bar` must paint the tab bar background at `rect.x`,
    /// not at the window origin. This test verifies that painting at a non-zero
    /// `rect.x` (representing, for example, a sidebar's right edge) leaves the
    /// area to the left untouched and starts the tab bar's background exactly
    /// at `rect.x`.
    ///
    /// Uses an empty bar (no tabs) so the whole strip is uniformly `tab_bar_bg`,
    /// so a probe anywhere in the strip can't land on an active tab's
    /// differently-coloured slot instead.
    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` — issue #823
    fn tab_bar_paints_at_rect_x_not_at_window_origin() {
        const SIDEBAR_W: f32 = 120.0;
        let canvas_w = SIDEBAR_W as u32 + W;
        let surface = BitmapSurface::new(canvas_w, H);
        surface.fill(0.0, 0.0, 0.0, 0.0);

        let bar = TabBar {
            id: WidgetId::new("empty"),
            tabs: vec![],
            scroll_offset: 0,
            right_segments: vec![],
            active_accent: None,
            show_tab_close: true,
            compact: false,
        };
        let mut backend = backend_with_test_fonts();
        backend.begin_frame(Viewport::new(canvas_w as f32, H as f32, 1.0));
        backend.enter_frame_scope(surface.context_ptr(), |b| {
            let _ = b.draw_tab_bar(QRect::new(SIDEBAR_W, 0.0, W as f32, H as f32), &bar, None);
        });
        backend.end_frame();

        // Left of the sidebar boundary must stay exactly as the surface
        // was initialised — fully transparent — never the tab bar's
        // background fill.
        let (_, _, _, a) = surface.pixel(4, H / 2);
        assert_eq!(
            a, 0,
            "sidebar column (x=4) must stay untouched by the tab bar fill",
        );

        // At (and past) the sidebar's right edge: tab bar background.
        let theme = Theme::default();
        let (r, g, b, _) = surface.pixel(SIDEBAR_W as u32 + 4, H / 2);
        assert_eq!(
            (r, g, b),
            (theme.tab_bar_bg.r, theme.tab_bar_bg.g, theme.tab_bar_bg.b),
            "tab bar background should start at rect.x, not the window origin",
        );
    }

    /// Companion to [`tab_bar_paints_at_rect_x_not_at_window_origin`]:
    /// `Backend::tab_bar_layout`/`draw_tab_bar` document absolute
    /// (target-surface) coordinates for `TabBarHits` — the first tab's
    /// slot must start at or after `rect.x`, never at bar-relative `0.0`.
    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` — issue #823
    fn tab_bar_hits_are_absolute_at_nonzero_rect_x() {
        const SIDEBAR_W: f32 = 120.0;
        let canvas_w = SIDEBAR_W as u32 + W;
        let surface = BitmapSurface::new(canvas_w, H);
        surface.fill(0.0, 0.0, 0.0, 0.0);

        let bar = sample_bar();
        let mut backend = backend_with_test_fonts();
        backend.begin_frame(Viewport::new(canvas_w as f32, H as f32, 1.0));
        let hits = std::cell::RefCell::new(None);
        backend.enter_frame_scope(surface.context_ptr(), |b| {
            let h = b.draw_tab_bar(QRect::new(SIDEBAR_W, 0.0, W as f32, H as f32), &bar, None);
            *hits.borrow_mut() = Some(h);
        });
        backend.end_frame();
        let hits = hits.into_inner().unwrap();

        let (first_start, _) = hits.slot_positions[0];
        assert!(
            first_start >= SIDEBAR_W as f64,
            "first tab slot should start at/after rect.x={SIDEBAR_W}, got {first_start}",
        );
    }

    /// The layout must match the painted hits at non-zero `rect.x`, with the
    /// same invariant as [`layout_twin_matches_the_painted_hits`] — paint and
    /// layout must agree once both are shifted to the absolute contract that
    /// `Backend::tab_bar_layout` documents.
    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` — issue #823
    fn layout_twin_matches_the_painted_hits_at_nonzero_origin() {
        const SIDEBAR_W: f32 = 120.0;
        let canvas_w = SIDEBAR_W as u32 + W;
        let surface = BitmapSurface::new(canvas_w, H);
        surface.fill(0.0, 0.0, 0.0, 0.0);

        let bar = sample_bar();
        let mut backend = backend_with_test_fonts();
        backend.begin_frame(Viewport::new(canvas_w as f32, H as f32, 1.0));
        let painted = std::cell::RefCell::new(None);
        backend.enter_frame_scope(surface.context_ptr(), |b| {
            let h = b.draw_tab_bar(QRect::new(SIDEBAR_W, 0.0, W as f32, H as f32), &bar, None);
            *painted.borrow_mut() = Some(h);
        });
        backend.end_frame();
        let painted = painted.into_inner().unwrap();

        let computed = backend.tab_bar_layout(QRect::new(SIDEBAR_W, 0.0, W as f32, H as f32), &bar);

        assert_eq!(painted.slot_positions, computed.slot_positions);
        assert_eq!(painted.close_bounds, computed.close_bounds);
        assert_eq!(painted.right_segment_bounds, computed.right_segment_bounds);
        // Check `available_cols` and `correct_scroll_offset` too; these are pure
        // functions of `rect.width` and the bar's tab widths, independent of `rect.x`,
        // but exercising them here keeps this non-zero-origin case consistent with
        // the zero-origin case.
        assert_eq!(painted.available_cols, computed.available_cols);
        assert_eq!(
            painted.correct_scroll_offset,
            computed.correct_scroll_offset
        );
        // Sanity: the agreement isn't just "both zero" — the geometry
        // actually moved with the origin.
        assert!(painted.slot_positions[0].0 >= SIDEBAR_W as f64);
    }

    /// The reported symptom (controls in `TabBar::right_segments` floating at
    /// the wrong position) occurs because `right_segments` paints through the
    /// same `draw_tab_bar_icons` call inside the same `CGContextTranslateCTM`
    /// wrap as the tabs themselves. This test verifies that `right_segment_bounds`
    /// are shifted by `rect.x` just like the tab slot positions.
    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` — issue #823
    fn right_segments_are_shifted_by_rect_x_like_the_tabs() {
        const SIDEBAR_W: f32 = 120.0;
        let canvas_w = SIDEBAR_W as u32 + W;
        let surface = BitmapSurface::new(canvas_w, H);
        surface.fill(0.0, 0.0, 0.0, 0.0);

        let mut bar = sample_bar();
        bar.right_segments = vec![TabBarSegment {
            text: "\u{22ef}".into(), // "⋯" overflow glyph
            width_cells: 3,
            id: Some(WidgetId::new("tb:overflow")),
            is_active: false,
        }];

        // Bar-relative geometry `draw_tab_bar_icons` computes internally,
        // before any `rect.x` shift — the pre-fix behaviour.
        let bar_relative = mac_tab_bar_layout(&font(), W as f64, &bar);
        assert_eq!(
            bar_relative.right_segment_bounds.len(),
            1,
            "fixture bar should have exactly one right segment",
        );
        let (rel_start, rel_end) = bar_relative.right_segment_bounds[0];

        let mut backend = backend_with_test_fonts();
        backend.begin_frame(Viewport::new(canvas_w as f32, H as f32, 1.0));
        let hits = std::cell::RefCell::new(None);
        backend.enter_frame_scope(surface.context_ptr(), |b| {
            let h = b.draw_tab_bar(QRect::new(SIDEBAR_W, 0.0, W as f32, H as f32), &bar, None);
            *hits.borrow_mut() = Some(h);
        });
        backend.end_frame();
        let hits = hits.into_inner().unwrap();

        assert_eq!(hits.right_segment_bounds.len(), 1);
        assert_eq!(
            hits.right_segment_bounds[0],
            (rel_start + SIDEBAR_W as f64, rel_end + SIDEBAR_W as f64),
            "right segment bounds should be the bar-relative geometry shifted by rect.x={SIDEBAR_W}",
        );

        // `tab_bar_layout`'s no-paint twin must agree, same invariant as
        // `layout_twin_matches_the_painted_hits_at_nonzero_origin` above.
        let computed = backend.tab_bar_layout(QRect::new(SIDEBAR_W, 0.0, W as f32, H as f32), &bar);
        assert_eq!(hits.right_segment_bounds, computed.right_segment_bounds);
    }

    /// The active tab's chip must fully enclose the painted label —
    /// icon, text and the close `×` — not just the label's *measured*
    /// width. Regression test for the real system UI font at the row
    /// height the `tui_tab_icons`/`macos_tab_icons` demo actually paints
    /// at: `backend.line_height()`'s hardcoded 16.0 editor-font default,
    /// which is tight enough relative to the chrome font's own line
    /// height that a fixed `TAB_CHIP_INSET_Y` on both edges would leave
    /// a chip shorter than the label, letting a descender like
    /// "Cargo.toml"'s "g" ink past the chip's bottom edge.
    #[test]
    #[allow(deprecated)]
    fn active_chip_fully_encloses_the_painted_label_at_the_real_chrome_font() {
        let icons = vec![
            Some(TabIcon {
                glyph: "R".into(),
                color: Color::rgb(222, 165, 132),
            }),
            Some(TabIcon {
                glyph: "T".into(),
                color: Color::rgb(160, 190, 210),
            }),
            Some(TabIcon {
                glyph: "M".into(),
                color: Color::rgb(120, 170, 240),
            }),
        ];
        let bar = TabBar {
            id: WidgetId::new("tabs"),
            tabs: [" main.rs ", " Cargo.toml ", " README.md "]
                .iter()
                .enumerate()
                .map(|(i, label)| TabItem {
                    label: (*label).to_string(),
                    is_active: i == 1,
                    ..Default::default()
                })
                .collect(),
            scroll_offset: 0,
            right_segments: vec![],
            active_accent: None,
            show_tab_close: true,
            compact: false,
        };

        const WIDE_W: u32 = 600;
        // The live `tui_tab_icons`/`macos_tab_icons` demo passes
        // `backend.line_height()` — `MacBackend::new()`'s hardcoded
        // editor-font default of 16.0, never overridden since the demo
        // never calls `AppLogic::setup()` to install an editor font — as
        // the tab bar's row height, not this module's `H = 28` test
        // constant. Reproduce that exact (much tighter) row height here
        // rather than the roomier one every other test in this module uses.
        const DEMO_ROW_H: u32 = 16;
        let surface = BitmapSurface::new(WIDE_W, DEMO_ROW_H);
        surface.fill(0.0, 0.0, 0.0, 0.0);
        let mut backend = MacBackend::new();
        backend.begin_frame(Viewport::new(WIDE_W as f32, DEMO_ROW_H as f32, 1.0));
        let (_, chrome_line_height) = backend.measure_text("M", crate::FontRole::Chrome);
        let hits = std::cell::RefCell::new(None);
        backend.enter_frame_scope(surface.context_ptr(), |b| {
            let h = b.draw_tab_bar_icons(
                QRect::new(0.0, 0.0, WIDE_W as f32, DEMO_ROW_H as f32),
                &bar,
                &icons,
                None,
            );
            *hits.borrow_mut() = Some(h);
        });
        backend.end_frame();
        let hits = hits.into_inner().unwrap();

        let theme = Theme::default();
        let (slot_x, slot_end) = hits.slot_positions[1];
        let chip_x1 = slot_end - TAB_OUTER_GAP;

        // Both the bar's own background and the chip's background are
        // dark, low-luma colours (`Theme::default()`'s
        // `tab_bar_bg`/`tab_active_bg`), while the label text and icon
        // glyphs are painted at a much higher-luma colour (`tab_active_fg`
        // and the icon tints) — a wide enough gap that a luma threshold
        // tells real label ink apart from the chip's own anti-aliased
        // fill edge. A fractional chip inset (the case under test) means
        // the chip's straight top/bottom edge sits mid-pixel, so the row
        // straddling it blends `tab_bar_bg` and `tab_active_bg` into a
        // third colour that matches neither exactly — an exact-colour
        // background check would misclassify that blend as escaped ink.
        fn luma(c: Color) -> f64 {
            0.299 * c.r as f64 + 0.587 * c.g as f64 + 0.114 * c.b as f64
        }
        let ink_luma_threshold = ((luma(theme.tab_bar_bg).max(luma(theme.tab_active_bg))
            + luma(theme.tab_active_fg))
            / 2.0)
            .max(luma(theme.tab_bar_bg).max(luma(theme.tab_active_bg)) + 20.0);
        // Inset well clear of the chip's own rounded corners (radius
        // `TAB_CHIP_RADIUS`) so corner anti-aliasing isn't mistaken for
        // label ink escaping the chip's top/bottom edge.
        let inset = (TAB_CHIP_RADIUS as u32) + 6;
        let probe_x0 = (slot_x as u32) + inset;
        let probe_x1 = (chip_x1 as u32).saturating_sub(inset).max(probe_x0);

        // No recomputed `chip_y`/`chip_bottom` here: trusting a formula
        // that mirrors `draw_tab_bar_icons`'s own adaptive-inset formula
        // only proves the two formulas agree with each other, not that
        // the chip the backend actually painted encloses the label it
        // actually painted. Instead, classify every sampled row purely
        // from rendered pixels.
        //
        // A row's non-ink pixels are overwhelmingly the flat colour
        // behind the label — either the chip (`tab_active_bg`, or a
        // `tab_bar_bg`/`tab_active_bg` blend on a row straddling the
        // chip's fractional top/bottom edge) or, when the chip doesn't
        // reach that row, the bar's own flat `tab_bar_bg`. The glyphs'
        // own anti-aliased stroke edges are a small minority of pixels
        // confined to a ring around the ink itself, and their colour
        // (a blend toward the bright label colour) sits below the ink
        // luma threshold without matching either flat background —
        // checking whether *any* non-ink pixel differs from
        // `tab_bar_bg` mistakes those stroke-edge pixels for chip
        // coverage even when no chip is present under the row at all.
        // Taking the *mode* (most frequent colour) of the row's
        // non-ink pixels instead picks out the dominant background
        // colour and ignores the rare stroke-edge outliers.
        let bar_bg = theme.tab_bar_bg;
        const BG_DIFF_EPSILON: f64 = 4.0;

        let mut violations: Vec<u32> = vec![];
        for y in 0..DEMO_ROW_H {
            let mut row_has_ink = false;
            let mut bg_color_counts: std::collections::HashMap<(u8, u8, u8), u32> =
                std::collections::HashMap::new();
            for x in probe_x0..probe_x1 {
                let (r, g, b, _) = surface.pixel(x, y);
                let pixel_luma = 0.299 * r as f64 + 0.587 * g as f64 + 0.114 * b as f64;
                if pixel_luma > ink_luma_threshold {
                    row_has_ink = true;
                } else {
                    *bg_color_counts.entry((r, g, b)).or_insert(0) += 1;
                }
            }
            let row_has_chip_coverage = bg_color_counts
                .into_iter()
                .max_by_key(|(_, count)| *count)
                .is_some_and(|((r, g, b), _)| {
                    (r as f64 - bar_bg.r as f64).abs() > BG_DIFF_EPSILON
                        || (g as f64 - bar_bg.g as f64).abs() > BG_DIFF_EPSILON
                        || (b as f64 - bar_bg.b as f64).abs() > BG_DIFF_EPSILON
                });
            if row_has_ink && !row_has_chip_coverage {
                violations.push(y);
            }
        }

        assert!(
            violations.is_empty(),
            "label ink painted in a row with no chip colour beneath it \
             (chrome_line_height={chrome_line_height}, demo_row_h={DEMO_ROW_H}): \
             rows={violations:?}"
        );
    }

    /// An app-supplied [`TabBarGlyphs`] override swaps the close/dirty
    /// mark `Backend::draw_tab_bar_with_chrome_and_glyphs` paints on
    /// [`MacBackend`]; with `glyphs: None` it paints the same codicon
    /// default as [`MacBackend::draw_tab_bar`].
    #[test]
    fn close_dirty_glyph_override_paints_app_glyph_default_paints_codicon() {
        use crate::primitives::tab_bar::TabChrome;

        let bar = sample_bar();
        let chrome = TabChrome::default();
        let rect = QRect::new(0.0, 0.0, W as f32, H as f32);

        let glyphs = TabBarGlyphs::new()
            .with_close_glyph("x")
            .with_dirty_glyph("*");

        let paint = |glyphs: Option<&TabBarGlyphs>| -> Vec<crate::testing::TextRun> {
            let surface = BitmapSurface::new(W, H);
            surface.fill(0.0, 0.0, 0.0, 0.0);
            let mut backend = backend_with_test_fonts();
            backend.set_painted_text_recording(true);
            backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
            backend.enter_frame_scope(surface.context_ptr(), |b| {
                let _ = b.draw_tab_bar_with_chrome_and_glyphs(rect, &bar, None, &chrome, glyphs);
            });
            let runs = backend.text_runs().to_vec();
            backend.end_frame();
            runs
        };

        let overridden = paint(Some(&glyphs));
        assert!(
            overridden.iter().any(|r| r.text == "*"),
            "expected the overridden dirty glyph among painted runs, got {:?}",
            overridden
                .iter()
                .map(|r| r.text.as_str())
                .collect::<Vec<_>>()
        );
        assert!(!overridden
            .iter()
            .any(|r| r.text.contains(crate::codicon::DIRTY)));
        // Tab 0 (`main.rs`) is closable and not dirty, so the close-glyph
        // override paints there too.
        assert!(
            overridden.iter().any(|r| r.text == "x"),
            "expected the overridden close glyph among painted runs, got {:?}",
            overridden
                .iter()
                .map(|r| r.text.as_str())
                .collect::<Vec<_>>()
        );
        assert!(!overridden
            .iter()
            .any(|r| r.text.contains(crate::codicon::CLOSE)));

        let default_runs = paint(None);
        assert!(
            default_runs
                .iter()
                .any(|r| r.text.contains(crate::codicon::DIRTY)),
            "expected the default codicon dirty glyph among painted runs, got {:?}",
            default_runs
                .iter()
                .map(|r| r.text.as_str())
                .collect::<Vec<_>>()
        );
        assert!(
            default_runs
                .iter()
                .any(|r| r.text.contains(crate::codicon::CLOSE)),
            "expected the default codicon close glyph among painted runs, got {:?}",
            default_runs
                .iter()
                .map(|r| r.text.as_str())
                .collect::<Vec<_>>()
        );
    }
}