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
//! Direct2D / DirectWrite rasteriser for [`crate::TabBar`].
//!
//! Calls [`TabBar::layout`] (the D6 layout API) with DirectWrite pixel
//! measurers, then paints from the resolved `visible_tabs` /
//! `visible_segments`. Converts to [`TabBarHits`] via the shared
//! [`crate::backend::tab_bar_hits_from_layout`] / `shift_tab_bar_hits`
//! helpers, the same ones the TUI and GTK backends use — see
//! `Backend::tab_bar_layout`'s doc for why that shift matters.
//!
//! Only the actual Direct2D paint entry points ([`draw_tab_bar`],
//! [`draw_tab_bar_icons`], [`draw_tab_bar_layout`],
//! [`draw_tab_bar_icons_layout`], and their shared paint loop) are
//! `#[cfg(target_os = "windows")]`-gated. [`compute_layout`] and every
//! `win_tab_bar_*` no-paint fn below are pure geometry generic over
//! [`crate::primitives::layout_metrics::TextMeasure`] — no Direct2D/
//! DirectWrite type in their signature — so they compile and run
//! everywhere, including a plain `cargo test --features win` on Linux.
//!
//! Takes the live theme as a `&Theme` parameter, matching every other
//! Win-GUI rasteriser's convention — the caller
//! ([`crate::win::WinBackend::draw_tab_bar_icons`] /
//! `draw_tab_bar_icons_layout`) passes `&self.current_theme`, the same
//! field `Backend::set_theme` writes.
//!
//! Scope: no [`crate::TabChrome`] / bracket-frame support (the `Backend`
//! trait gives `draw_tab_bar_with_chrome` / `tab_bar_layout_with_chrome`
//! default bodies that fall back to the plain methods below, so this is
//! not a compile-error gap — see those methods' docs) and no italic
//! preview-tab styling (would need a second `IDWriteTextFormat`; deferred
//! to a follow-up rather than widening this issue).
//!
//! Still a per-backend paint loop. Unlike `win::menu_bar` /
//! `win::toolbar` / `win::activity_bar`, which were collapsed into
//! `primitives::<name>::native_surface_paint::paint`, every pixel
//! `paint_tab_bar_icons_from_layout` below draws is still Direct2D-
//! specific and still triplicated with `gtk::tab_bar` / `macos::tab_bar`
//! — the two scope gaps just above (no bracket chrome, no italic preview
//! styling; this module also ignores `theme.tab_preview_*_fg` entirely)
//! are three of the five live drifts between those copies. See
//! [`crate::primitives::tab_bar`]'s "`PaintSurface` migration status"
//! section for the full drift table and the macOS `close_bounds`-convention
//! prerequisite that blocks the move.

#[cfg(target_os = "windows")]
use windows::Win32::Graphics::Direct2D::ID2D1RenderTarget;

#[cfg(target_os = "windows")]
use super::text::fill_rect;
#[cfg(target_os = "windows")]
use super::text::DWrite;
use crate::backend::{shift_tab_bar_hits, tab_bar_hits_from_layout};
use crate::event::Rect;
use crate::primitives::layout_metrics::TextMeasure;
#[cfg(target_os = "windows")]
use crate::primitives::tab_bar::TabBarGlyphs;
#[cfg(target_os = "windows")]
use crate::theme::Theme;
// `TabBarHits` is `#[deprecated]` — this module still
// narrows its `TabBarLayout` down to that struct because the six
// `Backend` tab-bar methods `WinBackend` implements still return it, so
// the import needs the same allow every use site below does.
#[allow(deprecated)]
use crate::{tab_icon_at, TabBar, TabBarHits, TabBarLayout, TabChrome, TabIcon};

/// Left+right padding (DIPs) inside a tab's background fill.
const TAB_PAD_DIP: f32 = 14.0;
/// Gap (DIPs) between a tab's label and its close glyph.
const TAB_INNER_GAP_DIP: f32 = 10.0;
/// Gap (DIPs) between adjacent tabs.
const TAB_OUTER_GAP_DIP: f32 = 1.0;
/// Gap (DIPs) between a tab's icon glyph ([`crate::TabIcon`]) and its label.
const TAB_ICON_GAP_DIP: f32 = 6.0;
/// Height (DIPs) of the active tab's top-edge accent line. Only used by
/// the paint path.
#[cfg(target_os = "windows")]
const TAB_ACTIVE_ACCENT_DIP: f32 = 2.0;

/// Only used by the paint loop below (for hover-rect/close-glyph
/// positioning) — the shared [`pixel_layout`] re-measures the same glyph
/// itself via `measure`, so paint and layout can never disagree about its
/// width even though each measures it once.
#[cfg(target_os = "windows")]
fn close_glyph_width(measure: &dyn TextMeasure, bar: &TabBar) -> f32 {
    if bar.show_tab_close {
        // The codicon close glyph — `measure` (a live `&DWrite`)
        // always has the bundled codicon fallback baked into its text
        // format, see `DWrite::new`'s doc.
        measure.width_of(&crate::codicon::CLOSE.to_string())
    } else {
        0.0
    }
}

fn icon_extra_width(measure: &dyn TextMeasure, icons: &[Option<TabIcon>], i: usize) -> f32 {
    match tab_icon_at(icons, i) {
        Some(icon) => measure.width_of(&icon.glyph) + TAB_ICON_GAP_DIP,
        None => 0.0,
    }
}

/// Resolve a [`TabBarGlyphs`] slot (the close or dirty override) to the
/// text run this rasteriser paints via `dwrite.draw_text`, falling back to
/// `default` when the slot is unset. Unlike the TUI backend's per-cell
/// `tab_glyph_char`, this keeps the resolved glyph as a whole `String` —
/// Direct2D paints it as one text run, not one terminal cell.
#[cfg(target_os = "windows")]
fn tab_glyph_text(
    icon: Option<&crate::types::Icon>,
    nerd_fonts_enabled: bool,
    default: char,
) -> String {
    icon.map(|icon| icon.resolve(nerd_fonts_enabled).to_string())
        .unwrap_or_else(|| default.to_string())
}

/// Compute `(layout, corrected_scroll_offset, available_cols)` for `bar`
/// against `rect`'s dimensions, measuring every tab/segment via `measure`.
/// Shared by every paint and no-paint entry point in this module so they
/// can never disagree on geometry.
///
/// Wraps the shared [`crate::primitives::layout_metrics::pixel_tab_bar_layout`].
/// Windows has no bracket-chrome support yet (see this module's "Scope" doc),
/// so `chrome` is always [`TabChrome::default`]. Pure geometry over
/// [`TextMeasure`] — no Direct2D/DirectWrite type needed, so
/// [`super::backend::WinBackend`] can call this directly with a
/// [`super::backend`]-local nominal measurer when no live `DWrite`
/// handle exists yet.
fn pixel_layout(
    measure: &dyn TextMeasure,
    rect: Rect,
    bar: &TabBar,
    icons: &[Option<TabIcon>],
) -> (TabBarLayout, usize, usize) {
    let tab_name_widths: Vec<f32> = bar
        .tabs
        .iter()
        .map(|t| measure.width_of(&t.label))
        .collect();
    let icon_extras: Vec<f32> = (0..bar.tabs.len())
        .map(|i| icon_extra_width(measure, icons, i))
        .collect();
    crate::primitives::layout_metrics::pixel_tab_bar_layout(
        bar,
        rect.width,
        rect.height,
        TAB_PAD_DIP,
        TAB_INNER_GAP_DIP,
        TAB_OUTER_GAP_DIP,
        &tab_name_widths,
        &icon_extras,
        &TabChrome::default(),
        measure,
    )
}

/// Compute the [`TabBarLayout`] half of [`pixel_layout`] — the icon-less
/// callers below only need the layout, not the scroll-offset/
/// available-cols engine feedback.
fn compute_layout(
    measure: &dyn TextMeasure,
    rect: Rect,
    bar: &TabBar,
    icons: &[Option<TabIcon>],
) -> TabBarLayout {
    pixel_layout(measure, rect, bar, icons).0
}

#[allow(deprecated)] // builds the deprecated `TabBarHits` — issue #823
fn hits_from_layout(
    rect: Rect,
    bar: &TabBar,
    layout: &TabBarLayout,
    corrected_scroll_offset: usize,
    available_cols: usize,
) -> TabBarHits {
    let mut hits = tab_bar_hits_from_layout(layout, bar);
    shift_tab_bar_hits(&mut hits, rect.x as f64);
    hits.correct_scroll_offset = corrected_scroll_offset;
    hits.available_cols = available_cols;
    hits
}

/// Compute a [`TabBar`]'s layout without painting, for a bar decorated
/// with per-tab icons — the no-paint twin of
/// [`draw_tab_bar_icons`]. `&[]` reproduces [`win_tab_bar_layout`].
#[allow(deprecated)] // returns the deprecated `TabBarHits` — issue #823
pub fn win_tab_bar_layout_icons(
    measure: &dyn TextMeasure,
    rect: Rect,
    bar: &TabBar,
    icons: &[Option<TabIcon>],
) -> TabBarHits {
    let (layout, corrected_scroll_offset, available_cols) = pixel_layout(measure, rect, bar, icons);
    hits_from_layout(rect, bar, &layout, corrected_scroll_offset, available_cols)
}

/// Compute a [`TabBar`]'s layout without painting — the icon-less twin of
/// [`win_tab_bar_layout_icons`].
#[allow(deprecated)] // returns the deprecated `TabBarHits` — issue #823
pub fn win_tab_bar_layout(measure: &dyn TextMeasure, rect: Rect, bar: &TabBar) -> TabBarHits {
    win_tab_bar_layout_icons(measure, rect, bar, &[])
}

/// Compute a [`TabBar`]'s [`TabBarLayout`] without painting, for a bar
/// decorated with per-tab icons. Unlike macOS's `mac_tab_bar_native_layout`,
/// no duplicated measurement code is needed here: [`compute_layout`] already
/// *is* the single measurement path both [`draw_tab_bar_icons`] and
/// [`win_tab_bar_layout_icons`] narrow down to `TabBarHits` — this just
/// returns it directly.
pub fn win_tab_bar_native_layout_icons(
    measure: &dyn TextMeasure,
    rect: Rect,
    bar: &TabBar,
    icons: &[Option<TabIcon>],
) -> TabBarLayout {
    compute_layout(measure, rect, bar, icons)
}

/// Compute a [`TabBar`]'s [`TabBarLayout`] without painting — the
/// icon-less twin of [`win_tab_bar_native_layout_icons`].
pub fn win_tab_bar_native_layout(
    measure: &dyn TextMeasure,
    rect: Rect,
    bar: &TabBar,
) -> TabBarLayout {
    win_tab_bar_native_layout_icons(measure, rect, bar, &[])
}

/// Draw a [`TabBar`] with per-tab icon glyphs into `rect` (DIPs)
/// on `target`. Returns [`TabBarHits`] in **target-surface (absolute)**
/// coordinates, matching [`crate::Backend::draw_tab_bar_icons`]'s
/// contract.
///
/// `icons` is a sidecar slice parallel to `bar.tabs` — see
/// [`crate::tab_icon_at`]. `hovered_close_tab` paints a lightened
/// background behind the hovered tab's close glyph.
///
/// # Visual contract
///
/// - **Active tab:** `theme.tab_active_bg` background, plus a
///   [`TAB_ACTIVE_ACCENT_DIP`]-tall top-edge accent line when
///   [`TabBar::active_accent`] is `Some` (`None` paints nothing, matching
///   every other backend).
/// - **Dirty tab:** close glyph is a codicon filled circle instead of
///   the codicon close mark (suppressed while hovered, so the hover
///   state always shows the close mark to close).
/// - **Right segments:** painted in `tab_inactive_fg`, or `tab_active_fg`
///   when `seg.is_active`.
#[cfg(target_os = "windows")]
#[allow(deprecated)] // returns the deprecated `TabBarHits` — issue #823
pub fn draw_tab_bar_icons(
    target: &ID2D1RenderTarget,
    dwrite: &DWrite,
    rect: Rect,
    bar: &TabBar,
    icons: &[Option<TabIcon>],
    hovered_close_tab: Option<usize>,
    theme: &Theme,
) -> TabBarHits {
    draw_tab_bar_icons_with_glyphs(
        target,
        dwrite,
        rect,
        bar,
        icons,
        hovered_close_tab,
        theme,
        None,
        false,
    )
}

/// [`draw_tab_bar_icons`], but honouring an optional
/// [`TabBarGlyphs`] override for the close/dirty mark — `glyphs: None`
/// reproduces [`draw_tab_bar_icons`] exactly.
///
/// Caveat: the close-glyph hover rect and hit zone
/// ([`crate::TabBarHits::close_bounds`]) are both sized from
/// [`close_glyph_width`], which measures the default codicon close glyph
/// — not the override. A visually wide `with_close_glyph`/
/// `with_dirty_glyph` override can overhang the tab and paint outside the
/// rect the hover/hit geometry reserved for it.
#[cfg(target_os = "windows")]
#[allow(deprecated, clippy::too_many_arguments)] // returns the deprecated `TabBarHits` — issue #823
pub fn draw_tab_bar_icons_with_glyphs(
    target: &ID2D1RenderTarget,
    dwrite: &DWrite,
    rect: Rect,
    bar: &TabBar,
    icons: &[Option<TabIcon>],
    hovered_close_tab: Option<usize>,
    theme: &Theme,
    glyphs: Option<&TabBarGlyphs>,
    nerd_fonts_enabled: bool,
) -> TabBarHits {
    let (layout, corrected_scroll_offset, available_cols) = pixel_layout(dwrite, rect, bar, icons);
    paint_tab_bar_icons_from_layout(
        target,
        dwrite,
        rect,
        bar,
        icons,
        hovered_close_tab,
        &layout,
        theme,
        glyphs,
        nerd_fonts_enabled,
    );
    hits_from_layout(rect, bar, &layout, corrected_scroll_offset, available_cols)
}

/// Draw a [`TabBar`] with per-tab icon glyphs, returning [`TabBarLayout`]
/// instead of the deprecated [`TabBarHits`] — the
/// `TabBarLayout`-returning counterpart to [`draw_tab_bar_icons`] above.
/// Shares [`compute_layout`] and [`paint_tab_bar_icons_from_layout`] with
/// it, so the two can never paint different pixels — only the return
/// value differs.
#[cfg(target_os = "windows")]
pub fn draw_tab_bar_icons_layout(
    target: &ID2D1RenderTarget,
    dwrite: &DWrite,
    rect: Rect,
    bar: &TabBar,
    icons: &[Option<TabIcon>],
    hovered_close_tab: Option<usize>,
    theme: &Theme,
) -> TabBarLayout {
    let layout = compute_layout(dwrite, rect, bar, icons);
    paint_tab_bar_icons_from_layout(
        target,
        dwrite,
        rect,
        bar,
        icons,
        hovered_close_tab,
        &layout,
        theme,
        None,
        false,
    );
    layout
}

/// Shared paint loop for [`draw_tab_bar_icons`] / [`draw_tab_bar_icons_layout`]
/// — paints `bar` from a pre-computed `layout` and returns nothing, so
/// both callers can hand back whichever return type (`TabBarHits` vs.
/// `TabBarLayout`) their contract needs.
#[cfg(target_os = "windows")]
#[allow(clippy::too_many_arguments)]
fn paint_tab_bar_icons_from_layout(
    target: &ID2D1RenderTarget,
    dwrite: &DWrite,
    rect: Rect,
    bar: &TabBar,
    icons: &[Option<TabIcon>],
    hovered_close_tab: Option<usize>,
    layout: &TabBarLayout,
    theme: &Theme,
    glyphs: Option<&TabBarGlyphs>,
    nerd_fonts_enabled: bool,
) {
    let _ = fill_rect(target, rect, theme.tab_bar_bg);

    let close_w = close_glyph_width(dwrite, bar);

    for vt in &layout.visible_tabs {
        let tab = &bar.tabs[vt.tab_idx];
        let visual_w = (vt.bounds.width - TAB_OUTER_GAP_DIP).max(0.0);
        let tab_rect = Rect::new(
            rect.x + vt.bounds.x,
            rect.y + vt.bounds.y,
            visual_w,
            vt.bounds.height,
        );

        let bg = if tab.is_active {
            theme.tab_active_bg
        } else {
            theme.tab_bar_bg
        };
        let _ = fill_rect(target, tab_rect, bg);

        if tab.is_active {
            if let Some(accent) = bar.active_accent {
                let accent_rect = Rect::new(
                    tab_rect.x,
                    tab_rect.y,
                    tab_rect.width,
                    TAB_ACTIVE_ACCENT_DIP,
                );
                let _ = fill_rect(target, accent_rect, accent);
            }
        }

        let fg = if tab.is_active {
            theme.tab_active_fg
        } else {
            theme.tab_inactive_fg
        };
        let mut cursor_x = tab_rect.x + TAB_PAD_DIP;

        if let Some(icon) = tab_icon_at(icons, vt.tab_idx) {
            let (iw, ih) = dwrite.measure_text(&icon.glyph).unwrap_or((0.0, 0.0));
            let icon_rect = Rect::new(cursor_x, tab_rect.y + (tab_rect.height - ih) / 2.0, iw, ih);
            let _ = dwrite.draw_text(target, &icon.glyph, icon_rect, icon.color);
            cursor_x += iw + TAB_ICON_GAP_DIP;
        }

        let (name_w, name_h) = dwrite.measure_text(&tab.label).unwrap_or((0.0, 0.0));
        let label_rect = Rect::new(
            cursor_x,
            tab_rect.y + (tab_rect.height - name_h) / 2.0,
            name_w,
            name_h,
        );
        let _ = dwrite.draw_text(target, &tab.label, label_rect, fg);

        if bar.show_tab_close && tab.is_closable {
            if let Some(cb) = vt.close_bounds {
                let close_x = rect.x + cb.x + TAB_INNER_GAP_DIP;
                let is_close_hovered = hovered_close_tab == Some(vt.tab_idx);

                if is_close_hovered {
                    let hover_bg = theme.tab_bar_bg.lighten(0.15);
                    let hover_rect = Rect::new(
                        close_x - 2.0,
                        tab_rect.y + 2.0,
                        close_w + 4.0,
                        (tab_rect.height - 4.0).max(0.0),
                    );
                    let _ = fill_rect(target, hover_rect, hover_bg);
                }

                // Codicon glyphs by default — `dwrite` always has the
                // bundled codicon fallback baked into its text format, see
                // `DWrite::new`'s doc. An app-supplied `glyphs` override
                // replaces either mark.
                let close_glyph = if tab.is_dirty && !is_close_hovered {
                    tab_glyph_text(
                        glyphs.and_then(TabBarGlyphs::dirty_glyph),
                        nerd_fonts_enabled,
                        crate::codicon::DIRTY,
                    )
                } else {
                    tab_glyph_text(
                        glyphs.and_then(TabBarGlyphs::close_glyph),
                        nerd_fonts_enabled,
                        crate::codicon::CLOSE,
                    )
                };
                let close_fg = if tab.is_dirty || is_close_hovered {
                    theme.foreground
                } else if tab.is_active {
                    theme.tab_inactive_fg
                } else {
                    theme.separator
                };
                let (cgw, cgh) = dwrite.measure_text(&close_glyph).unwrap_or((0.0, 0.0));
                let close_rect = Rect::new(
                    close_x,
                    tab_rect.y + (tab_rect.height - cgh) / 2.0,
                    cgw,
                    cgh,
                );
                let _ = dwrite.draw_text(target, &close_glyph, close_rect, close_fg);
            }
        }
    }

    for vs in &layout.visible_segments {
        let seg = &bar.right_segments[vs.segment_idx];
        let fg = if seg.is_active {
            theme.tab_active_fg
        } else {
            theme.tab_inactive_fg
        };
        let (seg_w, seg_h) = dwrite.measure_text(&seg.text).unwrap_or((0.0, 0.0));
        let seg_rect = Rect::new(
            rect.x + vs.bounds.x,
            rect.y + vs.bounds.y + (vs.bounds.height - seg_h) / 2.0,
            seg_w,
            seg_h,
        );
        let _ = dwrite.draw_text(target, &seg.text, seg_rect, fg);
    }
}

/// Draw a [`TabBar`] with no per-tab icons — [`draw_tab_bar_icons`] with
/// `icons: &[]`.
#[cfg(target_os = "windows")]
#[allow(deprecated)] // returns the deprecated `TabBarHits` — issue #823
pub fn draw_tab_bar(
    target: &ID2D1RenderTarget,
    dwrite: &DWrite,
    rect: Rect,
    bar: &TabBar,
    hovered_close_tab: Option<usize>,
    theme: &Theme,
) -> TabBarHits {
    draw_tab_bar_icons(target, dwrite, rect, bar, &[], hovered_close_tab, theme)
}

/// Draw a [`TabBar`] with no per-tab icons, returning [`TabBarLayout`]
/// instead of the deprecated [`TabBarHits`] —
/// [`draw_tab_bar_icons_layout`] with `icons: &[]`.
#[cfg(target_os = "windows")]
pub fn draw_tab_bar_layout(
    target: &ID2D1RenderTarget,
    dwrite: &DWrite,
    rect: Rect,
    bar: &TabBar,
    hovered_close_tab: Option<usize>,
    theme: &Theme,
) -> TabBarLayout {
    draw_tab_bar_icons_layout(target, dwrite, rect, bar, &[], hovered_close_tab, theme)
}

// Tests below paint through a real `DWrite`/`HeadlessSurface` — the module's
// paint fns are now the only Windows-only parts. A cross-platform-safe
// pure-geometry test lives in `win::list`'s test mod instead, since
// `list_layout` exercises the measurement code in a portable way.
#[cfg(all(test, target_os = "windows"))]
mod tests {
    use super::*;
    use crate::primitives::tab_bar::{TabBarHit, TabBarSegment, TabItem};
    use crate::types::{Color, WidgetId};
    use crate::win::testing::HeadlessSurface;

    const W: f32 = 300.0;
    const H: f32 = 30.0;

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

    /// Paint↔click round trip: the active tab's background must be
    /// painted at its own bounds, and a click at the centre of each
    /// visible tab (per the independently-computed `TabBarLayout`) must
    /// `hit_test` back to that tab.
    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` — issue #823
    fn paint_and_hit_test_round_trip() {
        let surface = HeadlessSurface::new(W as u32, H as u32).expect("create surface");
        let (dwrite, _, _) = DWrite::new("Segoe UI", 10.0, None).expect("create DWrite");
        let bar = bar();
        let rect = Rect::new(0.0, 0.0, W, H);

        surface
            .paint(|target| {
                draw_tab_bar(target, &dwrite, rect, &bar, None, &Theme::default());
            })
            .expect("paint tab bar");

        let layout = compute_layout(&dwrite, rect, &bar, &[]);
        assert_eq!(layout.visible_tabs.len(), 2, "both tabs should fit");

        for vt in &layout.visible_tabs {
            let cx = vt.bounds.x + vt.bounds.width / 2.0;
            let cy = vt.bounds.y + vt.bounds.height / 2.0;
            assert_eq!(
                layout.hit_test(cx, cy),
                TabBarHit::Tab(vt.tab_idx),
                "tab {} centre should hit-test back to itself",
                vt.tab_idx,
            );
        }

        // Active tab (index 0) is painted with `theme.tab_active_bg`,
        // distinct from the bar's own `tab_bar_bg` — sample just inside
        // its left padding, clear of the accent line and any glyph.
        let theme = Theme::default();
        let active_bounds = layout.visible_tabs[0].bounds;
        let sample_x = (active_bounds.x + 2.0) as u32;
        let sample_y = (active_bounds.y + active_bounds.height - 4.0) as u32;
        let px = surface.pixel_at(sample_x, sample_y);
        assert_eq!(
            (px.r, px.g, px.b),
            (
                theme.tab_active_bg.r,
                theme.tab_active_bg.g,
                theme.tab_active_bg.b
            ),
            "active tab should paint its background at its own bounds"
        );

        // Right segment's `TabBarHits.right_segment_bounds[0]` must agree
        // (in absolute coordinates) with where the layout's own
        // `visible_segments[0]` says it painted.
        let hits = win_tab_bar_layout(&dwrite, rect, &bar);
        let vs = &layout.visible_segments[0];
        assert_eq!(
            hits.right_segment_bounds[0],
            (vs.bounds.x as f64, (vs.bounds.x + vs.bounds.width) as f64),
            "TabBarHits right-segment bounds must be absolute (rect.x == 0 here) \
             and agree with the layout's own visible_segments"
        );
    }

    /// The no-paint layout (`win_tab_bar_layout`) must agree byte-for-byte
    /// with what `draw_tab_bar` painted — same bar, same rect, same
    /// measurer.
    #[test]
    fn no_paint_layout_matches_paint_layout() {
        let (dwrite, _, _) = DWrite::new("Segoe UI", 10.0, None).expect("create DWrite");
        let bar = bar();
        let rect = Rect::new(5.0, 0.0, W, H);

        let surface = HeadlessSurface::new((W + 5.0) as u32, H as u32).expect("create surface");
        let mut painted = None;
        surface
            .paint(|target| {
                painted = Some(draw_tab_bar(
                    target,
                    &dwrite,
                    rect,
                    &bar,
                    None,
                    &Theme::default(),
                ));
            })
            .expect("paint");
        let painted = painted.expect("draw_tab_bar ran");
        let no_paint = win_tab_bar_layout(&dwrite, rect, &bar);

        assert_eq!(painted, no_paint);
    }

    /// The new `TabBarLayout`-returning fns (`draw_tab_bar_layout` /
    /// `win_tab_bar_native_layout`) must agree with each other exactly as their
    /// `TabBarHits`-returning siblings do — same bar, same rect, same measurer.
    /// Since both new fns are thin wrappers over the shared `compute_layout`
    /// this is mostly a wiring check, but it pins the paint path's `layout`
    /// (post-paint) against the no-paint path's independently-called
    /// `compute_layout` so the two can't silently diverge later.
    #[test]
    fn native_layout_no_paint_matches_native_layout_paint() {
        let (dwrite, _, _) = DWrite::new("Segoe UI", 10.0, None).expect("create DWrite");
        let bar = bar();
        let rect = Rect::new(5.0, 0.0, W, H);

        let surface = HeadlessSurface::new((W + 5.0) as u32, H as u32).expect("create surface");
        let mut painted = None;
        surface
            .paint(|target| {
                painted = Some(draw_tab_bar_layout(
                    target,
                    &dwrite,
                    rect,
                    &bar,
                    None,
                    &Theme::default(),
                ));
            })
            .expect("paint");
        let painted = painted.expect("draw_tab_bar_layout ran");
        let no_paint = win_tab_bar_native_layout(&dwrite, rect, &bar);

        assert_eq!(painted, no_paint);
    }

    /// The `TabBarLayout`-returning accessor and the deprecated
    /// `TabBarHits`-returning one must report the same geometry — converting the
    /// former through the shared `tab_bar_hits_from_layout` helper and comparing
    /// field-by-field against the latter's direct output. This is the "twin"
    /// pattern: the other backends each get their own version of this test
    /// (`gtk::testing::tab_bar_layout_twin_matches_painted_geometry_headless`,
    /// its TUI counterpart, and macOS's `native_layout_agrees_with_hits_layout`).
    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` — issue #823
    fn native_layout_agrees_with_hits_layout() {
        let (dwrite, _, _) = DWrite::new("Segoe UI", 10.0, None).expect("create DWrite");
        let bar = bar();
        let rect = Rect::new(0.0, 0.0, W, H);

        let hits = win_tab_bar_layout(&dwrite, rect, &bar);
        let native = win_tab_bar_native_layout(&dwrite, rect, &bar);
        let mut native_as_hits = tab_bar_hits_from_layout(&native, &bar);
        shift_tab_bar_hits(&mut native_as_hits, rect.x as f64);

        assert_eq!(
            hits.slot_positions, native_as_hits.slot_positions,
            "tab slots must agree between the two accessors"
        );
        assert_eq!(
            hits.close_bounds, native_as_hits.close_bounds,
            "close-button spans must agree too"
        );
        assert_eq!(
            hits.right_segment_bounds, native_as_hits.right_segment_bounds,
            "right-segment spans must agree too"
        );
    }

    /// An app-supplied [`TabBarGlyphs`] override swaps the close/dirty
    /// mark the Windows rasteriser paints; with `glyphs: None`,
    /// [`draw_tab_bar_icons_with_glyphs`] paints the same codicon default
    /// as [`draw_tab_bar_icons`].
    #[test]
    fn close_dirty_glyph_override_paints_app_glyph_default_paints_codicon() {
        let (dwrite, _, _) = DWrite::new("Segoe UI", 10.0, None).expect("create DWrite");
        let mut dirty_bar = bar();
        dirty_bar.tabs[0].is_dirty = true;
        let rect = Rect::new(0.0, 0.0, W, H);

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

        let surface = HeadlessSurface::new(W as u32, H as u32).expect("create surface");
        let previous = crate::testing::install_text_run_sink();
        surface
            .paint(|target| {
                draw_tab_bar_icons_with_glyphs(
                    target,
                    &dwrite,
                    rect,
                    &dirty_bar,
                    &[],
                    None,
                    &Theme::default(),
                    Some(&glyphs),
                    true,
                );
            })
            .expect("paint with glyph override");
        let runs = crate::testing::take_text_run_sink(previous);
        assert!(
            runs.iter().any(|r| r.text == "*"),
            "expected the overridden dirty glyph among painted runs, got {:?}",
            runs.iter().map(|r| r.text.as_str()).collect::<Vec<_>>()
        );
        assert!(!runs.iter().any(|r| r.text.contains(crate::codicon::DIRTY)));
        // Tab 1 (`lib.rs`) is closable and not dirty, so the close-glyph
        // override paints there too.
        assert!(
            runs.iter().any(|r| r.text == "x"),
            "expected the overridden close glyph among painted runs, got {:?}",
            runs.iter().map(|r| r.text.as_str()).collect::<Vec<_>>()
        );
        assert!(!runs.iter().any(|r| r.text.contains(crate::codicon::CLOSE)));

        let surface = HeadlessSurface::new(W as u32, H as u32).expect("create surface");
        let previous = crate::testing::install_text_run_sink();
        surface
            .paint(|target| {
                draw_tab_bar_icons_with_glyphs(
                    target,
                    &dwrite,
                    rect,
                    &dirty_bar,
                    &[],
                    None,
                    &Theme::default(),
                    None,
                    true,
                );
            })
            .expect("paint with no override");
        let runs = crate::testing::take_text_run_sink(previous);
        assert!(
            runs.iter().any(|r| r.text.contains(crate::codicon::DIRTY)),
            "expected the default codicon dirty glyph among painted runs, got {:?}",
            runs.iter().map(|r| r.text.as_str()).collect::<Vec<_>>()
        );
        assert!(
            runs.iter().any(|r| r.text.contains(crate::codicon::CLOSE)),
            "expected the default codicon close glyph among painted runs, got {:?}",
            runs.iter().map(|r| r.text.as_str()).collect::<Vec<_>>()
        );
    }

    /// Drives the override through [`crate::backend::Backend`]'s
    /// `draw_tab_bar_with_chrome_and_glyphs` method on
    /// [`crate::win::backend::WinBackend`] — the actual deliverable this
    /// module's free functions are wired behind — rather than calling
    /// [`draw_tab_bar_icons_with_glyphs`] (the free fn) directly, the way
    /// the test above does.
    #[test]
    fn backend_trait_close_dirty_glyph_override_paints_app_glyph_default_paints_codicon() {
        use crate::backend::Backend;
        use crate::win::backend::WinBackend;

        let mut dirty_bar = bar();
        dirty_bar.tabs[0].is_dirty = true;
        let rect = Rect::new(0.0, 0.0, W, H);
        let chrome = TabChrome::default();

        let paint = |glyphs: Option<&TabBarGlyphs>| {
            let surface = HeadlessSurface::new(W as u32, H as u32).expect("create surface");
            let mut backend = WinBackend::new();
            backend
                .attach_headless(surface.target().clone(), W as u32, H as u32)
                .expect("attach headless surface");
            backend.set_painted_text_recording(true);
            backend.begin_frame(crate::event::Viewport::new(W, H, 1.0));
            #[allow(deprecated)] // returns the deprecated `TabBarHits` — issue #823
            let _ = backend
                .draw_tab_bar_with_chrome_and_glyphs(rect, &dirty_bar, None, &chrome, glyphs);
            backend.end_frame();
            backend.text_runs().to_vec()
        };

        let glyphs = TabBarGlyphs::new()
            .with_close_glyph("x")
            .with_dirty_glyph("*");
        let overridden = paint(Some(&glyphs));
        assert!(
            overridden.iter().any(|r| r.text == "*"),
            "expected the overridden dirty glyph among painted runs, got {:?}",
            overridden
                .iter()
                .map(|r| r.text.as_str())
                .collect::<Vec<_>>()
        );
        assert!(
            overridden.iter().any(|r| r.text == "x"),
            "expected the overridden close glyph among painted runs, got {:?}",
            overridden
                .iter()
                .map(|r| r.text.as_str())
                .collect::<Vec<_>>()
        );
        assert!(!overridden
            .iter()
            .any(|r| r.text.contains(crate::codicon::DIRTY)));
        assert!(!overridden
            .iter()
            .any(|r| r.text.contains(crate::codicon::CLOSE)));

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