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
//! GTK rasteriser for [`crate::TabBar`].
//!
//! Calls [`TabBar::layout`] with Pango pixel measurers to produce a
//! [`TabBarLayout`], then paints from the resolved `visible_tabs` and
//! `visible_segments`. Paint and hit-test consume one layout — no
//! independent geometry derivation.
//!
//! Returns a [`TabBarHits`] (converted from the layout, for callers that
//! resolve clicks using their own segment-id conventions) alongside the
//! [`TabBarLayout`] itself, whose bar-relative `visible_tabs` /
//! `close_bounds` geometry is what `GtkBackend::draw_tab_bar` caches per
//! `WidgetId` for `GtkDriver::tab_center`/`tab_close_center`.
//!
//! This module paints with Cairo — every pixel is still Cairo-specific
//! and triplicated with `macos::tab_bar` / `win::tab_bar`. See
//! [`crate::primitives::tab_bar`]'s "`PaintSurface` migration status"
//! section for the drift table between the three copies, the macOS
//! `close_bounds`-convention prerequisite that blocks the move, and why
//! the migration is ongoing.

use gtk4::cairo::Context;
use gtk4::pango;

use super::{cairo_rgb, set_source};
use crate::backend::tab_bar_hits_from_layout;
use crate::primitives::layout_metrics::TextMeasure;
// `TabBarHits` is `#[deprecated]` — this whole module's job is
// still converting a computed `TabBarLayout` into one per paint. See that
// struct's doc for the replacement plan.
#[allow(deprecated)]
use crate::primitives::tab_bar::{TabBar, TabBarHits, TabBarLayout, TabChrome, TabFrame};
use crate::theme::Theme;

/// Per-tab 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;
/// Gap between a tab's icon glyph (see [`crate::TabIcon`]) and its label.
pub(crate) const TAB_ICON_GAP: f64 = 6.0;
/// Height of the active-tab top-edge accent line — VS Code Dark Modern's
/// `tab.activeBorderTop`.
const TAB_ACTIVE_BORDER_TOP_PX: f64 = 1.0;
/// Vertical margin (px) above and below the active-tab chip fill. VS Code
/// insets its active-tab pill inside the tab strip rather than filling the
/// full row height edge to edge.
const TAB_CHIP_INSET_Y: f64 = 4.0;
/// Corner radius (px) of the active-tab chip, all four corners.
const TAB_CHIP_RADIUS: f64 = 4.0;

/// Adapts a live `pango::Layout` to the shared
/// [`crate::primitives::layout_metrics::TextMeasure`] trait so
/// [`crate::primitives::layout_metrics::pixel_tab_bar_layout`] never has
/// to name a Pango type. Unlike `gtk::backend`'s
/// `PangoTextMeasure`, this always has a live layout — `draw_tab_bar_*`
/// paints through a real Cairo context, never headless — so there is no
/// char-width fallback to carry. Measures in whatever font is currently
/// set on `layout`; callers set the desired font before invoking
/// [`Self::width_of`] (via the shared fn calling it).
struct PangoTabMeasure<'a> {
    layout: &'a pango::Layout,
}

impl TextMeasure for PangoTabMeasure<'_> {
    fn width_of(&self, text: &str) -> f32 {
        self.layout.set_text(text);
        self.layout.pixel_size().0 as f32
    }
}

/// The Nerd-Font-swapped variant of the tab bar's label font, used to
/// measure and paint [`crate::TabIcon`] glyphs. Icon glyphs share
/// the label's size/weight/style but swap in an icon family, matching the
/// activity bar's glyph-sourcing convention — the UI font itself typically
/// isn't patched with icon codepoints.
///
/// Shared by [`draw_tab_bar_icons`] and `GtkBackend::tab_bar_layout_icons`
/// so the no-paint measurement can't drift from the painted glyph.
///
/// Unlike [`super::with_nerd_font_fallback`] (#416, used by
/// list/tree/palette icon glyphs), this *replaces* the family entirely
/// rather than appending — tab icons are always painted as a Nerd-Font
/// glyph with no ASCII-fallback text form (`TabIcon` carries just one
/// `glyph` field, unlike `Icon`'s `glyph`/`fallback` pair), so there's
/// no caller-family text to preserve. Built from
/// [`super::current_nerd_font_fallback_family`] (unlike
/// [`super::activity_bar::ICON_FONT_DESC`], which hand-rolls
/// [`super::NERD_FONT_FALLBACK_FAMILY`] as a literal because it's a
/// `pub const` and consts can't be concatenated on stable, so it does
/// not pick up a `Backend::set_nerd_font_fallback` override — see that
/// const's doc for the known gap) so this and `with_nerd_font_fallback`
/// can't drift apart.
///
/// [`crate::codicon::FONT_FAMILY`] is appended unconditionally, the
/// same append [`super::with_nerd_font_fallback`] makes —
/// this is also the font [`draw_tab_bar_icons`] paints the built-in
/// dirty/close codicon glyphs with, so it must resolve codicon
/// codepoints regardless of the app's own `set_nerd_font_fallback`
/// choice.
pub(crate) fn tab_icon_font(base: &pango::FontDescription) -> pango::FontDescription {
    let mut f = base.clone();
    f.set_family(&format!(
        "{}, {}, monospace",
        super::current_nerd_font_fallback_family(),
        crate::codicon::FONT_FAMILY
    ));
    f
}

/// Per-tab extra width (px) reserved for an icon glyph + [`TAB_ICON_GAP`],
/// indexed like `bar.tabs`. `0.0` for every tab without an icon, so
/// icon-less tabs keep byte-identical width and hit-test geometry to the
/// pre-#620 rasteriser.
///
/// Mutates `pango_layout`'s font description + text as it measures; the
/// caller re-sets both before its next use (both call sites do).
pub(crate) fn tab_icon_extras(
    pango_layout: &pango::Layout,
    icon_font: &pango::FontDescription,
    tab_count: usize,
    icons: &[Option<crate::primitives::tab_bar::TabIcon>],
) -> Vec<f64> {
    (0..tab_count)
        .map(
            |i| match crate::primitives::tab_bar::tab_icon_at(icons, i) {
                Some(icon) => {
                    pango_layout.set_font_description(Some(icon_font));
                    pango_layout.set_text(&icon.glyph);
                    let (icon_w, _) = pango_layout.pixel_size();
                    icon_w as f64 + TAB_ICON_GAP
                }
                None => 0.0,
            },
        )
        .collect()
}

/// Trace a rounded-rectangle path on `cr` at `(x, y, w, h)` with corner
/// radius `radius` on all four corners. Callers set the source and consume
/// the path themselves (`cr.fill()` or otherwise) — this only builds it.
///
/// Shared by the active-tab chip fill and the close-button hover
/// background so the two rounded-rect shapes can't drift apart.
fn rounded_rect_path(cr: &Context, x: f64, y: f64, w: f64, h: f64, radius: f64) {
    cr.new_path();
    cr.arc(
        x + w - radius,
        y + radius,
        radius,
        -std::f64::consts::FRAC_PI_2,
        0.0,
    );
    cr.arc(
        x + w - radius,
        y + h - radius,
        radius,
        0.0,
        std::f64::consts::FRAC_PI_2,
    );
    cr.arc(
        x + radius,
        y + h - radius,
        radius,
        std::f64::consts::FRAC_PI_2,
        std::f64::consts::PI,
    );
    cr.arc(
        x + radius,
        y + radius,
        radius,
        std::f64::consts::PI,
        3.0 * std::f64::consts::FRAC_PI_2,
    );
    cr.close_path();
}

/// Draw a [`TabBar`] into `(x_offset, y_offset, width, row_height)` on `cr`.
/// Caller is responsible for setting the desired UI font on `layout`
/// *before* calling — the rasteriser uses
/// [`pango::Layout::font_description`] as the base font and toggles
/// to a Pango Italic variant for preview tabs.
///
/// `x_offset` is the left edge of the tab bar in Cairo surface
/// coordinates. Every background fill, tab rectangle, close-button
/// hover, and text `move_to` is offset by this value, so the rasteriser
/// paints into the correct column without the caller needing to
/// pre-translate the Cairo context.
///
/// `row_height` controls the tab bar's vertical extent. Callers that
/// want padded file-tab spacing pass `(line_height * 1.6).ceil()`;
/// callers that want compact bars (terminal toolbar, bottom panel tab
/// switcher) pass `line_height` directly.
///
/// `hovered_close_tab` is a per-frame interaction override: when
/// `Some(i)` the `i`-th tab gets a rounded hover background behind
/// its close glyph. The primitive itself carries no mouse state.
///
/// Returns `(hits, layout)`. `hits` reports its regions in
/// **target-surface (absolute) coordinates** — the same coordinate space
/// as raw click `x` values. `x_offset` is applied internally, so callers
/// compare click positions directly against the returned
/// `slot_positions`, `close_bounds`, and `right_segment_bounds` without
/// any further adjustment. `layout` is the underlying [`TabBarLayout`]
/// this function computed to paint and derive `hits` from — its own
/// `visible_tabs`/`close_bounds` rects are **bar-relative** (origin at
/// `(0, 0)`, *not* `x_offset`/`y_offset`); `GtkBackend::draw_tab_bar`
/// caches it per `WidgetId` for `GtkDriver::tab_center`/`tab_close_center`,
/// which add the bar's own screen-space origin back in.
///
/// # Visual contract
///
/// - **Tab row height:** caller-provided via `row_height`.
/// - **Active tab:** `theme.tab_active_bg` background, plus a 1 px accent
///   line at the top edge when [`TabBar::active_accent`] is `Some` — `None`
///   paints no accent at all, matching the TUI and macOS rasterisers.
/// - **Dirty tab:** close glyph is a codicon filled circle (in
///   `theme.foreground`) instead of the codicon close glyph.
/// - **Preview tab:** italicised label.
/// - **Right segments:** painted in `tab_inactive_fg` (or
///   `tab_active_fg` when `seg.is_active`), no bold.
#[allow(clippy::too_many_arguments)]
#[allow(deprecated)]
pub fn draw_tab_bar(
    cr: &Context,
    pango_layout: &pango::Layout,
    x_offset: f64,
    width: f64,
    line_height: f64,
    y_offset: f64,
    row_height: f64,
    bar: &TabBar,
    theme: &Theme,
    hovered_close_tab: Option<usize>,
) -> (TabBarHits, TabBarLayout) {
    draw_tab_bar_icons(
        cr,
        pango_layout,
        x_offset,
        width,
        line_height,
        y_offset,
        row_height,
        bar,
        &[],
        theme,
        hovered_close_tab,
    )
}

/// [`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.
///
/// Each decorated tab reserves `pango(glyph) + TAB_ICON_GAP` extra
/// pixels ahead of its label and paints the glyph in
/// [`crate::TabIcon::color`], independent of the tab's active/inactive
/// foreground. The reservation feeds the same [`crate::TabMeasure`] the
/// layout is built from, so close-button bounds and slot positions stay
/// on the glyphs the user sees.
///
/// Icon glyphs share the label's size/weight/style but swap in a Nerd
/// Font family, matching the activity bar's glyph-sourcing convention —
/// the UI font itself typically isn't patched with icon codepoints.
#[allow(clippy::too_many_arguments)]
#[allow(deprecated)]
pub fn draw_tab_bar_icons(
    cr: &Context,
    pango_layout: &pango::Layout,
    x_offset: f64,
    width: f64,
    line_height: f64,
    y_offset: f64,
    row_height: f64,
    bar: &TabBar,
    icons: &[Option<crate::primitives::tab_bar::TabIcon>],
    theme: &Theme,
    hovered_close_tab: Option<usize>,
) -> (TabBarHits, TabBarLayout) {
    draw_tab_bar_icons_with_chrome(
        cr,
        pango_layout,
        x_offset,
        width,
        line_height,
        y_offset,
        row_height,
        bar,
        icons,
        &TabChrome::default(),
        theme,
        hovered_close_tab,
    )
}

/// [`draw_tab_bar`] with an explicit [`TabChrome`] request.
///
/// `&[]` icons + [`TabChrome::default`] reproduces [`draw_tab_bar`] pixel
/// for pixel.
#[allow(clippy::too_many_arguments)]
#[allow(deprecated)]
pub fn draw_tab_bar_with_chrome(
    cr: &Context,
    pango_layout: &pango::Layout,
    x_offset: f64,
    width: f64,
    line_height: f64,
    y_offset: f64,
    row_height: f64,
    bar: &TabBar,
    chrome: &TabChrome,
    theme: &Theme,
    hovered_close_tab: Option<usize>,
) -> (TabBarHits, TabBarLayout) {
    draw_tab_bar_with_chrome_and_glyphs(
        cr,
        pango_layout,
        x_offset,
        width,
        line_height,
        y_offset,
        row_height,
        bar,
        chrome,
        theme,
        hovered_close_tab,
        None,
        false,
    )
}

/// Identical to [`draw_tab_bar_with_chrome`], plus an optional
/// [`crate::primitives::tab_bar::TabBarGlyphs`] override for the
/// close/dirty glyph and the `nerd_fonts_enabled` flag — see
/// [`draw_tab_bar_icons_with_chrome_and_glyphs`], which this delegates to.
#[allow(clippy::too_many_arguments)]
#[allow(deprecated)]
pub fn draw_tab_bar_with_chrome_and_glyphs(
    cr: &Context,
    pango_layout: &pango::Layout,
    x_offset: f64,
    width: f64,
    line_height: f64,
    y_offset: f64,
    row_height: f64,
    bar: &TabBar,
    chrome: &TabChrome,
    theme: &Theme,
    hovered_close_tab: Option<usize>,
    glyphs: Option<&crate::primitives::tab_bar::TabBarGlyphs>,
    nerd_fonts_enabled: bool,
) -> (TabBarHits, TabBarLayout) {
    draw_tab_bar_icons_with_chrome_and_glyphs(
        cr,
        pango_layout,
        x_offset,
        width,
        line_height,
        y_offset,
        row_height,
        bar,
        &[],
        chrome,
        theme,
        hovered_close_tab,
        glyphs,
        nerd_fonts_enabled,
    )
}

/// [`draw_tab_bar_icons`] plus an explicit [`TabChrome`] request.
///
/// When `chrome.active_frame` is [`TabFrame::Brackets`], the active tab's
/// full content — icon, label, and close glyph — is enclosed in literal
/// `[` / `]` glyphs, measured via Pango like every other glyph this
/// rasteriser paints. Mirrors `tui::tab_bar::draw_tab_bar_icons_with_chrome`
/// so the two backends agree on what "enclosing" means.
#[allow(clippy::too_many_arguments)]
#[allow(deprecated)]
pub fn draw_tab_bar_icons_with_chrome(
    cr: &Context,
    pango_layout: &pango::Layout,
    x_offset: f64,
    width: f64,
    line_height: f64,
    y_offset: f64,
    row_height: f64,
    bar: &TabBar,
    icons: &[Option<crate::primitives::tab_bar::TabIcon>],
    chrome: &TabChrome,
    theme: &Theme,
    hovered_close_tab: Option<usize>,
) -> (TabBarHits, TabBarLayout) {
    draw_tab_bar_icons_with_chrome_and_glyphs(
        cr,
        pango_layout,
        x_offset,
        width,
        line_height,
        y_offset,
        row_height,
        bar,
        icons,
        chrome,
        theme,
        hovered_close_tab,
        None,
        false,
    )
}

/// Identical to [`draw_tab_bar_icons_with_chrome`], plus an optional
/// [`crate::primitives::tab_bar::TabBarGlyphs`] override for the
/// close/dirty glyph and the `nerd_fonts_enabled` flag (see
/// [`crate::Backend::nerd_fonts_enabled`]) that selects each override
/// [`crate::types::Icon`]'s `glyph` vs. `fallback` form. `glyphs: None`
/// (what [`draw_tab_bar_icons_with_chrome`] passes) renders byte-for-byte
/// the same as today's codicon defaults.
#[allow(clippy::too_many_arguments)]
#[allow(deprecated)]
pub fn draw_tab_bar_icons_with_chrome_and_glyphs(
    cr: &Context,
    pango_layout: &pango::Layout,
    x_offset: f64,
    width: f64,
    line_height: f64,
    y_offset: f64,
    row_height: f64,
    bar: &TabBar,
    icons: &[Option<crate::primitives::tab_bar::TabIcon>],
    chrome: &TabChrome,
    theme: &Theme,
    hovered_close_tab: Option<usize>,
    glyphs: Option<&crate::primitives::tab_bar::TabBarGlyphs>,
    nerd_fonts_enabled: bool,
) -> (TabBarHits, TabBarLayout) {
    let tab_row_height = row_height;
    let text_y_offset = y_offset + (tab_row_height - line_height) / 2.0;

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

    // Tab bar background.
    set_source(cr, theme.tab_bar_bg);
    cr.rectangle(x_offset, y_offset, width, tab_row_height);
    cr.fill().ok();

    pango_layout.set_attributes(None);
    let saved_font = pango_layout.font_description().unwrap_or_default();
    let normal_font = saved_font.clone();
    let mut italic_font = normal_font.clone();
    italic_font.set_style(pango::Style::Italic);
    // The close/dirty glyph is a codicon codepoint, so its width must
    // be measured (and painted) against `icon_font`, not
    // `normal_font` — computed up front, ahead of the pre-measure block
    // below, since that block needs it already.
    let icon_font = tab_icon_font(&normal_font);

    // Resolved once, outside the pre-measure block and the per-tab
    // paint loop below — both consult the same two strings.
    let close_glyph_str: std::borrow::Cow<'_, str> = glyphs
        .and_then(crate::primitives::tab_bar::TabBarGlyphs::close_glyph)
        .map(|icon| std::borrow::Cow::Borrowed(icon.resolve(nerd_fonts_enabled)))
        .unwrap_or(std::borrow::Cow::Owned(crate::codicon::CLOSE.to_string()));
    let dirty_glyph_str: std::borrow::Cow<'_, str> = glyphs
        .and_then(crate::primitives::tab_bar::TabBarGlyphs::dirty_glyph)
        .map(|icon| std::borrow::Cow::Borrowed(icon.resolve(nerd_fonts_enabled)))
        .unwrap_or(std::borrow::Cow::Owned(crate::codicon::DIRTY.to_string()));

    // ── Pre-measure close glyph ─────────────────────────────────────
    // Measure the close glyph's width once; individual tabs use it
    // conditionally based on `bar.show_tab_close && tab.is_closable`.
    // Matches the un-overridden code's existing behaviour of sizing the
    // hover box / bracket offset off the close glyph's width even when
    // a dirty tab paints the dirty glyph instead.
    let close_glyph_w = if bar.show_tab_close {
        pango_layout.set_font_description(Some(&icon_font));
        pango_layout.set_text(close_glyph_str.as_ref());
        let (w, _) = pango_layout.pixel_size();
        w as f64
    } else {
        0.0
    };

    // ── Pre-measure tabs → TabMeasure ───────────────────────────────
    let tab_name_widths: Vec<f64> = bar
        .tabs
        .iter()
        .map(|tab| {
            if tab.is_preview {
                pango_layout.set_font_description(Some(&italic_font));
            } else {
                pango_layout.set_font_description(Some(&normal_font));
            }
            pango_layout.set_text(&tab.label);
            let (name_w, _) = pango_layout.pixel_size();
            name_w as f64
        })
        .collect();

    let tab_icon_extras = tab_icon_extras(pango_layout, &icon_font, bar.tabs.len(), icons);

    // Bracket glyph width, needed below only for the paint loop's
    // `content_pad` (where the label starts once a leading `[` is
    // painted). The shared layout fn below remeasures both bracket
    // glyphs itself via the same `measure` adapter, so paint and layout
    // can never disagree about their width.
    let brackets = matches!(chrome.active_frame, TabFrame::Brackets);
    pango_layout.set_font_description(Some(&normal_font));
    let bracket_open_w = if brackets {
        pango_layout.set_text("[");
        pango_layout.pixel_size().0 as f64
    } else {
        0.0
    };

    // ── Compute layout — single source of truth ────────────────────
    // `PangoTabMeasure` measures in whatever font is currently set on
    // `pango_layout` — reset to the (non-italic, non-icon) label font
    // before handing it to the shared fn, since every glyph it measures
    // itself ([, ], right-segment labels, the char-width sample) is
    // single-font.
    pango_layout.set_font_description(Some(&normal_font));
    let measure = PangoTabMeasure {
        layout: pango_layout,
    };
    let tab_name_widths_f32: Vec<f32> = tab_name_widths.iter().map(|&w| w as f32).collect();
    let tab_icon_extras_f32: Vec<f32> = tab_icon_extras.iter().map(|&w| w as f32).collect();
    let (layout, corrected_scroll_offset, available_cols) =
        crate::primitives::layout_metrics::pixel_tab_bar_layout(
            bar,
            width as f32,
            row_height as f32,
            tab_pad as f32,
            tab_inner_gap as f32,
            tab_outer_gap as f32,
            &tab_name_widths_f32,
            &tab_icon_extras_f32,
            chrome,
            &measure,
        );

    // ── Paint tabs from layout ──────────────────────────────────────
    for vt in &layout.visible_tabs {
        let tab = &bar.tabs[vt.tab_idx];
        let tab_x = vt.bounds.x as f64;
        let tab_visual_w = vt.bounds.width as f64 - tab_outer_gap;

        // Tab background. The active tab paints an inset, rounded chip
        // (VS Code's pill, ~24px inside a 35px strip) rather than a square
        // block filling the full row height edge to edge. Inactive
        // tabs are unchanged: a full-height rectangle (typically the same
        // colour as the bar background, since neither VS Code nor quadraui
        // chips an inactive tab).
        let chip_y = y_offset + TAB_CHIP_INSET_Y;
        let chip_h = (tab_row_height - 2.0 * TAB_CHIP_INSET_Y).max(0.0);
        if tab.is_active {
            set_source(cr, theme.tab_active_bg);
            rounded_rect_path(
                cr,
                x_offset + tab_x,
                chip_y,
                tab_visual_w,
                chip_h,
                TAB_CHIP_RADIUS,
            );
            cr.fill().ok();
        } else {
            set_source(cr, theme.tab_bar_bg);
            cr.rectangle(x_offset + tab_x, y_offset, tab_visual_w, tab_row_height);
            cr.fill().ok();
        }

        // Top accent line for the active tab — VS Code Dark Modern's
        // `tab.activeBorderTop`, 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 in the strip's top margin.
        // `bar.active_accent` is `None` = no accent, matching the TUI
        // (`tui/tab_bar.rs`) and macOS (`macos/tab_bar.rs`) rasterisers and
        // the field's own doc comment ("`None` = no underline accent
        // (typical for inactive groups)", `primitives/tab_bar.rs`). Callers
        // that want VS Code's focused-tab top border opt in explicitly with
        // `active_accent: Some(theme.tab_active_border_top())`; a bar with no
        // notion of focus (bottom-panel tab strip, terminal toolbar,
        // unfocused splits) passes `None` and gets no strip, same as every
        // other backend.
        if tab.is_active {
            if let Some(accent) = bar.active_accent {
                set_source(cr, accent);
                cr.rectangle(
                    x_offset + tab_x,
                    chip_y,
                    tab_visual_w,
                    TAB_ACTIVE_BORDER_TOP_PX,
                );
                cr.fill().ok();
            }
        }

        // Tab text colour, computed early so the bracket frame (if any)
        // paints in the same colour as the label it encloses.
        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,
        };

        // Opening bracket, when this tab is active and chrome
        // requests `TabFrame::Brackets`. `content_pad` shifts every
        // subsequent paint position right by the bracket's width.
        let is_bracket = brackets && tab.is_active;
        let content_pad = tab_pad + if is_bracket { bracket_open_w } else { 0.0 };
        if is_bracket {
            set_source(cr, fg_col);
            pango_layout.set_font_description(Some(&normal_font));
            pango_layout.set_text("[");
            cr.move_to(x_offset + tab_x + tab_pad, text_y_offset);
            super::painted_text::show_layout(cr, pango_layout);
        }

        // Icon glyph, if this tab has one — painted before the label in
        // its own colour, independent of the tab's active/inactive fg.
        let icon_extra = tab_icon_extras[vt.tab_idx];
        if let Some(icon) = crate::primitives::tab_bar::tab_icon_at(icons, vt.tab_idx) {
            set_source(cr, icon.color);
            pango_layout.set_font_description(Some(&icon_font));
            pango_layout.set_text(&icon.glyph);
            cr.move_to(x_offset + tab_x + content_pad, text_y_offset);
            super::painted_text::show_layout(cr, pango_layout);
        }

        // Tab text.
        set_source(cr, fg_col);
        pango_layout.set_font_description(Some(if tab.is_preview {
            &italic_font
        } else {
            &normal_font
        }));
        pango_layout.set_text(&tab.label);
        cr.move_to(x_offset + tab_x + content_pad + icon_extra, text_y_offset);
        super::painted_text::show_layout(cr, pango_layout);

        // Closing bracket, for a bracket-framed tab with no close
        // button — painted right after the label. (When there *is* a
        // close button, the closing bracket paints after the glyph,
        // inside the block below, since its position depends on the
        // glyph's own measured width.)
        if is_bracket && !(bar.show_tab_close && tab.is_closable) {
            set_source(cr, fg_col);
            pango_layout.set_font_description(Some(&normal_font));
            pango_layout.set_text("]");
            cr.move_to(
                x_offset + tab_x + content_pad + icon_extra + tab_name_widths[vt.tab_idx],
                text_y_offset,
            );
            super::painted_text::show_layout(cr, pango_layout);
        }

        // Paint the close glyph only when both the bar-level flag and the
        // per-tab `is_closable` flag are set — matching the measurement above.
        if bar.show_tab_close && tab.is_closable {
            if let Some(cb) = vt.close_bounds {
                let close_x = cb.x as f64 + tab_inner_gap;
                let is_close_hovered = hovered_close_tab == Some(vt.tab_idx);

                // Rounded hover background behind close glyph.
                if is_close_hovered {
                    let pad = 2.0;
                    let rx = x_offset + close_x - pad;
                    let ry = text_y_offset + pad;
                    let rw = close_glyph_w + pad * 2.0;
                    let rh = line_height - pad * 2.0;
                    let (hr, hg, hb) = cairo_rgb(theme.foreground);
                    cr.set_source_rgba(hr, hg, hb, 0.15);
                    let radius = 3.0;
                    rounded_rect_path(cr, rx, ry, rw, rh, radius);
                    cr.fill().ok();
                }

                // Codicon glyphs, painted through `icon_font` (same
                // font `tab_icon_extras` already paints app `TabIcon`
                // glyphs with), since that's the font whose family
                // list carries `codicon::FONT_FAMILY` (see
                // `tab_icon_font`'s doc).
                let selected_glyph = if tab.is_dirty && !is_close_hovered {
                    dirty_glyph_str.as_ref()
                } else {
                    close_glyph_str.as_ref()
                };
                let close_fg = if tab.is_dirty || is_close_hovered {
                    theme.foreground
                } else if tab.is_active {
                    theme.tab_inactive_fg
                } else {
                    theme.separator
                };
                set_source(cr, close_fg);
                pango_layout.set_font_description(Some(&icon_font));
                pango_layout.set_text(selected_glyph);
                cr.move_to(x_offset + close_x, text_y_offset);
                super::painted_text::show_layout(cr, pango_layout);
                pango_layout.set_font_description(Some(&normal_font));

                // Closing bracket, right after the glyph — `cb.x`
                // already stops short of it via
                // `TabMeasure::trailing_width`, so this lands exactly
                // where the reservation left room for it.
                if is_bracket {
                    set_source(cr, fg_col);
                    pango_layout.set_font_description(Some(&normal_font));
                    pango_layout.set_text("]");
                    cr.move_to(x_offset + close_x + close_glyph_w, text_y_offset);
                    super::painted_text::show_layout(cr, pango_layout);
                }
            }
        }
    }

    // ── Right segments from layout ──────────────────────────────────
    for vs in &layout.visible_segments {
        let seg = &bar.right_segments[vs.segment_idx];
        let fg_col = if seg.is_active {
            theme.tab_active_fg
        } else {
            theme.tab_inactive_fg
        };
        set_source(cr, fg_col);
        pango_layout.set_font_description(Some(&normal_font));
        pango_layout.set_text(&seg.text);
        cr.move_to(x_offset + vs.bounds.x as f64, text_y_offset);
        super::painted_text::show_layout(cr, pango_layout);
    }

    // Restore caller's font.
    pango_layout.set_font_description(Some(&saved_font));

    let mut hits = tab_bar_hits_from_layout(&layout, bar);
    // `tab_bar_hits_from_layout` yields bar-relative positions, but the
    // `TabBarHits` contract is target-surface coordinates (matching the TUI
    // rasteriser and the painted glyphs above, which all add `x_offset`).
    // Shift every hit range so consumers can hit-test against raw click x.
    // Shared with `Backend::tab_bar_layout` so the paint and no-paint
    // paths cannot drift apart again.
    crate::backend::shift_tab_bar_hits(&mut hits, x_offset);
    // Shared with `Backend::tab_bar_layout` so the paint and no-paint
    hits.correct_scroll_offset = corrected_scroll_offset;
    hits.available_cols = available_cols;
    (hits, layout)
}

// ── Tests ──────────────────────────────────────────────────────────────────
//
// Headless paint test: verify that `draw_tab_bar` respects `x_offset` and
// never paints tab chrome into columns left of that offset.
//
// Uses a Cairo `ImageSurface` (no display required) and reads back pixel
// data directly. The test is gated on the `gtk` feature so it only runs
// under `cargo test --features gtk`.

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::tab_bar::{TabBar, TabBarSegment, TabItem};
    use crate::theme::Theme;
    use crate::types::{Color, WidgetId};
    use pangocairo::cairo::{Context, Format, ImageSurface};

    // Surface dimensions: wide enough to contain the tab bar at x_offset=50,
    // tall enough for a single row.
    const W: i32 = 300;
    const ROW_H: i32 = 24;
    const LINE_H: f64 = 14.0;
    const X_OFFSET: f64 = 50.0;

    /// Read an RGB triple from an ARgb32 surface at pixel (x, y).
    ///
    /// Cairo's `ARgb32` stores each pixel as four bytes in native
    /// (little-endian) byte order: [B, G, R, A].  The `stride` from
    /// [`ImageSurface::stride`] is in bytes and may include padding.
    fn pixel(data: &[u8], stride: usize, x: i32, y: i32) -> (u8, u8, u8) {
        let off = y as usize * stride + x as usize * 4;
        // ARgb32 byte layout on little-endian: B=off+0, G=off+1, R=off+2
        (data[off + 2], data[off + 1], data[off])
    }

    fn make_bar() -> TabBar {
        TabBar {
            id: WidgetId::new("test-tabs"),
            tabs: vec![TabItem {
                label: "main.rs".to_string(),
                is_active: true,
                is_dirty: false,
                is_preview: false,
                is_closable: true,
            }],
            scroll_offset: 0,
            right_segments: vec![TabBarSegment {
                text: " ⇅ ".to_string(),
                width_cells: 3,
                id: None,
                is_active: false,
            }],
            active_accent: None,
            // Disable close button so the test doesn't depend on
            // close-glyph measurement.
            show_tab_close: false,
            compact: false,
        }
    }

    /// Theme with a tab_bar_bg that is clearly distinct from white so we
    /// can distinguish "untouched background" from "painted tab chrome".
    fn make_theme() -> Theme {
        Theme {
            tab_bar_bg: Color::rgb(40, 44, 52),
            tab_active_bg: Color::rgb(60, 66, 80),
            ..Theme::default()
        }
    }

    /// Paint a tab bar into a fresh white surface at `x_offset = X_OFFSET`
    /// and return the surface.
    fn paint_at_offset() -> ImageSurface {
        let surface = ImageSurface::create(Format::ARgb32, W, ROW_H).expect("create ImageSurface");
        {
            let cr = Context::new(&surface).expect("Context::new");
            // Fill with white so any pixel left untouched is clearly white.
            cr.set_source_rgb(1.0, 1.0, 1.0);
            cr.paint().ok();

            let pango_layout = pangocairo::functions::create_layout(&cr);
            let bar = make_bar();
            let theme = make_theme();
            draw_tab_bar(
                &cr,
                &pango_layout,
                X_OFFSET,
                (W as f64) - X_OFFSET,
                LINE_H,
                0.0,
                ROW_H as f64,
                &bar,
                &theme,
                None,
            );
        }
        surface
    }

    /// Columns 0..X_OFFSET-1 must be untouched white — the rasteriser must
    /// not paint any tab chrome left of `x_offset`.
    #[test]
    fn tab_bar_does_not_paint_before_x_offset() {
        let mut surface = paint_at_offset();
        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        let mid_y = ROW_H / 2;
        for x in 0..(X_OFFSET as i32) {
            let px = pixel(&data, stride, x, mid_y);
            assert_eq!(
                px,
                (255, 255, 255),
                "pixel at x={x} should be untouched white, got {px:?}"
            );
        }
    }

    /// Column X_OFFSET must show the tab bar background fill — confirming
    /// the rasteriser starts painting exactly at `x_offset`.
    #[test]
    fn tab_bar_starts_painting_at_x_offset() {
        let mut surface = paint_at_offset();
        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        let mid_y = ROW_H / 2;
        // x = X_OFFSET is the first pixel of the tab bar; it must differ
        // from the white fill we applied before painting.
        let px = pixel(&data, stride, X_OFFSET as i32, mid_y);
        assert_ne!(
            px,
            (255, 255, 255),
            "pixel at x={X_OFFSET} should be tab bar chrome, not white background"
        );
    }

    /// A tab with an [`crate::primitives::tab_bar::TabIcon`] must
    /// reserve extra width over an otherwise-identical icon-less tab, and
    /// its close button must still resolve to a `TabClose` hit at the
    /// close bounds the layout reports (the icon reservation must not
    /// disturb close-glyph hit-test geometry).
    #[test]
    #[allow(deprecated)]
    fn icon_reserves_extra_width_and_close_still_hit_tests() {
        use crate::primitives::tab_bar::{TabBarHit, TabIcon};

        let bar = TabBar {
            id: WidgetId::new("tabs"),
            tabs: vec![TabItem {
                label: "main.rs".to_string(),
                is_active: true,
                ..Default::default()
            }],
            scroll_offset: 0,
            right_segments: vec![],
            active_accent: None,
            show_tab_close: true,
            compact: false,
        };

        let surface = ImageSurface::create(Format::ARgb32, W, ROW_H).expect("create ImageSurface");
        let cr = Context::new(&surface).expect("Context::new");
        let pango_layout = pangocairo::functions::create_layout(&cr);
        let theme = make_theme();

        // Same bar painted twice — only the icon sidecar differs, so any
        // geometry delta below is attributable to the icon reservation.
        let (_, no_icon_layout) = draw_tab_bar(
            &cr,
            &pango_layout,
            0.0,
            W as f64,
            LINE_H,
            0.0,
            ROW_H as f64,
            &bar,
            &theme,
            None,
        );

        let icons = vec![Some(TabIcon {
            glyph: "\u{f09b}".to_string(),
            color: Color::rgb(240, 150, 60),
        })];
        let (icon_hits, icon_layout) = draw_tab_bar_icons(
            &cr,
            &pango_layout,
            0.0,
            W as f64,
            LINE_H,
            0.0,
            ROW_H as f64,
            &bar,
            &icons,
            &theme,
            None,
        );

        let no_icon_w = no_icon_layout.visible_tabs[0].bounds.width;
        let icon_w = icon_layout.visible_tabs[0].bounds.width;
        assert!(
            icon_w > no_icon_w,
            "tab with an icon should reserve more width than an otherwise-identical \
             icon-less tab: {icon_w} vs {no_icon_w}"
        );

        let close_bounds = icon_layout.visible_tabs[0]
            .close_bounds
            .expect("icon tab should still have a close button reserved");
        let click_x = close_bounds.x + close_bounds.width / 2.0;
        let click_y = close_bounds.y + close_bounds.height / 2.0;
        match icon_layout.hit_test(click_x, click_y) {
            TabBarHit::TabClose(0) => {}
            other => panic!("expected TabClose(0) at close bounds, got {other:?}"),
        }
        assert!(
            icon_hits.close_bounds[0].is_some(),
            "TabBarHits should also report the close bounds for the icon tab"
        );
    }

    /// When a bar opts in with `active_accent: Some(colour)`,
    /// the accent paints on the chip's inset top edge — `TAB_CHIP_INSET_Y`
    /// rows below the strip's own top edge, not row 0 of the strip
    /// itself. The strip's own inset margin above the chip must not be the
    /// accent colour, and the row a few pixels below the accent must be
    /// the tab body, confirming the accent is a thin strip on the chip,
    /// not the whole active-tab background.
    #[test]
    fn active_tab_top_row_is_accent_when_opted_in() {
        let accent = Color::rgb(90, 170, 255);
        let surface = ImageSurface::create(Format::ARgb32, W, ROW_H).expect("create ImageSurface");
        {
            let cr = Context::new(&surface).expect("Context::new");
            cr.set_source_rgb(1.0, 1.0, 1.0);
            cr.paint().ok();
            let pango_layout = pangocairo::functions::create_layout(&cr);
            let mut bar = make_bar();
            bar.active_accent = Some(accent);
            let theme = make_theme();
            draw_tab_bar(
                &cr,
                &pango_layout,
                0.0,
                W as f64,
                LINE_H,
                0.0,
                ROW_H as f64,
                &bar,
                &theme,
                None,
            );
        }
        let mut surface = surface;
        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");

        let chip_top = TAB_CHIP_INSET_Y as i32;

        let margin = pixel(&data, stride, 5, 0);
        assert_ne!(
            margin,
            (accent.r, accent.g, accent.b),
            "the strip's inset margin above the chip must not be the accent colour"
        );

        let top = pixel(&data, stride, 5, chip_top);
        assert_eq!(
            top,
            (accent.r, accent.g, accent.b),
            "the chip's inset top edge should be the opted-in active_accent colour"
        );

        let below = pixel(&data, stride, 5, chip_top + 3);
        assert_ne!(
            below,
            (accent.r, accent.g, accent.b),
            "a few rows below the top accent should be the tab body, not the accent colour"
        );
    }

    /// `active_accent: None` must paint no accent strip at all —
    /// the contract the TUI (`tui::tab_bar::draw_tab_bar`) and macOS
    /// (`macos::tab_bar`) rasterisers implement. When `active_accent` is
    /// `None`, callers like unfocused splits or bottom-panel tab strips
    /// expect no accent regardless of theme defaults.
    #[test]
    fn active_tab_top_row_has_no_accent_when_none() {
        let surface = ImageSurface::create(Format::ARgb32, W, ROW_H).expect("create ImageSurface");
        let theme = make_theme();
        {
            let cr = Context::new(&surface).expect("Context::new");
            cr.set_source_rgb(1.0, 1.0, 1.0);
            cr.paint().ok();
            let pango_layout = pangocairo::functions::create_layout(&cr);
            let bar = make_bar();
            assert_eq!(bar.active_accent, None, "test fixture must exercise None");
            draw_tab_bar(
                &cr,
                &pango_layout,
                0.0,
                W as f64,
                LINE_H,
                0.0,
                ROW_H as f64,
                &bar,
                &theme,
                None,
            );
        }
        let mut surface = surface;
        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");

        let border_top = theme.tab_active_border_top();
        let active_bg = theme.tab_active_bg;
        let chip_top = TAB_CHIP_INSET_Y as i32;
        let top = pixel(&data, stride, 5, chip_top);
        assert_ne!(
            top,
            (border_top.r, border_top.g, border_top.b),
            "with active_accent: None, the chip's top row must NOT be theme.tab_active_border_top()"
        );
        assert_eq!(
            top,
            (active_bg.r, active_bg.g, active_bg.b),
            "with active_accent: None, the chip's top row should just be the active tab's \
             background — no accent strip painted over it"
        );
    }

    /// `TabFrame::Brackets` must widen the active tab (room for `[`
    /// and `]`) and shift its close-button hit region right of the
    /// leading bracket — while `close_bounds`' own *width* stays exactly
    /// the glyph's, so a click still resolves to `TabClose`, not `Tab`.
    #[test]
    #[allow(deprecated)]
    fn bracket_frame_widens_active_tab_and_close_bounds_excludes_the_bracket() {
        use crate::primitives::tab_bar::{TabBarHit, TabChrome, TabFrame};

        let bar = TabBar {
            id: WidgetId::new("tabs"),
            tabs: vec![TabItem {
                label: "main.rs".to_string(),
                is_active: true,
                ..Default::default()
            }],
            scroll_offset: 0,
            right_segments: vec![],
            active_accent: None,
            show_tab_close: true,
            compact: false,
        };

        let surface = ImageSurface::create(Format::ARgb32, W, ROW_H).expect("create ImageSurface");
        let cr = Context::new(&surface).expect("Context::new");
        let pango_layout = pangocairo::functions::create_layout(&cr);
        let theme = make_theme();

        let (_, plain_layout) = draw_tab_bar(
            &cr,
            &pango_layout,
            0.0,
            W as f64,
            LINE_H,
            0.0,
            ROW_H as f64,
            &bar,
            &theme,
            None,
        );

        let chrome = TabChrome::new(TabFrame::Brackets);
        let (chrome_hits, chrome_layout) = draw_tab_bar_with_chrome(
            &cr,
            &pango_layout,
            0.0,
            W as f64,
            LINE_H,
            0.0,
            ROW_H as f64,
            &bar,
            &chrome,
            &theme,
            None,
        );

        let plain_w = plain_layout.visible_tabs[0].bounds.width;
        let chrome_w = chrome_layout.visible_tabs[0].bounds.width;
        assert!(
            chrome_w > plain_w,
            "bracket framing should widen the active tab: {chrome_w} vs {plain_w}"
        );

        let plain_close = plain_layout.visible_tabs[0]
            .close_bounds
            .expect("plain tab should still report close bounds");
        let chrome_close = chrome_layout.visible_tabs[0]
            .close_bounds
            .expect("bracket-framed tab should still report close bounds");
        // Since the plain close region is now *also* tight (just the
        // glyph + its leading gap, via `TabMeasure::trailing_width` — the
        // same mechanism the bracket path already used), the two close
        // regions are the same width; only their trailing chrome differs
        // (the bracket path additionally reserves room for `]`).
        assert!(
            (plain_close.width - chrome_close.width).abs() < 0.01,
            "post-#1080, the plain and bracket-framed close regions should be \
             the same tight width (glyph + leading gap only): plain={}, chrome={}",
            plain_close.width,
            chrome_close.width
        );
        assert!(
            chrome_close.x > plain_close.x,
            "close region should shift right to make room for the leading bracket"
        );
        let plain_tab_end =
            plain_layout.visible_tabs[0].bounds.x + plain_layout.visible_tabs[0].bounds.width;
        assert!(
            plain_close.x + plain_close.width < plain_tab_end,
            "#1080: the plain close bounds must also stop before the tab's own \
             right edge — a click in the trailing pad/gap must not resolve to \
             TabClose"
        );
        let chrome_tab_end =
            chrome_layout.visible_tabs[0].bounds.x + chrome_layout.visible_tabs[0].bounds.width;
        assert!(
            chrome_close.x + chrome_close.width < chrome_tab_end,
            "close bounds must stop before the tab's right edge, leaving room for ']'"
        );

        let click_x = chrome_close.x + chrome_close.width / 2.0;
        let click_y = chrome_close.y + chrome_close.height / 2.0;
        match chrome_layout.hit_test(click_x, click_y) {
            TabBarHit::TabClose(0) => {}
            other => panic!("expected TabClose(0) at close bounds, got {other:?}"),
        }

        assert_eq!(chrome_hits.close_bounds.len(), 1);
        assert!(chrome_hits.close_bounds[0].is_some());
    }

    /// The active-tab chip's fill height must equal
    /// `row_height - 2.0 * TAB_CHIP_INSET_Y` — checked for two different
    /// `row_height` values so a hardcoded inset (rather than one computed
    /// from `row_height`) would be caught. Antialiasing is disabled so the
    /// chip's straight top/bottom edges (the sample column is well clear of
    /// the rounded corners, which only affect the outermost
    /// `TAB_CHIP_RADIUS` px on each side) land on exact pixel rows.
    #[test]
    fn active_chip_height_scales_with_row_height() {
        let theme = make_theme();
        for row_h in [24.0_f64, 40.0_f64] {
            let h = row_h.ceil() as i32;
            let surface = ImageSurface::create(Format::ARgb32, W, h).expect("create ImageSurface");
            {
                let cr = Context::new(&surface).expect("Context::new");
                cr.set_antialias(pangocairo::cairo::Antialias::None);
                cr.set_source_rgb(1.0, 1.0, 1.0);
                cr.paint().ok();
                let pango_layout = pangocairo::functions::create_layout(&cr);
                let bar = make_bar();
                draw_tab_bar(
                    &cr,
                    &pango_layout,
                    0.0,
                    W as f64,
                    LINE_H,
                    0.0,
                    row_h,
                    &bar,
                    &theme,
                    None,
                );
            }
            let mut surface = surface;
            surface.flush();
            let stride = surface.stride() as usize;
            let data = surface.data().expect("surface data");
            let active_bg = theme.tab_active_bg;

            // Sample a column safely clear of the chip's rounded corners.
            let x = TAB_CHIP_RADIUS as i32 + 4;
            let mut count = 0;
            for y in 0..h {
                if pixel(&data, stride, x, y) == (active_bg.r, active_bg.g, active_bg.b) {
                    count += 1;
                }
            }
            let expected = (row_h - 2.0 * TAB_CHIP_INSET_Y).round() as i32;
            assert_eq!(
                count, expected,
                "chip fill height at row_height={row_h} should be row_height - 2*inset, \
                 got a run of {count} active_bg rows"
            );
        }
    }

    /// The chip's top edge sits `TAB_CHIP_INSET_Y` below the bar's
    /// own `y_offset`, and its bottom edge the same distance above the
    /// bar's bottom — symmetric, and relative to a non-zero `y_offset` so
    /// the test can't pass by accident on the `y_offset == 0` coincidence.
    #[test]
    fn active_chip_inset_is_symmetric_around_a_nonzero_y_offset() {
        const Y_OFFSET: f64 = 10.0;
        const ROW_H_F: f64 = 24.0;
        let full_h = (Y_OFFSET + ROW_H_F).ceil() as i32;
        let surface = ImageSurface::create(Format::ARgb32, W, full_h).expect("create ImageSurface");
        let theme = make_theme();
        {
            let cr = Context::new(&surface).expect("Context::new");
            cr.set_antialias(pangocairo::cairo::Antialias::None);
            cr.set_source_rgb(1.0, 1.0, 1.0);
            cr.paint().ok();
            let pango_layout = pangocairo::functions::create_layout(&cr);
            let bar = make_bar();
            draw_tab_bar(
                &cr,
                &pango_layout,
                0.0,
                W as f64,
                LINE_H,
                Y_OFFSET,
                ROW_H_F,
                &bar,
                &theme,
                None,
            );
        }
        let mut surface = surface;
        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        let active_bg = theme.tab_active_bg;

        let x = TAB_CHIP_RADIUS as i32 + 4;
        let is_chip =
            |y: i32| pixel(&data, stride, x, y) == (active_bg.r, active_bg.g, active_bg.b);

        let first_chip_row = (0..full_h)
            .find(|&y| is_chip(y))
            .expect("chip should paint");
        let last_chip_row = (0..full_h)
            .rev()
            .find(|&y| is_chip(y))
            .expect("chip should paint");

        let top_margin = first_chip_row as f64 - Y_OFFSET;
        let bottom_margin = (Y_OFFSET + ROW_H_F) - (last_chip_row as f64 + 1.0);

        assert_eq!(
            top_margin, TAB_CHIP_INSET_Y,
            "chip top edge should sit TAB_CHIP_INSET_Y below the bar's y_offset"
        );
        assert_eq!(
            bottom_margin, TAB_CHIP_INSET_Y,
            "chip bottom edge should sit TAB_CHIP_INSET_Y above the bar's bottom, \
             symmetric with the top margin"
        );
    }

    /// The four corner pixels of the active chip's bounding rect must
    /// be the bar background, not `tab_active_bg` — the assertion that
    /// actually pins the rounded radius (a square chip would fill those
    /// corners with the active colour).
    #[test]
    fn active_chip_corners_are_bar_background_not_active_fill() {
        let surface = ImageSurface::create(Format::ARgb32, W, ROW_H).expect("create ImageSurface");
        let theme = make_theme();
        let layout;
        {
            let cr = Context::new(&surface).expect("Context::new");
            cr.set_antialias(pangocairo::cairo::Antialias::None);
            cr.set_source_rgb(1.0, 1.0, 1.0);
            cr.paint().ok();
            let pango_layout = pangocairo::functions::create_layout(&cr);
            let bar = make_bar();
            let (_, l) = draw_tab_bar(
                &cr,
                &pango_layout,
                0.0,
                W as f64,
                LINE_H,
                0.0,
                ROW_H as f64,
                &bar,
                &theme,
                None,
            );
            layout = l;
        }
        let mut surface = surface;
        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");

        let bounds = layout.visible_tabs[0].bounds;
        let chip_x0 = bounds.x as i32;
        // Painted fill width excludes the trailing TAB_OUTER_GAP (see
        // `tab_visual_w` in `draw_tab_bar_icons_with_chrome`).
        let chip_x1 = (bounds.x + bounds.width - TAB_OUTER_GAP as f32) as i32 - 1;
        let chip_y0 = TAB_CHIP_INSET_Y as i32;
        let chip_y1 = ROW_H - TAB_CHIP_INSET_Y as i32 - 1;

        let bar_bg = theme.tab_bar_bg;
        for &(x, y) in &[
            (chip_x0, chip_y0),
            (chip_x1, chip_y0),
            (chip_x0, chip_y1),
            (chip_x1, chip_y1),
        ] {
            let px = pixel(&data, stride, x, y);
            assert_eq!(
                px,
                (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"
            );
        }
    }

    /// `tab_bar_hits_from_layout` (via `TabBarLayout::hit_test`) reports
    /// the tab's hit region at the full `row_height`, even though the
    /// visible chip is inset. A click 1px into the strip's top margin —
    /// above the chip's `TAB_CHIP_INSET_Y`-px inset — must resolve to the
    /// tab, not `Empty`.
    #[test]
    fn hit_test_in_top_margin_above_chip_still_resolves_to_tab() {
        use crate::primitives::tab_bar::TabBarHit;

        assert!(
            TAB_CHIP_INSET_Y > 1.0,
            "test assumes the chip's inset margin is more than 1px"
        );

        let surface = ImageSurface::create(Format::ARgb32, W, ROW_H).expect("create ImageSurface");
        let cr = Context::new(&surface).expect("Context::new");
        let pango_layout = pangocairo::functions::create_layout(&cr);
        let bar = make_bar();
        let theme = make_theme();
        let (_hits, layout) = draw_tab_bar(
            &cr,
            &pango_layout,
            0.0,
            W as f64,
            LINE_H,
            0.0,
            ROW_H as f64,
            &bar,
            &theme,
            None,
        );

        let bounds = layout.visible_tabs[0].bounds;
        assert_eq!(
            bounds.height, ROW_H as f32,
            "the tab's hit rect must stay the full row_height, not the visible chip height"
        );

        let click_x = bounds.x + 5.0;
        match layout.hit_test(click_x, 1.0) {
            TabBarHit::Tab(0) => {}
            other => panic!(
                "expected Tab(0) for a click in the top margin above the chip, got {other:?}"
            ),
        }
    }

    /// The inactive-tab paint path is untouched — no chip, no radius.
    /// An inactive tab must never show `tab_active_bg` anywhere in its
    /// column; if the chip logic ever leaked into the inactive branch (or
    /// the `is_active` check were dropped), this would catch it, since
    /// `tab_active_bg` is asserted distinct from `tab_bar_bg` by
    /// `make_theme`.
    #[test]
    fn inactive_tab_never_paints_the_active_chip_colour() {
        let theme = make_theme();
        assert_ne!(
            theme.tab_active_bg, theme.tab_bar_bg,
            "fixture requires active/inactive colours to differ"
        );

        let bar = TabBar {
            id: WidgetId::new("test-tabs"),
            tabs: vec![TabItem {
                label: "main.rs".to_string(),
                is_active: false,
                ..Default::default()
            }],
            scroll_offset: 0,
            right_segments: vec![],
            active_accent: None,
            show_tab_close: false,
            compact: false,
        };

        let surface = ImageSurface::create(Format::ARgb32, W, ROW_H).expect("create ImageSurface");
        let layout;
        {
            let cr = Context::new(&surface).expect("Context::new");
            cr.set_source_rgb(1.0, 1.0, 1.0);
            cr.paint().ok();
            let pango_layout = pangocairo::functions::create_layout(&cr);
            let (_, l) = draw_tab_bar(
                &cr,
                &pango_layout,
                0.0,
                W as f64,
                LINE_H,
                0.0,
                ROW_H as f64,
                &bar,
                &theme,
                None,
            );
            layout = l;
        }
        let mut surface = surface;
        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");

        let bounds = layout.visible_tabs[0].bounds;
        // Sample inside the tab's left padding (`TAB_PAD`), well clear of
        // the label glyphs — a column through the text would show the
        // label's foreground colour instead of the background fill.
        let x = bounds.x as i32 + 3;
        let active_bg = theme.tab_active_bg;
        let bar_bg = theme.tab_bar_bg;
        for y in 0..ROW_H {
            let px = pixel(&data, stride, x, y);
            assert_ne!(
                px,
                (active_bg.r, active_bg.g, active_bg.b),
                "inactive tab must never paint the active chip colour at y={y}"
            );
            assert_eq!(
                px,
                (bar_bg.r, bar_bg.g, bar_bg.b),
                "inactive tab should fill its full row_height with bar background, \
                 unrestricted by the chip's inset, at y={y}"
            );
        }
    }

    /// A click in the dead space just inside the tab's right edge —
    /// the trailing `tab_pad + tab_outer_gap` — must resolve to `Tab`,
    /// not `TabClose`. The `close_bounds` must not extend into the
    /// trailing padding.
    #[test]
    fn close_region_excludes_trailing_padding_via_draw_tab_bar() {
        use crate::primitives::tab_bar::TabBarHit;

        // `make_bar` disables `show_tab_close`, so build a closable variant
        // instead — same shape, close button on.
        let mut bar = make_bar();
        bar.show_tab_close = true;
        let theme = make_theme();
        let surface = ImageSurface::create(Format::ARgb32, W, ROW_H).expect("create ImageSurface");
        let cr = Context::new(&surface).expect("Context::new");
        let pango_layout = pangocairo::functions::create_layout(&cr);

        let (_, layout) = draw_tab_bar(
            &cr,
            &pango_layout,
            0.0,
            W as f64,
            LINE_H,
            0.0,
            ROW_H as f64,
            &bar,
            &theme,
            None,
        );

        let vt = &layout.visible_tabs[0];
        let close = vt
            .close_bounds
            .expect("closable tab must report close bounds");
        let tab_right_edge = vt.bounds.x + vt.bounds.width;
        let probe_y = vt.bounds.y + vt.bounds.height / 2.0;

        assert!(
            close.x + close.width < tab_right_edge,
            "close region must stop before the tab's right edge: close ends at {}, \
             tab ends at {tab_right_edge}",
            close.x + close.width,
        );
        match layout.hit_test(tab_right_edge - 1.0, probe_y) {
            TabBarHit::Tab(0) => {}
            other => panic!(
                "click 1px inside the tab's right edge (old dead padding) \
                 expected Tab(0), got {other:?}"
            ),
        }
        match layout.hit_test(close.x + close.width / 2.0, probe_y) {
            TabBarHit::TabClose(0) => {}
            other => {
                panic!("click at the close region's centre expected TabClose(0), got {other:?}")
            }
        }
    }
}