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
//! GTK rasteriser for [`crate::Minimap`]: fixed row pitch, per-column
//! colour blocks. Rows tile at a fixed [`crate::primitives::minimap::ROW_PITCH_PX`],
//! independent of the file's length ([`crate::MinimapSizing::FixedPitch`]) — see
//! `Minimap::layout`'s module docs for the slide behaviour when a file
//! needs more rows than the strip holds at that pitch. At that pitch,
//! [`is_legible`] is false, so painting lands in
//! [`MinimapRenderMode::ColumnBlocks`]: one 1px-wide block per non-blank
//! character column, coloured by whichever aggregated span covers it,
//! rather than one bar per line — this is what preserves the indent
//! silhouette VS Code's `renderCharacters: false` mode reads as.
//! [`MinimapRenderMode::Characters`] — real glyphs painted through Pango
//! at a scaled-down **absolute** size (`FontDescription::set_absolute_size`)
//! — is kept for pitches at or above
//! [`crate::primitives::minimap::LEGIBILITY_FLOOR_PX`] (not reached
//! by [`crate::primitives::minimap::ROW_PITCH_PX`] today, but still a real, tested code path: nothing
//! stops a future caller from requesting a taller fixed pitch). The mode
//! switch ([`render_mode`]) is a pure function of the row pitch so it's
//! deterministic and directly testable without a live surface.
//!
//! Both branches bound their per-row cost to [`COLUMN_CAPACITY`] columns:
//! `ColumnBlocks`' walk stops there, and `Characters` truncates the text
//! it hands to Pango there too, so a pathologically long line costs no
//! more to paint or shape than a short one.
//!
//! Colour lookups (both branches) walk `syntax_spans` once per paint via
//! [`SpanCursor`], not once per row — `aggregate_spans` documents its
//! output as sorted by `(line_idx, start_col)`, and `visible_lines` is
//! itself always ascending in `start_line_idx`, so a single merge-walk
//! is O(rows + spans) total rather than a per-row rescan.
//!
//! The legibility/render-mode thresholds (`is_legible`,
//! `render_mode`, `minimap_font_px`), the shared `ROW_PITCH_PX` /
//! `COLUMN_CAPACITY` geometry constants, and the span-lookup helpers
//! (`SpanCursor`, `color_at_column`, `truncate_to_columns`) now live in
//! [`crate::primitives::minimap`] so `win::minimap` (and, eventually, a
//! macOS rasteriser) consume the exact same decision logic instead of
//! growing an independent interpretation of either threshold — this
//! module only imports them.
//!
//! # Glyph atlas
//!
//! `render_mode`/`LEGIBILITY_FLOOR_PX` say a *shaped* font at
//! `ROW_PITCH_PX` is unreadable — true, and still what [`draw_minimap`]
//! (this module's public, uncached entry point, kept for source
//! compatibility) does: it stays on `render_mode`'s pitch gate, so it
//! still always lands in [`MinimapRenderMode::ColumnBlocks`], exactly as
//! before. [`draw_minimap_cached`] — what [`crate::gtk::backend::GtkBackend::draw_minimap`]
//! actually calls — takes a different path: it never shapes at the
//! target pitch at all. It builds a [`MinimapCharAtlas`] once per
//! `(font family, scale)` (cached in a [`MinimapAtlasCache`] owned by
//! `GtkBackend`, matching the `image_cache` pattern) by shaping each
//! ASCII character once, *large*, via [`render_char_sample_sheet`], then
//! box-filter-downsampling every cell to a device-pixel tile — the
//! technique [`crate::primitives::minimap`]'s "Character glyph atlas"
//! section docs describe. Painting a row then blits pre-downsampled
//! alpha tiles ([`paint_row_atlas`]/`blit_alpha_tile`) instead of asking
//! Pango to shape a 2px font — no per-frame shaping, and legible glyph
//! *shapes* at a pitch the shaper alone could never produce.

use gtk4::cairo::{Context, Format, ImageSurface};
use gtk4::pango;

use super::{cairo_rgb, set_source};
use crate::event::Rect as QRect;
use crate::primitives::layout_metrics::pixel_minimap_layout_scaled;
use crate::primitives::minimap::{
    color_at_column, minimap_font_px, render_mode, truncate_to_columns, Minimap, MinimapAtlasCache,
    MinimapCharAtlas, MinimapLayout, MinimapRenderMode, MinimapScale, MinimapSpan, SpanCursor,
    VisibleMinimapLine, ATLAS_FIRST_CHAR, ATLAS_LAST_CHAR, COLUMN_CAPACITY,
};
use crate::theme::Theme;

/// Compute the GTK pixel-unit layout for a [`Minimap`] without painting, at
/// [`MinimapScale::One`] — the pre-scaling fixed pitch. Kept for
/// source compatibility with any caller reaching this free function
/// directly; every real paint path goes through [`GtkBackend::minimap_layout`]'s
/// [`gtk_minimap_layout_scaled`] instead, so it can honor
/// [`crate::backend::Backend::minimap_scale`].
pub fn gtk_minimap_layout(minimap: &Minimap, x: f64, y: f64, w: f64, h: f64) -> MinimapLayout {
    gtk_minimap_layout_scaled(minimap, x, y, w, h, MinimapScale::One)
}

/// [`gtk_minimap_layout`], but at an explicit [`MinimapScale`]
/// — what [`GtkBackend::minimap_layout`] actually calls. Shares
/// its `lines_per_row`/sizing formula with `mac_minimap_layout_scaled` /
/// `win_minimap_layout_scaled` via [`pixel_minimap_layout_scaled`].
pub(crate) fn gtk_minimap_layout_scaled(
    minimap: &Minimap,
    x: f64,
    y: f64,
    w: f64,
    h: f64,
    scale: MinimapScale,
) -> MinimapLayout {
    pixel_minimap_layout_scaled(
        minimap,
        QRect::new(x as f32, y as f32, w as f32, h as f32),
        scale,
    )
}

/// Shared skeleton for [`draw_minimap`]/[`draw_minimap_cached`]: computes
/// the layout, paints the background and viewport highlight, clips to
/// the strip, then calls `paint_row` once per visible row via one
/// [`SpanCursor`] merge-walk. Returns early (no clip, no
/// callback invocations) when the layout has nothing to paint.
///
/// `paint_row` gets each row's own pitch (`vline.bounds.height`, post-cap),
/// even though every row shares one pitch under
/// [`MinimapSizing::FixedPitch`], so a caller never has to special-case
/// "read it off the first row instead" — plus `scale`'s own
/// [`MinimapScale::cell_w_px`], so a row's per-column paint
/// walk steps by the right cell width without re-deriving it from `scale`
/// itself.
#[allow(clippy::too_many_arguments)]
fn paint_minimap_rows(
    cr: &Context,
    x: f64,
    y: f64,
    w: f64,
    h: f64,
    minimap: &Minimap,
    theme: &Theme,
    scale: MinimapScale,
    mut paint_row: impl FnMut(&Context, &VisibleMinimapLine, f64, f64, &str, &[MinimapSpan]),
) -> MinimapLayout {
    let layout = gtk_minimap_layout_scaled(minimap, x, y, w, h, scale);

    if layout.visible_lines.is_empty() {
        return layout;
    }

    set_source(cr, theme.background);
    cr.rectangle(x, y, w, h);
    cr.fill().ok();

    let hl = &layout.viewport_highlight;
    if hl.height > 0.0 {
        let (r, g, b) = cairo_rgb(theme.accent_bg);
        cr.set_source_rgba(r, g, b, 0.25);
        cr.rectangle(hl.x as f64, hl.y as f64, hl.width as f64, hl.height as f64);
        cr.fill().ok();
    }

    // Clip all row painting to the strip: a legible pitch can still shape
    // a line longer than `w`, and below-floor colour blocks are already
    // width-bounded but glyphs are not -- without this, text bled across
    // whatever the host painted beside the minimap.
    cr.save().ok();
    cr.rectangle(x, y, w, h);
    cr.clip();

    // One merge-walk over `syntax_spans` for the whole paint, not a per-row
    // rescan -- `visible_lines` is always ascending in `start_line_idx`
    // (see `Minimap::layout`), matching `SpanCursor`'s own
    // non-decreasing-query requirement.
    let mut spans = SpanCursor::new(&minimap.syntax_spans);

    for vline in &layout.visible_lines {
        let Some(line) = minimap.lines.get(vline.start_line_idx) else {
            continue;
        };
        let row_spans = spans.row_spans(vline.start_line_idx);
        paint_row(
            cr,
            vline,
            vline.bounds.height as f64,
            scale.cell_w_px(),
            &line.text,
            row_spans,
        );
    }

    cr.restore().ok();

    layout
}

/// Draw a [`Minimap`] onto `cr`. Returns the layout for host click
/// dispatch (`layout.hit_test(x, y)` -> [`crate::MinimapHit`]).
///
/// This is kept exactly as it always behaved (still gated on [`render_mode`]'s
/// legibility floor, so it still always lands in [`MinimapRenderMode::ColumnBlocks`]
/// at the default `ROW_PITCH_PX`) — for source compatibility with any caller
/// reaching this free function directly rather than through
/// [`crate::backend::Backend::draw_minimap`], mirroring
/// `gtk::image::draw_image`'s relationship to `draw_image_cached`.
/// [`crate::gtk::backend::GtkBackend::draw_minimap`] — the path every real
/// app takes — calls [`draw_minimap_cached`] instead, which is where the
/// glyph atlas actually lives. See the module docs' "Glyph atlas" section.
#[allow(clippy::too_many_arguments)]
pub fn draw_minimap(
    cr: &Context,
    pango_layout: &pango::Layout,
    x: f64,
    y: f64,
    w: f64,
    h: f64,
    minimap: &Minimap,
    theme: &Theme,
) -> MinimapLayout {
    let saved_font = pango_layout.font_description();

    let layout = paint_minimap_rows(
        cr,
        x,
        y,
        w,
        h,
        minimap,
        theme,
        MinimapScale::One,
        |cr, vline, row_px, cell_w, text, row_spans| match render_mode(row_px) {
            MinimapRenderMode::Characters => paint_row_glyphs(
                cr,
                pango_layout,
                saved_font.as_ref(),
                vline,
                row_px,
                text,
                row_spans,
                theme,
            ),
            MinimapRenderMode::ColumnBlocks => {
                paint_row_blocks(cr, vline, text, row_spans, theme, cell_w)
            }
        },
    );

    pango_layout.set_attributes(None);
    pango_layout.set_font_description(saved_font.as_ref());
    // Reset the ellipsize/width state `paint_row_glyphs` sets so it
    // can't leak onto whatever the shared layout paints next.
    pango_layout.set_width(-1);
    pango_layout.set_ellipsize(pango::EllipsizeMode::None);

    layout
}

/// Draw a [`Minimap`] using a cached [`MinimapCharAtlas`] for real
/// character shapes, instead of [`draw_minimap`]'s legibility-gated
/// font scaling. `atlas_cache` should be a field the caller keeps alive
/// across frames — [`crate::gtk::backend::GtkBackend`] owns one, the same
/// way it owns `image_cache`. `dpi_scale` sizes each glyph tile
/// to real device pixels: a `mm_scale` cell at `dpi_scale` 2.0 gets twice
/// the real device pixels of glyph detail a `dpi_scale` 1.0 cell of the
/// same logical size does.
///
/// `mm_scale` is the *logical* cell size — [`MinimapScale::One`]
/// is a 1x2 px cell (pre-scaling: a density dot, since the atlas tile is too
/// small to carry a shape even at HiDPI), [`MinimapScale::Two`] a 2x4 px
/// cell (VS Code parity: large enough for the downsampled tile to read
/// back as a recognisable glyph). `dpi_scale` is an orthogonal axis — real
/// device-pixel crispness at whatever logical cell size `mm_scale` picked
/// — so a `mm_scale: Two` cell at `dpi_scale` 1.0 already paints
/// recognisable shapes; before scaling the only way to reach a 2x4-pixel
/// tile was a `dpi_scale` of 2.0, conflating "the user asked for bigger
/// minimap glyphs" with "the display has more physical pixels per DIP".
///
/// Never shapes at the target pitch: the atlas build (large, once per
/// `(font family, mm_scale, dpi_scale)`) happens inside
/// `atlas_cache.get_or_build` only on a cache miss; every paint after that
/// just blits pre-downsampled alpha tiles. Falls back to
/// [`paint_row_blocks`] only if the atlas itself degrades to
/// [`MinimapCharAtlas::filled`] returning a zero-sized tile (never happens
/// in practice — `filled` always clamps to at least `1x1` — kept as a
/// defensive no-op-safe branch rather than an `unwrap`).
#[allow(clippy::too_many_arguments)]
pub(crate) fn draw_minimap_cached(
    cr: &Context,
    pango_layout: &pango::Layout,
    x: f64,
    y: f64,
    w: f64,
    h: f64,
    minimap: &Minimap,
    theme: &Theme,
    atlas_cache: &mut MinimapAtlasCache,
    dpi_scale: f64,
    mm_scale: MinimapScale,
) -> MinimapLayout {
    let family = pango_layout
        .font_description()
        .and_then(|f| f.family())
        .map(|g| g.to_string())
        .unwrap_or_else(|| "Monospace".to_string());
    let dpi_scale = dpi_scale.max(1.0);
    // Convert `mm_scale`'s logical cell size to real device pixels via
    // `dpi_scale` (issue's HiDPI note: `m = round(scale * 2)` in VS Code's
    // own terms, keeping the *logical* cell size unchanged while the
    // atlas gets real device-pixel detail).
    let tile_w = (mm_scale.cell_w_px() * dpi_scale).round().max(1.0) as usize;
    let tile_h = (mm_scale.row_pitch_px() * dpi_scale).round().max(1.0) as usize;

    // `mm_scale` changes the atlas's tile dimensions just as much as
    // `family`/`dpi_scale` do, so it must be part of the cache key too —
    // folded into the family string rather than growing
    // `MinimapAtlasCache::get_or_build`'s own `(String, f32)` key shape.
    let family_key = format!("{family}#{mm_scale:?}");
    let atlas = atlas_cache.get_or_build(&family_key, dpi_scale as f32, || {
        build_char_atlas(&family, tile_w, tile_h)
    });

    paint_minimap_rows(
        cr,
        x,
        y,
        w,
        h,
        minimap,
        theme,
        mm_scale,
        |cr, vline, _row_px, cell_w, text, row_spans| {
            if atlas.tile_w() == 0 || atlas.tile_h() == 0 {
                paint_row_blocks(cr, vline, text, row_spans, theme, cell_w);
            } else {
                paint_row_atlas(cr, atlas, dpi_scale, vline, text, row_spans, theme, cell_w);
            }
        },
    )
}

/// Advance width (px) of one cell in [`render_char_sample_sheet`]'s
/// sample sheet — see [`crate::primitives::minimap::ATLAS_CHAR_COUNT`]
/// for the number of cells the sheet holds.
const CHAR_SAMPLE_CELL_W: f64 = 10.0;
/// Height (px) of one cell in [`render_char_sample_sheet`]'s sample
/// sheet (and of the sheet itself).
const CHAR_SAMPLE_CELL_H: f64 = 16.0;

/// Build a [`MinimapCharAtlas`] for `family` at `tile_w x tile_h`,
/// falling back to [`MinimapCharAtlas::filled`] (a safe, visually-inert
/// degraded result — see that constructor's docs) if the sample-sheet
/// render itself fails (e.g. surface allocation).
fn build_char_atlas(family: &str, tile_w: usize, tile_h: usize) -> MinimapCharAtlas {
    match render_char_sample_sheet(family) {
        Some(alpha) => MinimapCharAtlas::from_alpha_sheet(
            &alpha,
            (CHAR_SAMPLE_CELL_W as usize) * (crate::primitives::minimap::ATLAS_CHAR_COUNT),
            CHAR_SAMPLE_CELL_H as usize,
            CHAR_SAMPLE_CELL_W as usize,
            tile_w,
            tile_h,
        ),
        None => MinimapCharAtlas::filled(tile_w, tile_h),
    }
}

/// Shape every sampled ASCII character (see
/// [`crate::primitives::minimap::ATLAS_FIRST_CHAR`]/`ATLAS_LAST_CHAR`)
/// once, at `CHAR_SAMPLE_CELL_H` px bold, into one sample sheet —
/// mirrors VS Code's `MinimapCharRenderer.createSampleData` (96 cells,
/// 10px advance, 16px tall, bold 16px font). Returns a tightly-packed,
/// row-major *coverage* buffer (`sheet_w * CHAR_SAMPLE_CELL_H` bytes,
/// `0` transparent .. `255` opaque): text is painted solid white onto a
/// fully transparent background, so the surface's own alpha channel
/// *is* anti-aliasing coverage directly — no premultiplied-colour
/// division needed the way a canvas `getImageData` readback (VS Code's
/// own situation) would.
fn render_char_sample_sheet(family: &str) -> Option<Vec<u8>> {
    let char_count = crate::primitives::minimap::ATLAS_CHAR_COUNT;
    let cell_w = CHAR_SAMPLE_CELL_W as i32;
    let sheet_h = CHAR_SAMPLE_CELL_H as i32;
    let sheet_w = cell_w * char_count as i32;

    let surface = ImageSurface::create(Format::ARgb32, sheet_w, sheet_h).ok()?;
    let cr = Context::new(&surface).ok()?;
    let pango_layout = pangocairo::functions::create_layout(&cr);

    let mut font = pango::FontDescription::new();
    font.set_family(family);
    font.set_weight(pango::Weight::Bold);
    font.set_absolute_size(CHAR_SAMPLE_CELL_H * 0.85 * pango::SCALE as f64);
    pango_layout.set_font_description(Some(&font));

    cr.set_source_rgb(1.0, 1.0, 1.0);
    for (i, code) in (ATLAS_FIRST_CHAR..=ATLAS_LAST_CHAR).enumerate() {
        let ch = char::from_u32(code)?;
        pango_layout.set_text(&ch.to_string());
        cr.move_to(i as f64 * CHAR_SAMPLE_CELL_W, 0.0);
        // Deliberately the plain, non-recording `show_layout` — this
        // paints into a private, throwaway sample sheet surface, never
        // the real widget. The recording wrapper would record to a
        // **thread-local** sink, not one scoped to this `Context`, so
        // calling it here would append these 95 sample glyphs' bounds
        // (from this function's own private surface) to the shared sink,
        // polluting any caller's text-run tracking.
        pangocairo::functions::show_layout(&cr, &pango_layout);
    }
    // `ImageSurface::data()` needs exclusive access to the surface (it
    // hands back a mutable-capable view), and both `pango_layout` and
    // `cr` still hold their own reference to it -- drop them first, the
    // same ordering `blit_alpha_tile` already follows for its own tile
    // surface. Without this, `.data()` returns `Err` (the surface
    // has more than one live reference), `.ok()?` turns that into a
    // silent `None`, and the paint falls back to a zero-sized tile.
    drop(pango_layout);
    drop(cr);
    surface.flush();

    let stride = surface.stride() as usize;
    let mut surface = surface;
    let data = surface.data().ok()?;
    let (sheet_w, sheet_h) = (sheet_w as usize, sheet_h as usize);
    let mut alpha = vec![0u8; sheet_w * sheet_h];
    for row in 0..sheet_h {
        for col in 0..sheet_w {
            // Cairo's native `ARgb32` byte order is [B, G, R, A]
            // (little-endian) -- see `gtk::minimap::tests::pixel`'s own
            // comment for the same layout read from the colour side.
            alpha[row * sheet_w + col] = data[row * stride + col * 4 + 3];
        }
    }
    Some(alpha)
}

/// Paint one row using `atlas`'s pre-downsampled alpha tiles: blit a
/// tile per non-blank character, tinted by whichever span covers it — no
/// shaping, matching [`paint_row_blocks`]'s own column-capacity bound
/// and whitespace skip, but painting real glyph shapes instead of solid
/// blocks. `cell_w` (the [`MinimapScale::cell_w_px`]) is the logical
/// column advance — `col as f64 * cell_w`, not a bare `col as f64` — so a
/// wider [`MinimapScale::Two`] cell doesn't overlap its neighbour.
#[allow(clippy::too_many_arguments)]
fn paint_row_atlas(
    cr: &Context,
    atlas: &MinimapCharAtlas,
    dpi_scale: f64,
    vline: &VisibleMinimapLine,
    text: &str,
    row_spans: &[MinimapSpan],
    theme: &Theme,
    cell_w: f64,
) {
    for (col, ch) in text.chars().enumerate().take(COLUMN_CAPACITY) {
        if ch.is_whitespace() {
            continue;
        }
        let color = color_at_column(row_spans, col, theme.foreground);
        blit_alpha_tile(
            cr,
            atlas.tile(ch),
            atlas.tile_w(),
            atlas.tile_h(),
            vline.bounds.x as f64 + col as f64 * cell_w,
            vline.bounds.y as f64,
            dpi_scale,
            color,
        );
    }
}

/// Blit one `tile_w x tile_h` alpha tile (device pixels) at logical
/// position `(x, y)`, tinted by `color`. Builds a small `A8` surface
/// from `tile` and paints `color` through it via `mask_surface` — a pure
/// alpha blend, not a shaped glyph run. The `cr.scale(1.0 / dpi_scale,
/// ..)` maps the tile's device-pixel resolution back down to logical
/// units, so a `tile_w x tile_h` device-pixel tile always occupies
/// exactly one [`MinimapScale::cell_w_px`] x one
/// [`MinimapScale::row_pitch_px`] logical units on screen, regardless of
/// `dpi_scale`.
#[allow(clippy::too_many_arguments)]
fn blit_alpha_tile(
    cr: &Context,
    tile: &[u8],
    tile_w: usize,
    tile_h: usize,
    x: f64,
    y: f64,
    dpi_scale: f64,
    color: crate::types::Color,
) {
    if tile_w == 0 || tile_h == 0 {
        return;
    }
    let Ok(mut surface) = ImageSurface::create(Format::A8, tile_w as i32, tile_h as i32) else {
        return;
    };
    {
        let stride = surface.stride() as usize;
        let Ok(mut data) = surface.data() else {
            return;
        };
        for row in 0..tile_h {
            let src = &tile[row * tile_w..(row + 1) * tile_w];
            let dst_off = row * stride;
            data[dst_off..dst_off + tile_w].copy_from_slice(src);
        }
    }
    surface.flush();

    let (r, g, b) = cairo_rgb(color);
    cr.save().ok();
    cr.translate(x, y);
    let inv_scale = 1.0 / dpi_scale.max(f64::MIN_POSITIVE);
    cr.scale(inv_scale, inv_scale);
    cr.set_source_rgb(r, g, b);
    cr.mask_surface(&surface, 0.0, 0.0).ok();
    cr.restore().ok();
}

#[allow(clippy::too_many_arguments)]
fn paint_row_glyphs(
    cr: &Context,
    pango_layout: &pango::Layout,
    saved_font: Option<&pango::FontDescription>,
    vline: &VisibleMinimapLine,
    row_px: f64,
    text: &str,
    row_spans: &[MinimapSpan],
    theme: &Theme,
) {
    let mut font = saved_font.cloned().unwrap_or_default();
    font.set_absolute_size(minimap_font_px(row_px) * pango::SCALE as f64);
    pango_layout.set_font_description(Some(&font));
    // Bound the shaped run to the row's own width and ellipsize rather
    // than shaping (and then relying on the Cairo clip to hide) glyphs
    // that will never be visible -- keeps shaping cheap even for a very
    // long line; the `cr.clip()` in `draw_minimap` is the hard guarantee.
    pango_layout.set_width((vline.bounds.width * pango::SCALE as f32).round() as i32);
    pango_layout.set_ellipsize(pango::EllipsizeMode::End);

    // Never shape more than the strip's column capacity worth of a line
    // — a pathologically long line must cost no more to shape than a
    // short one, mirroring `paint_row_blocks`' own walk cap.
    let truncated = truncate_to_columns(text, COLUMN_CAPACITY);
    pango_layout.set_text(truncated);

    if row_spans.is_empty() {
        pango_layout.set_attributes(None);
    } else {
        let to_u16 = |c: u8| -> u16 { ((c as u16) << 8) | c as u16 };
        let attrs = pango::AttrList::new();
        for span in row_spans {
            let (start, end) = char_range_to_byte_range(truncated, span.start_col, span.end_col);
            let mut a = pango::AttrColor::new_foreground(
                to_u16(span.color.r),
                to_u16(span.color.g),
                to_u16(span.color.b),
            );
            a.set_start_index(start);
            a.set_end_index(end);
            attrs.insert(a);
        }
        pango_layout.set_attributes(Some(&attrs));
    }

    set_source(cr, theme.foreground);
    cr.move_to(vline.bounds.x as f64, vline.bounds.y as f64);
    super::painted_text::show_layout(cr, pango_layout);
}

/// Paint one `cell_w`-wide block per non-blank character column of
/// `text`, each coloured by whichever span covers it — VS Code's
/// `renderCharacters: false` look, which (unlike a single per-line bar)
/// preserves the line's indent and internal-gap silhouette.
/// Stops after [`COLUMN_CAPACITY`] columns, so a pathologically long
/// line costs no more to paint than a short one. `cell_w` is
/// [`MinimapScale::cell_w_px`] — `1.0` at [`MinimapScale::One`],
/// matching this function's original hardcoded block width.
fn paint_row_blocks(
    cr: &Context,
    vline: &VisibleMinimapLine,
    text: &str,
    row_spans: &[MinimapSpan],
    theme: &Theme,
    cell_w: f64,
) {
    for (col, ch) in text.chars().enumerate().take(COLUMN_CAPACITY) {
        if ch.is_whitespace() {
            continue;
        }
        let color = color_at_column(row_spans, col, theme.foreground);
        set_source(cr, color);
        cr.rectangle(
            vline.bounds.x as f64 + col as f64 * cell_w,
            vline.bounds.y as f64,
            cell_w,
            vline.bounds.height as f64,
        );
        cr.fill().ok();
    }
}

/// Convert a `[start_col, end_col)` character range into UTF-8 byte
/// offsets Pango attributes need. Out-of-range columns clamp to the
/// text's own char count rather than panicking.
fn char_range_to_byte_range(text: &str, start_col: usize, end_col: usize) -> (u32, u32) {
    let mut start_byte = text.len();
    let mut end_byte = text.len();
    let mut char_idx = 0usize;
    for (byte_idx, _) in text.char_indices() {
        if char_idx == start_col {
            start_byte = start_byte.min(byte_idx);
        }
        if char_idx == end_col {
            end_byte = byte_idx;
        }
        char_idx += 1;
    }
    if start_col == 0 {
        start_byte = 0;
    }
    if end_col >= char_idx {
        end_byte = text.len();
    }
    (
        start_byte.min(text.len()) as u32,
        end_byte.min(text.len()) as u32,
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::minimap::{MinimapHit, MinimapLine, ROW_PITCH_PX};
    use crate::types::{Color, WidgetId};
    use pangocairo::cairo::{Context as CairoContext, Format, ImageSurface};

    fn minimap_from(lines: Vec<&str>, total_buffer_lines: usize) -> Minimap {
        Minimap {
            id: WidgetId::new("mm"),
            lines: lines
                .into_iter()
                .enumerate()
                .map(|(i, t)| MinimapLine {
                    text: t.into(),
                    line_idx: i,
                })
                .collect(),
            syntax_spans: Vec::new(),
            visible_row_start: 0,
            visible_row_count: 0,
            total_buffer_lines,
        }
    }

    fn surface_and_layout() -> (CairoContext, pango::Layout) {
        let surface = ImageSurface::create(Format::ARgb32, 200, 200).expect("create ImageSurface");
        let cr = CairoContext::new(&surface).expect("Context::new");
        let layout = pangocairo::functions::create_layout(&cr);
        (cr, layout)
    }

    // ── fixed pitch, not file-length-dependent ───────────────────────

    #[test]
    fn row_pitch_is_independent_of_the_strip_height() {
        // The same buffer painted into strips of two very different
        // heights must resolve to the *same* row pitch under
        // [`MinimapSizing::FixedPitch`]. See `Minimap::layout`'s module docs.
        let lines: Vec<&str> = vec!["fn main() {}"; 8];
        let mm = minimap_from(lines, 8);

        let tall = gtk_minimap_layout(&mm, 0.0, 0.0, 40.0, 800.0);
        let short = gtk_minimap_layout(&mm, 0.0, 0.0, 40.0, 16.0);

        let tall_px = tall.visible_lines[0].bounds.height as f64;
        let short_px = short.visible_lines[0].bounds.height as f64;
        assert_eq!(tall_px, ROW_PITCH_PX);
        assert_eq!(short_px, ROW_PITCH_PX);
    }

    #[test]
    fn row_pitch_is_independent_of_the_file_length() {
        // The other half of the same guarantee: a 3-line file and a
        // 10,000-line file painted into the *same* strip must also
        // resolve to the same row pitch.
        let short_mm = minimap_from(vec!["fn main() {}"; 3], 3);
        let long_lines: Vec<String> = (0..10_000).map(|i| format!("line {i}")).collect();
        let long_refs: Vec<&str> = long_lines.iter().map(String::as_str).collect();
        let long_mm = minimap_from(long_refs, 10_000);

        let short_layout = gtk_minimap_layout(&short_mm, 0.0, 0.0, 40.0, 400.0);
        let long_layout = gtk_minimap_layout(&long_mm, 0.0, 0.0, 40.0, 400.0);

        assert_eq!(
            short_layout.visible_lines[0].bounds.height as f64,
            ROW_PITCH_PX
        );
        assert_eq!(
            long_layout.visible_lines[0].bounds.height as f64,
            ROW_PITCH_PX
        );
    }

    #[test]
    fn short_file_in_a_tall_strip_does_not_stretch() {
        // A 3-line file at the fixed pitch occupies 6px of a 200px
        // strip -- it must not stretch to fill it.
        let mm = minimap_from(vec!["//! Placeholder module"; 3], 3);
        let layout = gtk_minimap_layout(&mm, 0.0, 0.0, 200.0, 200.0);
        assert_eq!(layout.visible_lines.len(), 3);
        let last = layout.visible_lines.last().unwrap();
        assert!(
            (last.bounds.y + last.bounds.height) < 200.0,
            "a short file must not stretch its rows to fill the whole strip"
        );
    }

    // ── legibility floor ─────────────────────────────────────────────
    //
    // `is_legible`/`render_mode`'s own threshold behaviour is covered by
    // `primitives::minimap::tests::legibility_floor_switches_render_mode_on_both_sides`
    // — this module keeps only the paint-level regression that a
    // real Cairo/Pango pass actually respects that threshold.

    #[test]
    fn default_fixed_pitch_stays_below_the_floor_and_never_shapes_text() {
        // ROW_PITCH_PX (2px) is below LEGIBILITY_FLOOR_PX (4px), so the
        // default GTK minimap always lands in ColumnBlocks.
        let mm = minimap_from(vec!["fn main() {}"; 4], 4);
        let (cr, layout) = surface_and_layout();

        let _ = draw_minimap(&cr, &layout, 0.0, 0.0, 40.0, 4.0, &mm, &Theme::default());
        assert_eq!(layout.text(), "");

        let _ = draw_minimap(&cr, &layout, 0.0, 0.0, 40.0, 400.0, &mm, &Theme::default());
        assert_eq!(
            layout.text(),
            "",
            "the fixed pitch stays below the legibility floor regardless of strip height"
        );
    }

    #[test]
    fn characters_branch_truncates_to_the_column_capacity_before_shaping() {
        // The Characters branch must bound its shaping cost by the column
        // capacity even though it's unreachable at the default fixed pitch.
        let long_line = "y".repeat(10_000);
        let (cr, pango_layout) = surface_and_layout();
        let vline = VisibleMinimapLine {
            start_line_idx: 0,
            bounds: QRect::new(0.0, 0.0, 400.0, 20.0),
        };
        paint_row_glyphs(
            &cr,
            &pango_layout,
            None,
            &vline,
            20.0,
            &long_line,
            &[],
            &Theme::default(),
        );
        assert_eq!(
            pango_layout.text().chars().count(),
            COLUMN_CAPACITY,
            "must shape no more than COLUMN_CAPACITY characters even for a 10,000-char line"
        );
    }

    // ── glyph atlas ─────────────────────────────────────────────────────

    /// Paint `mm` through [`draw_minimap_cached`] into a fresh surface and
    /// return the raw pixel bytes.
    fn paint_cached_pixels(mm: &Minimap, w: i32, h: i32) -> Vec<u8> {
        paint_cached_pixels_at_scale(mm, w, h, MinimapScale::One, &Theme::default())
    }

    /// [`paint_cached_pixels`], but at an explicit [`MinimapScale`] and
    /// [`Theme`].
    fn paint_cached_pixels_at_scale(
        mm: &Minimap,
        w: i32,
        h: i32,
        mm_scale: MinimapScale,
        theme: &Theme,
    ) -> Vec<u8> {
        let mut surface = ImageSurface::create(Format::ARgb32, w, h).expect("create surface");
        {
            let cr = CairoContext::new(&surface).expect("Context::new");
            let pango_layout = pangocairo::functions::create_layout(&cr);
            let mut cache = MinimapAtlasCache::new();
            draw_minimap_cached(
                &cr,
                &pango_layout,
                0.0,
                0.0,
                w as f64,
                h as f64,
                mm,
                theme,
                &mut cache,
                1.0,
                mm_scale,
            );
        }
        surface.flush();
        let pixels = surface.data().expect("surface data").to_vec();
        pixels
    }

    #[test]
    fn atlas_mode_differentiates_content_column_blocks_would_make_identical() {
        // Two rows of equal length, both entirely non-blank, must paint
        // *different* alpha patterns under real character shapes — solid
        // columns would paint identically for both.
        let code_line = "fn main() {";
        let comment_line = "///////////";
        assert_eq!(
            code_line.chars().count(),
            comment_line.chars().count(),
            "both lines must be the same length for this to be a fair comparison"
        );

        let code_pixels = paint_cached_pixels(&minimap_from(vec![code_line], 1), 40, 4);
        let comment_pixels = paint_cached_pixels(&minimap_from(vec![comment_line], 1), 40, 4);

        assert_ne!(
            code_pixels, comment_pixels,
            "Characters-mode (atlas) rows for different same-length, all-non-blank \
             content must paint different pixels"
        );
    }

    #[test]
    fn render_char_sample_sheet_does_not_pollute_the_text_run_sink() {
        // The sample sheet shapes each ASCII glyph into a private,
        // throwaway surface (never real screen content), but the
        // text-run sink is **thread-local**, not scoped to any
        // particular `Context` — the recording wrapper must never be
        // called here, else every atlas cache miss during a test would
        // append bogus bounds to the shared sink.
        let previous = crate::testing::install_text_run_sink();
        let _ = render_char_sample_sheet("sans-serif");
        let recorded = crate::testing::take_text_run_sink(previous);
        assert!(
            recorded.is_empty(),
            "render_char_sample_sheet must never record into the text-run sink, got {recorded:?}"
        );
    }

    #[test]
    fn atlas_mode_paints_something_for_a_non_blank_line() {
        // A baseline sanity check alongside the differentiation test
        // above: a non-blank line must actually paint ink, not silently
        // no-op into an all-background surface (which would make the
        // "differentiates content" test above meaningless if both inputs
        // painted nothing).
        let bg = ImageSurface::create(Format::ARgb32, 40, 4)
            .and_then(|mut s| {
                let cr = CairoContext::new(&s)?;
                cr.set_source_rgb(0.0, 0.0, 0.0);
                cr.paint()?;
                drop(cr); // release the surface borrow before `s.data()`
                s.flush();
                Ok(s.data().expect("surface data").to_vec())
            })
            .expect("blank surface");

        let painted = paint_cached_pixels(&minimap_from(vec!["fn main() {"], 1), 40, 4);
        assert_ne!(
            painted, bg,
            "a non-blank line must paint something other than a uniform background"
        );
    }

    #[test]
    fn atlas_mode_falls_back_to_column_blocks_visuals_when_atlas_is_degenerate() {
        // `draw_minimap_cached`'s defensive branch for a zero-sized atlas
        // (never hit via the real `build_char_atlas` path, since
        // `MinimapCharAtlas::filled`/`from_alpha_sheet` both clamp
        // tile_w/tile_h to at least 1 -- see `draw_minimap_cached`'s own
        // doc) still needs to paint *something* sane rather than nothing.
        // Exercise `paint_row_blocks` directly (the same function the
        // fallback branch calls) to confirm that half of the contract
        // independently of atlas construction.
        let mm = minimap_from(vec!["    x  y"], 1);
        let theme = Theme {
            background: Color::rgb(10, 10, 10),
            foreground: Color::rgb(200, 200, 200),
            ..Theme::default()
        };
        let mut surface = ImageSurface::create(Format::ARgb32, 20, 4).expect("create surface");
        let layout = {
            let cr = CairoContext::new(&surface).expect("Context::new");
            let vline = layout_first_vline(&mm, 20.0, 4.0);
            let row_spans: &[MinimapSpan] = &[];
            paint_row_blocks(&cr, &vline, &mm.lines[0].text, row_spans, &theme, 1.0);
            vline
        };
        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        let fg = (theme.foreground.r, theme.foreground.g, theme.foreground.b);
        assert_eq!(pixel(&data, stride, layout.bounds.x as i32 + 4, 0), fg);
    }

    /// At [`MinimapScale::Two`] (a 2px wide x 4px tall cell), a row of
    /// real code paints *shapes* — non-uniform pixel values across a
    /// character's own cell, not solid, uniformly-coloured blocks — and
    /// blank (whitespace) columns stay fully background throughout their cells.
    #[test]
    fn scale_two_atlas_mode_paints_a_shape_and_leaves_blank_columns_empty() {
        let line = "fn main()";
        let mm = minimap_from(vec![line], 1);
        let cell_w = MinimapScale::Two.cell_w_px() as i32;
        let row_h = MinimapScale::Two.row_pitch_px() as i32;
        let w = line.chars().count() as i32 * cell_w;

        let theme = Theme {
            background: Color::rgb(255, 255, 255),
            foreground: Color::rgb(0, 0, 0),
            ..Theme::default()
        };

        let pixels = paint_cached_pixels_at_scale(&mm, w, row_h, MinimapScale::Two, &theme);
        let stride = ImageSurface::create(Format::ARgb32, w, row_h)
            .expect("create surface")
            .stride() as usize;
        let bg = (theme.background.r, theme.background.g, theme.background.b);

        // The space between "fn" and "main" is column 2 -- its whole
        // `cell_w`-wide, `row_h`-tall cell must stay fully background.
        let space_col = 2i32;
        for dx in 0..cell_w {
            for y in 0..row_h {
                let x = space_col * cell_w + dx;
                assert_eq!(
                    pixel(&pixels, stride, x, y),
                    bg,
                    "a blank column must stay fully background at ({x}, {y})"
                );
            }
        }

        // The first character's own cell ('f', column 0) must show a
        // *shape* — at least two pixels inside the cell with different
        // colours — rather than a solid, uniformly-filled block.
        let mut cell_pixels = Vec::new();
        for dx in 0..cell_w {
            for y in 0..row_h {
                cell_pixels.push(pixel(&pixels, stride, dx, y));
            }
        }
        assert!(
            cell_pixels.windows(2).any(|w| w[0] != w[1]),
            "expected non-uniform alpha (a glyph shape) across the 'f' cell, got {cell_pixels:?}"
        );
    }

    /// The atlas cache is keyed on `(family, dpi_scale)` alone
    /// ([`MinimapAtlasCache`]) — `mm_scale` is folded into the family
    /// string ([`draw_minimap_cached`]'s own `family_key`), precisely so
    /// reusing one cache across a [`MinimapScale`] change doesn't
    /// silently keep serving a wrong-sized tile from the previous scale
    #[test]
    fn atlas_cache_key_includes_minimap_scale_so_a_scale_change_rebuilds() {
        let mm = minimap_from(vec!["fn main() {}"], 1);
        let mut cache = MinimapAtlasCache::new();
        let theme = Theme::default();
        let bg = (theme.background.r, theme.background.g, theme.background.b);
        let w = 40;
        let two_h = MinimapScale::Two.row_pitch_px() as i32;

        // Paint once at `One` (a 1x2 cell) through the shared cache...
        let surface_one =
            ImageSurface::create(Format::ARgb32, w, MinimapScale::One.row_pitch_px() as i32)
                .expect("create surface");
        {
            let cr = CairoContext::new(&surface_one).expect("Context::new");
            let pango_layout = pangocairo::functions::create_layout(&cr);
            draw_minimap_cached(
                &cr,
                &pango_layout,
                0.0,
                0.0,
                w as f64,
                MinimapScale::One.row_pitch_px(),
                &mm,
                &theme,
                &mut cache,
                1.0,
                MinimapScale::One,
            );
        }

        // ...then at `Two` (a 2x4 cell) through the *same* cache instance.
        let mut surface_two =
            ImageSurface::create(Format::ARgb32, w, two_h).expect("create surface");
        {
            let cr = CairoContext::new(&surface_two).expect("Context::new");
            let pango_layout = pangocairo::functions::create_layout(&cr);
            draw_minimap_cached(
                &cr,
                &pango_layout,
                0.0,
                0.0,
                w as f64,
                two_h as f64,
                &mm,
                &theme,
                &mut cache,
                1.0,
                MinimapScale::Two,
            );
        }
        surface_two.flush();
        let stride = surface_two.stride() as usize;
        let data = surface_two.data().expect("surface data");

        // If the cache had wrongly reused `One`'s 1x2 tile for this
        // `Two` paint, the blit would only ever touch the tile's own
        // (much smaller) device-pixel footprint, leaving the bottom of
        // this 4px-tall row untouched (still background). A correctly
        // rebuilt 2x4 tile paints something below row 2.
        let mut painted_below_row_2 = false;
        for y in 2..two_h {
            for x in 0..w {
                if pixel(&data, stride, x, y) != bg {
                    painted_below_row_2 = true;
                }
            }
        }
        assert!(
            painted_below_row_2,
            "MinimapScale::Two's own 4px-tall cell must paint below row 2 -- a stale \
             1x2 tile carried over from MinimapScale::One would not"
        );
    }

    fn layout_first_vline(mm: &Minimap, w: f64, h: f64) -> VisibleMinimapLine {
        gtk_minimap_layout(mm, 0.0, 0.0, w, h).visible_lines[0]
    }

    #[test]
    fn column_blocks_skip_indentation_and_internal_gaps() {
        // 4-space indent, "x", 2-space internal gap, "y": the walk must
        // paint no block over the indent or the gap -- only over the two
        // non-blank columns, preserving the indent silhouette.
        let mm = minimap_from(vec!["    x  y"], 1);
        let theme = Theme {
            background: Color::rgb(10, 10, 10),
            foreground: Color::rgb(200, 200, 200),
            ..Theme::default()
        };

        let mut surface = ImageSurface::create(Format::ARgb32, 20, 4).expect("create surface");
        {
            let cr = CairoContext::new(&surface).expect("Context::new");
            let pango_layout = pangocairo::functions::create_layout(&cr);
            draw_minimap(&cr, &pango_layout, 0.0, 0.0, 20.0, 4.0, &mm, &theme);
        }
        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");

        let bg = (theme.background.r, theme.background.g, theme.background.b);
        let fg = (theme.foreground.r, theme.foreground.g, theme.foreground.b);

        for col in 0..4 {
            assert_eq!(
                pixel(&data, stride, col, 0),
                bg,
                "indent column {col} must stay blank"
            );
        }
        assert_eq!(
            pixel(&data, stride, 4, 0),
            fg,
            "'x' column must paint a block"
        );
        for col in 5..7 {
            assert_eq!(
                pixel(&data, stride, col, 0),
                bg,
                "gap column {col} must stay blank"
            );
        }
        assert_eq!(
            pixel(&data, stride, 7, 0),
            fg,
            "'y' column must paint a block"
        );
    }

    #[test]
    fn column_blocks_stop_at_the_column_capacity() {
        let long_line = "x".repeat(10_000);
        let mm = minimap_from(vec![&long_line], 1);
        let theme = Theme {
            background: Color::rgb(1, 1, 1),
            foreground: Color::rgb(250, 250, 250),
            ..Theme::default()
        };
        let strip_w = (COLUMN_CAPACITY + 50) as i32;

        let mut surface = ImageSurface::create(Format::ARgb32, strip_w, 4).expect("create surface");
        {
            let cr = CairoContext::new(&surface).expect("Context::new");
            let pango_layout = pangocairo::functions::create_layout(&cr);
            draw_minimap(
                &cr,
                &pango_layout,
                0.0,
                0.0,
                strip_w as f64,
                4.0,
                &mm,
                &theme,
            );
        }
        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");

        let fg = (theme.foreground.r, theme.foreground.g, theme.foreground.b);
        let bg = (theme.background.r, theme.background.g, theme.background.b);
        assert_eq!(
            pixel(&data, stride, (COLUMN_CAPACITY - 1) as i32, 0),
            fg,
            "the last in-capacity column must still paint"
        );
        assert_eq!(
            pixel(&data, stride, COLUMN_CAPACITY as i32, 0),
            bg,
            "the walk must stop at COLUMN_CAPACITY and paint no further"
        );
    }

    // `color_at_column`/`SpanCursor`'s own behaviour is covered by
    // `primitives::minimap::tests::color_at_column_*` /
    // `span_cursor_matches_a_full_linear_scan_per_row` — nothing
    // GTK-specific left to re-test here.

    // ── paint/click round trip ────────────────────────────────────────

    /// Shared body for `paint_and_click_round_trip_returns_seek_for_the_clicked_fraction`
    /// — `minimap_layout` returns coordinates in absolute frame
    /// (see `docs/PRIMITIVE_RULES.md`), so `hit_test` must be called with
    /// coordinates shifted by the same `x`/`y` origin the strip was painted at.
    fn paint_and_click_round_trip_at(x: f64, y: f64) {
        let mm = minimap_from(vec!["x"; 8], 8);
        let (cr, pango_layout) = surface_and_layout();
        let layout = draw_minimap(
            &cr,
            &pango_layout,
            x,
            y,
            40.0,
            100.0,
            &mm,
            &Theme::default(),
        );
        assert_eq!(
            layout.hit_test((x + 20.0) as f32, (y + 50.0) as f32),
            MinimapHit::Seek { fraction: 0.5 }
        );
        assert_eq!(
            layout.hit_test((x + 20.0) as f32, y as f32),
            MinimapHit::Seek { fraction: 0.0 }
        );
    }

    #[test]
    fn paint_and_click_round_trip_returns_seek_for_the_clicked_fraction() {
        paint_and_click_round_trip_at(0.0, 0.0);
    }

    /// Regression guard: `(x, y) = (0, 0)` is exactly the case where a
    /// LOCAL/ABSOLUTE mixup in `gtk_minimap_layout` would be invisible.
    #[test]
    fn paint_and_click_round_trip_returns_seek_for_the_clicked_fraction_at_nonzero_origin() {
        paint_and_click_round_trip_at(7.0, 13.0);
    }

    #[test]
    fn char_range_to_byte_range_handles_multibyte_text() {
        // "café" — 'é' is 2 bytes (bytes 3-4), so the byte length (5)
        // diverges from the char count (4).
        let (start, end) = char_range_to_byte_range("café", 3, 4);
        assert_eq!(start, 3);
        assert_eq!(end, 5);
    }

    #[test]
    fn empty_minimap_is_a_no_op() {
        let mm = minimap_from(vec![], 0);
        let (cr, pango_layout) = surface_and_layout();
        let layout = draw_minimap(
            &cr,
            &pango_layout,
            0.0,
            0.0,
            40.0,
            100.0,
            &mm,
            &Theme::default(),
        );
        assert!(layout.visible_lines.is_empty());
    }

    // ── strip clipping ──────────────────────────────────────────────────

    /// 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].
    fn pixel(data: &[u8], stride: usize, x: i32, y: i32) -> (u8, u8, u8) {
        let off = y as usize * stride + x as usize * 4;
        (data[off + 2], data[off + 1], data[off])
    }

    #[test]
    fn wide_line_blocks_never_paint_right_of_bounds() {
        // Without `cr.clip()` and Pango layout width, a line wider than
        // the strip paints across whatever sat beside it. Paint a
        // pathologically long line into a strip embedded in a wider white
        // canvas and assert nothing right of the strip is touched.
        const STRIP_W: i32 = 40;
        const CANVAS_W: i32 = 200;
        const H: i32 = 40;

        let long_line = "x".repeat(500);
        let mm = minimap_from(vec![&long_line], 1);

        let mut surface =
            ImageSurface::create(Format::ARgb32, CANVAS_W, H).expect("create surface");
        {
            let cr = CairoContext::new(&surface).expect("Context::new");
            cr.set_source_rgb(1.0, 1.0, 1.0); // white sentinel
            cr.paint().ok();

            let pango_layout = pangocairo::functions::create_layout(&cr);
            let theme = Theme {
                background: Color::rgb(20, 20, 20),
                foreground: Color::rgb(255, 255, 255),
                ..Theme::default()
            };
            // The fixed pitch (ROW_PITCH_PX, 2px) is below the
            // legibility floor, so this exercises the ColumnBlocks
            // branch -- the column-capacity walk on its own already
            // bounds how far right it paints, but the clip is still the
            // hard guarantee this test checks.
            draw_minimap(
                &cr,
                &pango_layout,
                0.0,
                0.0,
                STRIP_W as f64,
                H as f64,
                &mm,
                &theme,
            );
        }
        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");

        for y in 0..H {
            for x in STRIP_W..CANVAS_W {
                assert_eq!(
                    pixel(&data, stride, x, y),
                    (255, 255, 255),
                    "pixel ({x},{y}) is right of bounds.x + bounds.width and must be untouched"
                );
            }
        }
    }
}