BREP_app 0.2.0

The BREP CAD application: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame — native + wasm from one codebase.
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
use super::*;

/// The egui text color for CONSTRAINT annotations (the dimension VALUE labels), read
/// from the engine's single source of truth — the display-settings sketch palette
/// ([`brep_render::style::RenderSettings::sketch_colors`]) — so the label text follows
/// the same (editable) color as the engine-drawn leaders + geometric glyphs.
fn constraint_text_color(settings: &brep_render::style::RenderSettings) -> egui::Color32 {
    let c = settings.sketch_colors().constraint;
    egui::Color32::from_rgb((c >> 16) as u8, (c >> 8) as u8, c as u8)
}

/// The ONE font every model-overlaid label draws and measures with: the base
/// `Monospace` text style, its size multiplied by the user's "Label scale" setting
/// ([`brep_render::style::RenderSettings::label_scale`], clamped engine-side to
/// `[0.25, 3.0]`, 1.0 = unchanged).
///
/// EVERY label site routes through here — the read-only chips AND the inline
/// `TextEdit`s AND the [`text_edit_width`] measurement — which is what keeps the
/// four sizes that must move together in lockstep:
///   1. the GLYPHS (this `FontId`),
///   2. the measured EDIT-BOX WIDTH (`text_edit_width`, fed this same `FontId`),
///   3. the chip's PADDING ([`chip_margin`]),
///   4. the WIDGET METRICS egui would otherwise apply unscaled
///      ([`scale_label_spacing`] + the `TextEdit`'s own `margin`) — WITHOUT which
///      a shrinking label is tiny glyphs floating in a fixed-height box.
/// The chip's FRAME then follows for free: egui sizes a `Frame` to its content, so
/// the background box AND the widget's click/hit rect are the widget rect grown by
/// [`chip_margin`] at every scale — the visible chip and the hit target can never
/// come apart. A read-only chip and its editable counterpart therefore TRACK each
/// other (see `chip_height_follows_the_label_scale`), so a label does not visibly
/// jump when it is clicked to edit. Measuring with an unscaled font while drawing
/// with a scaled one would drift the background box and the click target off the
/// glyphs — never resolve `TextStyle::Monospace` directly at a label site.
fn label_font(ui: &egui::Ui, scale: f32) -> egui::FontId {
    let mut font = egui::TextStyle::Monospace.resolve(ui.style());
    font.size *= scale;
    font
}

/// Scale the `ui.spacing()` metrics that size the WIDGETS INSIDE a label chip, so
/// the chip's HEIGHT follows its glyphs instead of egui's fixed chrome minimums.
/// Call it on the chip `Frame`'s inner `ui` (it mutates only that `Ui`'s cloned
/// style, never the app-wide one), alongside [`label_font`] + [`chip_margin`].
///
/// THE BUG THIS FIXES: `egui::Button` floors its height at
/// `ui.spacing().interact_size.y` (18pt by default — egui's "a button is at least
/// this tall so you can hit it" rule) and pads with `ui.spacing().button_padding`.
/// Neither knows about the label scale, so a 0.5x label drew 6pt glyphs inside a
/// chip that stayed exactly as tall as a 1.0x one — the reported "the label itself
/// stays the same height". Scaling these by the SAME factor as the font keeps the
/// relationship the 1.0 default has (the floor lands at `18 * scale`, a hair above
/// the `~17 * scale` content) at every scale, so the chip is proportional all the
/// way down instead of bottoming out. `item_spacing` is scaled for the same reason
/// — it costs nothing on today's one-widget chips and is the right value the day a
/// chip grows a second widget.
///
/// NOT a `set_height`/`set_min_size`: the chip must stay CONTENT-sized, because
/// its background box and its click/hit rect are both derived from what the widget
/// allocates. Forcing a size would move the box off the glyphs.
///
/// At `scale == 1.0` every one of these is an exact identity (`v * 1.0 == v`), so
/// the default everyone sees is untouched — pinned by
/// `scale_1_0_is_pixel_identical_to_the_unscaled_chip`.
fn scale_label_spacing(ui: &mut egui::Ui, scale: f32) {
    let spacing = ui.spacing_mut();
    spacing.interact_size *= scale;
    spacing.button_padding *= scale;
    spacing.item_spacing *= scale;
}

/// A label chip's `inner_margin`, scaled with the text so a 3x label keeps its
/// padding proportionate instead of hugging the glyphs. `x`/`y` are the base
/// (scale 1.0) paddings in egui points.
///
/// Also used for the sketch-dimension `TextEdit`'s OWN text margin, whose egui
/// default is exactly `Margin::symmetric(4, 2)` — so `chip_margin(4.0, 2.0, 1.0)`
/// reproduces it byte for byte while every other scale finally moves it. (That
/// margin is a `TextEdit` builder field, NOT a `ui.spacing()` one, which is why
/// [`scale_label_spacing`] cannot reach it.)
fn chip_margin(x: f32, y: f32, scale: f32) -> egui::Margin {
    egui::Margin::symmetric((x * scale).round() as i8, (y * scale).round() as i8)
}

/// The width (egui points) to give a dimension value-edit `TextEdit` so its current
/// `text` never wraps: the measured no-wrap width of the string in `font` (same
/// `layout_no_wrap` path the action rail uses), plus a little padding for the caret
/// + inner margin, floored so an emptied box (select-all + delete) stays a usable
/// size. Both the padding and the floor scale with the font, so the box tracks the
/// glyphs at every "Label scale". `font` MUST be the same [`label_font`] the
/// `TextEdit` draws with. Sizing only — value / color / placement are unchanged.
fn text_edit_width(ui: &egui::Ui, text: &str, font: &egui::FontId) -> f32 {
    let measured = ui.ctx().fonts_mut(|f| {
        f.layout_no_wrap(text.to_owned(), font.clone(), egui::Color32::PLACEHOLDER)
            .size()
            .x
    });
    // The base 12pt caret/margin allowance and 24pt floor, scaled by how much this
    // font is bigger than the unscaled base — so an emptied box at 3x is still a
    // usable size for 3x glyphs.
    let base = egui::TextStyle::Monospace.resolve(ui.style()).size;
    let k = if base > 0.0 { font.size / base } else { 1.0 };
    (measured + 12.0 * k).max(24.0 * k)
}

/// The ONE inline value editor a dimension label opens, with every SCALE-dependent
/// input already applied: the box is sized to its text ([`text_edit_width`]) in the
/// [`label_font`], and its own text margin — the `TextEdit` builder field egui
/// defaults to `Margin::symmetric(4, 2)` and which [`scale_label_spacing`] cannot
/// reach — is scaled through [`chip_margin`], so the box's HEIGHT tracks the glyphs
/// instead of adding a fixed 4pt at every scale. Callers add only NON-sizing
/// decoration (`text_color`, `frame`). A caller that passes `Frame::NONE` makes
/// egui ignore the margin entirely, which is equally scale-following.
fn label_text_edit<'t>(
    ui: &egui::Ui,
    buf: &'t mut String,
    font: &egui::FontId,
    scale: f32,
) -> egui::TextEdit<'t> {
    // Size the box to its text so the value never wraps — measured in the SAME
    // scaled font it draws with.
    let width = text_edit_width(ui, buf.as_str(), font);
    egui::TextEdit::singleline(buf)
        .desired_width(width)
        .margin(chip_margin(4.0, 2.0, scale))
        .font(egui::FontSelection::FontId(font.clone()))
}

/// Select the ENTIRE contents of a just-opened inline `TextEdit`. Call on the
/// first frame the editor opens (right after `request_focus`) so a
/// double-click-to-edit starts with everything selected — typing replaces the
/// whole value at once. `char_count` is the field text's char length.
fn select_all_text_edit(ctx: &egui::Context, id: egui::Id, char_count: usize) {
    if let Some(mut state) = egui::TextEdit::load_state(ctx, id) {
        state.cursor.set_char_range(Some(egui::text::CCursorRange::two(
            egui::text::CCursor::new(0),
            egui::text::CCursor::new(char_count),
        )));
        egui::TextEdit::store_state(ctx, id, state);
    }
}

impl Viewport {
    /// Draw the editable dimension labels (S5) over the viewport while in sketch
    /// mode. For each dimensional constraint the engine reports a label anchor in
    /// world space + its display text; we project it to screen and draw a small
    /// clickable value. DOUBLE-clicking opens an inline single-line `TextEdit`
    /// (seeded from the number, or the `valueExpr` when set) with all text
    /// selected; Enter applies via
    /// [`EngineState::sketch_set_dimension_value`], Esc cancels. Dragging a label
    /// repositions it via [`EngineState::sketch_dimension_drag_to`]. The labels ride
    /// in `Order::Middle` areas so they float over the 3D and take pointer priority
    /// over the viewport's own select/place handling.
    pub(super) fn draw_dimension_labels(
        &mut self,
        ctx: &egui::Context,
        rect: egui::Rect,
        state: &mut EngineState,
    ) {
        if !state.sketch_mode() {
            self.editing_dim = None;
            return;
        }

        // The dimension labels (id/text/world/value/valueExpr/mode) from the engine.
        let labels: Vec<serde_json::Value> =
            serde_json::from_str(&state.sketch_dimension_labels_json()).unwrap_or_default();

        // Drop an open editor whose constraint no longer has a label (e.g. deleted).
        if let Some((id, _)) = self.editing_dim.as_ref() {
            let key = id.to_string();
            if !labels.iter().any(|l| l["id"].to_string() == key) {
                self.editing_dim = None;
            }
        }
        if labels.is_empty() {
            return;
        }

        // Project every label anchor world→screen in one shot.
        let worlds: Vec<[f64; 3]> = labels
            .iter()
            .map(|l| {
                let w = &l["world"];
                [
                    w[0].as_f64().unwrap_or(0.0),
                    w[1].as_f64().unwrap_or(0.0),
                    w[2].as_f64().unwrap_or(0.0),
                ]
            })
            .collect();
        let screens: Vec<[f64; 4]> = serde_json::to_string(&worlds)
            .ok()
            .and_then(|s| state.world_to_screen_json(&s).ok())
            .and_then(|s| serde_json::from_str(&s).ok())
            .unwrap_or_default();
        if screens.len() != labels.len() {
            return;
        }

        // Editing state pulled out so the draw closures can mutate the buffer without
        // borrowing `self` twice; written back after the loop.
        let fresh = self.dim_edit_fresh;
        self.dim_edit_fresh = false;
        let mut editing = self.editing_dim.take();
        let editing_key = editing.as_ref().map(|(id, _)| id.to_string());

        // The label text color from the live settings (read BEFORE the closures, which
        // must never touch `state`) — follows the editable sketch constraint color.
        let dim_text_color = constraint_text_color(&state.settings);
        // The user's "Label scale" (read BEFORE the closures, which must never touch
        // `state`) — drives the glyphs, the edit-box measurement and the chip padding
        // through the ONE `label_font` / `chip_margin` pair.
        let label_scale = state.settings.label_scale;

        // Deferred engine mutations (never call `state` inside the area closures).
        let mut start_edit: Option<serde_json::Value> = None;
        let mut apply: bool = false;
        let mut cancel: bool = false;
        let mut drag_to: Option<(serde_json::Value, f64, f64)> = None;
        // A label drag ended this frame → reset the sketch undo's per-drag guard (S6a)
        // so the whole drag was one undo step and the next drag starts a fresh one.
        let mut drag_ended = false;

        for (i, label) in labels.iter().enumerate() {
            let scr = screens[i];
            if scr[3] < 0.5 {
                // The engine's ONE label policy (ViewCamera::label_anchor_visible):
                // hidden only when perspective-behind-the-eye or the 3D anchor
                // projects OUTSIDE the viewport (otherwise the egui Area would
                // clamp the chip to the edge). Ortho depth / near / far NEVER
                // cull — never add such a test here.
                continue;
            }
            let cid = label["id"].clone();
            let cid_key = cid.to_string();
            let pos = egui::pos2(rect.min.x + scr[0] as f32, rect.min.y + scr[1] as f32);
            let is_editing = editing_key.as_deref() == Some(cid_key.as_str());

            let area_id = egui::Id::new(("brep-dim-label", cid_key.clone()));
            egui::Area::new(area_id)
                .order(egui::Order::Middle)
                .fixed_pos(pos)
                .pivot(egui::Align2::CENTER_CENTER)
                .show(ctx, |ui| {
                    let font = label_font(ui, label_scale);
                    egui::Frame::popup(ui.style())
                        .inner_margin(chip_margin(4.0, 2.0, label_scale))
                        .show(ui, |ui| {
                            // The widget metrics egui would otherwise apply
                            // unscaled — without this the chip's HEIGHT is
                            // floored at the 1.0 button height at every scale.
                            scale_label_spacing(ui, label_scale);
                            if is_editing {
                                let buf = &mut editing.as_mut().expect("editing buffer").1;
                                let editor = label_text_edit(ui, buf, &font, label_scale);
                                let resp = ui.add(editor);
                                if fresh {
                                    resp.request_focus();
                                    select_all_text_edit(ui.ctx(), resp.id, buf.chars().count());
                                }
                                let enter =
                                    ui.input(|i| i.key_pressed(egui::Key::Enter));
                                if resp.lost_focus() {
                                    if enter {
                                        apply = true;
                                    } else if !fresh {
                                        cancel = true;
                                    }
                                }
                                if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
                                    cancel = true;
                                }
                            } else {
                                let text = label["text"].as_str().unwrap_or("").to_string();
                                let resp = ui.add(
                                    egui::Button::new(
                                        egui::RichText::new(text)
                                            .font(font.clone())
                                            .color(dim_text_color),
                                    )
                                    // Never wrap/clip the chip — extend to fit its text.
                                    .wrap_mode(egui::TextWrapMode::Extend)
                                    .sense(egui::Sense::click_and_drag()),
                                );
                                if resp.double_clicked() {
                                    start_edit = Some(cid.clone());
                                }
                                if resp.dragged() {
                                    if let Some(p) = resp.interact_pointer_pos() {
                                        drag_to = Some((
                                            cid.clone(),
                                            (p.x - rect.min.x) as f64,
                                            (p.y - rect.min.y) as f64,
                                        ));
                                    }
                                }
                                if resp.drag_stopped() {
                                    drag_ended = true;
                                }
                            }
                        });
                });
        }

        // --- apply deferred actions (state is free to borrow again here) ---------
        if apply {
            if let Some((id, text)) = editing.take() {
                state.sketch_set_dimension_value(&id, &text);
            }
            self.editing_dim = None;
        } else if cancel {
            self.editing_dim = None;
        } else {
            // Keep the (possibly edited) buffer for the next frame.
            self.editing_dim = editing;
        }

        if let Some((id, lx, ly)) = drag_to {
            state.sketch_dimension_drag_to(&id, lx, ly);
        }
        if drag_ended {
            state.sketch_dimension_drag_end();
        }

        if let Some(id) = start_edit {
            // Seed the field from the display value (diameter shows the diameter),
            // preferring the expression when one is set.
            let seed: serde_json::Value =
                serde_json::from_str(&state.sketch_dimension_value_json(&id)).unwrap_or_default();
            let text = seed
                .get("valueExpr")
                .and_then(|v| v.as_str())
                .map(str::to_string)
                .or_else(|| {
                    seed.get("value")
                        .and_then(|v| v.as_f64())
                        .map(|n| format!("{n}"))
                })
                .unwrap_or_default();
            self.editing_dim = Some((id, text));
            self.dim_edit_fresh = true;
        }

        // Keep animating while a field is open (focus / caret).
        if self.editing_dim.is_some() {
            ctx.request_repaint();
        }
    }

    /// Draw the editable FEATURE-dimension labels (FD-1) over the viewport while
    /// the ◎ is in DIMENSION mode. For each linear param dim the engine reports a
    /// leader midpoint (world) + its value; we project it to screen and draw a
    /// small `"{label} {value}"` chip. DOUBLE-clicking opens an inline `TextEdit`
    /// seeded from the value with all text selected; Enter applies via
    /// [`EngineState::feature_dimension_set_value`]
    /// (numeric literal OR live expression), Esc cancels. Dragging the chip drives
    /// [`EngineState::feature_dimension_drag`] (the dim resizes the param live).
    /// The chips ride `Order::Middle`, taking pointer priority over the viewport's
    /// select/orbit — so a drag that starts on a handle never orbits the camera.
    pub(super) fn draw_feature_dimension_labels(
        &mut self,
        ctx: &egui::Context,
        rect: egui::Rect,
        state: &mut EngineState,
    ) {
        if state.gizmo_mode() != "dimension" {
            self.editing_feature_dim = None;
            return;
        }
        let feature = state.dimension_armed_feature();
        if feature.is_empty() {
            self.editing_feature_dim = None;
            return;
        }

        let annotations: Vec<serde_json::Value> =
            serde_json::from_str(&state.feature_dimension_annotations_json(&feature))
                .unwrap_or_default();

        // Drop an open editor whose field no longer has an annotation.
        if let Some((_, field, _)) = self.editing_feature_dim.as_ref() {
            let key = field.clone();
            if !annotations
                .iter()
                .any(|a| a["fieldKey"].as_str() == Some(key.as_str()))
            {
                self.editing_feature_dim = None;
            }
        }
        if annotations.is_empty() {
            return;
        }

        // Project every leader midpoint world→screen in one shot.
        let worlds: Vec<[f64; 3]> = annotations
            .iter()
            .map(|a| {
                let m = &a["mid"];
                [
                    m[0].as_f64().unwrap_or(0.0),
                    m[1].as_f64().unwrap_or(0.0),
                    m[2].as_f64().unwrap_or(0.0),
                ]
            })
            .collect();
        let screens: Vec<[f64; 4]> = serde_json::to_string(&worlds)
            .ok()
            .and_then(|s| state.world_to_screen_json(&s).ok())
            .and_then(|s| serde_json::from_str(&s).ok())
            .unwrap_or_default();
        if screens.len() != annotations.len() {
            return;
        }

        // The user's "Label scale" (read BEFORE the closures, which must never touch
        // `state`).
        let label_scale = state.settings.label_scale;

        let fresh = self.feature_dim_edit_fresh;
        self.feature_dim_edit_fresh = false;
        let mut editing = self.editing_feature_dim.take();
        let editing_key = editing.as_ref().map(|(_, field, _)| field.clone());

        // Deferred engine mutations (never touch `state` inside the area closures).
        let mut start_edit: Option<(String, String)> = None; // (field, seed)
        let mut apply = false;
        let mut cancel = false;
        let mut drag_to: Option<(String, f64, f64)> = None;

        for (i, annotation) in annotations.iter().enumerate() {
            let scr = screens[i];
            if scr[3] < 0.5 {
                // The engine's ONE label policy (ViewCamera::label_anchor_visible):
                // hidden only when perspective-behind-the-eye or the 3D anchor
                // projects OUTSIDE the viewport (otherwise the egui Area would
                // clamp the chip to the edge). Ortho depth / near / far NEVER
                // cull — never add such a test here.
                continue;
            }
            let Some(field) = annotation["fieldKey"].as_str() else {
                continue;
            };
            let field = field.to_string();
            let value = annotation["value"].as_f64().unwrap_or(0.0);
            let prefix = annotation["label"].as_str().unwrap_or("").to_string();
            // An angular dim (torus `arc`, revolve `angle`) shows its value in
            // DEGREES with a trailing `°`; the edit seed stays the bare number.
            let is_angular = annotation["kind"].as_str() == Some("angular");
            let pos = egui::pos2(rect.min.x + scr[0] as f32, rect.min.y + scr[1] as f32);
            let is_editing = editing_key.as_deref() == Some(field.as_str());

            let area_id = egui::Id::new(("brep-feature-dim", feature.clone(), field.clone()));
            egui::Area::new(area_id)
                .order(egui::Order::Middle)
                .fixed_pos(pos)
                .pivot(egui::Align2::CENTER_CENTER)
                .show(ctx, |ui| {
                    // Dark rounded chip with a thin orange border + orange
                    // monospace text (matches the reference dimension image).
                    let orange = egui::Color32::from_rgb(245, 166, 35);
                    let dark = egui::Color32::from_rgb(20, 20, 20);
                    let font = label_font(ui, label_scale);
                    egui::Frame::new()
                        .fill(dark)
                        .stroke(egui::Stroke::new(1.0, orange))
                        .corner_radius(egui::CornerRadius::same(6))
                        .inner_margin(chip_margin(6.0, 3.0, label_scale))
                        .show(ui, |ui| {
                            // The widget metrics egui would otherwise apply
                            // unscaled — without this the chip's HEIGHT is
                            // floored at the 1.0 button height at every scale.
                            // (This editor passes `Frame::NONE`, which makes egui
                            // ignore the `TextEdit`'s own text margin entirely, so
                            // there is nothing to scale there.)
                            scale_label_spacing(ui, label_scale);
                            if is_editing {
                                let buf = &mut editing.as_mut().expect("editing buffer").2;
                                let editor = label_text_edit(ui, buf, &font, label_scale)
                                    .text_color(orange)
                                    .frame(egui::Frame::NONE);
                                let resp = ui.add(editor);
                                if fresh {
                                    resp.request_focus();
                                    select_all_text_edit(ui.ctx(), resp.id, buf.chars().count());
                                }
                                let enter = ui.input(|i| i.key_pressed(egui::Key::Enter));
                                if resp.lost_focus() {
                                    if enter {
                                        apply = true;
                                    } else if !fresh {
                                        cancel = true;
                                    }
                                }
                                if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
                                    cancel = true;
                                }
                            } else {
                                let text = if is_angular {
                                    format!("{prefix} {}\u{00b0}", fmt_dim_value(value))
                                } else {
                                    format!("{prefix} {}", fmt_dim_value(value))
                                };
                                let resp = ui.add(
                                    egui::Button::new(
                                        egui::RichText::new(text)
                                            .font(font.clone())
                                            .color(orange),
                                    )
                                    .frame(false)
                                    // Never wrap/clip the chip — extend to fit its text.
                                    .wrap_mode(egui::TextWrapMode::Extend)
                                    .sense(egui::Sense::click_and_drag()),
                                );
                                if resp.double_clicked() {
                                    start_edit = Some((field.clone(), fmt_dim_value(value)));
                                }
                                if resp.dragged() {
                                    if let Some(p) = resp.interact_pointer_pos() {
                                        drag_to = Some((
                                            field.clone(),
                                            (p.x - rect.min.x) as f64,
                                            (p.y - rect.min.y) as f64,
                                        ));
                                    }
                                }
                            }
                        });
                });
        }

        // --- apply deferred actions (state free to borrow again) -----------------
        if apply {
            if let Some((feat, field, text)) = editing.take() {
                state.feature_dimension_set_value(&feat, &field, &text);
            }
            self.editing_feature_dim = None;
        } else if cancel {
            self.editing_feature_dim = None;
        } else {
            self.editing_feature_dim = editing;
        }

        if let Some((field, lx, ly)) = drag_to {
            state.feature_dimension_drag(&feature, &field, lx, ly);
        }

        if let Some((field, seed)) = start_edit {
            self.editing_feature_dim = Some((feature.clone(), field, seed));
            self.feature_dim_edit_fresh = true;
        }

        if self.editing_feature_dim.is_some() {
            ctx.request_repaint();
        }
    }

    /// Draw the ASSEMBLY-CONSTRAINT labels (build-spec §8.4) over the viewport:
    /// for every cached constraint overlay the engine reports a world label
    /// anchor (leader midpoint / arc mid-sweep) plus its status-colored text —
    /// we project each to screen and draw a small chip. HOVERING a chip
    /// highlights the constraint's referenced geometry (the engine's element
    /// hover — deduped, with the one-frame viewport yield flag); CLICKING it
    /// expands that constraint's row in the Assembly Constraints panel (the
    /// kernel `open` flag via [`EngineState::constraint_label_clicked`]). The
    /// chips are hidden whenever the engine's overlay cache is empty (Show
    /// Constraint Graphics off, sketch mode, no assembly). During a handle drag
    /// the chip text tracks the live preview value (the cache carries it).
    pub(super) fn draw_constraint_labels(
        &mut self,
        ctx: &egui::Context,
        rect: egui::Rect,
        state: &mut EngineState,
    ) {
        let labels: Vec<serde_json::Value> =
            serde_json::from_str(&state.constraint_labels_json()).unwrap_or_default();
        if labels.is_empty() {
            if self.constraint_label_hovered.take().is_some() {
                state.constraint_hover_end();
            }
            return;
        }

        // Project every label anchor world→screen in one shot.
        let worlds: Vec<[f64; 3]> = labels
            .iter()
            .map(|l| {
                let w = &l["world"];
                [
                    w[0].as_f64().unwrap_or(0.0),
                    w[1].as_f64().unwrap_or(0.0),
                    w[2].as_f64().unwrap_or(0.0),
                ]
            })
            .collect();
        let screens: Vec<[f64; 4]> = serde_json::to_string(&worlds)
            .ok()
            .and_then(|s| state.world_to_screen_json(&s).ok())
            .and_then(|s| serde_json::from_str(&s).ok())
            .unwrap_or_default();
        if screens.len() != labels.len() {
            return;
        }

        // The user's "Label scale" (read BEFORE the closures, which must never touch
        // `state`).
        let label_scale = state.settings.label_scale;

        // Deferred engine mutations (never touch `state` inside the area closures).
        let mut hovered: Option<String> = None;
        let mut clicked: Option<String> = None;

        for (i, label) in labels.iter().enumerate() {
            let scr = screens[i];
            if scr[3] < 0.5 {
                // The engine's ONE label policy (ViewCamera::label_anchor_visible):
                // hidden only when perspective-behind-the-eye or the 3D anchor
                // projects OUTSIDE the viewport (otherwise the egui Area would
                // clamp the chip to the edge). Ortho depth / near / far NEVER
                // cull — never add such a test here.
                continue;
            }
            let Some(id) = label["id"].as_str() else {
                continue;
            };
            let text = label["text"].as_str().unwrap_or(id).to_string();
            let message = label["message"].as_str().unwrap_or("").to_string();
            let status = label["status"].as_str().unwrap_or("").to_string();
            // The status → color vocabulary comes from the engine (ONE map).
            let rgb = &label["color"];
            let color = egui::Color32::from_rgb(
                (rgb[0].as_f64().unwrap_or(1.0) * 255.0).round() as u8,
                (rgb[1].as_f64().unwrap_or(1.0) * 255.0).round() as u8,
                (rgb[2].as_f64().unwrap_or(1.0) * 255.0).round() as u8,
            );
            let pos = egui::pos2(rect.min.x + scr[0] as f32, rect.min.y + scr[1] as f32);
            let area_id = egui::Id::new(("brep-constraint-label", id));
            egui::Area::new(area_id)
                .order(egui::Order::Middle)
                .fixed_pos(pos)
                .pivot(egui::Align2::CENTER_CENTER)
                .show(ctx, |ui| {
                    // Dark rounded chip with a thin status-colored border +
                    // status-colored monospace text (the feature-dim chip look,
                    // colored by the requirements-§5 status vocabulary). The
                    // label-click-SELECTED constraint gets a thicker border.
                    let selected = label["selected"].as_bool().unwrap_or(false);
                    let dark = egui::Color32::from_rgb(20, 20, 20);
                    let font = label_font(ui, label_scale);
                    egui::Frame::new()
                        .fill(dark)
                        .stroke(egui::Stroke::new(if selected { 2.5 } else { 1.0 }, color))
                        .corner_radius(egui::CornerRadius::same(6))
                        .inner_margin(chip_margin(6.0, 3.0, label_scale))
                        .show(ui, |ui| {
                            // The widget metrics egui would otherwise apply
                            // unscaled — without this the chip's HEIGHT is
                            // floored at the 1.0 button height at every scale.
                            scale_label_spacing(ui, label_scale);
                            let resp = ui.add(
                                egui::Button::new(
                                    egui::RichText::new(text).font(font.clone()).color(color),
                                )
                                .frame(false)
                                // Never wrap/clip the chip — extend to fit its text.
                                .wrap_mode(egui::TextWrapMode::Extend)
                                .sense(egui::Sense::click()),
                            );
                            let resp = if message.is_empty() {
                                resp.on_hover_text(status.clone())
                            } else {
                                resp.on_hover_text(format!("{status}: {message}"))
                            };
                            if resp.hovered() {
                                hovered = Some(id.to_string());
                            }
                            if resp.clicked() {
                                clicked = Some(id.to_string());
                            }
                        });
                });
        }

        // --- apply deferred actions (state free to borrow again) -----------------
        match hovered {
            Some(id) => {
                // Highlight the referenced geometry; deduped engine-side, and the
                // one-frame yield flag keeps next frame's scene hover off it.
                state.constraint_hover(&id);
                self.constraint_label_hovered = Some(id);
            }
            None => {
                if self.constraint_label_hovered.take().is_some() {
                    state.constraint_hover_end();
                }
            }
        }
        if let Some(id) = clicked {
            state.constraint_label_clicked(&id);
        }
    }

    /// Draw the transform gizmo's axis-end labels (`XC` red, `YC` green, `ZC`
    /// blue) at each cone tip while the ◎ is in TRANSFORM mode. These are pure
    /// display text (non-interactable, so they never intercept a gizmo drag).
    pub(super) fn draw_transform_axis_labels(
        &mut self,
        ctx: &egui::Context,
        rect: egui::Rect,
        state: &mut EngineState,
    ) {
        if state.gizmo_mode() != "transform" {
            return;
        }
        let labels: Vec<serde_json::Value> =
            serde_json::from_str(&state.transform_axis_labels_json()).unwrap_or_default();
        if labels.is_empty() {
            return;
        }
        // Project every label anchor world→screen in one shot.
        let worlds: Vec<[f64; 3]> = labels
            .iter()
            .map(|l| {
                let w = &l["world"];
                [
                    w[0].as_f64().unwrap_or(0.0),
                    w[1].as_f64().unwrap_or(0.0),
                    w[2].as_f64().unwrap_or(0.0),
                ]
            })
            .collect();
        let screens: Vec<[f64; 4]> = serde_json::to_string(&worlds)
            .ok()
            .and_then(|s| state.world_to_screen_json(&s).ok())
            .and_then(|s| serde_json::from_str(&s).ok())
            .unwrap_or_default();
        if screens.len() != labels.len() {
            return;
        }
        // The user's "Label scale" (read BEFORE the closures, which must never touch
        // `state`).
        let label_scale = state.settings.label_scale;
        for (i, label) in labels.iter().enumerate() {
            let scr = screens[i];
            if scr[3] < 0.5 {
                // The engine's ONE label policy (ViewCamera::label_anchor_visible):
                // hidden only when perspective-behind-the-eye or the 3D anchor
                // projects OUTSIDE the viewport (otherwise the egui Area would
                // clamp the chip to the edge). Ortho depth / near / far NEVER
                // cull — never add such a test here.
                continue;
            }
            let text = label["text"].as_str().unwrap_or("").to_string();
            let rgb = &label["rgb"];
            let color = egui::Color32::from_rgb(
                (rgb[0].as_f64().unwrap_or(1.0) * 255.0).round() as u8,
                (rgb[1].as_f64().unwrap_or(1.0) * 255.0).round() as u8,
                (rgb[2].as_f64().unwrap_or(1.0) * 255.0).round() as u8,
            );
            let pos = egui::pos2(rect.min.x + scr[0] as f32, rect.min.y + scr[1] as f32);
            let area_id = egui::Id::new(("brep-transform-axis", i));
            egui::Area::new(area_id)
                .order(egui::Order::Middle)
                .interactable(false)
                .fixed_pos(pos)
                .pivot(egui::Align2::CENTER_CENTER)
                .show(ctx, |ui| {
                    let font = label_font(ui, label_scale);
                    ui.label(egui::RichText::new(text).font(font).strong().color(color));
                });
        }
    }

    /// DEBUG overlay: draw a 1px RED outline of the EXACT click/hit region of
    /// EVERY currently-shown gizmo handle — arrows AND balls, for EVERY gizmo:
    /// the feature transform widget, the dimension arrows, AND the assembly
    /// component Move gizmo (which feeds the same widget with ◎ mode "none").
    /// The engine exposers ([`EngineState::transform_hit_areas_json`] /
    /// [`EngineState::dimension_hit_areas_json`]) hand back the SAME screen-space
    /// (viewport-local px) regions the hit test 2D-tests the cursor against — each
    /// a `{kind:"capsule", a, b, r}` (axis arrows, dimension leaders) or a
    /// `{kind:"circle", c, r}` (center / origin / grab / arc-handle spheres). The
    /// projection + the perspective front-clip ALREADY happened in the region
    /// builder, so here we only offset by `rect.min` and stroke — there is nothing
    /// to project or clip, and the outline is byte-identical to the pickable region.
    pub(super) fn draw_gizmo_hit_areas(
        &self,
        ctx: &egui::Context,
        rect: egui::Rect,
        state: &EngineState,
    ) {
        // Debug-only overlay: off unless the "Debug grab handles" setting is on.
        if !state.settings.debug_grab_handles {
            return;
        }
        let json = match state.gizmo_mode() {
            "dimension" => state.dimension_hit_areas_json(),
            // The widget transform gizmo serves BOTH the feature transform mode
            // AND the component Move gizmo (whose ◎ mode is "none"), so anything
            // else asks the widget exposer — it returns `[]` exactly when the
            // widget is hidden, i.e. when nothing is grabbable.
            _ => state.transform_hit_areas_json(),
        };
        let areas: Vec<serde_json::Value> = serde_json::from_str(&json).unwrap_or_default();
        if areas.is_empty() {
            return;
        }
        let stroke = egui::Stroke::new(1.0, egui::Color32::RED);
        let mut painter = ctx.layer_painter(egui::LayerId::new(
            egui::Order::Foreground,
            egui::Id::new("brep-gizmo-hit-areas"),
        ));
        painter.set_clip_rect(rect);
        let at = |v: &serde_json::Value| {
            egui::pos2(
                rect.min.x + v[0].as_f64().unwrap_or(0.0) as f32,
                rect.min.y + v[1].as_f64().unwrap_or(0.0) as f32,
            )
        };
        for area in &areas {
            let r = area["r"].as_f64().unwrap_or(0.0) as f32;
            match area["kind"].as_str() {
                Some("capsule") => {
                    draw_capsule_outline(&painter, at(&area["a"]), at(&area["b"]), r, stroke);
                }
                Some("circle") => {
                    painter.circle_stroke(at(&area["c"]), r, stroke);
                }
                _ => {}
            }
        }
    }
}

/// Stroke the 1px outline of a screen-space capsule (stadium): the pickable region
/// of a transform axis arrow — the segment `a→b` expanded by radius `px`. Two long
/// parallel edges + a semicircular cap at each end (each cap bulging AWAY from the
/// other end), assembled as ONE closed polyline. A projected segment that collapses
/// to ~a point (axis pointing at / away from the camera) degenerates to a disc of
/// radius `px` — the true region there — so a circle is stroked instead.
fn draw_capsule_outline(
    painter: &egui::Painter,
    a: egui::Pos2,
    b: egui::Pos2,
    px: f32,
    stroke: egui::Stroke,
) {
    let seg = b - a;
    let len = seg.length();
    if len < 1.0 {
        painter.circle_stroke(a, px, stroke);
        return;
    }
    let dir = seg / len;
    let perp = egui::vec2(-dir.y, dir.x) * px; // +perp offset (angle `ang0`)
    let ang0 = perp.y.atan2(perp.x);
    const CAP_SEGS: usize = 8;
    let pi = std::f32::consts::PI;
    let mut pts: Vec<egui::Pos2> = Vec::with_capacity(4 + 2 * CAP_SEGS);
    // +perp long edge: a+perp → b+perp.
    pts.push(a + perp);
    pts.push(b + perp);
    // Cap at b, bulging toward +dir: sweep +perp → -perp (angle ang0 → ang0-π).
    for k in 1..CAP_SEGS {
        let t = ang0 - pi * (k as f32) / (CAP_SEGS as f32);
        pts.push(b + egui::vec2(t.cos(), t.sin()) * px);
    }
    pts.push(b - perp);
    // -perp long edge: b-perp → a-perp.
    pts.push(a - perp);
    // Cap at a, bulging toward -dir: sweep -perp → +perp (angle ang0+π → ang0).
    for k in 1..CAP_SEGS {
        let t = (ang0 + pi) - pi * (k as f32) / (CAP_SEGS as f32);
        pts.push(a + egui::vec2(t.cos(), t.sin()) * px);
    }
    painter.add(egui::Shape::closed_line(pts, stroke));
}

/// A compact display string for a dimension value: up to 4 decimals, trailing
/// zeros (and a bare trailing dot) trimmed — so `10.0` shows as `10`, `12.5` as
/// `12.5`, `14.0000` as `14`.
fn fmt_dim_value(value: f64) -> String {
    let s = format!("{value:.4}");
    let trimmed = s.trim_end_matches('0').trim_end_matches('.');
    if trimmed.is_empty() || trimmed == "-" {
        "0".to_string()
    } else {
        trimmed.to_string()
    }
}

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

    /// Build the sketch-dimension label chip HEADLESS exactly as
    /// [`Viewport::draw_dimension_labels`] builds it — an `egui::Frame::popup` with
    /// `chip_margin(4, 2, scale)` wrapped around either the read-only `Button` or
    /// the inline [`label_text_edit`] — and hand back `(frame_rect, widget_rect,
    /// frame_total_margin_y)`. Font layout is CPU-only, so this measures the REAL
    /// geometry (the same `run_ui` harness the width tests use); a wgpu canvas is
    /// never involved.
    ///
    /// `legacy = true` reproduces the code BEFORE the height fix — no
    /// [`scale_label_spacing`], and a bare `TextEdit` carrying egui's fixed
    /// `Margin::symmetric(4, 2)` — so a test can diff the two paths directly.
    fn measure_chip(scale: f32, editing: bool, legacy: bool) -> (egui::Rect, egui::Rect, f32) {
        let ctx = egui::Context::default();
        let (mut frame_rect, mut widget_rect, mut pad) =
            (egui::Rect::ZERO, egui::Rect::ZERO, 0.0f32);
        let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
            let font = label_font(ui, scale);
            let frame = egui::Frame::popup(ui.style()).inner_margin(chip_margin(4.0, 2.0, scale));
            // inner_margin + stroke width + outer_margin: EXACTLY what egui adds
            // around the content to get the visible chip (`Frame::total_margin`).
            pad = frame.total_margin().sum().y;
            let shown = frame.show(ui, |ui| {
                if !legacy {
                    scale_label_spacing(ui, scale);
                }
                let mut buf = "12.5".to_string();
                if editing {
                    if legacy {
                        let width = text_edit_width(ui, buf.as_str(), &font);
                        ui.add(
                            egui::TextEdit::singleline(&mut buf)
                                .desired_width(width)
                                .font(egui::FontSelection::FontId(font.clone())),
                        )
                    } else {
                        let editor = label_text_edit(ui, &mut buf, &font, scale);
                        ui.add(editor)
                    }
                } else {
                    ui.add(
                        egui::Button::new(egui::RichText::new(buf).font(font.clone()))
                            .wrap_mode(egui::TextWrapMode::Extend)
                            .sense(egui::Sense::click_and_drag()),
                    )
                }
            });
            widget_rect = shown.inner.rect;
            frame_rect = shown.response.rect;
        });
        (frame_rect, widget_rect, pad)
    }

    /// The dimension value-edit box is sized to its text: a longer value string yields
    /// a wider box (so the text never wraps), and an emptied box stays a usable floor.
    /// Exercised through a headless egui frame (font layout is CPU-only) — the same
    /// `run_ui` harness the toolbar test uses.
    #[test]
    fn text_edit_width_grows_with_text_and_floors_when_empty() {
        let ctx = egui::Context::default();
        let (mut empty_w, mut short_w, mut long_w) = (0.0f32, 0.0f32, 0.0f32);
        let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
            let font = label_font(ui, 1.0);
            empty_w = text_edit_width(ui, "", &font);
            short_w = text_edit_width(ui, "20", &font);
            long_w = text_edit_width(ui, "1234.5678", &font);
        });
        // A longer value needs a wider box so it never wraps.
        assert!(long_w > short_w, "long {long_w} must exceed short {short_w}");
        assert!(short_w >= empty_w, "text is at least as wide as the empty box");
        // An emptied box (select-all + delete) keeps the ~24px usable floor.
        assert!(empty_w >= 24.0, "empty box floored, got {empty_w}");
    }

    /// The "Label scale" setting scales the label FONT: 1.0 leaves the base
    /// monospace size untouched (so nothing changes until the user edits it), and a
    /// multiplier scales it proportionally.
    #[test]
    fn label_font_scales_the_base_monospace_size() {
        let ctx = egui::Context::default();
        let (mut raw, mut base, mut half, mut triple) = (0.0f32, 0.0f32, 0.0f32, 0.0f32);
        let mut quarter = 0.0f32;
        let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
            // The style's own Monospace size, resolved WITHOUT going through the
            // helper — the thing scale 1.0 must reproduce exactly.
            raw = egui::TextStyle::Monospace.resolve(ui.style()).size;
            base = label_font(ui, 1.0).size;
            // 0.25 is the CLAMP FLOOR (`RenderSettings::label_scale`), 0.5 the old one.
            quarter = label_font(ui, 0.25).size;
            half = label_font(ui, 0.5).size;
            triple = label_font(ui, 3.0).size;
        });
        let unscaled = raw;
        assert!(unscaled > 0.0, "the base monospace size must be positive");
        // 1.0 is the identity — the default leaves every label exactly as it was.
        assert_eq!(
            base, unscaled,
            "scale 1.0 must be the base Monospace size (no change by default)"
        );
        // The clamp endpoints scale the glyphs proportionally.
        assert!(
            (quarter - unscaled * 0.25).abs() < 1e-4,
            "0.25x (the clamp FLOOR) must quarter the size: {quarter} vs {unscaled}"
        );
        assert!(
            (half - unscaled * 0.5).abs() < 1e-4,
            "0.5x must halve the size: {half} vs {unscaled}"
        );
        assert!(
            (triple - unscaled * 3.0).abs() < 1e-4,
            "3.0x must triple the size: {triple} vs {unscaled}"
        );
    }

    /// THE COUPLING THAT MATTERS: the edit box is MEASURED in the same scaled font
    /// it is DRAWN in, so the box (and therefore the chip background and the click
    /// target egui sizes to it) tracks the glyphs at every "Label scale". Measuring
    /// with the unscaled font while drawing scaled — the subtle way to get this
    /// wrong — would leave these widths flat and fail here.
    #[test]
    fn text_edit_width_follows_the_label_scale() {
        let ctx = egui::Context::default();
        let (mut w1, mut w2, mut w3) = (0.0f32, 0.0f32, 0.0f32);
        let (mut empty1, mut empty3) = (0.0f32, 0.0f32);
        let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
            let text = "1234.5678";
            w1 = text_edit_width(ui, text, &label_font(ui, 1.0));
            w2 = text_edit_width(ui, text, &label_font(ui, 2.0));
            w3 = text_edit_width(ui, text, &label_font(ui, 3.0));
            empty1 = text_edit_width(ui, "", &label_font(ui, 1.0));
            empty3 = text_edit_width(ui, "", &label_font(ui, 3.0));
        });
        // The SAME text needs a strictly wider box as the scale grows.
        assert!(w2 > w1, "2x must widen the box: {w2} vs {w1}");
        assert!(w3 > w2, "3x must widen it further: {w3} vs {w2}");
        // ...and roughly proportionally: both the measured glyphs and the caret
        // allowance scale, so 2x lands near double (generous band — the monospace
        // metrics need not be exactly linear).
        let ratio = w2 / w1;
        assert!(
            (1.7..=2.3).contains(&ratio),
            "2x must roughly double the measured box width, got {ratio}x ({w1} -> {w2})"
        );
        // The empty-box floor scales too, so an emptied 3x field stays usable for
        // 3x glyphs instead of collapsing to a 1x-sized stub.
        assert!(
            empty3 > empty1 * 2.0,
            "the empty-box floor must scale with the font: {empty3} vs {empty1}"
        );
    }

    /// THE HEIGHT ANALOGUE of `text_edit_width_follows_the_label_scale`, and the
    /// regression test for the reported bug: "if the text gets smaller the label
    /// itself stays the same height". The chip's HEIGHT must track the glyphs at
    /// every "Label scale" — a 0.25x chip is a quarter as tall, not a 1.0x-tall box
    /// with tiny text floating in it.
    ///
    /// What used to floor it: `egui::Button` clamps its height to
    /// `ui.spacing().interact_size.y` (18pt) and pads with
    /// `ui.spacing().button_padding`, and a framed `egui::TextEdit` adds its own
    /// fixed `Margin::symmetric(4, 2)`. None of the three knew about the label
    /// scale, so the read-only chip measured 18.0pt tall at 0.25x, 0.5x AND 1.0x
    /// alike. [`scale_label_spacing`] + [`label_text_edit`] scale all three.
    #[test]
    fn chip_height_follows_the_label_scale() {
        let h = |scale: f32, editing: bool| measure_chip(scale, editing, false).1.height();
        let (ro_q, ro_1, ro_3) = (h(0.25, false), h(1.0, false), h(3.0, false));
        let (ed_q, ed_1, ed_3) = (h(0.25, true), h(1.0, true), h(3.0, true));

        // 1. STRICTLY monotone in the scale — the bug made the read-only row flat.
        assert!(
            ro_q < ro_1 && ro_1 < ro_3,
            "the read-only chip height must grow with the scale: {ro_q} / {ro_1} / {ro_3}"
        );
        assert!(
            ed_q < ed_1 && ed_1 < ed_3,
            "the edit chip height must grow with the scale: {ed_q} / {ed_1} / {ed_3}"
        );

        // 2. ...and PROPORTIONALLY: `h(s) ~= s * h(1.0)`. Tolerance = 10% (the font
        //    row height is not perfectly linear in the point size) + 1.0pt (both
        //    margins are `i8` egui points, so each of the two sides can quantise by
        //    half a point). Proportional is the right target rather than "never
        //    floored": egui's floor is still there, it now sits at `18 * scale`,
        //    exactly the relationship the untouched 1.0 default has.
        for (label, scale, got, at_one) in [
            ("read-only 0.25x", 0.25, ro_q, ro_1),
            ("read-only 3x", 3.0, ro_3, ro_1),
            ("edit 0.25x", 0.25, ed_q, ed_1),
            ("edit 3x", 3.0, ed_3, ed_1),
        ] {
            let want = scale * at_one;
            let tol = 0.1 * want + 1.0;
            assert!(
                (got - want).abs() <= tol,
                "{label}: height must be ~{want} (= {scale} x {at_one}), got {got} (tol {tol})"
            );
        }

        // 2b. The WIDTH stays proportional too. [`scale_label_spacing`] scales the
        //     WHOLE `interact_size` vector, so this is the guard that its `x` half
        //     never starts flooring a short chip ("20") into a 40pt-wide box —
        //     today neither `Button` nor `TextEdit` reads it, and this fails the
        //     day one does.
        for (label, scale) in [("0.25x", 0.25f32), ("3x", 3.0)] {
            let at_one = measure_chip(1.0, false, false).1.width();
            let got = measure_chip(scale, false, false).1.width();
            let want = scale * at_one;
            assert!(
                (got - want).abs() <= 0.1 * want + 1.0,
                "{label}: the chip WIDTH must be ~{want}, got {got}"
            );
        }

        // 3. NO JUMP ON EDIT: the read-only `Button` and the inline `TextEdit` are
        //    the two halves of ONE chip, so clicking a label to edit it must not
        //    resize the box. They are not pixel-identical — egui pads a button with
        //    `button_padding` (4,1) and a framed text edit with its own (4,2)
        //    margin, a ~1.1pt difference baked into the 1.0 default we must not
        //    disturb — so the assertion is that the gap TRACKS the scale instead of
        //    exploding. Before the fix the 0.25x pair was 18.0 vs 8.0 (a 2.25x jump
        //    on click); this catches that.
        let gap_at_one = (ro_1 - ed_1).abs();
        for (label, scale, ro, ed) in [
            ("0.25x", 0.25, ro_q, ed_q),
            ("1x", 1.0, ro_1, ed_1),
            ("3x", 3.0, ro_3, ed_3),
        ] {
            let tol = gap_at_one * scale + 1.5;
            assert!(
                (ro - ed).abs() <= tol,
                "{label}: the chip must not jump when clicked to edit — \
                 read-only {ro} vs edit {ed} (gap tol {tol})"
            );
        }

        // 4. THE HIT TARGET IS THE VISIBLE CHIP at every scale. egui sizes a `Frame`
        //    to its content, so the painted box is the widget's own click/hit rect
        //    grown by exactly `Frame::total_margin()` — it can never drift off the
        //    glyphs, and it shrinks with them.
        for scale in [0.25f32, 1.0, 3.0] {
            for editing in [false, true] {
                let (frame_rect, widget_rect, pad) = measure_chip(scale, editing, false);
                assert!(
                    frame_rect.contains_rect(widget_rect),
                    "scale {scale} editing {editing}: the click rect {widget_rect:?} must sit \
                     inside the painted chip {frame_rect:?}"
                );
                assert!(
                    (frame_rect.height() - widget_rect.height() - pad).abs() < 1e-3,
                    "scale {scale} editing {editing}: the chip must be the hit rect plus \
                     exactly its frame margin ({pad}), got {} vs {}",
                    frame_rect.height(),
                    widget_rect.height()
                );
            }
        }
    }

    /// NON-NEGOTIABLE: the 1.0 default — what every user sees until they touch the
    /// slider — is untouched by the height fix, to the pixel. Proven by rendering
    /// the chip twice in the same harness: once through the PRE-FIX code path
    /// (`legacy = true`: no [`scale_label_spacing`], egui's fixed `TextEdit`
    /// margin) and once through the new one, and demanding identical geometry. Both
    /// halves of the chip, both the painted box and the click rect.
    #[test]
    fn scale_1_0_is_pixel_identical_to_the_unscaled_chip() {
        for editing in [false, true] {
            let (frame_new, widget_new, _) = measure_chip(1.0, editing, false);
            let (frame_old, widget_old, _) = measure_chip(1.0, editing, true);
            assert_eq!(
                widget_new.size(),
                widget_old.size(),
                "editing {editing}: the click rect drifted at scale 1.0"
            );
            assert_eq!(
                frame_new.size(),
                frame_old.size(),
                "editing {editing}: the painted chip drifted at scale 1.0"
            );
        }

        // ...and the reason it cannot drift: every scaling helper is an exact
        // identity at 1.0, so scale 1.0 is literally the untouched egui style.
        let ctx = egui::Context::default();
        let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
            let before = ui.spacing().clone();
            scale_label_spacing(ui, 1.0);
            let after = ui.spacing().clone();
            assert_eq!(before.interact_size, after.interact_size);
            assert_eq!(before.button_padding, after.button_padding);
            assert_eq!(before.item_spacing, after.item_spacing);
            // The `TextEdit`'s own text margin at 1.0 is egui's default (4, 2).
            let m = chip_margin(4.0, 2.0, 1.0);
            assert_eq!(
                (m.left, m.right, m.top, m.bottom),
                (4, 4, 2, 2),
                "the scaled TextEdit margin at 1.0 must be egui's own default"
            );
        });
    }

    /// The chip padding scales with the text, so a large label keeps its background
    /// proportionate instead of hugging the glyphs — and a small one never inverts
    /// to a negative margin.
    #[test]
    fn chip_margin_scales_and_stays_non_negative() {
        let base = chip_margin(6.0, 3.0, 1.0);
        assert_eq!((base.left, base.top), (6, 3), "1.0 is the base padding");
        let big = chip_margin(6.0, 3.0, 3.0);
        assert_eq!((big.left, big.top), (18, 9), "3x triples the padding");
        let small = chip_margin(6.0, 3.0, 0.5);
        assert!(
            small.left >= 0 && small.top >= 0 && small.left < base.left,
            "0.5x shrinks the padding without going negative, got {small:?}"
        );
        // The 0.25 clamp FLOOR: the i8 margin can only quantise to whole points, so
        // the padding bottoms out at a visible 1-2pt rather than vanishing (or, far
        // worse, inverting negative and clipping the glyphs).
        let floor6 = chip_margin(6.0, 3.0, 0.25);
        assert_eq!((floor6.left, floor6.top), (2, 1), "0.25x of (6,3)");
        let floor4 = chip_margin(4.0, 2.0, 0.25);
        assert_eq!((floor4.left, floor4.top), (1, 1), "0.25x of (4,2)");
    }
}