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
//! `FindReplace` overlay primitive — the inline find/replace panel
//! that anchors at the top-right of the active editor group.
//!
//! This primitive owns the data shape, hit-region layout, and click-
//! target enum, plus (as of #809, `PaintSurface` Phase 2b) the shared
//! [`native_surface_paint::paint`] rasteriser every pixel backend
//! (GTK/macOS/Win) calls through `Backend::draw_find_replace`. TUI
//! stays a separate rasteriser, [`crate::tui::draw_find_replace`] —
//! see `paint_surface.rs`'s module doc for why TUI never implements
//! `PaintSurface` (a cell grid has no sub-cell `Rect`).
//!
//! # Why a primitive (and not just a `StatusBar` variant)
//!
//! The find/replace overlay has multi-row content (find row + optional
//! replace row), input-field cursor + selection, toggle-button states
//! (match-case / whole-word / regex / preserve-case / in-selection —
//! TUI paints these as plain-text glyph pairs `Aa` / `ab` / `.*` / `AB`,
//! GUI backends paint codicon glyphs, see [`native_surface_paint`]),
//! and clickable nav + action buttons all packed inside a 50-cell-wide
//! bordered box.
//! That doesn't fit any of the simpler primitives — so it gets its
//! own `FindReplacePanel` shape.
//!
//! # Hit-region cell-coordinate contract
//!
//! Hit regions are in **character-cell units** relative to the panel
//! content corner (inside the 1-cell borders). Backends translate to
//! native units when dispatching clicks. This keeps the layout
//! algorithm cell-based and identical across TUI and GTK — backends
//! supply their own pixel-per-cell measurer (`char_width`).

use crate::event::Rect;
use serde::{Deserialize, Serialize};

/// Click target within the find/replace overlay. Backends resolve
/// native coordinates → `FindReplaceClickTarget`, then call the
/// engine's shared `handle_find_replace_click` dispatcher.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum FindReplaceClickTarget {
    /// Toggle replace row visibility (the ▶/▼ chevron).
    Chevron,
    /// Click in the find input field at the given char offset.
    FindInput(usize),
    /// Click in the replace input field at the given char offset.
    ReplaceInput(usize),
    ToggleCase,
    ToggleWholeWord,
    ToggleRegex,
    PrevMatch,
    NextMatch,
    ToggleInSelection,
    Close,
    TogglePreserveCase,
    ReplaceCurrent,
    ReplaceAll,
}

/// A hit region within the find/replace panel, expressed in
/// character-cell units relative to the panel's top-left **content**
/// corner (inside borders).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FrHitRegion {
    /// Column offset from panel content-left edge.
    pub col: u16,
    /// Row: 0 = find row, 1 = replace row.
    pub row: u16,
    /// Width of this region in char cells.
    pub width: u16,
}

/// Default panel width for the find/replace overlay (in char cells,
/// including borders).
pub const FR_PANEL_WIDTH: u16 = 50;

/// Compute hit regions for the find/replace overlay.
///
/// Layout (cell widths — glyph names are shorthand for the toggle
/// slot, not a claim about what's painted there; TUI paints the named
/// text pair, GUI backends paint a same-width codicon glyph):
/// `[chevron(2)] [input(variable)] [Aa(2+1)][ab(2+1)][.*(2+1)] [count(max(len,5)+1)] [↑(2)][↓(2)][≡(2)][×(2)]`
///
/// Returns `(regions, input_width)` — the input field's width (in
/// cells) is computed last and returned alongside so the caller can
/// store it on the panel for cursor placement.
///
/// `replace_one_glyph_width` and `replace_all_glyph_width` are the
/// char-cell widths of the replace-button glyphs. Apps with Nerd Font
/// glyphs typically pass `1` (single-cell glyph); ASCII-fallback apps
/// pass the string's `chars().count()` (e.g. 2 for `"R1"` / `"R*"`).
/// The widths are app-supplied (rather than read from a global icon
/// registry) so this primitive doesn't depend on any host app's icon
/// system.
pub fn compute_hit_regions(
    panel_w: u16,
    show_replace: bool,
    match_info: &str,
    replace_one_glyph_width: u16,
    replace_all_glyph_width: u16,
) -> (Vec<(FrHitRegion, FindReplaceClickTarget)>, u16) {
    use FindReplaceClickTarget::*;

    let mut regions = Vec::with_capacity(16);
    let content_w = panel_w.saturating_sub(2);

    // Chevron: cols 0..2
    regions.push((
        FrHitRegion {
            col: 0,
            row: 0,
            width: 2,
        },
        Chevron,
    ));

    // Find input: starts at col 2, right side uses remaining space for buttons.
    // Right side: toggles(3×3=9) + gap(1) + match_info(max(len,5)) + gap(1) + nav(4×2=8) = dynamic
    let info_len = (match_info.len() as u16).max(5);
    let right_side_w: u16 = 9 + info_len + 1 + 8; // toggles + count + gap + nav
    let input_start: u16 = 2;
    let input_w = content_w.saturating_sub(2 + right_side_w);
    regions.push((
        FrHitRegion {
            col: input_start,
            row: 0,
            width: input_w,
        },
        FindInput(0),
    ));

    // Toggle buttons: [Aa(2)gap(1)] [ab(2)gap(1)] [.*(2)gap(1)] — cell
    // widths only; glyph names are shorthand (TUI paints these text
    // pairs literally, GUI backends paint same-width codicon glyphs).
    let mut tx = input_start + input_w + 1;
    for target in [ToggleCase, ToggleWholeWord, ToggleRegex] {
        regions.push((
            FrHitRegion {
                col: tx,
                row: 0,
                width: 2,
            },
            target,
        ));
        tx += 3;
    }

    // Match count (not clickable)
    tx += info_len + 1;

    // Nav buttons: [↑(2)][↓(2)][≡(2)][×(2)]
    for target in [PrevMatch, NextMatch, ToggleInSelection, Close] {
        regions.push((
            FrHitRegion {
                col: tx,
                row: 0,
                width: 2,
            },
            target,
        ));
        tx += 2;
    }

    // Replace row (row 1)
    if show_replace {
        regions.push((
            FrHitRegion {
                col: input_start,
                row: 1,
                width: input_w,
            },
            ReplaceInput(0),
        ));

        let mut bx = input_start + input_w + 1;
        regions.push((
            FrHitRegion {
                col: bx,
                row: 1,
                width: 2,
            },
            TogglePreserveCase,
        ));
        bx += 3;

        regions.push((
            FrHitRegion {
                col: bx,
                row: 1,
                width: replace_one_glyph_width,
            },
            ReplaceCurrent,
        ));
        bx += replace_one_glyph_width + 1;

        regions.push((
            FrHitRegion {
                col: bx,
                row: 1,
                width: replace_all_glyph_width,
            },
            ReplaceAll,
        ));
    }

    (regions, input_w)
}

/// The inline find/replace overlay displayed at the top-right of the
/// active editor group.
///
/// Backends consume this by walking `hit_regions` (paint per region
/// + click hit-test against the same list).
///
/// Glyph fields (`replace_one_glyph` / `replace_all_glyph`) are
/// app-supplied strings — apps with Nerd Font glyphs pass single-char
/// strings, ASCII apps pass multi-char fallbacks like `"R1"` / `"R*"`.
///
/// # Examples
///
/// ```
/// use quadraui::{
///     compute_find_replace_hit_regions, FindReplaceClickTarget, FindReplaceHit, FindReplacePanel,
///     Rect,
/// };
///
/// let panel_width = 50;
/// let (hit_regions, _input_width) =
///     compute_find_replace_hit_regions(panel_width, false, "1 of 3", 1, 1);
///
/// let panel = FindReplacePanel {
///     query: "foo".to_string(),
///     replacement: String::new(),
///     show_replace: false,
///     focus: 0,
///     cursor: 3,
///     sel_anchor: None,
///     match_info: "1 of 3".to_string(),
///     case_sensitive: false,
///     whole_word: false,
///     use_regex: false,
///     preserve_case: false,
///     in_selection: false,
///     group_bounds: Rect::new(0.0, 0.0, 80.0, 24.0),
///     panel_width,
///     replace_one_glyph: "R1".to_string(),
///     replace_all_glyph: "R*".to_string(),
///     hit_regions,
/// };
///
/// // Column 0, row 0 is the chevron that toggles the replace row.
/// let hit = panel.hit_test(0.0, 0.0, (0.0, 0.0), 1.0, 1.0);
/// assert_eq!(hit, FindReplaceHit::Target(FindReplaceClickTarget::Chevron));
/// ```
#[derive(Debug, Clone)]
pub struct FindReplacePanel {
    /// Current query text in the find field.
    pub query: String,
    /// Current replacement text (only shown when `show_replace` is true).
    pub replacement: String,
    /// Whether the replace row is visible.
    pub show_replace: bool,
    /// Which field has focus: 0 = find, 1 = replace.
    pub focus: u8,
    /// Cursor position within the focused field (char offset).
    pub cursor: usize,
    /// Selection anchor in the focused field. When Some, text between anchor and cursor is selected.
    pub sel_anchor: Option<usize>,
    /// "N of M" match count display, or "No results" / empty.
    pub match_info: String,
    /// Toggle button states (find row).
    pub case_sensitive: bool,
    pub whole_word: bool,
    pub use_regex: bool,
    /// Toggle button states (replace row).
    pub preserve_case: bool,
    /// Find in selection mode.
    pub in_selection: bool,
    /// Bounding rect of the active editor group. The overlay positions
    /// itself at the top-right of this rect. Apps with f64 native
    /// rect types convert via `as f32` at construction.
    pub group_bounds: Rect,
    /// Panel width in char cells (used by backends for positioning).
    pub panel_width: u16,
    /// App-supplied glyph string for the "replace current" button.
    /// Single char (Nerd Font) or multi-char (ASCII fallback).
    pub replace_one_glyph: String,
    /// App-supplied glyph string for the "replace all" button.
    pub replace_all_glyph: String,
    /// Hit regions for click handling, in char-cell units relative to
    /// the panel content corner (inside borders). Computed once via
    /// [`compute_hit_regions`] at panel construction.
    pub hit_regions: Vec<(FrHitRegion, FindReplaceClickTarget)>,
}

/// Hit-test classification for a click against a [`FindReplacePanel`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FindReplaceHit {
    /// Click landed on a clickable target.
    Target(FindReplaceClickTarget),
    /// Click missed every hit region (e.g. the borders, the non-clickable
    /// match-count text, or outside the panel entirely).
    Empty,
}

impl FindReplacePanel {
    /// Hit-test a click at surface-native `(x, y)` against
    /// [`Self::hit_regions`].
    ///
    /// `content_origin` is the absolute position of the panel's content
    /// corner — inside the 1-cell/1px border — the same `(content_x,
    /// content_y)` every backend already derives when painting (see
    /// `native_surface_paint::paint`'s `Metrics` and
    /// `tui::draw_find_replace`'s `(x + 1, y + 1)`). `char_width` /
    /// `line_height` are the backend's per-cell metrics. Passing the
    /// caller's own resolved origin/metrics — rather than re-deriving
    /// the popup position here — keeps this in lock-step with each
    /// backend's paint position without duplicating that placement
    /// arithmetic (which differs across backends: TUI's `group_bounds`
    /// is content-relative and needs an `editor_left` offset; GTK/macOS/
    /// Win's is already absolute).
    ///
    /// Coordinate frame: **ABSOLUTE** — `(x, y)` is compared directly
    /// against `content_origin`, no further adjustment by the caller.
    ///
    /// Each [`FrHitRegion`] is still stored in character-cell units (TUI
    /// paints cells, so it needs that), but the comparison below is done
    /// in px: every region's cell rect is projected to a px rect — `rx0
    /// = ox + col * char_width`, `rx1 = rx0 + width * char_width`, and
    /// likewise for `y` — using the same cell-to-px projection as
    /// `native_surface_paint::region_rect`, and then `(x, y)` is tested
    /// against that px rect directly. Note `region_rect` additionally
    /// floors its width to `.max(1.0)` for painting a visible rect, which
    /// this comparison does not need (a zero-width region simply never
    /// matches). For every `char_width`/`line_height` pair a backend
    /// actually passes, `x` falls in `[rx0, rx1)` iff `floor((x - ox) /
    /// cw)` lands in `[region.col, region.col + region.width)` — so this
    /// is a direct px-space comparison with no caller-visible behaviour
    /// difference. TUI in particular always calls this with `char_width =
    /// line_height = 1.0`, where px and cell space are numerically
    /// identical.
    pub fn hit_test(
        &self,
        x: f32,
        y: f32,
        content_origin: (f32, f32),
        char_width: f32,
        line_height: f32,
    ) -> FindReplaceHit {
        if char_width <= 0.0 || line_height <= 0.0 {
            return FindReplaceHit::Empty;
        }
        let (ox, oy) = content_origin;
        if x < ox || y < oy {
            return FindReplaceHit::Empty;
        }
        for (region, target) in &self.hit_regions {
            let rx0 = ox + region.col as f32 * char_width;
            let rx1 = rx0 + region.width as f32 * char_width;
            let ry0 = oy + region.row as f32 * line_height;
            let ry1 = ry0 + line_height;
            if x >= rx0 && x < rx1 && y >= ry0 && y < ry1 {
                return FindReplaceHit::Target(*target);
            }
        }
        FindReplaceHit::Empty
    }
}

// ─────────────────────────────────────────────────────────────────────
// PaintSurface Phase 2b: shared paint implementation
// ─────────────────────────────────────────────────────────────────────
//
// Before this, `gtk::find_replace::draw_find_replace`,
// `macos::find_replace::draw_find_replace` and
// `win::find_replace::draw_find_replace` each independently walked
// `panel.hit_regions` and painted every region with their own cairo /
// CoreGraphics / Direct2D calls (quadraui#785 child #809 — re-measure
// rather than trust the parent audit's 270/220/205 line counts, which
// predate this PR and this repo's own history of two closed-as-wrong
// audit findings, #481/#482).
//
// Behavioural divergence found while unifying — reported per this
// issue's acceptance bar, not resolved silently:
//   - GTK painted a focused input's selection as a 50%-alpha rect
//     drawn *after* the full (unsplit) text run, so the selected
//     characters showed through, tinted.
//   - Windows painted the same highlight as an **opaque** rect, also
//     drawn after the full text run — so on Windows the selected
//     characters were completely hidden underneath it. This reads as
//     a latent rendering bug, not a deliberate style choice.
//   - macOS painted no selection highlight at all — its module doc
//     explicitly called this out as a "Scope omission (follow-up)".
//
// `paint` below resolves this by adopting the same shape
// `primitives::form::paint`'s bracketed-text selection already uses
// (`paint_bracketed_text`, #808): fill the selection rect first, at
// full opacity, then draw the field's text in three runs (prefix /
// selected / suffix) on top, so the selected characters stay legible
// on every backend. `PaintSurface::surface_fill_rect` doesn't
// guarantee alpha blending — GTK's implementation discards the alpha
// channel entirely (`GtkBackend::surface_fill_rect` calls
// `crate::gtk::set_source`, which is `cr.set_source_rgb`) — so an
// opaque fill is the only shape that reads correctly on all three
// pixel backends. It also matches how
// [`crate::tui::draw_find_replace`] already renders this: a solid
// `sel_bg` cell background, never blended.
//
// `#[allow(dead_code)]`: exercised by each backend's own
// `Backend::draw_find_replace` call site once compiled in, and by this
// module's own `RecordingSurface` tests on every leg that enables one
// of the three cfg'd features (gtk, win, or macos-on-macos) — see
// `paint_surface.rs`'s module doc for why that's not actually dead
// under `--features win` on a non-Windows host, the same shape this
// module borrows from `primitives::form`'s `native_surface_paint`.
#[cfg(any(
    feature = "gtk",
    feature = "win",
    all(feature = "macos", target_os = "macos")
))]
#[allow(dead_code)]
mod native_surface_paint {
    use super::{FindReplaceClickTarget, FindReplacePanel};
    use crate::paint_surface::PaintSurface;
    use crate::theme::Theme;
    use crate::types::Color;
    use crate::Rect;

    /// Layout constants shared by every helper below, computed once per
    /// [`paint`] call.
    struct Metrics {
        cw: f32,
        lh: f32,
        content_x: f32,
        content_y: f32,
    }

    /// A hit-region's bounds in `surface`-absolute coordinates: `col`/
    /// `row` are char-cell offsets from the panel's content corner,
    /// `width` is in char cells. Width is floored to 1 device unit so a
    /// theoretically-zero-width region never produces a degenerate
    /// fill/stroke rect.
    fn region_rect(m: &Metrics, col: u16, row: u16, width: u16) -> Rect {
        Rect::new(
            m.content_x + col as f32 * m.cw,
            m.content_y + row as f32 * m.lh,
            (width as f32 * m.cw).max(1.0),
            m.lh,
        )
    }

    /// Paint a plain text label at a cell position — no background, no
    /// centering. Used for the chevron and the match-count string.
    fn paint_label(
        surface: &mut dyn PaintSurface,
        m: &Metrics,
        col: u16,
        row: u16,
        text: &str,
        fg: Color,
    ) {
        let (tw, _) = surface.surface_measure_text(text);
        let px = m.content_x + col as f32 * m.cw;
        let py = m.content_y + row as f32 * m.lh;
        surface.surface_draw_text_run(Rect::new(px, py, tw, m.lh), text, fg);
    }

    /// Paint a toggle button (codicon glyph for match-case / whole-word /
    /// regex / preserve-case — TUI paints the plain-text equivalents `Aa`
    /// / `ab` / `.*` / `AB` instead, see `tui::find_replace`): filled with
    /// `accent_bg` and inverted text when `active`, outlined with
    /// `separator` and normal text otherwise.
    #[allow(clippy::too_many_arguments)]
    fn paint_toggle(
        surface: &mut dyn PaintSurface,
        theme: &Theme,
        m: &Metrics,
        col: u16,
        row: u16,
        width: u16,
        label: &str,
        active: bool,
    ) {
        let rect = region_rect(m, col, row, width);
        let fg = if active {
            surface.surface_fill_rect(rect, theme.accent_bg);
            theme.background
        } else {
            surface.surface_stroke_rect(rect, theme.separator, 0.5);
            theme.foreground
        };
        let (tw, _) = surface.surface_measure_text(label);
        let tx = rect.x + ((rect.width - tw) / 2.0).max(0.0);
        surface.surface_draw_text_run(Rect::new(tx, rect.y, tw, m.lh), label, fg);
    }

    /// Paint a nav/dismiss/replace glyph (`↑` `↓` `≡` `×` and the
    /// app-supplied replace-one/replace-all glyphs): filled +
    /// inverted when `active`, plain text with no outline otherwise —
    /// every deleted per-backend copy painted no outline here, unlike
    /// [`paint_toggle`]'s inactive state.
    #[allow(clippy::too_many_arguments)]
    fn paint_glyph(
        surface: &mut dyn PaintSurface,
        theme: &Theme,
        m: &Metrics,
        col: u16,
        row: u16,
        width: u16,
        label: &str,
        active: bool,
    ) {
        let rect = region_rect(m, col, row, width);
        let fg = if active {
            surface.surface_fill_rect(rect, theme.accent_bg);
            theme.background
        } else {
            theme.foreground
        };
        let (tw, _) = surface.surface_measure_text(label);
        let tx = rect.x + ((rect.width - tw) / 2.0).max(0.0);
        surface.surface_draw_text_run(Rect::new(tx, rect.y, tw, m.lh), label, fg);
    }

    /// Paint a find/replace input field: background + border, the
    /// field's text, and — only when `is_focused` — the selection
    /// highlight and cursor.
    ///
    /// See this module's doc for why the selection highlight is filled
    /// *before* the text (split into prefix/selected/suffix runs)
    /// rather than as a translucent overlay drawn after a single full
    /// run — that's the shape the three deleted per-backend copies
    /// disagreed on.
    #[allow(clippy::too_many_arguments)]
    fn paint_input(
        surface: &mut dyn PaintSurface,
        theme: &Theme,
        m: &Metrics,
        col: u16,
        row: u16,
        width: u16,
        text: &str,
        is_focused: bool,
        cursor: usize,
        sel_anchor: Option<usize>,
    ) {
        let rect = region_rect(m, col, row, width);
        surface.surface_fill_rect(rect, theme.background);
        surface.surface_stroke_rect(rect, theme.separator, 0.5);

        let text_x = rect.x + 4.0;

        let has_sel = is_focused && sel_anchor.is_some_and(|a| a != cursor) && !text.is_empty();

        if !has_sel {
            let (tw, _) = surface.surface_measure_text(text);
            surface.surface_draw_text_run(
                Rect::new(text_x, rect.y, tw, m.lh),
                text,
                theme.foreground,
            );
        } else {
            let anchor = sel_anchor.expect("has_sel implies sel_anchor is Some");
            let (lo, hi) = (anchor.min(cursor), anchor.max(cursor));
            let lo_b = crate::text_util::char_to_byte_idx(text, lo);
            let hi_b = crate::text_util::char_to_byte_idx(text, hi);
            let prefix = &text[..lo_b];
            let selected = &text[lo_b..hi_b];
            let suffix = &text[hi_b..];
            let (pw, _) = surface.surface_measure_text(prefix);
            let (sw, _) = surface.surface_measure_text(selected);
            let (suw, _) = surface.surface_measure_text(suffix);

            surface.surface_fill_rect(
                Rect::new(text_x + pw, rect.y, sw.max(1.0), m.lh),
                theme.selection_bg,
            );
            surface.surface_draw_text_run(
                Rect::new(text_x, rect.y, pw, m.lh),
                prefix,
                theme.foreground,
            );
            surface.surface_draw_text_run(
                Rect::new(text_x + pw, rect.y, sw, m.lh),
                selected,
                theme.foreground,
            );
            surface.surface_draw_text_run(
                Rect::new(text_x + pw + sw, rect.y, suw, m.lh),
                suffix,
                theme.foreground,
            );
        }

        if !is_focused {
            return;
        }

        // Cursor: a 2-device-unit-wide bar at the char offset, inset 2
        // top/bottom — same shape all three deleted copies drew.
        let cursor_b = crate::text_util::char_to_byte_idx(text, cursor);
        let (cursor_px, _) = surface.surface_measure_text(&text[..cursor_b]);
        surface.surface_fill_rect(
            Rect::new(text_x + cursor_px, rect.y + 2.0, 2.0, (m.lh - 4.0).max(1.0)),
            theme.foreground,
        );
    }

    /// Paint a laid-out [`FindReplacePanel`] using `surface`'s
    /// [`PaintSurface`] verbs.
    ///
    /// Walks `panel.hit_regions` — the same list
    /// [`super::compute_hit_regions`] builds once at panel construction
    /// and every backend's click dispatch hit-tests against — so paint
    /// and click can never disagree about where a target lives.
    pub(crate) fn paint(panel: &FindReplacePanel, surface: &mut dyn PaintSurface, theme: &Theme) {
        use FindReplaceClickTarget as T;

        let cw = surface.surface_char_width().max(1.0);
        let lh = surface.surface_line_height().max(1.0);

        let popup_w = panel.panel_width as f32 * cw;
        let row_count = if panel.show_replace { 2.0 } else { 1.0 };
        let popup_h = (row_count + 2.0) * lh;

        let gb = &panel.group_bounds;
        let popup_x = ((gb.x + gb.width) - popup_w - 10.0).max(gb.x);
        let popup_y = gb.y + 2.0;
        let popup_rect = Rect::new(popup_x, popup_y, popup_w, popup_h);

        surface.surface_fill_rect(popup_rect, theme.surface_bg);
        surface.surface_stroke_rect(popup_rect, theme.separator, 1.0);

        let m = Metrics {
            cw,
            lh,
            content_x: popup_x + cw,
            content_y: popup_y + lh,
        };

        // Positions derived from neighbouring hit regions, not a hit
        // region itself — the match-count string isn't clickable. Same
        // trick every deleted per-backend copy (and TUI) used.
        let mut regex_end_col: Option<u16> = None;
        let mut prev_match_col: Option<u16> = None;

        for (region, target) in &panel.hit_regions {
            match target {
                T::Chevron => {
                    let chevron = if panel.show_replace {
                        "\u{25bc}"
                    } else {
                        "\u{25b6}"
                    };
                    paint_label(
                        surface,
                        &m,
                        region.col,
                        region.row,
                        chevron,
                        theme.foreground,
                    );
                }
                T::FindInput(_) => paint_input(
                    surface,
                    theme,
                    &m,
                    region.col,
                    region.row,
                    region.width,
                    &panel.query,
                    panel.focus == 0,
                    panel.cursor,
                    panel.sel_anchor,
                ),
                T::ReplaceInput(_) => paint_input(
                    surface,
                    theme,
                    &m,
                    region.col,
                    region.row,
                    region.width,
                    &panel.replacement,
                    panel.focus == 1,
                    panel.cursor,
                    panel.sel_anchor,
                ),
                T::ToggleCase => {
                    let label = crate::codicon::CASE_SENSITIVE.to_string();
                    paint_toggle(
                        surface,
                        theme,
                        &m,
                        region.col,
                        region.row,
                        region.width,
                        &label,
                        panel.case_sensitive,
                    );
                }
                T::ToggleWholeWord => {
                    let label = crate::codicon::WHOLE_WORD.to_string();
                    paint_toggle(
                        surface,
                        theme,
                        &m,
                        region.col,
                        region.row,
                        region.width,
                        &label,
                        panel.whole_word,
                    );
                }
                T::ToggleRegex => {
                    let label = crate::codicon::REGEX.to_string();
                    paint_toggle(
                        surface,
                        theme,
                        &m,
                        region.col,
                        region.row,
                        region.width,
                        &label,
                        panel.use_regex,
                    );
                    regex_end_col = Some(region.col + region.width);
                }
                T::PrevMatch => {
                    paint_glyph(
                        surface,
                        theme,
                        &m,
                        region.col,
                        region.row,
                        region.width,
                        "\u{2191}",
                        false,
                    );
                    prev_match_col.get_or_insert(region.col);
                }
                T::NextMatch => paint_glyph(
                    surface,
                    theme,
                    &m,
                    region.col,
                    region.row,
                    region.width,
                    "\u{2193}",
                    false,
                ),
                T::ToggleInSelection => paint_glyph(
                    surface,
                    theme,
                    &m,
                    region.col,
                    region.row,
                    region.width,
                    "\u{2261}",
                    panel.in_selection,
                ),
                T::Close => paint_glyph(
                    surface,
                    theme,
                    &m,
                    region.col,
                    region.row,
                    region.width,
                    "\u{00d7}",
                    false,
                ),
                T::TogglePreserveCase => {
                    let label = crate::codicon::PRESERVE_CASE.to_string();
                    paint_toggle(
                        surface,
                        theme,
                        &m,
                        region.col,
                        region.row,
                        region.width,
                        &label,
                        panel.preserve_case,
                    );
                }
                T::ReplaceCurrent => paint_glyph(
                    surface,
                    theme,
                    &m,
                    region.col,
                    region.row,
                    region.width,
                    &panel.replace_one_glyph,
                    false,
                ),
                T::ReplaceAll => paint_glyph(
                    surface,
                    theme,
                    &m,
                    region.col,
                    region.row,
                    region.width,
                    &panel.replace_all_glyph,
                    false,
                ),
            }
        }

        if let (Some(start_col), Some(end_col)) = (regex_end_col, prev_match_col) {
            let info_col = start_col + 1;
            if end_col > info_col + 1 {
                paint_label(
                    surface,
                    &m,
                    info_col,
                    0,
                    &panel.match_info,
                    theme.foreground,
                );
            }
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use crate::backend::ImagePaintResult;
        use crate::event::Viewport;
        use crate::primitives::find_replace::compute_hit_regions;
        use crate::Image;

        /// Records every drawing verb `paint` issues, so a paint
        /// assertion can run on any host — no cairo, Core Graphics or
        /// Direct2D needed. The pixel backends' own probes (real
        /// `ImageSurface`/`BitmapSurface`/`HeadlessSurface` renders)
        /// still cover "the verb reached real pixels"; this covers "the
        /// shared painter emits the right verb at all", on every leg of
        /// the quality gate that enables gtk, win, or macos — not just
        /// whichever one happens to run on this host.
        #[derive(Default)]
        struct RecordingSurface {
            fills: Vec<(Rect, Color)>,
            strokes: Vec<(Rect, Color, f32)>,
            text_runs: Vec<(Rect, String, Color)>,
        }

        impl PaintSurface for RecordingSurface {
            fn surface_begin_frame(&mut self, _viewport: Viewport) {}
            fn surface_end_frame(&mut self) {}
            fn surface_viewport(&self) -> Viewport {
                Viewport::new(600.0, 200.0, 1.0)
            }
            fn surface_line_height(&self) -> f32 {
                16.0
            }
            fn surface_char_width(&self) -> f32 {
                8.0
            }
            fn surface_measure_text(&self, text: &str) -> (f32, f32) {
                (text.chars().count() as f32 * 8.0, 14.0)
            }
            fn surface_fill_rect(&mut self, rect: Rect, color: Color) {
                self.fills.push((rect, color));
            }
            /// Test-only recorder — `paint` never calls this verb
            /// (see this module's own doc for why no primitive here has been
            /// migrated onto it yet); this exists only so `RecordingSurface`
            /// satisfies the trait. Records into the same `fills` list as
            /// `surface_fill_rect` (radius dropped) — no test asserts on it
            /// today.
            fn surface_fill_rounded_rect(&mut self, rect: Rect, _radius: f32, color: Color) {
                self.fills.push((rect, color));
            }
            fn surface_stroke_rect(&mut self, rect: Rect, color: Color, stroke_width: f32) {
                self.strokes.push((rect, color, stroke_width));
            }
            fn surface_stroke_rounded_rect(
                &mut self,
                rect: Rect,
                _radius: f32,
                color: Color,
                stroke_width: f32,
            ) {
                self.strokes.push((rect, color, stroke_width));
            }
            fn surface_draw_text_run(&mut self, rect: Rect, text: &str, color: Color) {
                self.text_runs.push((rect, text.to_string(), color));
            }
            fn surface_draw_line(
                &mut self,
                _from: crate::Point,
                _to: crate::Point,
                _color: Color,
                _stroke_width: f32,
            ) {
            }
            fn surface_push_clip(&mut self, _rect: Rect) {}
            fn surface_pop_clip(&mut self) {}
            fn surface_draw_image(&mut self, _rect: Rect, _image: &Image) -> ImagePaintResult {
                ImagePaintResult::Unsupported
            }
        }

        fn sample_panel(query: &str, cursor: usize, sel_anchor: Option<usize>) -> FindReplacePanel {
            let (hit_regions, _input_width) = compute_hit_regions(50, false, "1 of 3", 2, 2);
            FindReplacePanel {
                query: query.into(),
                replacement: String::new(),
                show_replace: false,
                focus: 0,
                cursor,
                sel_anchor,
                match_info: "1 of 3".into(),
                case_sensitive: false,
                whole_word: false,
                use_regex: false,
                preserve_case: false,
                in_selection: false,
                group_bounds: Rect::new(0.0, 0.0, 600.0, 200.0),
                panel_width: 50,
                replace_one_glyph: "R1".into(),
                replace_all_glyph: "R*".into(),
                hit_regions,
            }
        }

        #[test]
        fn paints_popup_background_and_border() {
            let panel = sample_panel("needle", 6, None);
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            paint(&panel, &mut surface, &theme);

            assert!(
                surface.fills.iter().any(|(_, c)| *c == theme.surface_bg),
                "expected a surface_bg fill for the popup background, fills were {:?}",
                surface.fills,
            );
            assert!(
                surface
                    .strokes
                    .iter()
                    .any(|(_, c, w)| *c == theme.separator && *w == 1.0),
                "expected a 1.0-wide separator stroke for the popup border, strokes were {:?}",
                surface.strokes,
            );
        }

        #[test]
        fn active_toggle_paints_accent_bg() {
            let mut panel = sample_panel("needle", 6, None);
            panel.case_sensitive = true;
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            paint(&panel, &mut surface, &theme);

            assert!(
                surface.fills.iter().any(|(_, c)| *c == theme.accent_bg),
                "expected an accent_bg fill for the active toggle, fills were {:?}",
                surface.fills,
            );
        }

        /// Verify that the selection fill renders and selected text remains
        /// visible, so it is not obscured by the fill rect.
        #[test]
        fn focused_input_selection_fills_and_still_draws_selected_text() {
            let mut panel = sample_panel("needle", 3, Some(0));
            panel.focus = 0;
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            paint(&panel, &mut surface, &theme);

            assert!(
                surface.fills.iter().any(|(_, c)| *c == theme.selection_bg),
                "expected a selection_bg fill for the focused input's selection, fills were {:?}",
                surface.fills,
            );
            assert!(
                surface.text_runs.iter().any(|(_, t, _)| t == "nee"),
                "selected substring \"nee\" must still be drawn as its own text run \
                 (the fill happens before text, so it can't hide it), text runs were {:?}",
                surface.text_runs,
            );
        }

        /// GUI backends (GTK/macOS/Win — anything routing through this
        /// shared `paint`) render the four toggle buttons as codicon
        /// glyphs, not the TUI's literal text pairs. TUI's own
        /// rasteriser (`tui::find_replace`) has no `PaintSurface` impl
        /// and keeps painting `"Aa"`/`"ab"`/`".*"`/`"AB"`; this test
        /// covers only the `PaintSurface` path this module owns.
        ///
        /// Beyond "each glyph is painted somewhere", this binds each
        /// glyph to *its own* hit region's projected x — the same
        /// `region_rect`/centering math `paint_toggle` uses — so a slot
        /// mix-up (e.g. the case-sensitive glyph landing in the regex
        /// toggle's rect) would fail here even though every glyph would
        /// still technically appear in `text_runs`.
        #[test]
        fn toggle_buttons_paint_codicon_glyphs_not_literal_text() {
            let mut panel = sample_panel("needle", 6, None);
            panel.show_replace = true;
            let (hit_regions, _input_width) = compute_hit_regions(50, true, "1 of 3", 2, 2);
            panel.hit_regions = hit_regions.clone();
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            paint(&panel, &mut surface, &theme);

            // Derive content_x the same way `paint` does — from the
            // popup background fill it always records first — rather
            // than re-deriving the popup-placement arithmetic by hand.
            let cw = surface.surface_char_width();
            let popup_rect = surface
                .fills
                .first()
                .map(|(r, _)| *r)
                .expect("popup background fill recorded first");
            let content_x = popup_rect.x + cw;

            let toggles = [
                (
                    FindReplaceClickTarget::ToggleCase,
                    crate::codicon::CASE_SENSITIVE,
                ),
                (
                    FindReplaceClickTarget::ToggleWholeWord,
                    crate::codicon::WHOLE_WORD,
                ),
                (FindReplaceClickTarget::ToggleRegex, crate::codicon::REGEX),
                (
                    FindReplaceClickTarget::TogglePreserveCase,
                    crate::codicon::PRESERVE_CASE,
                ),
            ];

            for (target, glyph) in toggles {
                let (region, _) = hit_regions
                    .iter()
                    .find(|(_, t)| *t == target)
                    .unwrap_or_else(|| panic!("{target:?} region must exist"));
                let label = glyph.to_string();
                let (tw, _) = surface.surface_measure_text(&label);
                let rect_width = region.width as f32 * cw;
                let expected_x =
                    content_x + region.col as f32 * cw + ((rect_width - tw) / 2.0).max(0.0);

                let run = surface
                    .text_runs
                    .iter()
                    .find(|(_, t, _)| t == &label)
                    .unwrap_or_else(|| {
                        panic!(
                            "expected codicon glyph {glyph:?} for {target:?} to be painted, \
                             text runs were {:?}",
                            surface.text_runs
                        )
                    });
                assert!(
                    (run.0.x - expected_x).abs() < 0.01,
                    "{target:?}'s glyph {glyph:?} painted at x={}, expected x={} \
                     (its own region's projected rx0, not a neighbouring toggle's) — \
                     text runs were {:?}",
                    run.0.x,
                    expected_x,
                    surface.text_runs,
                );
            }

            for stale in ["Aa", "ab", ".*", "AB"] {
                assert!(
                    !surface.text_runs.iter().any(|(_, t, _)| t == stale),
                    "GUI toggle buttons must not paint the TUI-only literal {stale:?} \
                     text pair, text runs were {:?}",
                    surface.text_runs,
                );
            }
        }

        /// An unfocused input paints its text but no cursor and no
        /// selection highlight, even if `sel_anchor` is set — matches
        /// every deleted per-backend copy's `if !is_focused { return }`
        /// guard.
        #[test]
        fn unfocused_input_paints_no_selection_or_cursor() {
            let mut panel = sample_panel("needle", 3, Some(0));
            panel.focus = 1; // no replace row exists, so FindInput (focus 0) is unfocused
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            paint(&panel, &mut surface, &theme);

            assert!(
                !surface.fills.iter().any(|(_, c)| *c == theme.selection_bg),
                "unfocused input must not paint a selection highlight, fills were {:?}",
                surface.fills,
            );
            assert!(
                surface.text_runs.iter().any(|(_, t, _)| t == "needle"),
                "unfocused input must still paint its full text as one run, text runs were {:?}",
                surface.text_runs,
            );
        }

        /// Verify that multibyte queries with boundary-adjacent or out-of-range
        /// cursor/selection offsets do not panic, since offsets are character-based.
        #[test]
        fn multibyte_query_with_out_of_range_selection_does_not_panic() {
            let panel = sample_panel("café🎉中文", 3, Some(6));
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            paint(&panel, &mut surface, &theme);
        }
    }
}

// ── #818: hit_test (ungated — no PaintSurface feature needed) ─────────────

#[cfg(test)]
mod hit_test_tests {
    use super::*;

    fn panel(show_replace: bool) -> FindReplacePanel {
        let (hit_regions, _input_width) = compute_hit_regions(50, show_replace, "1 of 3", 2, 2);
        FindReplacePanel {
            query: "needle".into(),
            replacement: String::new(),
            show_replace,
            focus: 0,
            cursor: 0,
            sel_anchor: None,
            match_info: "1 of 3".into(),
            case_sensitive: false,
            whole_word: false,
            use_regex: false,
            preserve_case: false,
            in_selection: false,
            group_bounds: Rect::new(0.0, 0.0, 600.0, 200.0),
            panel_width: 50,
            replace_one_glyph: "R1".into(),
            replace_all_glyph: "R*".into(),
            hit_regions,
        }
    }

    #[test]
    fn hit_test_chevron_at_content_origin() {
        let p = panel(false);
        // Chevron region: col 0..2, row 0 — content_origin (10,10), 8x16 cells.
        let hit = p.hit_test(11.0, 12.0, (10.0, 10.0), 8.0, 16.0);
        assert_eq!(hit, FindReplaceHit::Target(FindReplaceClickTarget::Chevron));
    }

    #[test]
    fn hit_test_toggle_case_on_find_row() {
        let p = panel(false);
        // ToggleCase sits right after the find input; find its column
        // from the computed regions rather than hardcoding it.
        let (region, _) = p
            .hit_regions
            .iter()
            .find(|(_, t)| matches!(t, FindReplaceClickTarget::ToggleCase))
            .expect("ToggleCase region present");
        let x = 10.0 + (region.col as f32 + 0.5) * 8.0;
        let y = 10.0 + (region.row as f32 + 0.5) * 16.0;
        let hit = p.hit_test(x, y, (10.0, 10.0), 8.0, 16.0);
        assert_eq!(
            hit,
            FindReplaceHit::Target(FindReplaceClickTarget::ToggleCase)
        );
    }

    #[test]
    fn hit_test_replace_row_only_present_when_show_replace() {
        let p = panel(true);
        let (region, _) = p
            .hit_regions
            .iter()
            .find(|(_, t)| matches!(t, FindReplaceClickTarget::ReplaceCurrent))
            .expect("ReplaceCurrent region present when show_replace");
        let x = 10.0 + (region.col as f32 + 0.5) * 8.0;
        let y = 10.0 + (region.row as f32 + 0.5) * 16.0;
        assert_eq!(
            p.hit_test(x, y, (10.0, 10.0), 8.0, 16.0),
            FindReplaceHit::Target(FindReplaceClickTarget::ReplaceCurrent)
        );
    }

    #[test]
    fn hit_test_miss_returns_empty() {
        let p = panel(false);
        assert_eq!(
            p.hit_test(0.0, 0.0, (10.0, 10.0), 8.0, 16.0),
            FindReplaceHit::Empty
        );
    }

    #[test]
    fn hit_test_zero_metrics_returns_empty() {
        let p = panel(false);
        assert_eq!(
            p.hit_test(11.0, 12.0, (10.0, 10.0), 0.0, 16.0),
            FindReplaceHit::Empty
        );
    }

    #[test]
    fn hit_test_right_edge_is_exclusive() {
        let p = panel(false);
        let (region, target) = p
            .hit_regions
            .iter()
            .find(|(_, t)| matches!(t, FindReplaceClickTarget::ToggleCase))
            .expect("ToggleCase region present");
        let target = *target;
        let rx1 = 10.0 + (region.col as f32 + region.width as f32) * 8.0;
        let y = 10.0 + (region.row as f32 + 0.5) * 16.0;

        // Exactly on the right edge: must miss this region (half-open
        // interval — `x < rx1`, not `x <= rx1`).
        let hit_at_edge = p.hit_test(rx1, y, (10.0, 10.0), 8.0, 16.0);
        assert_ne!(hit_at_edge, FindReplaceHit::Target(target));

        // A hair inside the edge: must still hit.
        let eps = 0.01;
        let hit_just_inside = p.hit_test(rx1 - eps, y, (10.0, 10.0), 8.0, 16.0);
        assert_eq!(hit_just_inside, FindReplaceHit::Target(target));
    }

    #[test]
    fn hit_test_fractional_char_width_diverges_from_cell_space() {
        let p = panel(false);
        let (region, target) = p
            .hit_regions
            .iter()
            .find(|(_, t)| matches!(t, FindReplaceClickTarget::ToggleCase))
            .expect("ToggleCase region present");
        let target = *target;
        // char_width = 7.5: px and cell-index space diverge (unlike the
        // integer-cw cases above, `col` here is not an integer multiple
        // of 1px). Pick a point inside the region's px rect and confirm
        // it still resolves — exercising the px comparison directly
        // rather than any cell-space shortcut.
        let cw = 7.5_f32;
        let lh = 16.0_f32;
        let rx0 = 10.0 + region.col as f32 * cw;
        let x = rx0 + 0.5;
        let y = 10.0 + (region.row as f32 + 0.5) * lh;
        let hit = p.hit_test(x, y, (10.0, 10.0), cw, lh);
        assert_eq!(hit, FindReplaceHit::Target(target));
    }
}

#[cfg(any(
    feature = "gtk",
    feature = "win",
    all(feature = "macos", target_os = "macos")
))]
#[allow(unused_imports)]
pub(crate) use native_surface_paint::paint;