BREP_app 0.35.0

The next.BREP.io CAD application on the Rust B-rep kernel: 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
//! The developer gallery: every component in every state, in both themes and
//! both densities, with the four open decisions (spec section 9) as dropdowns
//! so the owner can try each option, and a switch that previews the theme on
//! the whole app.
//!
//! Reached from MCP (`ui.gallery`), from `BREP_UI_GALLERY=1` on the desktop and
//! from `?uiGallery` in the browser. It is not in any menu: nothing in the
//! app's chrome changes until the owner has signed off on the look.
use super::preview::{theme_for, Choices, FontChoice, LightScope, Preview, PreviewFonts, View};
use super::surface::{self, Kind, TreeRow};
use super::{chips, dropdown, icon_button, input, paint, tabs, toggle, Button, Chip, DocumentTab, IconButton, Show, Size, Variant};
use crate::automation::hit_keys::HitKeyDoc;
use crate::theme::{self, contrast, over, space, Density, Mode, Text, Theme, ACCENTS};
use eframe::egui::{self, Color32, Rect, Vec2};
use std::collections::HashMap;
use std::sync::Arc;

pub static HIT_KEYS: &[HitKeyDoc] = &[
    HitKeyDoc { panel: "uigallery", prefix: "choice:", meaning: "one of the four open decisions as a dropdown (choice:font, choice:accent, choice:density, choice:light); while it is open its rows are choice:<name>:<index>", command: Some("gallery") },
    HitKeyDoc { panel: "uigallery", prefix: "view:", meaning: "how the gallery is shown: view:theme (dropdown; rows view:theme:<index>), view:preview (switch: the theme on the whole app), view:reduceMotion (switch), view:close", command: Some("gallery") },
    HitKeyDoc { panel: "uigallery", prefix: "section:", meaning: "a gallery section's card (section:decisions, section:colours, section:buttons, ...): a region to capture", command: None },
    HitKeyDoc { panel: "uigallery", prefix: "demo:", meaning: "a live sample control (demo:primary, demo:tab:<index>, demo:switch, demo:checkbox, demo:dropdown and its rows demo:dropdown:<index>, demo:long and demo:long:<index>, demo:search, demo:number)", command: None },
];

/// The values the gallery's live samples hold.
struct Demo {
    clicks: u32,
    tab: usize,
    wide_tab: usize,
    document: usize,
    documents: Vec<(String, bool)>,
    name: String,
    search: String,
    depth: f64,
    width_in: f64,
    angle: f64,
    operation: usize,
    material: usize,
    checked: bool,
    switch_on: bool,
    slider: f32,
    picks: Vec<String>,
    picking: bool,
    panel_collapsed: bool,
    tree_selected: usize,
    tool: usize,
}

impl Default for Demo {
    fn default() -> Self {
        Demo {
            clicks: 0,
            tab: 0,
            wide_tab: 1,
            document: 0,
            documents: vec![("bracket.nbrep".into(), true), ("gearbox.nbrep".into(), false), ("board.nbrep".into(), false)],
            name: "Bracket".into(),
            search: String::new(),
            depth: 12.5,
            width_in: 2.0,
            angle: 45.0,
            operation: 0,
            material: 3,
            checked: true,
            switch_on: true,
            slider: 0.4,
            picks: (1..=3).map(|i| format!("Face {i}")).collect(),
            picking: false,
            panel_collapsed: false,
            tree_selected: 2,
            tool: 1,
        }
    }
}

const OPERATIONS: &[&str] = &["New body", "Join", "Cut", "Intersect"];
const OPERATION_GROUPS: &[(usize, &str)] = &[(0, "Create"), (1, "Combine with the target")];
const MATERIALS: &[&str] = &[
    "ABS", "Acetal", "Aluminium 6061", "Aluminium 7075", "Brass", "Bronze", "Carbon steel", "Cast iron", "Copper", "Nylon", "PEEK", "Polycarbonate", "Stainless 304", "Stainless 316", "Titanium Gr 5",
];
const WORKBENCHES: &[&str] = &["Modeling", "Sketch", "Assembly", "Drawing", "PMI", "CAM", "PCB"];
const MANY_TABS: &[&str] = &["Features", "Bodies", "Sketches", "Constraints", "Expressions", "Materials", "Appearance", "Simulation", "Toolpaths", "Notes", "History", "Diagnostics"];

/// The gallery, the decisions chosen in it, and the whole-app preview.
#[derive(Default)]
pub struct Gallery {
    pub open: bool,
    /// Whether the theme is previewed on the whole app. Never saved.
    pub preview: bool,
    pub choices: Choices,
    pub view: View,
    /// Fill the whole window (captures).
    pub maximized: bool,
    pub reduce_motion: bool,
    fonts: PreviewFonts,
    applied: Preview,
    demo: Demo,
    hits: HashMap<String, Rect>,
    /// The hit blob was published non-empty last frame, so one more (empty)
    /// publish is owed after closing.
    published: bool,
}

impl Default for View {
    fn default() -> Self {
        View::App
    }
}

fn hex(c: Color32) -> String {
    format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b())
}

impl Gallery {
    /// The gallery as the launch environment asks for it: open when
    /// `BREP_UI_GALLERY` is set (desktop) or the page URL carries `?uiGallery`
    /// (browser), closed otherwise.
    pub fn from_launch() -> Self {
        Gallery { open: launch_requested(), ..Default::default() }
    }

    /// Nothing to do this frame: closed, not previewing, nothing to restore.
    pub fn idle(&self) -> bool {
        !self.open && !self.preview && !self.applied.active() && !self.fonts.touched()
    }

    /// Whether the hit blob must be published this frame.
    pub fn publishes(&self) -> bool {
        self.open || self.published
    }

    pub fn hits_json(&mut self) -> String {
        self.published = !self.hits.is_empty();
        crate::automation::hit_rects::hits_json(&self.hits)
    }

    /// The theme mode the app is in.
    fn app_mode(ctx: &egui::Context) -> Mode {
        Mode::of(ctx.theme() == egui::Theme::Dark)
    }

    /// The mode the gallery window is drawn in.
    pub fn mode(&self, ctx: &egui::Context) -> Mode {
        match self.view {
            View::App => Self::app_mode(ctx),
            View::Dark => Mode::Dark,
            View::Light => Mode::Light,
        }
    }

    fn theme(&self, ctx: &egui::Context, mode: Mode) -> Theme {
        theme_for(self.choices, mode, &self.fonts.families(ctx), self.reduce_motion)
    }

    /// Bring the context in line with the gallery's state: bind or restore the
    /// preview fonts, install or remove the whole-app preview. Called once per
    /// frame, before any panel draws; returns at once while [`Gallery::idle`].
    pub fn sync(&mut self, ctx: &egui::Context) {
        if self.idle() {
            return;
        }
        if self.open || self.preview {
            self.fonts.ensure(ctx, self.choices.font);
        }
        if self.preview {
            let families = self.fonts.families(ctx);
            self.applied.apply(ctx, self.choices, &families, self.reduce_motion);
            theme::set(ctx, Arc::new(self.theme(ctx, Self::app_mode(ctx))));
        } else if self.applied.active() {
            self.applied.remove(ctx);
            theme::clear(ctx);
        }
        if !self.open && !self.preview {
            // Styles first (above), fonts after: no style names a family that
            // is about to be unbound.
            self.fonts.restore(ctx);
        }
    }

    /// The gallery's state, as the `gallery` command answers it.
    pub fn state_json(&self, ctx: &egui::Context) -> serde_json::Value {
        let accent = ACCENTS[self.choices.accent];
        let mode = self.mode(ctx);
        let theme = self.theme(ctx, mode);
        let c = &theme.colors;
        serde_json::json!({
            "open": self.open,
            "preview": self.preview,
            "previewApplied": self.applied.active(),
            "font": self.choices.font,
            "fontDescription": self.fonts.description(),
            "accent": { "key": accent.key, "label": accent.label, "hex": hex(accent.color) },
            "density": self.choices.density.label().to_lowercase(),
            "light": self.choices.light,
            "view": self.view,
            "mode": mode.label().to_lowercase(),
            "maximized": self.maximized,
            "reduceMotion": self.reduce_motion,
            "summary": self.choices.summary(),
            "tokens": {
                "bgApp": hex(c.bg_app), "bgPanel": hex(c.bg_panel), "bgRaised": hex(c.bg_raised), "bgInput": hex(c.bg_input),
                "textPrimary": hex(c.text_primary), "textSecondary": hex(c.text_secondary),
                "accent": hex(c.accent), "accentFill": hex(c.accent_fill), "accentText": hex(c.accent_text), "accentRing": hex(c.accent_ring),
                "controlHeight": theme.control_height(),
                "whiteOnAccent": (f64::from(contrast(Color32::WHITE, c.accent)) * 100.0).round() / 100.0,
                "whiteOnAccentFill": (f64::from(contrast(Color32::WHITE, c.accent_fill)) * 100.0).round() / 100.0,
            },
            "demo": {
                "clicks": self.demo.clicks,
                "tab": self.demo.tab,
                "switchOn": self.demo.switch_on,
                "checked": self.demo.checked,
                "operation": OPERATIONS[self.demo.operation],
                "material": MATERIALS[self.demo.material],
                "search": self.demo.search,
                "depth": self.demo.depth,
            },
        })
    }

    pub fn show(&mut self, ctx: &egui::Context) {
        self.hits.clear();
        if !self.open {
            return;
        }
        let theme = Arc::new(self.theme(ctx, self.mode(ctx)));
        let c = theme.colors;
        let frame = egui::Frame::new()
            .fill(c.bg_panel)
            .stroke(egui::Stroke::new(1.0, c.border_subtle))
            .corner_radius(theme::radius::CARD)
            .shadow(theme.shadow_medium())
            .inner_margin(egui::Margin::same(space::LG as i8));
        let mut window = egui::Window::new("UI gallery (developer)").id(egui::Id::new("brep-ui-gallery-window")).title_bar(false).frame(frame).collapsible(false);
        window = if self.maximized {
            window.fixed_rect(ctx.content_rect().shrink(6.0))
        } else {
            window.resizable(true).default_size([1180.0, 760.0]).default_pos(crate::panels::below_chrome(ctx, 60.0, 0.0))
        };
        window.show(ctx, |ui| {
            super::themed(ui, theme.clone(), |ui| {
                self.header(ui, &theme);
                ui.add_space(space::MD);
                egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
                    ui.spacing_mut().item_spacing.y = space::LG;
                    self.decisions(ui, &theme);
                    ui.columns(2, |columns| {
                        let (left, right) = columns.split_at_mut(1);
                        let left = &mut left[0];
                        left.spacing_mut().item_spacing.y = space::LG;
                        self.colours(left, &theme);
                        self.typography(left, &theme);
                        self.buttons(left, &theme);
                        self.icon_buttons(left, &theme);
                        self.tabs(left, &theme);
                        let right = &mut right[0];
                        right.spacing_mut().item_spacing.y = space::LG;
                        self.inputs(right, &theme);
                        self.dropdowns(right, &theme);
                        self.toggles(right, &theme);
                        self.references(right, &theme);
                        self.surfaces(right, &theme);
                    });
                });
            });
        });
    }

    fn hit(&mut self, key: impl Into<String>, rect: Rect) {
        self.hits.insert(key.into(), rect);
    }

    /// A section card that takes the column's width and publishes its rect.
    fn card(&mut self, ui: &mut egui::Ui, key: &str, title: &str, contents: impl FnOnce(&mut Self, &mut egui::Ui)) {
        let rect = surface::section(ui, title, |ui| {
            ui.set_width(ui.available_width());
            ui.spacing_mut().item_spacing.y = space::SM;
            contents(self, ui);
        })
        .response
        .rect;
        self.hit(format!("section:{key}"), rect);
    }

    fn header(&mut self, ui: &mut egui::Ui, theme: &Theme) {
        ui.horizontal(|ui| {
            ui.label(egui::RichText::new("UI gallery").font(theme.font(Text::Title)).color(theme.colors.text_primary));
            ui.label(egui::RichText::new("developer preview of the UI refresh · rollout step 1 · nothing here changes the app until the preview switch is on").font(theme.font(Text::Caption)).color(theme.colors.text_secondary));
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                let close = ui.add(Button::ghost("Close").size(Size::Sm));
                self.hit("view:close", close.rect);
                if close.clicked() {
                    self.open = false;
                }
            });
        });
    }

    /// A dropdown of the gallery's own, with its closed rect and open rows published.
    fn choice(&mut self, ui: &mut egui::Ui, key: &str, items: &[&str], selected: &mut usize, width: f32) -> bool {
        let out = dropdown(("brep-ui-gallery", key), items).width(width).show(ui, selected);
        self.hit(key, out.response.rect);
        for (i, rect) in &out.rows {
            self.hit(format!("{key}:{i}"), *rect);
        }
        out.changed
    }

    fn caption(ui: &mut egui::Ui, theme: &Theme, text: &str) {
        ui.label(egui::RichText::new(text).font(theme.font(Text::Caption)).color(theme.colors.text_secondary));
    }

    fn decisions(&mut self, ui: &mut egui::Ui, theme: &Theme) {
        self.card(ui, "decisions", "Decisions for the owner", |this, ui| {
            Self::caption(ui, theme, "Spec section 9. Each choice restyles this gallery at once, and the whole app while the preview is on. Nothing is saved.");
            let label = 130.0;
            let width = 300.0;
            ui.columns(2, |columns| {
                let ui = &mut columns[0];
                ui.spacing_mut().item_spacing.y = space::SM;
                surface::field_row(ui, "1. Font", label, |ui| {
                    let labels: Vec<&str> = FontChoice::ALL.iter().map(|f| f.label()).collect();
                    let mut index = FontChoice::ALL.iter().position(|f| *f == this.choices.font).unwrap_or(0);
                    if this.choice(ui, "choice:font", &labels, &mut index, width) {
                        this.choices.font = FontChoice::ALL[index];
                    }
                });
                surface::field_row(ui, "", label, |ui| Self::caption(ui, theme, this.fonts.description()));
                surface::field_row(ui, "2. Accent colour", label, |ui| {
                    let labels: Vec<&str> = ACCENTS.iter().map(|a| a.label).collect();
                    let mut index = this.choices.accent;
                    if this.choice(ui, "choice:accent", &labels, &mut index, width) {
                        this.choices.accent = index;
                    }
                    for (name, color) in [("accent", theme.colors.accent), ("fill", theme.colors.accent_fill), ("text", theme.colors.accent_text)] {
                        let (rect, _) = ui.allocate_exact_size(Vec2::splat(theme.control_height()), egui::Sense::hover());
                        ui.painter().rect_filled(rect.shrink(3.0), 4.0, color);
                        Self::caption(ui, theme, name);
                    }
                });
                surface::field_row(ui, "3. Default density", label, |ui| {
                    let all = [Density::Compact, Density::Comfortable];
                    let labels = ["Compact (24 px controls, proposed)", "Comfortable (28 px controls)"];
                    let mut index = all.iter().position(|d| *d == this.choices.density).unwrap_or(0);
                    if this.choice(ui, "choice:density", &labels, &mut index, width) {
                        this.choices.density = all[index];
                    }
                });
                surface::field_row(ui, "4. Light theme", label, |ui| {
                    let labels: Vec<&str> = LightScope::ALL.iter().map(|l| l.label()).collect();
                    let mut index = LightScope::ALL.iter().position(|l| *l == this.choices.light).unwrap_or(0);
                    if this.choice(ui, "choice:light", &labels, &mut index, width) {
                        this.choices.light = LightScope::ALL[index];
                    }
                });
                let ui = &mut columns[1];
                ui.spacing_mut().item_spacing.y = space::SM;
                surface::field_row(ui, "Gallery theme", label, |ui| {
                    let labels: Vec<&str> = View::ALL.iter().map(|v| v.label()).collect();
                    let mut index = View::ALL.iter().position(|v| *v == this.view).unwrap_or(0);
                    if this.choice(ui, "view:theme", &labels, &mut index, 180.0) {
                        this.view = View::ALL[index];
                    }
                });
                surface::field_row(ui, "Whole app", label, |ui| {
                    let r = toggle::switch(ui, &mut this.preview, "Preview the theme on the whole app");
                    this.hit("view:preview", r.rect);
                });
                surface::field_row(ui, "Motion", label, |ui| {
                    let r = toggle::switch(ui, &mut this.reduce_motion, "Reduce motion");
                    this.hit("view:reduceMotion", r.rect);
                });
                let white = contrast(Color32::WHITE, theme.colors.accent);
                if white < 4.5 {
                    surface::field_row(ui, "Finding", label, |ui| {
                        ui.vertical(|ui| {
                        ui.set_max_width(380.0);
                        ui.add(egui::Label::new(
                            egui::RichText::new(format!(
                                "White text on this accent is {white:.2}:1, under the 4.5:1 the spec asks for. Filled buttons use the accent darkened to {} ({:.2}:1); rings, bars and marks keep the accent itself.",
                                hex(theme.colors.accent_fill),
                                contrast(Color32::WHITE, theme.colors.accent_fill)
                            ))
                            .font(theme.font(Text::Caption))
                            .color(theme.colors.warning),
                        ).wrap());
                        });
                    });
                }
            });
            ui.label(egui::RichText::new(format!("Chosen: {}", this.choices.summary())).font(theme.font(Text::Label)).color(theme.colors.text_primary));
        });
    }

    fn colours(&mut self, ui: &mut egui::Ui, theme: &Theme) {
        self.card(ui, "colours", &format!("Colour roles ({})", theme.mode.label().to_lowercase()), |_, ui| {
            let c = &theme.colors;
            let swatches: [(&str, Color32, Color32); 16] = [
                ("bg.app", c.bg_app, c.text_primary),
                ("bg.panel", c.bg_panel, c.text_primary),
                ("bg.raised", c.bg_raised, c.text_primary),
                ("bg.input", c.bg_input, c.text_primary),
                ("bg.hover", over(c.bg_panel, c.hover), c.text_primary),
                ("bg.pressed", over(c.bg_panel, c.pressed), c.text_primary),
                ("border.subtle", c.border_subtle, c.text_primary),
                ("border.strong", c.border_strong, c.text_primary),
                ("accent", c.accent, c.on_accent),
                ("accent.fill", c.accent_fill, c.on_accent),
                ("accent.muted", over(c.bg_panel, c.accent_muted), c.text_primary),
                ("text.secondary", c.bg_panel, c.text_secondary),
                ("text.disabled", c.bg_panel, c.text_disabled),
                ("danger", c.bg_panel, c.danger),
                ("warning", c.bg_panel, c.warning),
                ("success", c.bg_panel, c.success),
            ];
            egui::Grid::new("brep-ui-gallery-swatches").num_columns(4).spacing([space::SM, space::SM]).show(ui, |ui| {
                for (i, (name, bg, fg)) in swatches.iter().enumerate() {
                    let (rect, _) = ui.allocate_exact_size(Vec2::new(128.0, 40.0), egui::Sense::hover());
                    ui.painter().rect(rect, 6.0, *bg, egui::Stroke::new(1.0, c.border_subtle), egui::StrokeKind::Inside);
                    let g = paint::galley(ui, name, theme.font(Text::Label));
                    ui.painter().galley(rect.min + Vec2::new(8.0, 5.0), g, *fg);
                    let shown = if *bg == c.bg_panel && !name.starts_with("bg.") { *fg } else { *bg };
                    let detail = format!("{}  {:.1}:1", hex(shown), contrast(*fg, *bg));
                    let g = paint::galley(ui, &detail, theme.font(Text::Caption));
                    ui.painter().galley(rect.min + Vec2::new(8.0, 22.0), g, *fg);
                    if i % 4 == 3 {
                        ui.end_row();
                    }
                }
            });
            Self::caption(ui, theme, "Each swatch shows its hex and the contrast of its text on its fill. Body text roles meet 4.5:1 on every surface; focus rings meet 3:1.");
        });
    }

    fn typography(&mut self, ui: &mut egui::Ui, theme: &Theme) {
        self.card(ui, "typography", "Typography", |_, ui| {
            for (role, name, sample) in [
                (Text::Title, "Panel title 16 semibold", "Extrude"),
                (Text::Section, "Section header 14 semibold", "Profile and direction"),
                (Text::Body, "Body 13", "Select a closed profile, then set the depth."),
                (Text::Label, "Label 12 semibold", "Depth"),
                (Text::Caption, "Caption 11", "Measured along the sketch normal"),
                (Text::Code, "Code 12 monospace", "depth = width / 2 + 0.5"),
            ] {
                ui.horizontal(|ui| {
                    let g = paint::galley(ui, name, theme.font(Text::Caption));
                    let (rect, _) = ui.allocate_exact_size(Vec2::new(170.0, 22.0), egui::Sense::hover());
                    ui.painter().galley(egui::pos2(rect.left(), rect.center().y - g.size().y / 2.0), g, theme.colors.text_secondary);
                    ui.label(egui::RichText::new(sample).font(theme.font(role)).color(theme.colors.text_primary));
                });
            }
            ui.horizontal(|ui| {
                let (rect, _) = ui.allocate_exact_size(Vec2::new(170.0, 40.0), egui::Sense::hover());
                let g = paint::galley(ui, "Numbers, right-aligned", theme.font(Text::Caption));
                ui.painter().galley(egui::pos2(rect.left(), rect.top() + 4.0), g, theme.colors.text_secondary);
                ui.vertical(|ui| {
                    ui.spacing_mut().item_spacing.y = 0.0;
                    for value in ["1 111.10", "8 888.88", "12.50"] {
                        let g = paint::galley(ui, value, theme.font(Text::Body));
                        let (rect, _) = ui.allocate_exact_size(Vec2::new(80.0, g.size().y), egui::Sense::hover());
                        ui.painter().galley(egui::pos2(rect.right() - g.size().x, rect.top()), g, theme.colors.text_primary);
                    }
                });
            });
        });
    }

    fn buttons(&mut self, ui: &mut egui::Ui, theme: &Theme) {
        self.card(ui, "buttons", "Buttons", |this, ui| {
            let glyphs = demo_glyphs();
            egui::Grid::new("brep-ui-gallery-buttons").spacing([space::MD, space::MD]).show(ui, |ui| {
                for head in ["", "Rest", "Hover", "Pressed", "Focus", "Disabled", "Busy"] {
                    Self::caption(ui, theme, head);
                }
                ui.end_row();
                for (name, variant, text) in [
                    ("primary", Variant::Primary, "Apply"),
                    ("secondary", Variant::Secondary, "Cancel"),
                    ("ghost", Variant::Ghost, "Reset"),
                    ("danger", Variant::Danger, "Delete"),
                    ("danger, confirm", Variant::DangerFilled, "Delete"),
                ] {
                    Self::caption(ui, theme, name);
                    for show in [Show::Live, Show::Hover, Show::Pressed, Show::Focus] {
                        ui.add(Button::new(text).variant(variant).show(show));
                    }
                    ui.add(Button::new(text).variant(variant).enabled(false));
                    ui.add(Button::new(text).variant(variant).icon(&glyphs[0]).busy(true));
                    ui.end_row();
                }
            });
            ui.horizontal_wrapped(|ui| {
                Self::caption(ui, theme, "sizes and content");
                ui.add(Button::new("Small 24").size(Size::Sm));
                ui.add(Button::new("Medium 28").size(Size::Md));
                ui.add(Button::primary("Create").icon(&glyphs[1]).size(Size::Md));
                ui.add(Button::new("Save").icon(&glyphs[2]).shortcut("Ctrl+S"));
                ui.add(Button::ghost("Undo").shortcut("Ctrl+Z"));
            });
            ui.horizontal(|ui| {
                Self::caption(ui, theme, "live");
                let r = ui.add(Button::primary("Click me"));
                this.hit("demo:primary", r.rect);
                if r.clicked() {
                    this.demo.clicks += 1;
                }
                ui.label(egui::RichText::new(format!("clicked {} times", this.demo.clicks)).font(theme.font(Text::Body)).color(theme.colors.text_secondary));
            });
        });
    }

    fn icon_buttons(&mut self, ui: &mut egui::Ui, theme: &Theme) {
        self.card(ui, "iconButtons", "Icon buttons and the ribbon", |this, ui| {
            let glyphs = demo_glyphs();
            ui.horizontal(|ui| {
                Self::caption(ui, theme, "toolbar 28:");
                ui.add(IconButton::new(&glyphs[0], "Rest"));
                ui.add(IconButton::new(&glyphs[1], "Hover").show(Show::Hover));
                ui.add(IconButton::new(&glyphs[2], "Pressed").show(Show::Pressed));
                ui.add(IconButton::new(&glyphs[3], "Focus").show(Show::Focus));
                ui.add(IconButton::new(&glyphs[4], "Active").active(true));
                ui.add(IconButton::new(&glyphs[5], "Disabled").enabled(false));
                ui.add_space(space::LG);
                Self::caption(ui, theme, "rail:");
                ui.add(IconButton::new(&glyphs[6], "Active on a rail").active(true).bar(icon_button::BarSide::Left));
            });
            // A mock ribbon: groups, caption labels, separators.
            let frame = egui::Frame::new().fill(theme.colors.bg_app).corner_radius(6.0).inner_margin(egui::Margin::same(space::MD as i8));
            frame.show(ui, |ui| {
                ui.horizontal(|ui| {
                    let groups: [(&str, usize); 3] = [("Create", 4), ("Modify", 3), ("Inspect", 2)];
                    let mut next = 0;
                    for (g, (label, count)) in groups.iter().enumerate() {
                        if g > 0 {
                            icon_button::group_separator(ui, 50.0);
                        }
                        icon_button::ribbon_group(ui, label, |ui| {
                            for _ in 0..*count {
                                let index = next;
                                let name = format!("Tool {}", index + 1);
                                let r = ui.add(
                                    IconButton::new(&glyphs[index % glyphs.len()], &name)
                                        .ribbon()
                                        .active(this.demo.tool == index)
                                        .description("What the tool does, in one line.")
                                        .shortcut("E"),
                                );
                                if r.clicked() {
                                    this.demo.tool = index;
                                }
                                next += 1;
                            }
                        });
                    }
                });
            });
            ui.horizontal(|ui| {
                Self::caption(ui, theme, "tooltip:");
                surface::popup_frame(theme).inner_margin(egui::Margin::same(space::MD as i8)).show(ui, |ui| {
                    ui.vertical(|ui| icon_button::tooltip_card(ui, "Extrude", Some("Pull a profile into a solid or a cut."), Some("E")));
                });
            });
        });
    }

    fn tabs(&mut self, ui: &mut egui::Ui, theme: &Theme) {
        self.card(ui, "tabs", "Tabs", |this, ui| {
            Self::caption(ui, theme, "Workbench and panel tabs: the underline slides to the tab you pick.");
            let out = tabs::tab_bar(ui, "brep-ui-gallery-workbench", WORKBENCHES, &mut this.demo.tab);
            for (i, rect) in out.tabs {
                this.hit(format!("demo:tab:{i}"), rect);
            }
            Self::caption(ui, theme, "Hover and focus:");
            let mut fixed = 0;
            tabs::tab_bar_shown(ui, "brep-ui-gallery-tab-hover", &["Active", "Hover", "Inactive"], &mut fixed, Some((1, Show::Hover)));
            let mut fixed = 0;
            tabs::tab_bar_shown(ui, "brep-ui-gallery-tab-focus", &["Active", "Focus", "Inactive"], &mut fixed, Some((1, Show::Focus)));
            Self::caption(ui, theme, "Overflow: tabs that do not fit go into the chevron menu.");
            ui.scope(|ui| {
                ui.set_max_width(420.0);
                tabs::tab_bar(ui, "brep-ui-gallery-overflow", MANY_TABS, &mut this.demo.wide_tab);
            });
            Self::caption(ui, theme, "Document tabs: the active tab joins the content; a dot marks unsaved changes.");
            let docs: Vec<DocumentTab<'_>> = this.demo.documents.iter().map(|(name, dirty)| DocumentTab { name, dirty: *dirty }).collect();
            let out = tabs::document_tabs(ui, "brep-ui-gallery-documents", &docs, this.demo.document);
            if let Some(i) = out.activated {
                this.demo.document = i;
            }
            if let Some(i) = out.closed {
                if this.demo.documents.len() > 1 {
                    this.demo.documents.remove(i);
                    this.demo.document = this.demo.document.min(this.demo.documents.len() - 1);
                }
            }
            let (content, _) = ui.allocate_exact_size(Vec2::new(ui.available_width(), 28.0), egui::Sense::hover());
            ui.painter().rect_filled(content, 0.0, theme.colors.bg_panel);
        });
    }

    fn inputs(&mut self, ui: &mut egui::Ui, theme: &Theme) {
        self.card(ui, "inputs", "Text and number inputs", |this, ui| {
            let label = 110.0;
            let width = 200.0;
            surface::field_row(ui, "Name", label, |ui| {
                input::text_input(&mut this.demo.name).placeholder("Name").width(width).show(ui);
            });
            surface::field_row(ui, "Placeholder", label, |ui| {
                let mut empty = String::new();
                input::text_input(&mut empty).placeholder("Optional note").width(width).id(egui::Id::new("brep-ui-gallery-empty")).show(ui);
            });
            surface::field_row(ui, "Hover / focus", label, |ui| {
                let mut a = String::from("Hover");
                input::text_input(&mut a).width(96.0).id(egui::Id::new("brep-ui-gallery-hover")).show_state(Show::Hover).show(ui);
                let mut b = String::from("Focus");
                input::text_input(&mut b).width(96.0).id(egui::Id::new("brep-ui-gallery-focus")).show_state(Show::Focus).show(ui);
            });
            surface::field_row(ui, "Disabled", label, |ui| {
                let mut text = String::from("Locked by the feature");
                input::text_input(&mut text).width(width).enabled(false).id(egui::Id::new("brep-ui-gallery-disabled")).show(ui);
            });
            surface::field_row(ui, "Error", label, |ui| {
                ui.vertical(|ui| {
                    let mut text = String::from("12 +");
                    input::text_input(&mut text).width(width).suffix("mm").right_aligned(true).error(Some("a value is missing")).id(egui::Id::new("brep-ui-gallery-error")).show(ui);
                });
            });
            surface::field_row(ui, "Search", label, |ui| {
                let out = input::search_input(&mut this.demo.search).width(width).id(egui::Id::new("brep-ui-gallery-search")).show(ui);
                this.hit("demo:search", out.rect);
                let mut filled = String::from("fillet");
                input::search_input(&mut filled).width(140.0).id(egui::Id::new("brep-ui-gallery-search-filled")).show(ui);
            });
            Self::caption(ui, theme, "Numbers: the unit sits inside the field; type an expression or another unit (1/2 in becomes 12.7 mm); drag the label to scrub.");
            surface::field_row(ui, "", 0.0, |ui| {
                let out = input::number_input(&mut this.demo.depth).unit("mm").label("Depth").width(120.0).id(egui::Id::new("brep-ui-gallery-depth")).show(ui);
                this.hit("demo:number", out.input.rect);
                ui.add_space(space::LG);
                input::number_input(&mut this.demo.width_in).unit("in").label("Width").width(100.0).id(egui::Id::new("brep-ui-gallery-width")).show(ui);
                ui.add_space(space::LG);
                input::number_input(&mut this.demo.angle).unit("deg").label("Angle").width(100.0).speed(0.5).id(egui::Id::new("brep-ui-gallery-angle")).show(ui);
            });
        });
    }

    fn dropdowns(&mut self, ui: &mut egui::Ui, theme: &Theme) {
        self.card(ui, "dropdowns", "Dropdowns (every enumeration)", |this, ui| {
            let label = 110.0;
            surface::field_row(ui, "Operation", label, |ui| {
                let out = dropdown("brep-ui-gallery-operation", OPERATIONS).groups(OPERATION_GROUPS).width(200.0).show(ui, &mut this.demo.operation);
                this.hit("demo:dropdown", out.response.rect);
                for (i, rect) in out.rows {
                    this.hit(format!("demo:dropdown:{i}"), rect);
                }
            });
            surface::field_row(ui, "Material", label, |ui| {
                let out = dropdown("brep-ui-gallery-material", MATERIALS).width(200.0).show(ui, &mut this.demo.material);
                this.hit("demo:long", out.response.rect);
                for (i, rect) in out.rows {
                    this.hit(format!("demo:long:{i}"), rect);
                }
                Self::caption(ui, theme, "more than 12 items: search at the top");
            });
            surface::field_row(ui, "States", label, |ui| {
                let mut i = 0;
                dropdown("brep-ui-gallery-dd-hover", &["Hover"]).width(96.0).show_state(Show::Hover).show(ui, &mut i);
                dropdown("brep-ui-gallery-dd-focus", &["Focus"]).width(96.0).show_state(Show::Focus).show(ui, &mut i);
                dropdown("brep-ui-gallery-dd-disabled", &["Disabled"]).width(96.0).enabled(false).show(ui, &mut i);
            });
            surface::field_row(ui, "Open", label, |ui| {
                // The popup's look, drawn in place.
                surface::popup_frame(theme).show(ui, |ui| {
                    ui.vertical(|ui| {
                        ui.set_width(200.0);
                        ui.spacing_mut().item_spacing.y = 0.0;
                        surface::menu_header(ui, "Create");
                        surface::menu_row_with(ui, "New body", None, true, false);
                        surface::menu_header(ui, "Combine with the target");
                        surface::menu_row_with(ui, "Join", None, false, true);
                        surface::menu_row_with(ui, "Cut", None, false, false);
                        surface::menu_row_with(ui, "Intersect", None, false, false);
                    });
                });
            });
        });
    }

    fn toggles(&mut self, ui: &mut egui::Ui, theme: &Theme) {
        self.card(ui, "toggles", "Checkboxes, switches and sliders", |this, ui| {
            ui.horizontal_wrapped(|ui| {
                let r = toggle::checkbox(ui, &mut this.demo.checked, "Symmetric");
                this.hit("demo:checkbox", r.rect);
                toggle::checkbox_shown(ui, toggle::Check::Off, "Off", true, Show::Live);
                toggle::checkbox_shown(ui, toggle::Check::On, "Hover", true, Show::Hover);
                toggle::checkbox_shown(ui, toggle::Check::On, "Focus", true, Show::Focus);
                toggle::checkbox_shown(ui, toggle::Check::Indeterminate, "Mixed", true, Show::Live);
                toggle::checkbox_shown(ui, toggle::Check::On, "Disabled", false, Show::Live);
            });
            ui.horizontal_wrapped(|ui| {
                let r = toggle::switch(ui, &mut this.demo.switch_on, "Show edges");
                this.hit("demo:switch", r.rect);
                toggle::switch_shown(ui, false, "Off", true, Show::Live);
                toggle::switch_shown(ui, true, "Focus", true, Show::Focus);
                toggle::switch_shown(ui, true, "Disabled", false, Show::Live);
            });
            ui.horizontal(|ui| {
                Self::caption(ui, theme, "slider");
                toggle::slider(ui, &mut this.demo.slider, 0.0..=1.0, 180.0);
                let mut hover = 0.7;
                toggle::slider_shown(ui, &mut hover, 0.0..=1.0, 120.0, true, Show::Hover);
                let mut off = 0.3;
                toggle::slider_shown(ui, &mut off, 0.0..=1.0, 120.0, false, Show::Live);
            });
        });
    }

    fn references(&mut self, ui: &mut egui::Ui, theme: &Theme) {
        self.card(ui, "references", "Reference-selection fields", |this, ui| {
            let glyphs = demo_glyphs();
            let label = 110.0;
            surface::field_row(ui, "Faces", label, |ui| {
                let chip_list: Vec<Chip<'_>> = this.demo.picks.iter().map(|name| Chip { glyph: &glyphs[3], name }).collect();
                let out = chips::reference_field("brep-ui-gallery-picks", &chip_list, "faces").picking(this.demo.picking).width(300.0).show(ui);
                if let Some(i) = out.removed {
                    this.demo.picks.remove(i);
                } else if out.response.clicked() {
                    this.demo.picking = !this.demo.picking;
                }
            });
            surface::field_row(ui, "Picking, empty", label, |ui| {
                chips::reference_field("brep-ui-gallery-picking", &[], "edges").picking(true).width(300.0).show(ui);
            });
            surface::field_row(ui, "Many picks", label, |ui| {
                let names: Vec<String> = (1..=12).map(|i| format!("Face {i}")).collect();
                let many: Vec<Chip<'_>> = names.iter().map(|name| Chip { glyph: &glyphs[3], name }).collect();
                chips::reference_field("brep-ui-gallery-many", &many, "faces").width(300.0).show(ui);
            });
            Self::caption(ui, theme, "Click the first field to start or stop picking (the border pulses); more than 6 picks collapse to a count.");
        });
    }

    fn surfaces(&mut self, ui: &mut egui::Ui, theme: &Theme) {
        self.card(ui, "surfaces", "Surfaces: panel, tree, menu, dialog, toasts", |this, ui| {
            let glyphs = demo_glyphs();
            ui.horizontal_top(|ui| {
                ui.vertical(|ui| {
                    ui.set_width(250.0);
                    // A panel with its header and a tree.
                    let frame = egui::Frame::new().fill(theme.colors.bg_panel).stroke(egui::Stroke::new(1.0, theme.colors.border_subtle)).corner_radius(6.0);
                    frame.show(ui, |ui| {
                        ui.spacing_mut().item_spacing.y = 0.0;
                        surface::panel_header(ui, "Model", &mut this.demo.panel_collapsed, |ui| {
                            ui.add(IconButton::new(&glyphs[5], "Panel action"));
                        });
                        if !this.demo.panel_collapsed {
                            let rows = [
                                (0, "Bracket", None, false),
                                (1, "Sketch 1", None, false),
                                (1, "Extrude 1", None, false),
                                (1, "Fillet 1", Some(Kind::Warning), false),
                                (1, "Shell 1", Some(Kind::Error), false),
                                (1, "Pattern 1", None, true),
                            ];
                            for (i, (depth, label, badge, suppressed)) in rows.into_iter().enumerate() {
                                let row = TreeRow { depth, glyph: &glyphs[i % glyphs.len()], label, selected: this.demo.tree_selected == i, badge, suppressed };
                                if surface::tree_row(ui, row).clicked() {
                                    this.demo.tree_selected = i;
                                }
                            }
                        }
                    });
                    ui.add_space(space::MD);
                    // A context menu, drawn in place.
                    surface::popup_frame(theme).show(ui, |ui| {
                        ui.set_width(220.0);
                        ui.spacing_mut().item_spacing.y = 0.0;
                        surface::menu_row(ui, "Edit feature", Some("Enter"), false);
                        surface::menu_row(ui, "Suppress", Some("Ctrl+H"), false);
                        surface::menu_row(ui, "Show edges", None, true);
                        surface::menu_separator(ui);
                        surface::menu_row(ui, "Delete", Some("Del"), false);
                    });
                });
                ui.add_space(space::LG);
                ui.vertical(|ui| {
                    surface::dialog(ui, "Delete 3 features?", "Delete", "Cancel", 300.0, |ui| {
                        ui.label(egui::RichText::new("Fillet 1, Shell 1 and Pattern 1 will be removed. Features that depend on them will fail.").font(theme.font(Text::Body)).color(theme.colors.text_primary));
                    });
                    ui.add_space(space::LG);
                    surface::toast(ui, Kind::Success, "Saved bracket.nbrep", 300.0);
                    ui.add_space(space::SM);
                    surface::toast(ui, Kind::Warning, "Fillet 1 was rebuilt with a smaller radius.", 300.0);
                    ui.add_space(space::SM);
                    surface::toast(ui, Kind::Error, "Shell 1 failed: the wall is thicker than the body.", 300.0);
                });
            });
        });
    }
}

/// A handful of glyphs from the icon catalog for the samples (their meaning
/// does not matter here), padded with letters if the catalog is short.
fn demo_glyphs() -> Vec<String> {
    let mut glyphs: Vec<String> = crate::icons::ICONS.iter().step_by((crate::icons::ICONS.len() / 12).max(1)).take(12).map(|icon| icon.ch.to_string()).collect();
    while glyphs.len() < 12 {
        glyphs.push(char::from(b'A' + glyphs.len() as u8).to_string());
    }
    glyphs
}

#[cfg(not(target_arch = "wasm32"))]
fn launch_requested() -> bool {
    std::env::var("BREP_UI_GALLERY").is_ok_and(|v| !v.is_empty() && v != "0")
}

#[cfg(target_arch = "wasm32")]
fn launch_requested() -> bool {
    web_sys::window()
        .and_then(|w| w.location().search().ok())
        .and_then(|search| web_sys::UrlSearchParams::new_with_str(&search).ok())
        .is_some_and(|params| params.has("uiGallery"))
}