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
//! macOS layout + settings-chrome rasteriser for [`crate::Form`].
//!
//! Field-kind painting moved to the shared [`crate::primitives::form::paint`].
//! `mac_form_layout` here only computes geometry (used both for hit-testing via
//! `MacBackend::form_layout` and to feed `paint` from `MacBackend::draw_form`).
//! The shared `paint` handles all 14 `FieldKind` variants, so coverage is complete.

use core_graphics::geometry::CGRect;
use core_graphics::sys::CGContextRef;
use core_text::font::CTFont;

use super::text::{draw_text, measure_text};
use crate::event::Rect as QRect;
use crate::primitives::form::{Form, FormLayout};
use crate::theme::Theme;
use crate::types::Color;

/// Compute the layout the macOS rasteriser would produce for `form`
/// in `area` at `line_height`. Rows are `(line_height * 1.4).round()`
/// tall.
///
/// Per-item measurement (`ToggleGroup`, `SegmentedControl`,
/// `ButtonRow`) uses `font` so paint and hit-test agree on each
/// item's x position. Mirrors the per-`FieldKind` measurement in
/// [`crate::gtk::backend`]'s `form_layout` impl.
///
/// Coordinate frame: `visible_fields.bounds`, `item_bounds`, and
/// `hit_regions` are in **form-local** coords (origin at 0, 0),
/// matching `gtk_form_layout` and the `tree_layout` contract. Hosts
/// (e.g. `SidebarSystem`, `FormController`) subtract `area.x`/`area.y`
/// from absolute click coords before calling
/// [`FormLayout::hit_test`].
pub fn mac_form_layout(form: &Form, area: QRect, line_height: f64, font: &CTFont) -> FormLayout {
    let row_h = crate::primitives::layout_metrics::form_row_height(line_height);
    form.layout(area.width, area.height, |i| {
        crate::primitives::layout_metrics::form_field_measure(&form.fields[i], row_h, font)
    })
}

/// Cursor width in points for the settings-chrome search row. Matches
/// the GTK twin's 1.5px caret.
const SETTINGS_CURSOR_W: f64 = 1.5;
/// Prefix rendered before the settings search query.
const SETTINGS_SEARCH_PREFIX: &str = " /  ";

/// Draw settings-panel chrome: a header row and, when `height` leaves room for it,
/// a search input row beneath it, designed to sit immediately above a [`Form`] body.
///
/// Mirrors [`crate::gtk::form::draw_settings_chrome`] — same row layout, same
/// `" /  "` prefix, same placeholder rule (shown only when the query is empty
/// *and* the row is inactive), same accent caret when active. The header row always
/// paints at one `line_height`; the search row paints only when
/// `height >= line_height * 1.5`, so a caller reserving a single row gets a
/// header-only strip instead of an unrequested second row painted past its rect.
///
/// Chrome only: the form body and any scrollbar layered below are painted
/// separately by the caller.
///
/// # Safety
///
/// `ctx` must be a valid `CGContextRef` borrowed for the duration of the call
/// (typical: the frame-scope pointer stashed on [`super::MacBackend`]). Calling
/// with a freed or null pointer is UB.
#[allow(clippy::too_many_arguments)]
pub unsafe fn draw_settings_chrome(
    ctx: CGContextRef,
    font: &CTFont,
    x: f64,
    y: f64,
    w: f64,
    height: f64,
    line_height: f64,
    header_text: &str,
    query: &str,
    placeholder: &str,
    active: bool,
    theme: &Theme,
) {
    if w <= 0.0 || line_height <= 0.0 {
        return;
    }

    let paints_search_row = height >= line_height * 1.5;
    let clip_h = if paints_search_row {
        line_height * 2.0
    } else {
        line_height
    };

    CGContextSaveGState(ctx);
    CGContextClipToRect(ctx, CGRect::new_xywh(x, y, w, clip_h));

    // Row 0: header bar.
    fill_rect(ctx, x, y, w, line_height, theme.header_bg);
    draw_text(
        ctx,
        font,
        header_text,
        x + 2.0,
        y,
        color_to_cg(theme.header_fg),
    );

    // Row 1: search input — only when `height` leaves room for it (see
    // this fn's doc). Skipped for a header-only strip instead of
    // overpainting whatever the caller placed directly beneath it.
    if paints_search_row {
        let search_y = y + line_height;
        let row_bg = if active {
            theme.selected_bg
        } else {
            theme.tab_bar_bg
        };
        fill_rect(ctx, x, search_y, w, line_height, row_bg);

        draw_text(
            ctx,
            font,
            SETTINGS_SEARCH_PREFIX,
            x + 2.0,
            search_y,
            color_to_cg(theme.muted_fg),
        );
        let (prefix_w, _) = measure_text(font, SETTINGS_SEARCH_PREFIX);
        let q_x = x + 2.0 + prefix_w;

        let show_placeholder = query.is_empty() && !placeholder.is_empty() && !active;
        let (text, color) = if show_placeholder {
            (placeholder, theme.muted_fg)
        } else if query.is_empty() {
            (query, theme.muted_fg)
        } else {
            (query, theme.foreground)
        };
        draw_text(ctx, font, text, q_x, search_y, color_to_cg(color));

        if active {
            let (q_w, _) = measure_text(font, query);
            let cur_x = q_x + if query.is_empty() { 0.0 } else { q_w };
            fill_rect(
                ctx,
                cur_x,
                search_y + 2.0,
                SETTINGS_CURSOR_W,
                line_height - 4.0,
                theme.accent_fg,
            );
        }
    }

    CGContextRestoreGState(ctx);
}

fn color_to_cg(c: Color) -> (f64, f64, f64, f64) {
    (
        c.r as f64 / 255.0,
        c.g as f64 / 255.0,
        c.b as f64 / 255.0,
        c.a as f64 / 255.0,
    )
}

unsafe fn fill_rect(ctx: CGContextRef, x: f64, y: f64, w: f64, h: f64, c: Color) {
    let (r, g, b, a) = color_to_cg(c);
    CGContextSetRGBFillColor(ctx, r, g, b, a);
    CGContextFillRect(ctx, CGRect::new_xywh(x, y, w, h));
}

trait CGRectExt {
    fn new_xywh(x: f64, y: f64, w: f64, h: f64) -> Self;
}
impl CGRectExt for CGRect {
    fn new_xywh(x: f64, y: f64, w: f64, h: f64) -> Self {
        use core_graphics::geometry::{CGPoint, CGSize};
        CGRect::new(&CGPoint::new(x, y), &CGSize::new(w, h))
    }
}

extern "C" {
    fn CGContextSaveGState(c: CGContextRef);
    fn CGContextRestoreGState(c: CGContextRef);
    fn CGContextClipToRect(c: CGContextRef, rect: CGRect);
    fn CGContextSetRGBFillColor(
        c: CGContextRef,
        red: core_graphics::base::CGFloat,
        green: core_graphics::base::CGFloat,
        blue: core_graphics::base::CGFloat,
        alpha: core_graphics::base::CGFloat,
    );
    fn CGContextFillRect(c: CGContextRef, rect: CGRect);
}

#[cfg(test)]
mod tests {
    use super::super::headless::BitmapSurface;
    use super::super::text::make_font;
    use super::super::MacBackend;
    use super::*;
    use crate::event::Viewport;
    use crate::primitives::form::{ButtonRowItem, FieldKind, FormField, FormHit, ToggleGroupItem};
    use crate::theme::Theme;
    use crate::types::{StyledText, WidgetId};
    use crate::Backend;

    const W: u32 = 320;
    const H: u32 = 160;

    fn font() -> CTFont {
        make_font("Menlo", 14.0).expect("Menlo installed")
    }

    fn label(id: &str, text: &str) -> FormField {
        FormField {
            id: WidgetId::new(id),
            label: StyledText::plain(text),
            kind: FieldKind::Label,
            hint: StyledText::default(),
            disabled: false,
            validation: None,
        }
    }

    fn text_input(id: &str, label_text: &str, value: &str) -> FormField {
        FormField {
            id: WidgetId::new(id),
            label: StyledText::plain(label_text),
            kind: FieldKind::TextInput {
                value: value.into(),
                placeholder: String::new(),
                cursor: Some(value.len()),
                selection_anchor: None,
            },
            hint: StyledText::default(),
            disabled: false,
            validation: None,
        }
    }

    fn toggle(id: &str, label_text: &str, value: bool) -> FormField {
        FormField {
            id: WidgetId::new(id),
            label: StyledText::plain(label_text),
            kind: FieldKind::Toggle { value },
            hint: StyledText::default(),
            disabled: false,
            validation: None,
        }
    }

    fn sample_form() -> Form {
        Form {
            id: WidgetId::new("settings"),
            fields: vec![
                label("hdr", "General"),
                text_input("name", "Name", "alice"),
                toggle("enabled", "Enabled", true),
            ],
            focused_field: Some(WidgetId::new("name")),
            scroll_offset: 0,
            has_focus: true,
        }
    }

    /// Paint `form` through the real `Backend::draw_form` and return the
    /// painted pixels alongside the layout that paint used.
    ///
    /// The layout comes from [`Backend::form_layout`] — the no-paint twin
    /// of `draw_form` — rather than a local `mac_form_layout` call with a
    /// font of the test's own choosing. A `Form` is chrome, so both of
    /// those backend methods resolve the *chrome* font; re-deriving the
    /// expectation here against the editor font this helper installs as
    /// `current_font` would measure per-item widths in a font nothing
    /// painted with, and every `item_bounds`-relative pixel probe below
    /// would drift by the difference between the two fonts' advances.
    /// Asking the backend is also what a host does, so paint↔hit-test
    /// agreement is part of what these tests cover.
    fn paint_via_backend(form: &Form) -> (BitmapSurface, FormLayout) {
        let surface = BitmapSurface::new(W, H);
        surface.fill(0.0, 0.0, 0.0, 0.0);
        let mut backend = MacBackend::new();
        backend.set_current_font(font());
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        let layout = std::cell::RefCell::new(None);
        backend.enter_frame_scope(surface.context_ptr(), |b| {
            let area = QRect::new(0.0, 0.0, W as f32, H as f32);
            b.draw_form(area, form);
            *layout.borrow_mut() = Some(b.form_layout(area, form));
        });
        backend.end_frame();
        (surface, layout.into_inner().unwrap())
    }

    #[test]
    fn focused_field_paints_selected_bg() {
        let form = sample_form();
        let (surface, layout) = paint_via_backend(&form);
        let theme = Theme::default();
        let name = layout
            .visible_fields
            .iter()
            .find(|v| v.id == WidgetId::new("name"))
            .expect("name field visible");
        // Probe near right edge to avoid the label glyph "Name".
        let px = (name.bounds.x + name.bounds.width - 4.0) as u32;
        let py = (name.bounds.y + name.bounds.height / 2.0) as u32;
        let (r, g, b, _) = surface.pixel(px, py);
        // Focused field row gets selected_bg.
        assert_eq!(
            (r, g, b),
            (
                theme.selected_bg.r,
                theme.selected_bg.g,
                theme.selected_bg.b
            ),
            "focused TextInput row should paint selected_bg",
        );
    }

    #[test]
    fn header_field_paints_header_bg() {
        let form = sample_form();
        let (surface, layout) = paint_via_backend(&form);
        let theme = Theme::default();
        let hdr = layout
            .visible_fields
            .iter()
            .find(|v| v.id == WidgetId::new("hdr"))
            .expect("header visible");
        let px = (hdr.bounds.x + hdr.bounds.width - 4.0) as u32;
        let py = (hdr.bounds.y + hdr.bounds.height / 2.0) as u32;
        let (r, g, b, _) = surface.pixel(px, py);
        assert_eq!(
            (r, g, b),
            (theme.header_bg.r, theme.header_bg.g, theme.header_bg.b),
        );
    }

    #[test]
    fn hit_test_resolves_field_at_painted_centre() {
        let form = sample_form();
        let (_surface, layout) = paint_via_backend(&form);
        for vis in &layout.visible_fields {
            let cx = vis.bounds.x + vis.bounds.width * 0.5;
            let cy = vis.bounds.y + vis.bounds.height * 0.5;
            assert_eq!(
                layout.hit_test(cx, cy),
                FormHit::Field(vis.id),
                "field {:?} hit-test",
                vis.id,
            );
        }
    }

    #[test]
    fn layout_returns_local_coords_when_area_offset() {
        // Cross-backend contract: visible_fields.bounds, item_bounds, and hit_regions
        // are in form-local coords (origin 0, 0), regardless of where `area` lives.
        // Hosts subtract area.x/area.y from absolute click coords before hit_test.
        // Matches the gtk_form_layout and mac_tree_layout contract.
        let form = sample_form();
        // Area offset by (0, 40) — typical when a form lives below an
        // MSV section header.
        let area = QRect::new(0.0, 40.0, 320.0, 120.0);
        let layout = mac_form_layout(&form, area, 16.0, &font());
        // Locality: first field's bounds.y must be 0, not 40.
        let first = &layout.visible_fields[0];
        assert_eq!(
            first.bounds.y, 0.0,
            "visible_fields.bounds.y must be local (0.0), got {}",
            first.bounds.y,
        );
        // Round-trip: simulate a click at the absolute centre of each
        // painted field, localise the way the AppLogic does, and assert
        // it hits the right field. Pre-fix this returned the field N
        // positions earlier.
        for vis in &layout.visible_fields {
            let abs_x = area.x + vis.bounds.x + vis.bounds.width * 0.5;
            let abs_y = area.y + vis.bounds.y + vis.bounds.height * 0.5;
            let local_x = abs_x - area.x;
            let local_y = abs_y - area.y;
            assert_eq!(
                layout.hit_test(local_x, local_y),
                FormHit::Field(vis.id),
                "field {:?} click → wrong hit (coord-frame drift)",
                vis.id,
            );
        }
    }

    fn toggle_group_field(id: &str, toggles: Vec<ToggleGroupItem>) -> FormField {
        FormField {
            id: WidgetId::new(id),
            label: StyledText::plain(""),
            kind: FieldKind::ToggleGroup { toggles },
            hint: StyledText::default(),
            disabled: false,
            validation: None,
        }
    }

    fn search_flags_form() -> Form {
        // Mirrors the `macos_sidebar_search` shape — three toggles with
        // the middle one ON, no label so items start at the row's left.
        Form {
            id: WidgetId::new("search"),
            fields: vec![toggle_group_field(
                "flags",
                vec![
                    ToggleGroupItem {
                        id: WidgetId::new("case"),
                        label: "Aa".into(),
                        value: false,
                    },
                    ToggleGroupItem {
                        id: WidgetId::new("regex"),
                        label: ".*".into(),
                        value: true,
                    },
                    ToggleGroupItem {
                        id: WidgetId::new("word"),
                        label: "W".into(),
                        value: false,
                    },
                ],
            )],
            focused_field: None,
            scroll_offset: 0,
            has_focus: false,
        }
    }

    #[test]
    fn toggle_group_layout_resolves_per_item_bounds() {
        // ToggleGroup must populate item_bounds so per-toggle clicks
        // dispatch the right `ToggleGroupItem` id rather than the
        // parent field id.
        let form = search_flags_form();
        let (_surface, layout) = paint_via_backend(&form);
        let vis = &layout.visible_fields[0];
        assert_eq!(
            vis.item_bounds.len(),
            3,
            "ToggleGroup should resolve 3 item_bounds",
        );
        let ids: Vec<&WidgetId> = vis.item_bounds.iter().map(|(id, _)| id).collect();
        assert_eq!(
            ids,
            vec![
                &WidgetId::new("case"),
                &WidgetId::new("regex"),
                &WidgetId::new("word"),
            ],
        );
    }

    /// True when at least one pixel *strictly inside* `rect` is exactly
    /// `color`.
    ///
    /// Scanned rather than probed at one hard-coded offset: the only
    /// pixels a solid fill leaves un-blended are the ones no glyph's
    /// antialiasing touches, and where those sit inside an item's rect
    /// depends on the host's font metrics and Core Text's rasteriser —
    /// not on anything this crate controls. A single-offset probe
    /// therefore asserts "this exact pixel is glyph-free" (a fact about
    /// Menlo) on top of the fact under test ("the fill happened"), and
    /// fails on the former the moment the painter nudges a glyph by a
    /// fraction of a point. Same lesson as the macOS selection-highlight
    /// probe.
    ///
    /// The rect is inset one pixel on every side so a *neighbouring*
    /// item's fill (segments butt up against each other with no gap)
    /// can never leak in through a boundary pixel.
    fn region_has_color(surface: &BitmapSurface, rect: &QRect, color: Color) -> bool {
        let x0 = rect.x.ceil() as u32 + 1;
        let x1 = ((rect.x + rect.width).floor() as u32)
            .saturating_sub(1)
            .min(W);
        let y0 = rect.y.ceil() as u32 + 1;
        let y1 = ((rect.y + rect.height).floor() as u32)
            .saturating_sub(1)
            .min(H);
        for y in y0..y1 {
            for x in x0..x1 {
                let (r, g, b, _) = surface.pixel(x, y);
                if (r, g, b) == (color.r, color.g, color.b) {
                    return true;
                }
            }
        }
        false
    }

    /// True when `px` carries `ink`'s colour over a `bg` backdrop —
    /// either `ink` outright, or any antialiased blend of the two.
    ///
    /// Each channel must sit between the two endpoints (one unit of
    /// rounding slack either side) and the pixel must differ from `bg`,
    /// so an untouched backdrop pixel never counts as ink. For a thin
    /// fill at a fractional offset that is the strongest claim available
    /// per pixel — see the caller's comment.
    fn carries_ink_of(px: (u8, u8, u8), bg: Color, ink: Color) -> bool {
        let on_blend_line = |v: u8, from: u8, to: u8| {
            let lo = from.min(to).saturating_sub(1);
            let hi = from.max(to).saturating_add(1);
            (lo..=hi).contains(&v)
        };
        px != (bg.r, bg.g, bg.b)
            && on_blend_line(px.0, bg.r, ink.r)
            && on_blend_line(px.1, bg.g, ink.g)
            && on_blend_line(px.2, bg.b, ink.b)
    }

    #[test]
    fn toggle_group_on_item_paints_selected_bg() {
        // The "on" toggle must paint `selected_bg` behind its rect so it is visually
        // distinguishable from the off toggles at a glance. This test stays macOS-only
        // because `region_has_color` scans real `BitmapSurface` pixels for glyph-free
        // ground — which pixels a Core Text-rasterised glyph does or doesn't touch is
        // genuinely host-specific, not arithmetic. The widget-state decision is covered
        // independently: `paint_geometry::selected_item_fill` tests the pure decision,
        // and `native_surface_paint::tests::toggle_group_fills_selected_bg_behind_on_items_only`
        // tests the full `paint()` pipeline via a `RecordingSurface` mock.
        let form = search_flags_form();
        let (surface, layout) = paint_via_backend(&form);
        let theme = Theme::default();
        let vis = &layout.visible_fields[0];
        let rect_for = |name: &str| {
            vis.item_bounds
                .iter()
                .find(|(id, _)| id == &WidgetId::new(name))
                .map(|(_, r)| *r)
                .unwrap_or_else(|| panic!("{name} toggle in layout"))
        };
        assert!(
            region_has_color(&surface, &rect_for("regex"), theme.selected_bg),
            "on-toggle should paint selected_bg behind its rect",
        );
        for off in ["case", "word"] {
            assert!(
                !region_has_color(&surface, &rect_for(off), theme.selected_bg),
                "off-toggle {off:?} must not paint the on-state pill",
            );
        }
    }

    #[test]
    fn toggle_group_click_dispatches_individual_toggle_id() {
        // Round-trip the acceptance criteria: click at a known
        // on-toggle's centre, assert hit_test returns the toggle's
        // own WidgetId (not the parent field's id).
        let form = search_flags_form();
        let (_surface, layout) = paint_via_backend(&form);
        for (id, rect) in &layout.visible_fields[0].item_bounds {
            let cx = rect.x + rect.width * 0.5;
            let cy = rect.y + rect.height * 0.5;
            assert_eq!(
                layout.hit_test(cx, cy),
                FormHit::Field(*id),
                "click on toggle {id:?} should resolve to its own id",
            );
        }
    }

    #[test]
    fn segmented_control_selected_paints_selected_bg() {
        // Stays macOS-only for the same reason as
        // `toggle_group_on_item_paints_selected_bg` above — a real
        // pixel/glyph probe, not compositing arithmetic. See that
        // test's comment and `paint_geometry`'s module doc for the
        // layered, host-independent coverage of the decision itself.
        let form = Form {
            id: WidgetId::new("seg-form"),
            fields: vec![FormField {
                id: WidgetId::new("scope"),
                label: StyledText::plain(""),
                kind: FieldKind::SegmentedControl {
                    options: vec!["File".into(), "Folder".into(), "Project".into()],
                    selected_idx: 1,
                },
                hint: StyledText::default(),
                disabled: false,
                validation: None,
            }],
            focused_field: None,
            scroll_offset: 0,
            has_focus: false,
        };
        let (surface, layout) = paint_via_backend(&form);
        let theme = Theme::default();
        let vis = &layout.visible_fields[0];
        // Synthetic per-segment ids `<field>__seg_<idx>` — assert the SELECTED segment
        // paints selected_bg and its neighbours don't.
        let rect_for = |id: &str| {
            vis.item_bounds
                .iter()
                .find(|(item, _)| item.as_str() == id)
                .map(|(_, r)| *r)
                .unwrap_or_else(|| panic!("{id} in layout"))
        };
        assert!(
            region_has_color(&surface, &rect_for("scope__seg_1"), theme.selected_bg),
            "selected segment should paint selected_bg behind its rect",
        );
        for other in ["scope__seg_0", "scope__seg_2"] {
            assert!(
                !region_has_color(&surface, &rect_for(other), theme.selected_bg),
                "unselected segment {other:?} must not paint the selection pill",
            );
        }
    }

    #[test]
    fn button_row_layout_resolves_per_item_bounds() {
        let form = Form {
            id: WidgetId::new("actions-form"),
            fields: vec![FormField {
                id: WidgetId::new("actions"),
                label: StyledText::plain(""),
                kind: FieldKind::ButtonRow {
                    buttons: vec![
                        ButtonRowItem {
                            id: WidgetId::new("find"),
                            label: "Find".into(),
                            disabled: false,
                            icon: None,
                        },
                        ButtonRowItem {
                            id: WidgetId::new("replace"),
                            label: "Replace".into(),
                            disabled: false,
                            icon: None,
                        },
                    ],
                },
                hint: StyledText::default(),
                disabled: false,
                validation: None,
            }],
            focused_field: None,
            scroll_offset: 0,
            has_focus: false,
        };
        let (_surface, layout) = paint_via_backend(&form);
        let vis = &layout.visible_fields[0];
        assert_eq!(vis.item_bounds.len(), 2);
        // Each item rect has to span the text painted inside it. The
        // bound is measured in the chrome font the backend paints a
        // `Form` with rather than assumed to be a count of monospace
        // cells: a proportional UI font has no single cell width, and
        // "wide enough for its own label" is the invariant either way.
        let label_of = |id: &WidgetId| match id.as_str() {
            "find" => "Find",
            "replace" => "Replace",
            other => panic!("unexpected button id {other:?}"),
        };
        for (id, rect) in &vis.item_bounds {
            let label_w = chrome_text_width(label_of(id)) as f32;
            assert!(
                rect.width >= label_w,
                "button {id:?} rect width {} too narrow for its {label_w}pt label",
                rect.width,
            );
            let hit = layout.hit_test(rect.x + 1.0, rect.y + rect.height * 0.5);
            assert_eq!(
                hit,
                FormHit::Field(*id),
                "click at button {id:?} should hit its own id",
            );
        }
    }

    #[test]
    fn password_input_paints_with_mask_char() {
        // PasswordInput should render `mask_char` repeated `value.chars().count()`
        // times, NOT the plaintext. Verify by computing the expected
        // masked-text width and asserting paint geometry agrees.
        let form = Form {
            id: WidgetId::new("auth-form"),
            fields: vec![FormField {
                id: WidgetId::new("pw"),
                label: StyledText::plain(""),
                kind: FieldKind::PasswordInput {
                    value: "hunter2".into(),
                    placeholder: String::new(),
                    cursor: Some(7),
                    mask_char: '•',
                },
                hint: StyledText::default(),
                disabled: false,
                validation: None,
            }],
            focused_field: Some(WidgetId::new("pw")),
            scroll_offset: 0,
            has_focus: true,
        };
        let (surface, layout) = paint_via_backend(&form);
        // Locate the field bounds.
        let vis = &layout.visible_fields[0];
        // Probe inside the field row at the very centre Y. Pre-fix
        // this pixel would have been background (label-only fallback);
        // post-fix the row contains painted `[`, masked text, `]`.
        // Cheap shape-check: at least ONE pixel inside the row should
        // be foreground (mask glyphs) rather than the focused-row bg.
        let theme = Theme::default();
        let mut saw_glyph = false;
        let y = (vis.bounds.y + vis.bounds.height / 2.0) as u32;
        for x in (vis.bounds.x as u32)..(vis.bounds.x + vis.bounds.width) as u32 {
            let (r, g, b, _) = surface.pixel(x, y);
            // Foreground-ish pixel: differs from both selected_bg (focused row)
            // and pure transparent surface clear.
            let is_bg = (r, g, b)
                == (
                    theme.selected_bg.r,
                    theme.selected_bg.g,
                    theme.selected_bg.b,
                );
            if !is_bg && !(r == 0 && g == 0 && b == 0) {
                saw_glyph = true;
                break;
            }
        }
        assert!(
            saw_glyph,
            "PasswordInput row should paint masked glyphs (none found)",
        );
    }

    /// `TextInput.cursor` is a host-supplied byte offset with no guarantee it lands
    /// on a char boundary. Byte officing must not panic on multibyte characters.
    #[test]
    fn text_input_with_multibyte_cursor_does_not_panic() {
        // "café🎉" — byte 4 sits inside the 2-byte 'é' (starts at byte 3).
        let value = "café🎉";
        assert!(!value.is_char_boundary(4));
        let form = Form {
            id: WidgetId::new("settings"),
            fields: vec![FormField {
                id: WidgetId::new("name"),
                label: StyledText::plain("Name"),
                kind: FieldKind::TextInput {
                    value: value.into(),
                    placeholder: String::new(),
                    cursor: Some(4),
                    selection_anchor: None,
                },
                hint: StyledText::default(),
                disabled: false,
                validation: None,
            }],
            focused_field: Some(WidgetId::new("name")),
            scroll_offset: 0,
            has_focus: true,
        };

        // Must not panic.
        let _ = paint_via_backend(&form);
    }

    /// `PasswordInput` byte-cursor-to-mask-char-position conversion must not panic
    /// on multibyte characters.
    #[test]
    fn password_input_with_multibyte_cursor_does_not_panic() {
        let value = "café🎉";
        assert!(!value.is_char_boundary(4));
        let form = Form {
            id: WidgetId::new("settings"),
            fields: vec![FormField {
                id: WidgetId::new("pw"),
                label: StyledText::plain("Password"),
                kind: FieldKind::PasswordInput {
                    value: value.into(),
                    placeholder: String::new(),
                    cursor: Some(4),
                    mask_char: '*',
                },
                hint: StyledText::default(),
                disabled: false,
                validation: None,
            }],
            focused_field: Some(WidgetId::new("pw")),
            scroll_offset: 0,
            has_focus: true,
        };

        // Must not panic.
        let _ = paint_via_backend(&form);
    }

    // ── Settings chrome ─────────────────────────────────────────────────

    /// Paint the settings chrome through the real
    /// `Backend::draw_settings_chrome` path at an arbitrary origin.
    fn paint_settings_chrome_at(
        origin: QRect,
        header: &str,
        query: &str,
        placeholder: &str,
        active: bool,
    ) -> (BitmapSurface, f64) {
        let surface = BitmapSurface::new(W, H);
        // Known non-theme background so "did the chrome paint here?" is
        // answerable per pixel.
        surface.fill(1.0, 1.0, 1.0, 1.0);
        let mut backend = MacBackend::new();
        backend.set_current_font(font());
        let lh = backend.line_height() as f64;
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.enter_frame_scope(surface.context_ptr(), |b| {
            b.draw_settings_chrome(origin, header, query, placeholder, active);
        });
        backend.end_frame();
        (surface, lh)
    }

    /// Width of `text` in the font `Backend::draw_settings_chrome`
    /// actually paints with.
    ///
    /// The settings header and search row are chrome, so the backend
    /// renders them through [`crate::FontRole::Chrome`] regardless of
    /// which editor font a host last installed as `current_font`.
    /// Measuring with [`Backend::measure_text`] against that role is what
    /// keeps an x-offset expectation here pointing at the glyphs on the
    /// surface; measuring with [`font`] (the editor font
    /// [`paint_settings_chrome_at`] installs, to prove it is *not* what
    /// chrome uses) would offset every probe by the difference between
    /// the two fonts' advances.
    ///
    /// Measures through a fresh `MacBackend::new()` rather than the
    /// backend the caller painted with — safe only because neither
    /// caller in this module ever calls `set_chrome_font`/`set_ui_font`,
    /// so every `MacBackend` in this file resolves the identical
    /// deterministic `chrome_font` [`MacBackend::new`] seeds (a pure
    /// CoreText system-font query, not process state this file mutates).
    /// A test that *does* install a non-default chrome font must measure
    /// through the painting backend itself instead of this helper.
    fn chrome_text_width(text: &str) -> f64 {
        MacBackend::new()
            .measure_text(text, crate::FontRole::Chrome)
            .0 as f64
    }

    #[test]
    fn settings_chrome_paints_header_then_search_row() {
        let (surface, lh) = paint_settings_chrome_at(
            QRect::new(0.0, 0.0, W as f32, H as f32),
            "Settings",
            "",
            "type to filter",
            false,
        );
        let theme = Theme::default();

        // Row 0 = header strip. Probe clear of the "Settings" glyphs.
        let (r, g, b, _) = surface.pixel(W - 4, (lh * 0.5) as u32);
        assert_eq!(
            (r, g, b),
            (theme.header_bg.r, theme.header_bg.g, theme.header_bg.b),
            "row 0 should be the header strip",
        );

        // Row 1 = search input, inactive → `tab_bar_bg`.
        let (r, g, b, _) = surface.pixel(W - 4, (lh * 1.5) as u32);
        assert_eq!(
            (r, g, b),
            (theme.tab_bar_bg.r, theme.tab_bar_bg.g, theme.tab_bar_bg.b),
            "row 1 inactive should be the panel background",
        );

        // Row 2 is the form body's job — chrome must not paint it.
        let (r, g, b, _) = surface.pixel(W - 4, (lh * 2.5) as u32);
        assert_eq!(
            (r, g, b),
            (255, 255, 255),
            "settings chrome paints exactly two rows",
        );
    }

    #[test]
    fn settings_chrome_active_row_uses_selected_bg_and_paints_a_caret() {
        let (surface, lh) = paint_settings_chrome_at(
            QRect::new(0.0, 0.0, W as f32, H as f32),
            "Settings",
            "",
            "type to filter",
            true,
        );
        let theme = Theme::default();

        let (r, g, b, _) = surface.pixel(W - 4, (lh * 1.5) as u32);
        assert_eq!(
            (r, g, b),
            (
                theme.selected_bg.r,
                theme.selected_bg.g,
                theme.selected_bg.b
            ),
            "an active search row uses `selected_bg`",
        );

        // With an empty query the caret sits right after the " /  "
        // prefix (whose two trailing spaces leave the band scanned below
        // free of prefix ink). Scan that band for the accent stroke.
        //
        // Asserting "some pixel is *exactly* `accent_fg`" would be
        // asserting a fact about the caret's sub-pixel position rather
        // than about the caret: Core Graphics antialiases the
        // `SETTINGS_CURSOR_W`-wide fill, and a 1.5pt span starting at a
        // fractional x covers no whole pixel for half of the possible
        // fractions — it lands as two partially-covered columns blended
        // with the row background. So the band only has to carry accent
        // *ink*: a pixel off the row's `selected_bg` and on the
        // `selected_bg`→`accent_fg` blend line. Same lesson as
        // `region_has_color` above.
        let prefix_w = chrome_text_width(SETTINGS_SEARCH_PREFIX);
        let caret_x = (2.0 + prefix_w) as u32;
        let row = (lh * 1.5) as u32;
        let found = (caret_x.saturating_sub(1)..=caret_x + 2).any(|x| {
            let (r, g, b, _) = surface.pixel(x.min(W - 1), row);
            carries_ink_of((r, g, b), theme.selected_bg, theme.accent_fg)
        });
        assert!(
            found,
            "active chrome should paint an accent caret at x≈{caret_x}"
        );
    }

    /// Non-zero-origin regression guard (LESSONS.md:159-181).
    #[test]
    fn settings_chrome_paints_at_a_nonzero_origin_only() {
        let ox = 24.0_f32;
        let oy = 30.0_f32;
        let (surface, lh) = paint_settings_chrome_at(
            QRect::new(ox, oy, W as f32 - ox, H as f32 - oy),
            "Settings",
            "",
            "",
            false,
        );
        let theme = Theme::default();

        let (r, g, b, _) = surface.pixel(W - 4, oy as u32 + (lh * 0.5) as u32);
        assert_eq!(
            (r, g, b),
            (theme.header_bg.r, theme.header_bg.g, theme.header_bg.b),
            "header row should follow the requested origin",
        );
        assert_eq!(
            {
                let (r, g, b, _) = surface.pixel(4, oy as u32 + (lh * 0.5) as u32);
                (r, g, b)
            },
            (255, 255, 255),
            "nothing should paint left of the origin",
        );
        assert_eq!(
            {
                let (r, g, b, _) = surface.pixel(W - 4, oy as u32 - 4);
                (r, g, b)
            },
            (255, 255, 255),
            "nothing should paint above the origin",
        );
    }

    #[test]
    fn settings_chrome_zero_width_is_a_no_op() {
        let (surface, _lh) = paint_settings_chrome_at(
            QRect::new(0.0, 0.0, 0.0, H as f32),
            "Settings",
            "",
            "",
            true,
        );
        assert_eq!(
            {
                let (r, g, b, _) = surface.pixel(1, 1);
                (r, g, b)
            },
            (255, 255, 255),
        );
    }

    /// A `rect.height` of exactly one `line_height` must not paint the search row.
    /// The second row paints only when `height >= line_height * 1.5`, so
    /// a header-only chrome strip does not overpaint content beneath it.
    #[test]
    fn settings_chrome_one_row_height_paints_no_search_row() {
        let one_row_lh = MacBackend::new().line_height() as f64;
        let (surface, lh) = paint_settings_chrome_at(
            QRect::new(0.0, 0.0, W as f32, one_row_lh as f32),
            "HEADER",
            "",
            "placeholder",
            false,
        );
        let theme = Theme::default();

        let (r, g, b, _) = surface.pixel(W - 4, (lh * 0.5) as u32);
        assert_eq!(
            (r, g, b),
            (theme.header_bg.r, theme.header_bg.g, theme.header_bg.b),
            "the header row must still paint even when the search row doesn't",
        );

        let (r, g, b, _) = surface.pixel(W - 4, (lh * 1.5) as u32);
        assert_eq!(
            (r, g, b),
            (255, 255, 255),
            "a 1-row-tall chrome rect must not paint a search row past its own height",
        );
    }
}