quadraui 0.6.1

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
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
//! TUI rasteriser for [`crate::TabBar`].
//!
//! Per D6: this function consumes a pre-computed
//! [`crate::TabBarLayout`] (built by the caller via
//! [`crate::TabBar::layout`] with its native cell-width measurer)
//! and paints the resolved `visible_tabs` + `visible_segments`
//! verbatim. Returns the tab-content width (in cells) so the caller
//! can adjust scroll offset for the next frame.

use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Modifier;

use super::text::char_cell_width;
use super::{ratatui_color, set_cell, set_cell_styled, set_cell_wide, set_cell_wide_styled};
// `TabBarHits` is `#[deprecated]` — this whole module's job is
// still building one per frame; see that struct's doc for the replacement
// plan (`TabBarLayout`, which every function below already receives as
// its `layout` parameter).
#[allow(deprecated)]
use crate::primitives::tab_bar::{TabBar, TabBarHits, TabBarLayout, TabChrome, TabFrame};
use crate::theme::Theme;
use crate::types::Icon;

/// Resolve a [`crate::primitives::tab_bar::TabBarGlyphs`] slot (the close
/// or dirty override) to the single `char` this rasteriser paints,
/// falling back to `default` when the slot is unset. Shared so the
/// close-glyph and dirty-glyph branches below don't repeat the same
/// `Option` chain.
fn tab_glyph_char(icon: Option<&Icon>, nerd_fonts_enabled: bool, default: char) -> char {
    icon.map(|icon| icon.resolve(nerd_fonts_enabled))
        .and_then(|s| s.chars().next())
        .unwrap_or(default)
}

/// Close-button glyph rendered on each tab. `×` (U+00D7 MULTIPLICATION
/// SIGN) — narrower than `✕` and present in every monospaced terminal
/// font we've encountered.
pub const TAB_CLOSE_CHAR: char = '×';

/// Cell width reserved per tab for the close-button + trailing
/// separator. Apps that build a [`crate::TabMeasure`] for tab-bar
/// layout pass this as the `close_width` so the layout reserves the
/// right amount of trailing space.
pub const TAB_CLOSE_COLS: u16 = 2;

/// Separator glyph painted between adjacent tab labels that have no
/// close button to provide their own visual boundary (`show_tab_close:
/// false`, or a non-closable tab). Light vertical box-drawing rule —
/// renders in every monospaced terminal font and reads as a distinct
/// item boundary rather than running labels together.
pub const TAB_SEPARATOR_CHAR: char = '│';

/// Cell width reserved after a tab with no close button, for
/// [`TAB_SEPARATOR_CHAR`]. Apps that build a [`crate::TabMeasure`] for a
/// tab with `close_width: 0.0` should add this to the tab's measured
/// width so the rasteriser has a cell to paint the separator into — with
/// one exception: a bracket-framed active tab (see [`TabChrome`]) also
/// measures `close_width: 0.0`, but its final column is the closing `]`,
/// not a separator, so it must not add this constant.
///
/// The rasteriser paints the separator right after the label (plus any
/// close glyph), not necessarily at the tab's last column — if the
/// measurer reserves more trailing width than this constant, the extra
/// slack lands as blank space between the separator and the next tab.
/// Every no-close tab gets one, including the last visible tab, so a bar
/// with no right segments ends on a trailing rule rather than a blank
/// edge; that's deliberate, matching how a close-button bar always ends
/// on its last `×`/`●` glyph rather than blank space.
pub const TAB_SEPARATOR_COLS: u16 = 1;

/// Draw a [`TabBar`] into `area` on `buf`. Returns the **tab-content
/// width** in cells (`area.width - reserved_by_right_segments`) so
/// the caller can decide how many tabs fit and what scroll offset to
/// use on the next frame.
///
/// # Visual contract
///
/// - **Bar background:** filled with `theme.tab_bar_bg`.
/// - **Active tab:** `tab_active_fg` + `tab_active_bg`. When
///   [`TabBar::active_accent`] is `Some`, the filename portion (chars
///   after the last `": "` in `tab.label`) gets a
///   [`Modifier::UNDERLINED`] with that accent colour.
/// - **Dirty tab:** the close cell shows `●` in `theme.foreground`
///   instead of `×`.
/// - **Preview tab:** `*_preview_*_fg` and [`Modifier::ITALIC`]; combines
///   with the underline accent when active.
/// - **Icon:** never painted by this entry point — it passes an empty
///   icon sidecar. Call [`draw_tab_bar_icons`] to decorate tabs with
///   [`crate::TabIcon`] glyphs.
/// - **Right segments:** painted in `tab_inactive_fg` (or
///   `tab_active_fg` when `seg.is_active`). Double-width glyphs
///   (per `unicode-width`) use [`set_cell_wide`].
/// - **Tab labels:** measured and painted in display columns, not
///   `char`s — a double-width glyph (per `unicode-width`) uses
///   [`set_cell_wide`]/[`set_cell_wide_styled`] and advances the cursor
///   by 2, mirroring the right-segment loop above. The measure side
///   (`TuiBackend::draw_tab_bar` / `tab_bar_layout` in `backend.rs`)
///   must agree, or a tab is measured narrower than it paints.
///
///   Downstream: vimcode's `tab_hit_width` (`src/render.rs`) is
///   deliberately pinned on the pre-#554 `.chars().count()` measure
///   because it must agree with what this rasteriser paints; its own
///   doc comment names this fix as the unblocker for switching to a
///   `display_width` measure there. coord-tui consumes the same tab
///   bar and should be checked for the equivalent assumption.
#[allow(deprecated)] // returns the deprecated `TabBarHits`
pub fn draw_tab_bar(
    buf: &mut Buffer,
    area: Rect,
    bar: &TabBar,
    layout: &TabBarLayout,
    theme: &Theme,
) -> TabBarHits {
    draw_tab_bar_icons(buf, area, bar, &[], layout, theme)
}

/// [`draw_tab_bar`] plus per-tab icon glyphs.
///
/// `icons` is a sidecar slice parallel to `bar.tabs` (see
/// [`crate::Backend::draw_tab_bar_icons`]); resolve entries with
/// [`crate::tab_icon_at`] / [`crate::tab_icon_cols`] so a short slice
/// means "no icon" rather than a panic. Passing `&[]` reproduces
/// [`draw_tab_bar`] cell for cell.
///
/// Each decorated tab paints its glyph at the tab's leading edge in
/// [`crate::TabIcon::color`] — independent of the tab's
/// active/inactive foreground, so the icon keeps its identity colour on
/// an inactive tab — followed by a 1-column gap before the label. That
/// reservation is [`crate::tab_icon_cols`], exactly what
/// `TuiBackend::draw_tab_bar_icons` / `tab_bar_layout_icons`
/// (`backend.rs`) add to the tab's measured width, so paint and
/// measurement cannot drift.
#[allow(deprecated)] // returns the deprecated `TabBarHits`
pub fn draw_tab_bar_icons(
    buf: &mut Buffer,
    area: Rect,
    bar: &TabBar,
    icons: &[Option<crate::primitives::tab_bar::TabIcon>],
    layout: &TabBarLayout,
    theme: &Theme,
) -> TabBarHits {
    draw_tab_bar_icons_with_chrome(buf, area, bar, icons, &TabChrome::default(), layout, theme)
}

/// [`draw_tab_bar`] with an explicit [`TabChrome`] request.
///
/// `&[]` icons + [`TabChrome::default`] reproduces [`draw_tab_bar`] cell
/// for cell. See [`TabChrome::active_frame`] for what each frame paints.
#[allow(deprecated)] // returns the deprecated `TabBarHits`
pub fn draw_tab_bar_with_chrome(
    buf: &mut Buffer,
    area: Rect,
    bar: &TabBar,
    chrome: &TabChrome,
    layout: &TabBarLayout,
    theme: &Theme,
) -> TabBarHits {
    draw_tab_bar_icons_with_chrome(buf, area, bar, &[], chrome, layout, theme)
}

/// [`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. The caller's measurer must have already reserved the
/// extra columns this needs in `layout` (see `TuiBackend::draw_tab_bar_*`
/// in `backend.rs`, which build the chrome-aware
/// [`crate::TabMeasure`] before calling [`TabBar::layout`]) — this
/// function paints from `layout` verbatim and does not recompute widths.
#[allow(deprecated)] // returns the deprecated `TabBarHits`
pub fn draw_tab_bar_icons_with_chrome(
    buf: &mut Buffer,
    area: Rect,
    bar: &TabBar,
    icons: &[Option<crate::primitives::tab_bar::TabIcon>],
    chrome: &TabChrome,
    layout: &TabBarLayout,
    theme: &Theme,
) -> TabBarHits {
    draw_tab_bar_icons_with_chrome_and_glyphs(
        buf, area, bar, icons, chrome, layout, theme, None, false,
    )
}

/// [`draw_tab_bar_icons_with_chrome`] with an optional app-supplied
/// [`crate::primitives::tab_bar::TabBarGlyphs`] override for the close
/// and dirty marks.
///
/// `glyphs: None` reproduces [`draw_tab_bar_icons_with_chrome`] cell for
/// cell — the default `×`/`●` glyphs are unchanged. Passing `Some` only
/// overrides the glyphs it sets; any field left `None` keeps the
/// default for that mark. `nerd_fonts_enabled` selects which half of
/// each override [`Icon`] — `glyph` or `fallback` — is resolved (see
/// [`crate::Backend::nerd_fonts_enabled`]); it is ignored when `glyphs`
/// does not set the mark being drawn.
#[allow(deprecated)] // returns the deprecated `TabBarHits`
#[allow(clippy::too_many_arguments)]
pub fn draw_tab_bar_icons_with_chrome_and_glyphs(
    buf: &mut Buffer,
    area: Rect,
    bar: &TabBar,
    icons: &[Option<crate::primitives::tab_bar::TabIcon>],
    chrome: &TabChrome,
    layout: &TabBarLayout,
    theme: &Theme,
    glyphs: Option<&crate::primitives::tab_bar::TabBarGlyphs>,
    nerd_fonts_enabled: bool,
) -> TabBarHits {
    if area.width == 0 || area.height == 0 {
        return TabBarHits::default();
    }

    let bar_bg = ratatui_color(theme.tab_bar_bg);
    let btn_fg = ratatui_color(theme.tab_inactive_fg);
    let btn_fg_active = ratatui_color(theme.tab_active_fg);
    let foreground = ratatui_color(theme.foreground);

    // Fill bar background.
    for x in area.x..area.x + area.width {
        set_cell(buf, x, area.y, ' ', bar_bg, bar_bg);
    }

    // Tab-content width (engine feedback): bar minus reserved right area.
    let reserved: u16 = bar.right_segments.iter().map(|s| s.width_cells).sum();
    let tab_content_width = if area.width >= reserved {
        (area.width - reserved) as usize
    } else {
        area.width as usize
    };

    // ── Right-aligned segments (from layout) ───────────────────────────
    let mut right_segment_bounds: Vec<(f64, f64)> = Vec::with_capacity(bar.right_segments.len());
    for vs in &layout.visible_segments {
        let seg = &bar.right_segments[vs.segment_idx];
        let fg = if seg.is_active { btn_fg_active } else { btn_fg };
        let bx = area.x + vs.bounds.x.round() as u16;
        let seg_end = bx + seg.width_cells;
        right_segment_bounds.push((bx as f64, seg_end as f64));
        let mut cx = bx;
        for ch in seg.text.chars() {
            if cx >= seg_end {
                break;
            }
            let w = char_cell_width(ch);
            if w == 2 {
                if cx + 1 < seg_end + 1 {
                    set_cell_wide(buf, cx, area.y, ch, fg, bar_bg);
                    cx += 2;
                } else {
                    cx += 1;
                }
            } else {
                set_cell(buf, cx, area.y, ch, fg, bar_bg);
                cx += 1;
            }
        }
    }

    // ── Tabs (from layout) ─────────────────────────────────────────────
    let accent = bar.active_accent.map(ratatui_color);
    let active_fg = ratatui_color(theme.tab_active_fg);
    let active_bg = ratatui_color(theme.tab_active_bg);
    let preview_active_fg = ratatui_color(theme.tab_preview_active_fg);
    let inactive_fg = ratatui_color(theme.tab_inactive_fg);
    let preview_inactive_fg = ratatui_color(theme.tab_preview_inactive_fg);
    let separator = ratatui_color(theme.separator);

    let mut slot_positions: Vec<(f64, f64)> = Vec::with_capacity(bar.tabs.len());
    let mut close_bounds: Vec<Option<(f64, f64)>> = Vec::with_capacity(bar.tabs.len());
    for _ in 0..bar.scroll_offset.min(bar.tabs.len()) {
        slot_positions.push((0.0, 0.0));
        close_bounds.push(None);
    }
    for vt in &layout.visible_tabs {
        let tab = &bar.tabs[vt.tab_idx];
        let tab_x = area.x + vt.bounds.x.round() as u16;
        let tab_w = vt.bounds.width.round() as u16;
        slot_positions.push((tab_x as f64, (tab_x + tab_w) as f64));
        // Layout carries close_bounds in primitive (cell) coords; offset by area.x.
        close_bounds.push(vt.close_bounds.map(|cb| {
            let cx = area.x as f64 + cb.x as f64;
            (cx, cx + cb.width as f64)
        }));

        let (fg, bg) = match (tab.is_active, tab.is_preview) {
            (true, true) => (preview_active_fg, active_bg),
            (true, false) => (active_fg, active_bg),
            (false, true) => (preview_inactive_fg, bar_bg),
            (false, false) => (inactive_fg, bar_bg),
        };

        // When chrome requests bracket framing, the active tab's
        // full content — icon, label, close glyph — is enclosed in `[` /
        // `]`. `lead` shifts every subsequent paint position right by one
        // column to make room for the opening bracket; the closing
        // bracket is painted after the close glyph (or after the label,
        // for a bar with no close button) below.
        let bracket_active = matches!(chrome.active_frame, TabFrame::Brackets) && tab.is_active;
        let lead: u16 = if bracket_active { 1 } else { 0 };
        if bracket_active {
            set_cell(buf, tab_x, area.y, '[', fg, bg);
        }

        // Icon glyph, if this tab has one — painted before the label in
        // its own colour, independent of the tab's active/inactive fg.
        // `tab_icon_cols` (glyph width + 1-column gap) is exactly what
        // `TuiBackend::draw_tab_bar_icons`/`tab_bar_layout_icons`
        // (backend.rs) added to this tab's measured width, so the label
        // loop below can start right after it without re-deriving the
        // reservation.
        let icon_cols = crate::primitives::tab_bar::tab_icon_cols(icons, vt.tab_idx);
        if let Some(icon) = crate::primitives::tab_bar::tab_icon_at(icons, vt.tab_idx) {
            let icon_fg = ratatui_color(icon.color);
            let icon_end = tab_x + lead + icon_cols;
            let mut cx = tab_x + lead;
            for ch in icon.glyph.chars() {
                if cx >= icon_end {
                    break;
                }
                let w = char_cell_width(ch);
                if w == 2 {
                    set_cell_wide(buf, cx, area.y, ch, icon_fg, bg);
                    cx += 2;
                } else {
                    set_cell(buf, cx, area.y, ch, icon_fg, bg);
                    cx += 1;
                }
            }
        }

        let mut modifier = Modifier::empty();
        if tab.is_preview {
            modifier |= Modifier::ITALIC;
        }
        if tab.is_active && accent.is_some() {
            modifier |= Modifier::UNDERLINED;
        }
        let prefix_mod = if tab.is_preview {
            Modifier::ITALIC
        } else {
            Modifier::empty()
        };

        // Layout carries total tab width; close_bounds (when present)
        // covers the close-glyph cells (already positioned before any
        // trailing chrome via `TabMeasure::trailing_width` — see
        // `TuiBackend::draw_tab_bar_with_chrome`). Label occupies the
        // cells between the leading bracket (if any) and close_bounds.x.
        let tab_width = vt.bounds.width.round() as u16;
        // A bracket-framed tab with no close button still reserves its
        // last column for the closing bracket; `close_bounds` is `None`
        // in that case (no close button), so it isn't already excluded
        // from `tab_width` the way the close region is.
        let trailing_bracket_no_close: u16 = if bracket_active && vt.close_bounds.is_none() {
            1
        } else {
            0
        };
        let label_end = match vt.close_bounds {
            Some(cb) => area.x + cb.x.round() as u16,
            None => tab_x + tab_width - trailing_bracket_no_close,
        };
        let tab_end = tab_x + tab_width;

        // Filename (after the last ": ") carries the underline accent.
        let prefix_len = tab.label.rfind(": ").map(|p| p + 2).unwrap_or(0);

        // Stride by display width, not by `char`: a double-width
        // glyph (CJK, many emoji) must land in two columns, mirroring the
        // right-segment loop above. `TuiBackend::draw_tab_bar` /
        // `tab_bar_layout` (backend.rs) measure `label_end`'s budget with
        // the same `display_width` function, so the two sides agree.
        let mut x = tab_x + lead + icon_cols;
        for (ci, ch) in tab.label.chars().enumerate() {
            if x >= label_end {
                break;
            }
            let in_filename = ci >= prefix_len;
            let cell_mod = if in_filename { modifier } else { prefix_mod };
            let ul = if in_filename && tab.is_active {
                accent
            } else {
                None
            };
            let w = char_cell_width(ch);
            if w == 2 {
                if x + 1 < label_end + 1 {
                    set_cell_wide_styled(buf, x, area.y, ch, fg, bg, cell_mod, ul);
                    x += 2;
                } else {
                    // Not enough budget left for the glyph's second column
                    // — skip rather than paint half of a wide char.
                    x += 1;
                }
            } else {
                set_cell_styled(buf, x, area.y, ch, fg, bg, cell_mod, ul);
                x += 1;
            }
        }

        // Close glyph: ● for dirty, × otherwise (or the app-supplied
        // override from `glyphs`).
        if vt.close_bounds.is_some() && x < tab_end {
            let (close_ch, close_fg) = if tab.is_dirty {
                let ch = tab_glyph_char(
                    glyphs.and_then(crate::primitives::tab_bar::TabBarGlyphs::dirty_glyph),
                    nerd_fonts_enabled,
                    '●',
                );
                (ch, foreground)
            } else {
                let ch = tab_glyph_char(
                    glyphs.and_then(crate::primitives::tab_bar::TabBarGlyphs::close_glyph),
                    nerd_fonts_enabled,
                    TAB_CLOSE_CHAR,
                );
                let fg = if tab.is_active { active_fg } else { separator };
                (ch, fg)
            };
            set_cell(buf, x, area.y, close_ch, close_fg, bg);
            x += 1;
        }
        // The closing bracket lands right after the close glyph
        // (or right after the label, for a bracket-framed tab with no
        // close button) — taking the place of the plain trailing
        // separator cell a non-bracket tab paints here.
        if bracket_active {
            if x < tab_end {
                set_cell(buf, x, area.y, ']', fg, bg);
            }
        } else if x < tab_end {
            if vt.close_bounds.is_none() {
                // No close button reserved for this tab — the measurer
                // (`TuiBackend::draw_tab_bar_icons`/`_with_chrome` in
                // `backend.rs`) reserved this cell as a separator column
                // instead, so paint a visible rule rather than blank
                // space; otherwise adjacent labels read as one run of
                // text with only bold-vs-not telling them apart.
                set_cell(buf, x, area.y, TAB_SEPARATOR_CHAR, separator, bar_bg);
            } else {
                // Trailing separator space (within tab bounds, uses bar bg).
                set_cell(buf, x, area.y, ' ', bar_bg, bar_bg);
            }
        }
    }

    TabBarHits {
        slot_positions,
        close_bounds,
        right_segment_bounds,
        available_cols: tab_content_width,
        // TUI's char-based fit is exact; no correction needed.
        correct_scroll_offset: bar.scroll_offset,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::tab_bar::{SegmentMeasure, TabBar, TabBarSegment, TabItem, TabMeasure};
    use crate::types::WidgetId;

    fn make_bar(active_idx: usize) -> TabBar {
        TabBar {
            id: WidgetId::new("tabs"),
            tabs: vec![
                TabItem {
                    label: "main.rs".into(),
                    is_active: active_idx == 0,
                    is_dirty: false,
                    is_preview: false,
                    is_closable: true,
                },
                TabItem {
                    label: "lib.rs".into(),
                    is_active: active_idx == 1,
                    is_dirty: true,
                    is_preview: false,
                    is_closable: true,
                },
            ],
            right_segments: vec![],
            active_accent: None,
            scroll_offset: 0,
            show_tab_close: true,
            compact: false,
        }
    }

    fn cell_char(buf: &Buffer, x: u16, y: u16) -> char {
        buf[(x, y)].symbol().chars().next().unwrap_or(' ')
    }

    /// Each tab is 12 cells total with a 1-cell close button on the right.
    fn measure_tab(_idx: usize) -> TabMeasure {
        TabMeasure::new(12.0, 1.0)
    }

    #[test]
    fn paints_two_tabs_with_close_glyph() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 40, 1));
        let bar = make_bar(0);
        let layout = bar.layout(40.0, 1.0, 0.0, measure_tab, |_| SegmentMeasure::new(0.0));
        draw_tab_bar(
            &mut buf,
            Rect::new(0, 0, 40, 1),
            &bar,
            &layout,
            &Theme::default(),
        );

        // First tab is active and not dirty — its close glyph is '×';
        // second tab is dirty — its close glyph is '●'.
        let mut found_x_close = false;
        let mut found_dirty_dot = false;
        for x in 0..40 {
            match cell_char(&buf, x, 0) {
                '×' => found_x_close = true,
                '●' => found_dirty_dot = true,
                _ => {}
            }
        }
        assert!(found_x_close, "expected '×' close glyph somewhere");
        assert!(found_dirty_dot, "expected '●' dirty glyph somewhere");
    }

    /// An app-supplied [`crate::primitives::tab_bar::TabBarGlyphs`]
    /// override swaps the close and dirty marks for the app's own
    /// glyphs; with no override,
    /// [`draw_tab_bar_icons_with_chrome_and_glyphs`] (what
    /// [`draw_tab_bar`] always calls) paints the same `×`/`●` glyphs as
    /// today's default.
    #[test]
    fn tab_bar_glyphs_override_swaps_close_and_dirty_default_keeps_defaults() {
        use crate::primitives::tab_bar::TabBarGlyphs;

        let bar = make_bar(0);
        let layout = bar.layout(40.0, 1.0, 0.0, measure_tab, |_| SegmentMeasure::new(0.0));

        // Override: the app's own glyphs replace the defaults.
        let glyphs = TabBarGlyphs::new()
            .with_close_glyph("x")
            .with_dirty_glyph("*");
        let mut buf = Buffer::empty(Rect::new(0, 0, 40, 1));
        draw_tab_bar_icons_with_chrome_and_glyphs(
            &mut buf,
            Rect::new(0, 0, 40, 1),
            &bar,
            &[],
            &TabChrome::default(),
            &layout,
            &Theme::default(),
            Some(&glyphs),
            false,
        );
        let mut found_override_close = false;
        let mut found_override_dirty = false;
        let mut found_default_close = false;
        let mut found_default_dirty = false;
        for x in 0..40 {
            match cell_char(&buf, x, 0) {
                'x' => found_override_close = true,
                '*' => found_override_dirty = true,
                '×' => found_default_close = true,
                '●' => found_default_dirty = true,
                _ => {}
            }
        }
        assert!(found_override_close, "expected overridden close glyph 'x'");
        assert!(found_override_dirty, "expected overridden dirty glyph '*'");
        assert!(!found_default_close, "default '×' should not appear");
        assert!(!found_default_dirty, "default '●' should not appear");

        // No override — byte-for-byte the same as `draw_tab_bar`'s default.
        let mut default_buf = Buffer::empty(Rect::new(0, 0, 40, 1));
        draw_tab_bar_icons_with_chrome_and_glyphs(
            &mut default_buf,
            Rect::new(0, 0, 40, 1),
            &bar,
            &[],
            &TabChrome::default(),
            &layout,
            &Theme::default(),
            None,
            false,
        );
        let mut default_found_close = false;
        let mut default_found_dirty = false;
        for x in 0..40 {
            match cell_char(&default_buf, x, 0) {
                '×' => default_found_close = true,
                '●' => default_found_dirty = true,
                _ => {}
            }
        }
        assert!(default_found_close, "expected default '×' close glyph");
        assert!(default_found_dirty, "expected default '●' dirty glyph");
    }

    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` return
    fn returns_full_width_when_no_right_segments() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 30, 1));
        let bar = make_bar(0);
        let layout = bar.layout(30.0, 1.0, 0.0, measure_tab, |_| SegmentMeasure::new(0.0));
        let hits = draw_tab_bar(
            &mut buf,
            Rect::new(0, 0, 30, 1),
            &bar,
            &layout,
            &Theme::default(),
        );
        assert_eq!(hits.available_cols, 30);
    }

    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` return
    fn reserves_right_segment_width() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 30, 1));
        let bar = TabBar {
            id: WidgetId::new("tabs"),
            tabs: vec![TabItem {
                label: "x".into(),
                is_active: true,
                is_dirty: false,
                is_preview: false,
                is_closable: true,
            }],
            right_segments: vec![TabBarSegment {
                id: Some(WidgetId::new("seg:0")),
                text: "[+]".into(),
                width_cells: 3,
                is_active: false,
            }],
            active_accent: None,
            scroll_offset: 0,
            show_tab_close: true,
            compact: false,
        };
        let layout = bar.layout(
            30.0,
            1.0,
            0.0,
            |_| TabMeasure::new(5.0, 0.0),
            |_| SegmentMeasure::new(3.0),
        );
        let hits = draw_tab_bar(
            &mut buf,
            Rect::new(0, 0, 30, 1),
            &bar,
            &layout,
            &Theme::default(),
        );
        assert_eq!(hits.available_cols, 27);
        // Right-segment bounds: 1 segment "[+]" 3 cells wide ending at col 30.
        assert_eq!(hits.right_segment_bounds.len(), 1);
        let (start, end) = hits.right_segment_bounds[0];
        assert_eq!((start, end), (27.0, 30.0));
    }

    /// Regression guard: a CJK label must paint every glyph in
    /// its own columns, not lose glyphs to a flat `x += 1` stride. This
    /// reconstructs the painted row the way a real terminal (and
    /// `TuiDriver::row_cells`) reads it — stepping by each cell's own
    /// display width and skipping the blank continuation cell that
    /// `set_cell_wide`/`set_cell_wide_styled` leave after a double-width
    /// glyph — rather than concatenating every stored cell verbatim
    /// (which would hide the bug; see contract.md §2 for the equivalent
    /// check at the acceptance layer).
    #[test]
    fn wide_glyph_label_paints_every_char_across_its_own_columns() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 40, 1));
        let label = "日本語.rs";
        let bar = TabBar {
            id: WidgetId::new("tabs"),
            tabs: vec![TabItem {
                label: label.into(),
                is_active: true,
                is_dirty: false,
                is_preview: false,
                is_closable: false,
            }],
            right_segments: vec![],
            active_accent: None,
            scroll_offset: 0,
            show_tab_close: false,
            compact: false,
        };
        // Measure with the same `display_width` function the `TuiBackend`
        // measure side uses, so the label's budget covers every column it
        // actually paints (9: 3 wide glyphs x2 + 3 narrow). No close
        // button and no separator reservation here — this test pins the
        // wide-glyph stride, not the no-close separator (see
        // `no_close_tabs_paint_a_separator_between_labels` below).
        let width = crate::tui::display_width(label) as f32;
        assert_eq!(width, 9.0);
        let layout = bar.layout(
            40.0,
            1.0,
            0.0,
            |_| TabMeasure::new(width, 0.0),
            |_| SegmentMeasure::new(0.0),
        );
        draw_tab_bar(
            &mut buf,
            Rect::new(0, 0, 40, 1),
            &bar,
            &layout,
            &Theme::default(),
        );

        let mut rendered = String::new();
        let mut x = 0u16;
        while x < 40 {
            let sym = buf[(x, 0)].symbol();
            if sym.is_empty() {
                // Blank continuation cell of a double-width glyph — the
                // terminal doesn't read this as a separate character.
                x += 1;
                continue;
            }
            rendered.push_str(sym);
            let w = sym.chars().next().map(char_cell_width).unwrap_or(1).max(1);
            x += w;
        }

        assert!(
            rendered.starts_with(label),
            "expected {label:?} to paint intact (no dropped glyphs), got {rendered:?}"
        );
    }

    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` return
    fn zero_size_is_a_no_op() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 10, 1));
        let bar = make_bar(0);
        let layout = bar.layout(10.0, 1.0, 0.0, measure_tab, |_| SegmentMeasure::new(0.0));
        // Zero-width area: function must return defaults without panicking.
        let hits = draw_tab_bar(
            &mut buf,
            Rect::new(0, 0, 0, 1),
            &bar,
            &layout,
            &Theme::default(),
        );
        assert_eq!(hits.available_cols, 0);
        assert!(hits.slot_positions.is_empty());
    }

    /// An icon glyph paints at the tab's leading edge in its own
    /// [`crate::TabIcon::color`], and the label starts right after it +
    /// the 1-column gap [`crate::tab_icon_cols`] reserves. This test's
    /// measurer reserves `icon_cols + label_w` with no close button and
    /// no separator column (`close_width: 0.0` with no
    /// `TAB_SEPARATOR_COLS` added), so it is narrower by one column than
    /// what `TuiBackend::draw_tab_bar_icons`/`tab_bar_layout_icons`
    /// (backend.rs) would reserve for the same tab — fine here since this
    /// test pins the icon-before-label paint order, not the no-close
    /// separator.
    #[test]
    fn icon_glyph_paints_before_label_and_widens_measured_tab() {
        use crate::primitives::tab_bar::TabIcon;
        use crate::types::Color;

        let icon = TabIcon {
            glyph: "\u{f09b}".into(), // single-column PUA glyph
            color: Color::rgb(240, 150, 60),
        };
        let icons = vec![Some(icon.clone())];
        let bar = TabBar {
            id: WidgetId::new("tabs"),
            tabs: vec![TabItem {
                label: "main.rs".into(),
                is_active: true,
                is_closable: false,
                ..Default::default()
            }],
            right_segments: vec![],
            active_accent: None,
            scroll_offset: 0,
            show_tab_close: false,
            compact: false,
        };

        let icon_cols = crate::tab_icon_cols(&icons, 0);
        assert_eq!(
            icon_cols, 2,
            "1-column glyph + 1-column gap before the label"
        );

        let label_w = crate::text_util::display_width(&bar.tabs[0].label) as f32;

        let mut buf = Buffer::empty(Rect::new(0, 0, 40, 1));
        let layout = bar.layout(
            40.0,
            1.0,
            0.0,
            |_| TabMeasure::new(icon_cols as f32 + label_w, 0.0),
            |_| SegmentMeasure::new(0.0),
        );
        draw_tab_bar_icons(
            &mut buf,
            Rect::new(0, 0, 40, 1),
            &bar,
            &icons,
            &layout,
            &Theme::default(),
        );

        assert_eq!(
            cell_char(&buf, 0, 0),
            '\u{f09b}',
            "icon glyph should paint at the tab's leading column"
        );
        assert_eq!(
            buf[(0, 0)].fg,
            ratatui_color(icon.color),
            "icon glyph should paint in TabIcon::color"
        );
        assert_eq!(
            cell_char(&buf, icon_cols, 0),
            'm',
            "label should start right after icon_cols (glyph + 1-column gap)"
        );
    }

    /// An empty icon sidecar must paint exactly what the icon-less
    /// [`draw_tab_bar`] entry point paints — that equivalence is what
    /// lets every backend route both entry points through one rasteriser
    /// without changing a single existing pixel.
    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` return
    fn empty_icon_sidecar_paints_identically_to_draw_tab_bar() {
        let bar = make_bar(0);
        let area = Rect::new(0, 0, 40, 1);
        let layout = bar.layout(40.0, 1.0, 0.0, measure_tab, |_| SegmentMeasure::new(0.0));

        let mut plain = Buffer::empty(area);
        let plain_hits = draw_tab_bar(&mut plain, area, &bar, &layout, &Theme::default());

        let mut sidecar = Buffer::empty(area);
        let sidecar_hits =
            draw_tab_bar_icons(&mut sidecar, area, &bar, &[], &layout, &Theme::default());

        assert_eq!(plain, sidecar, "empty sidecar must not change any cell");
        assert_eq!(
            plain_hits.slot_positions, sidecar_hits.slot_positions,
            "empty sidecar must not move any tab slot"
        );
        assert_eq!(
            plain_hits.close_bounds, sidecar_hits.close_bounds,
            "empty sidecar must not move any close button"
        );
    }

    /// `TabFrame::Brackets` must enclose the active tab's close
    /// glyph in literal `[` / `]` — and `close_bounds` must still land on
    /// the glyph itself, not the bracket wrapping it, so a click on `×`
    /// still resolves to `TabClose` rather than `Tab`.
    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` return
    fn bracket_frame_encloses_close_glyph_and_close_bounds_stay_on_the_glyph() {
        use crate::primitives::tab_bar::{TabBarHit, TabChrome, TabFrame};

        let bar = TabBar {
            id: WidgetId::new("tabs"),
            tabs: vec![
                TabItem {
                    label: "main.rs".into(),
                    is_active: true,
                    ..Default::default()
                },
                TabItem {
                    label: "lib.rs".into(),
                    is_active: false,
                    ..Default::default()
                },
            ],
            right_segments: vec![],
            active_accent: None,
            scroll_offset: 0,
            show_tab_close: true,
            compact: false,
        };
        let chrome = TabChrome::new(TabFrame::Brackets);
        // Tab 0 (active, bracketed): '[' + "main.rs"(7) + ×(1) + ']' = 10.
        // Tab 1 (inactive, plain): "lib.rs"(6) + close_cols(2) = 8.
        let layout = bar.layout(
            40.0,
            1.0,
            0.0,
            |i| {
                if i == 0 {
                    TabMeasure::new(10.0, 1.0).with_trailing(1.0)
                } else {
                    TabMeasure::new(8.0, 2.0)
                }
            },
            |_| SegmentMeasure::new(0.0),
        );

        let mut buf = Buffer::empty(Rect::new(0, 0, 40, 1));
        let hits = draw_tab_bar_with_chrome(
            &mut buf,
            Rect::new(0, 0, 40, 1),
            &bar,
            &chrome,
            &layout,
            &Theme::default(),
        );

        assert_eq!(cell_char(&buf, 0, 0), '[', "opening bracket at tab start");
        assert_eq!(cell_char(&buf, 1, 0), 'm', "label starts right after '['");
        assert_eq!(cell_char(&buf, 8, 0), '×', "close glyph right after label");
        assert_eq!(
            cell_char(&buf, 9, 0),
            ']',
            "closing bracket right after the close glyph"
        );
        // The inactive tab gets no bracket framing at all.
        assert_eq!(cell_char(&buf, 10, 0), 'l', "tab 1's label is unframed");

        let (start, end) = hits.close_bounds[0].expect("tab 0 should report close bounds");
        assert_eq!(
            (start, end),
            (8.0, 9.0),
            "close_bounds must cover just the × cell, not the ']' beside it"
        );

        match layout.hit_test(8.5, 0.0) {
            TabBarHit::TabClose(0) => {}
            other => panic!("click on the × glyph expected TabClose(0), got {other:?}"),
        }
        match layout.hit_test(9.5, 0.0) {
            TabBarHit::Tab(0) => {}
            other => panic!("click on the ']' bracket expected Tab(0) (not close), got {other:?}"),
        }
    }

    /// A compact bar with `show_tab_close: false` reserves one trailing
    /// column per tab for [`TAB_SEPARATOR_CHAR`], so adjacent labels read
    /// as distinct items instead of running together.
    #[test]
    fn no_close_tabs_paint_a_separator_between_labels() {
        use crate::primitives::tab_bar::TabBarHit;

        let bar = TabBar {
            id: WidgetId::new("tabs"),
            tabs: vec![
                TabItem {
                    label: "Problems".into(),
                    is_active: true,
                    is_closable: false,
                    ..Default::default()
                },
                TabItem {
                    label: "Output".into(),
                    is_active: false,
                    is_closable: false,
                    ..Default::default()
                },
                TabItem {
                    label: "Terminal".into(),
                    is_active: false,
                    is_closable: false,
                    ..Default::default()
                },
            ],
            right_segments: vec![],
            active_accent: None,
            scroll_offset: 0,
            show_tab_close: false,
            compact: true,
        };
        // Mirrors `TuiBackend`'s measurer: no close button reserved, so each
        // tab's width is its label plus one `TAB_SEPARATOR_COLS` column.
        let layout = bar.layout(
            40.0,
            1.0,
            0.0,
            |i| {
                let label_w = crate::tui::display_width(&bar.tabs[i].label) as f32;
                TabMeasure::new(label_w + TAB_SEPARATOR_COLS as f32, 0.0)
            },
            |_| SegmentMeasure::new(0.0),
        );

        let mut buf = Buffer::empty(Rect::new(0, 0, 40, 1));
        draw_tab_bar(
            &mut buf,
            Rect::new(0, 0, 40, 1),
            &bar,
            &layout,
            &Theme::default(),
        );

        // Column 8 is the cell right after "Problems" (8 chars) — the
        // separator this tab's measurer reserved.
        assert_eq!(
            cell_char(&buf, 8, 0),
            TAB_SEPARATOR_CHAR,
            "expected a separator glyph between the first and second tab"
        );
        // Column 15 is right after "Output" (6 chars) starting at col 9.
        assert_eq!(
            cell_char(&buf, 15, 0),
            TAB_SEPARATOR_CHAR,
            "expected a separator glyph between the second and third tab"
        );
        assert_eq!(
            layout.hit_test(8.5, 0.0),
            TabBarHit::Tab(0),
            "the separator column must stay part of the tab it follows, not a dead zone"
        );
    }
}