BREP_app 0.36.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
//! Theme tokens: the one place a colour, size, radius, shadow or duration of
//! the refreshed UI is written (section 3).
//!
//! STATUS: rollout step 1. Nothing in the app reads these tokens except the
//! developer gallery ([`crate::ui_kit::gallery`]) and its whole-app PREVIEW,
//! which is off unless the gallery turns it on. With the gallery closed and the
//! preview off the app makes no call into this module.
//!
//! A [`Theme`](crate::theme::Theme) is built per mode (dark, light), density (compact, comfortable)
//! and accent. [`Theme::apply`](crate::theme::Theme::apply) writes it into an `egui::Style`, which restyles
//! every default egui widget; the [`crate::ui_kit`] components read the tokens
//! directly through [`Theme::of`](crate::theme::Theme::of).
use eframe::egui::{self, Color32};
use std::sync::Arc;

/// Dark or light chrome. The 3D viewport's colours are render settings and are
/// not part of the theme.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Mode {
    Dark,
    Light,
}

impl Mode {
    pub fn of(dark: bool) -> Self {
        if dark { Mode::Dark } else { Mode::Light }
    }
    pub fn label(self) -> &'static str {
        match self {
            Mode::Dark => "Dark",
            Mode::Light => "Light",
        }
    }
}

/// Control heights and spacing. Compact is the proposed default (spec section 2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Density {
    Compact,
    Comfortable,
}

impl Density {
    pub fn label(self) -> &'static str {
        match self {
            Density::Compact => "Compact",
            Density::Comfortable => "Comfortable",
        }
    }
}

/// One accent the owner can choose between (spec section 9, decision 2).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Accent {
    /// The key a command names it by.
    pub key: &'static str,
    pub label: &'static str,
    pub color: Color32,
}

/// The accent candidates. The first is the spec's proposal.
pub const ACCENTS: &[Accent] = &[
    Accent { key: "blue", label: "Blue #3d8bfd (proposed)", color: Color32::from_rgb(0x3d, 0x8b, 0xfd) },
    Accent { key: "brand", label: "Help-site blue #0b6bcb", color: Color32::from_rgb(0x0b, 0x6b, 0xcb) },
    Accent { key: "teal", label: "Teal #14b8a6", color: Color32::from_rgb(0x14, 0xb8, 0xa6) },
    Accent { key: "violet", label: "Violet #8b5cf6", color: Color32::from_rgb(0x8b, 0x5c, 0xf6) },
    Accent { key: "orange", label: "Orange #f08c2e", color: Color32::from_rgb(0xf0, 0x8c, 0x2e) },
    Accent { key: "green", label: "Green #2fb170", color: Color32::from_rgb(0x2f, 0xb1, 0x70) },
];

/// The accent with this key.
pub fn accent(key: &str) -> Option<Accent> {
    ACCENTS.iter().copied().find(|a| a.key == key)
}

/// The colour roles (spec section 3). Every colour is opaque except the three
/// overlays, which are laid over whatever surface the control sits on.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Palette {
    /// The window background behind panels.
    pub bg_app: Color32,
    /// Panel surfaces.
    pub bg_panel: Color32,
    /// Cards, popups, menus.
    pub bg_raised: Color32,
    /// Text and number field fill.
    pub bg_input: Color32,
    /// Hover overlay (translucent).
    pub hover: Color32,
    /// Pressed overlay (translucent).
    pub pressed: Color32,
    /// Card and panel borders.
    pub border_subtle: Color32,
    /// Input borders.
    pub border_strong: Color32,
    /// The accent as chosen: focus rings, underlines, check marks, sliders.
    pub accent: Color32,
    /// The accent as a FILL under [`Palette::on_accent`] text: the accent
    /// itself when white text reads on it at 4.5:1, else darkened until it does.
    pub accent_fill: Color32,
    /// The accent as TEXT on this mode's surfaces (4.5:1 on every one of them
    /// and on [`Palette::accent_muted`] over them).
    pub accent_text: Color32,
    /// The accent as a focus RING or 2 px bar: 3:1 on every surface.
    pub accent_ring: Color32,
    /// Selected rows, active tab background (translucent: accent at 18 %).
    /// Text on it is `text.primary` or `accent.text`, never `text.secondary`.
    pub accent_muted: Color32,
    /// Text on [`Palette::accent_fill`] and on the filled danger button.
    pub on_accent: Color32,
    pub text_primary: Color32,
    pub text_secondary: Color32,
    /// Disabled text. Exempt from the contrast rule (WCAG 1.4.3).
    pub text_disabled: Color32,
    pub danger: Color32,
    /// The danger colour as a fill under [`Palette::on_accent`] text.
    pub danger_fill: Color32,
    pub warning: Color32,
    pub success: Color32,
    /// Informational text and marks: a blue that reads 4.5:1 on every
    /// surface of the mode, whatever accent the user chose.
    pub info: Color32,
    /// Popup and window shadow colour (translucent).
    pub shadow: Color32,
}

const fn rgb(hex: u32) -> Color32 {
    Color32::from_rgb((hex >> 16) as u8, (hex >> 8) as u8, hex as u8)
}

/// WCAG relative luminance of an opaque colour.
pub fn luminance(c: Color32) -> f32 {
    let f = |v: u8| {
        let v = f32::from(v) / 255.0;
        if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
    };
    0.2126 * f(c.r()) + 0.7152 * f(c.g()) + 0.0722 * f(c.b())
}

/// WCAG contrast ratio of two opaque colours (1 to 21).
pub fn contrast(a: Color32, b: Color32) -> f32 {
    let (la, lb) = (luminance(a), luminance(b));
    (la.max(lb) + 0.05) / (la.min(lb) + 0.05)
}

/// `top` laid over the opaque `base` at `top`'s own alpha.
pub fn over(base: Color32, top: Color32) -> Color32 {
    let [r, g, b, a] = top.to_srgba_unmultiplied();
    mix(base, Color32::from_rgb(r, g, b), f32::from(a) / 255.0)
}

/// `a` moved `t` of the way to `b` (both opaque).
pub fn mix(a: Color32, b: Color32, t: f32) -> Color32 {
    let ch = |x: u8, y: u8| (f32::from(x) * (1.0 - t) + f32::from(y) * t).round() as u8;
    Color32::from_rgb(ch(a.r(), b.r()), ch(a.g(), b.g()), ch(a.b(), b.b()))
}

fn alpha(c: Color32, a: f32) -> Color32 {
    Color32::from_rgba_unmultiplied(c.r(), c.g(), c.b(), (a * 255.0).round() as u8)
}

/// `color` moved towards `toward` in 2 % steps until `ok` accepts it.
/// Returns `toward` if nothing less does.
fn moved_until(color: Color32, toward: Color32, ok: impl Fn(Color32) -> bool) -> Color32 {
    (0..=50).map(|step| mix(color, toward, step as f32 * 0.02)).find(|c| ok(*c)).unwrap_or(toward)
}

impl Palette {
    pub fn new(mode: Mode, accent: Color32) -> Self {
        let white = Color32::WHITE;
        let black = Color32::BLACK;
        let mut p = match mode {
            Mode::Dark => Palette {
                bg_app: rgb(0x0f151c),
                bg_panel: rgb(0x151d26),
                bg_raised: rgb(0x1b2531),
                bg_input: rgb(0x0f151c),
                hover: alpha(white, 0.06),
                pressed: alpha(white, 0.10),
                border_subtle: rgb(0x263241),
                border_strong: rgb(0x334255),
                accent,
                accent_fill: accent,
                accent_text: accent,
                accent_ring: accent,
                accent_muted: alpha(accent, 0.18),
                on_accent: white,
                text_primary: rgb(0xe6edf3),
                text_secondary: rgb(0x9fb0c0),
                text_disabled: rgb(0x5c6b7a),
                // The spec's #f05252 reads 4.45:1 on bg.raised; one step lighter passes.
                danger: rgb(0xf26464),
                danger_fill: rgb(0xf05252),
                warning: rgb(0xf5a524),
                success: rgb(0x3fb950),
                info: ACCENTS[0].color,
                shadow: alpha(black, 0.45),
            },
            Mode::Light => Palette {
                bg_app: rgb(0xe9edf2),
                bg_panel: rgb(0xf4f6f9),
                bg_raised: rgb(0xffffff),
                bg_input: rgb(0xffffff),
                hover: alpha(black, 0.05),
                pressed: alpha(black, 0.09),
                border_subtle: rgb(0xd3dae3),
                border_strong: rgb(0xaeb9c6),
                accent,
                accent_fill: accent,
                accent_text: accent,
                accent_ring: accent,
                accent_muted: alpha(accent, 0.18),
                on_accent: white,
                text_primary: rgb(0x17212b),
                text_secondary: rgb(0x4a5868),
                text_disabled: rgb(0x8d99a6),
                danger: rgb(0xc62828),
                danger_fill: rgb(0xc62828),
                warning: rgb(0x8f5d00),
                success: rgb(0x177332),
                info: ACCENTS[0].color,
                shadow: alpha(black, 0.18),
            },
        };
        // The accent's derived forms. The accent the owner picks stays the hue;
        // each use moves it only as far as its contrast rule needs.
        let surfaces = [p.bg_app, p.bg_panel, p.bg_raised, p.bg_input];
        let away = if mode == Mode::Dark { white } else { black };
        let (hover, pressed, muted) = (p.hover, p.pressed, p.accent_muted);
        // A fill carries white text; hovered and pressed it only gets darker
        // ([`Palette::fill_hover`], [`Palette::fill_pressed`]).
        let carries_white = |fill: Color32| contrast(white, fill) >= 4.5;
        p.accent_fill = moved_until(accent, black, carries_white);
        p.danger_fill = moved_until(p.danger_fill, black, carries_white);
        p.accent_ring = moved_until(accent, away, |c| surfaces.iter().all(|bg| contrast(c, *bg) >= 3.0));
        // Accent text reads on every surface at rest, hovered, pressed and selected.
        let states: Vec<Color32> = surfaces
            .iter()
            .flat_map(|s| [*s, over(*s, hover), over(*s, pressed), over(*s, muted), over(over(*s, muted), hover)])
            .collect();
        p.accent_text = moved_until(accent, away, |c| states.iter().all(|bg| contrast(c, *bg) >= 4.5));
        p.info = moved_until(ACCENTS[0].color, away, |c| states.iter().all(|bg| contrast(c, *bg) >= 4.5));
        p
    }

    /// A filled button's fill while hovered: 8 % towards black, in both
    /// modes, so its white text never loses contrast.
    pub fn fill_hover(fill: Color32) -> Color32 {
        mix(fill, Color32::BLACK, 0.08)
    }

    /// A filled button's fill while pressed: 16 % towards black.
    pub fn fill_pressed(fill: Color32) -> Color32 {
        mix(fill, Color32::BLACK, 0.16)
    }
}

/// The 4 px spacing scale (spec section 3).
pub mod space {
    pub const XXS: f32 = 2.0;
    pub const XS: f32 = 4.0;
    pub const SM: f32 = 6.0;
    pub const MD: f32 = 8.0;
    pub const LG: f32 = 12.0;
    pub const XL: f32 = 16.0;
    pub const XXL: f32 = 24.0;
    pub const XXXL: f32 = 32.0;
}

/// Corner radii (spec section 3).
pub mod radius {
    /// Inputs and small buttons.
    pub const INPUT: f32 = 4.0;
    /// Buttons and tabs.
    pub const BUTTON: f32 = 6.0;
    /// Cards and popups.
    pub const CARD: f32 = 8.0;
}

/// Every border is 1 px; a focus ring or an active bar is 2 px.
pub const BORDER: f32 = 1.0;
pub const RING: f32 = 2.0;

/// The type scale (spec section 4).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Text {
    /// 11: captions, group labels, error messages.
    Caption,
    /// 13: body text and control text.
    Body,
    /// 12 semibold: field labels.
    Label,
    /// 14 semibold: section headers.
    Section,
    /// 16 semibold: panel and dialog titles.
    Title,
    /// 12 monospace: code, the console.
    Code,
    /// 12 monospace: tree, table and list rows (owner 2026-11-28: these
    /// widgets need same-width characters so their columns line up, whichever
    /// UI font is chosen).
    Data,
}

/// The font families the theme draws with. Until a UI font is chosen and bound
/// (spec section 9, decision 1) all three are egui's own families, so a theme
/// can always be drawn.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Families {
    pub text: egui::FontFamily,
    /// The semibold face; the regular one where there is no semibold.
    pub strong: egui::FontFamily,
    pub mono: egui::FontFamily,
}

impl Default for Families {
    fn default() -> Self {
        Self {
            text: egui::FontFamily::Proportional,
            strong: egui::FontFamily::Proportional,
            mono: egui::FontFamily::Monospace,
        }
    }
}

/// One theme: every token a component or the base egui style needs.
#[derive(Debug, Clone, PartialEq)]
pub struct Theme {
    pub mode: Mode,
    pub density: Density,
    pub colors: Palette,
    pub families: Families,
    /// Turns every transition off.
    pub reduce_motion: bool,
    /// The smallest height a control or row may have: 0 with a mouse, the
    /// touch target on a touch browser ([`install`] sets it), so `ui_kit`
    /// controls grow there without their callers asking.
    pub min_target: f32,
}

impl Default for Theme {
    fn default() -> Self {
        Theme::new(Mode::Dark, Density::Compact, ACCENTS[0].color)
    }
}

impl Theme {
    pub fn new(mode: Mode, density: Density, accent: Color32) -> Self {
        Theme { mode, density, colors: Palette::new(mode, accent), families: Families::default(), reduce_motion: false, min_target: 0.0 }
    }

    pub fn with_families(mut self, families: Families) -> Self {
        self.families = families;
        self
    }

    pub fn with_min_target(mut self, min_target: f32) -> Self {
        self.min_target = min_target;
        self
    }

    pub fn with_reduce_motion(mut self, reduce: bool) -> Self {
        self.reduce_motion = reduce;
        self
    }

    /// The height of inputs, buttons and dropdowns: 24 compact, 28 comfortable.
    pub fn control_height(&self) -> f32 {
        let height: f32 = match self.density {
            Density::Compact => 24.0,
            Density::Comfortable => 28.0,
        };
        height.max(self.min_target)
    }

    /// The height of a small (`sm`) button; never under the 24 px hit target.
    pub fn control_height_sm(&self) -> f32 {
        24.0_f32.max(self.min_target)
    }

    /// The height of a list, menu or tree row.
    pub fn row_height(&self) -> f32 {
        let height: f32 = match self.density {
            Density::Compact => 24.0,
            Density::Comfortable => 28.0,
        };
        height.max(self.min_target)
    }

    /// Horizontal padding inside a control.
    pub fn control_padding(&self) -> f32 {
        match self.density {
            Density::Compact => space::MD,
            Density::Comfortable => space::LG,
        }
    }

    pub fn font(&self, role: Text) -> egui::FontId {
        let (size, family) = match role {
            Text::Caption => (11.0, &self.families.text),
            Text::Body => (13.0, &self.families.text),
            Text::Label => (12.0, &self.families.strong),
            Text::Section => (14.0, &self.families.strong),
            Text::Title => (16.0, &self.families.strong),
            Text::Code | Text::Data => (12.0, &self.families.mono),
        };
        egui::FontId::new(size, family.clone())
    }

    fn seconds(&self, s: f32) -> f32 {
        if self.reduce_motion { 0.0 } else { s }
    }
    /// 80 ms: hover.
    pub fn motion_fast(&self) -> f32 {
        self.seconds(0.08)
    }
    /// 120 ms: press, focus, toggles.
    pub fn motion_base(&self) -> f32 {
        self.seconds(0.12)
    }
    /// 160 ms: the tab indicator, popups opening.
    pub fn motion_slow(&self) -> f32 {
        self.seconds(0.16)
    }

    /// The small shadow: popups and menus.
    pub fn shadow_small(&self) -> egui::Shadow {
        egui::Shadow { offset: [0, 2], blur: 8, spread: 0, color: self.colors.shadow }
    }
    /// The medium shadow: windows and dialogs.
    pub fn shadow_medium(&self) -> egui::Shadow {
        egui::Shadow { offset: [0, 6], blur: 20, spread: 0, color: self.colors.shadow }
    }

    /// The frame of a popup, menu or card on `bg.raised`.
    pub fn raised_frame(&self) -> egui::Frame {
        egui::Frame::new()
            .fill(self.colors.bg_raised)
            .stroke(egui::Stroke::new(BORDER, self.colors.border_subtle))
            .corner_radius(radius::CARD)
    }

    /// Write the tokens into `style`: this alone restyles every default egui
    /// widget (rollout step 2's foundation). Fields the theme has no token for
    /// keep the value `style` came with.
    pub fn apply(&self, style: &mut egui::Style) {
        let c = &self.colors;
        style.text_styles = [
            (egui::TextStyle::Small, self.font(Text::Caption)),
            (egui::TextStyle::Body, self.font(Text::Body)),
            (egui::TextStyle::Button, self.font(Text::Body)),
            (egui::TextStyle::Heading, self.font(Text::Title)),
            (egui::TextStyle::Monospace, self.font(Text::Code)),
        ]
        .into();
        style.animation_time = self.motion_base();

        let s = &mut style.spacing;
        let compact = self.density == Density::Compact;
        s.item_spacing = if compact { egui::vec2(space::SM, space::XS) } else { egui::vec2(space::MD, space::SM) };
        s.button_padding = egui::vec2(self.control_padding(), if compact { 3.0 } else { 5.0 });
        s.interact_size = egui::vec2(40.0, self.control_height());
        s.window_margin = egui::Margin::same(space::LG as i8);
        s.menu_margin = egui::Margin::same(space::SM as i8);
        s.indent = space::XL;
        s.icon_width = 16.0;
        s.icon_width_inner = 10.0;
        s.icon_spacing = space::SM;
        s.slider_rail_height = 4.0;
        s.combo_height = 28.0 * 12.0;
        // Solid bars stay (the app's own rule: overflow is visible without
        // hovering); they only get thinner.
        s.scroll.bar_width = 6.0;
        s.scroll.handle_min_length = 24.0;

        let v = &mut style.visuals;
        *v = if self.mode == Mode::Dark { egui::Visuals::dark() } else { egui::Visuals::light() };
        v.panel_fill = c.bg_panel;
        v.window_fill = c.bg_raised;
        v.extreme_bg_color = c.bg_input;
        v.text_edit_bg_color = Some(c.bg_input);
        v.faint_bg_color = over(c.bg_panel, c.hover);
        v.code_bg_color = c.bg_input;
        v.hyperlink_color = c.accent_text;
        v.warn_fg_color = c.warning;
        v.error_fg_color = c.danger;
        v.weak_text_color = Some(c.text_secondary);
        v.window_corner_radius = egui::CornerRadius::same(radius::CARD as u8);
        v.menu_corner_radius = egui::CornerRadius::same(radius::CARD as u8);
        v.window_stroke = egui::Stroke::new(BORDER, c.border_subtle);
        v.window_shadow = self.shadow_medium();
        v.popup_shadow = self.shadow_small();
        // egui writes a selected label's text in `selection.stroke`'s colour
        // on `selection.bg_fill`: the pair the palette tests for 4.5:1.
        v.selection.bg_fill = over(c.bg_panel, c.accent_muted);
        v.selection.stroke = egui::Stroke::new(BORDER, c.accent_text);
        v.text_cursor.stroke = egui::Stroke::new(RING, c.accent_ring);
        v.slider_trailing_fill = true;
        v.handle_shape = egui::style::HandleShape::Circle;
        v.striped = false;

        let button = egui::CornerRadius::same(radius::BUTTON as u8);
        let w = &mut v.widgets;
        // Labels, separators, frames.
        w.noninteractive.bg_fill = c.bg_panel;
        w.noninteractive.weak_bg_fill = c.bg_panel;
        w.noninteractive.bg_stroke = egui::Stroke::new(BORDER, c.border_subtle);
        w.noninteractive.fg_stroke = egui::Stroke::new(BORDER, c.text_primary);
        w.noninteractive.corner_radius = button;
        // A control at rest: the secondary button. `bg_fill` is what egui
        // fills a checkbox's box and a slider's rail and handle with: the
        // input fill, so an unticked box reads as empty.
        w.inactive.bg_fill = c.bg_input;
        w.inactive.weak_bg_fill = c.bg_raised;
        w.inactive.bg_stroke = egui::Stroke::new(BORDER, c.border_strong);
        w.inactive.fg_stroke = egui::Stroke::new(BORDER, c.text_primary);
        w.inactive.corner_radius = button;
        w.inactive.expansion = 0.0;
        w.hovered.bg_fill = over(c.bg_input, c.hover);
        w.hovered.weak_bg_fill = over(c.bg_raised, c.hover);
        w.hovered.bg_stroke = egui::Stroke::new(BORDER, c.border_strong);
        w.hovered.fg_stroke = egui::Stroke::new(BORDER, c.text_primary);
        w.hovered.corner_radius = button;
        w.hovered.expansion = 0.0;
        w.active.bg_fill = over(c.bg_input, c.pressed);
        w.active.weak_bg_fill = over(c.bg_raised, c.pressed);
        w.active.bg_stroke = egui::Stroke::new(BORDER, c.accent_ring);
        w.active.fg_stroke = egui::Stroke::new(BORDER, c.text_primary);
        w.active.corner_radius = button;
        w.active.expansion = 0.0;
        w.open.bg_fill = over(c.bg_raised, c.pressed);
        w.open.weak_bg_fill = over(c.bg_raised, c.pressed);
        w.open.bg_stroke = egui::Stroke::new(BORDER, c.accent_ring);
        w.open.fg_stroke = egui::Stroke::new(BORDER, c.text_primary);
        w.open.corner_radius = button;
        w.open.expansion = 0.0;
    }

    /// `base` with this theme applied.
    pub fn style(&self, base: &egui::Style) -> egui::Style {
        let mut style = base.clone();
        self.apply(&mut style);
        style
    }

    /// The theme the components under `ui` draw with: the one [`set`] stored,
    /// or the default (dark, compact, the proposed accent).
    pub fn of(ui: &egui::Ui) -> Arc<Theme> {
        current(ui.ctx())
    }
}

fn slot() -> egui::Id {
    egui::Id::new("brep-theme")
}

/// Make `theme` the one [`Theme::of`] answers for this context.
pub fn set(ctx: &egui::Context, theme: Arc<Theme>) {
    ctx.data_mut(|d| d.insert_temp(slot(), theme));
}

/// Forget the stored theme.
pub fn clear(ctx: &egui::Context) {
    ctx.data_mut(|d| d.remove::<Arc<Theme>>(slot()));
}

/// The stored theme, if one is stored.
pub fn stored(ctx: &egui::Context) -> Option<Arc<Theme>> {
    ctx.data(|d| d.get_temp::<Arc<Theme>>(slot()))
}

/// The stored theme, or the default.
pub fn current(ctx: &egui::Context) -> Arc<Theme> {
    stored(ctx).unwrap_or_default()
}

/// What the app's installed style was built from: the three Appearance
/// settings. The styles of both modes are rewritten only when this changes.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Installed {
    accent: Color32,
    density: Density,
    reduce_motion: bool,
    min_target: f32,
}

/// The spacing and text sizes of a style before the theme was installed.
///
/// COMPACT density keeps them for widgets that are still plain egui: compact is
/// "as dense as the app was", so an unconverted panel keeps its layout (and the
/// scripts that pin it keep passing) while it takes the theme's colours, radii
/// and fonts. A panel gets the 24 px token metrics when it is converted to
/// `ui_kit` controls, which size from [`Theme::control_height`]. COMFORTABLE
/// applies the token metrics to everything.
#[derive(Debug, Clone)]
struct ClassicMetrics {
    spacing: egui::style::Spacing,
    text_sizes: Vec<(egui::TextStyle, f32)>,
    /// For the widths that take part in layout: strokes and expansions.
    visuals: egui::Visuals,
    /// egui's own animations (a window opening, a list scrolling to a row)
    /// keep their pace: a longer one leaves a dialog moving for more frames,
    /// and scripts that click a row as soon as it is published then miss it.
    animation_time: f32,
}

impl ClassicMetrics {
    fn restore(&self, style: &mut egui::Style) {
        style.spacing = self.spacing.clone();
        for (text_style, size) in &self.text_sizes {
            if let Some(font) = style.text_styles.get_mut(text_style) {
                font.size = *size;
            }
        }
        let (v, classic) = (&mut style.visuals, &self.visuals);
        v.window_stroke.width = classic.window_stroke.width;
        v.selection.stroke.width = classic.selection.stroke.width;
        v.text_cursor.stroke.width = classic.text_cursor.stroke.width;
        v.handle_shape = classic.handle_shape;
        let states = |w: &mut egui::style::Widgets, c: &egui::style::Widgets| {
            for (state, classic) in [(&mut w.noninteractive, &c.noninteractive), (&mut w.inactive, &c.inactive), (&mut w.hovered, &c.hovered), (&mut w.active, &c.active), (&mut w.open, &c.open)] {
                state.bg_stroke.width = classic.bg_stroke.width;
                state.fg_stroke.width = classic.fg_stroke.width;
                state.expansion = classic.expansion;
            }
        };
        states(&mut v.widgets, &classic.widgets);
    }
}

/// Make the Appearance settings the app's style (rollout step 2): write the
/// tokens into the context's dark and light styles when a setting changed, and
/// store the theme of the mode now showing for the `ui_kit` components. Called
/// once per frame, before any panel draws; a frame with nothing changed only
/// compares three values.
pub fn install(ctx: &egui::Context, settings: &brep_render::style::RenderSettings) {
    let want = Installed {
        accent: accent(settings.ui_accent).unwrap_or(ACCENTS[0]).color,
        density: match settings.ui_density {
            brep_render::style::UiDensity::Compact => Density::Compact,
            brep_render::style::UiDensity::Comfortable => Density::Comfortable,
        },
        reduce_motion: settings.reduce_motion,
        min_target: crate::viewport::touch::target_size(ctx, egui::Vec2::ZERO).y,
    };
    let key = egui::Id::new("brep-theme-installed");
    let mode = if ctx.theme() == egui::Theme::Dark { Mode::Dark } else { Mode::Light };
    let build = |mode| Theme::new(mode, want.density, want.accent).with_reduce_motion(want.reduce_motion).with_min_target(want.min_target);
    if ctx.data(|d| d.get_temp::<Installed>(key)) != Some(want) {
        for (egui_theme, mode) in [(egui::Theme::Dark, Mode::Dark), (egui::Theme::Light, Mode::Light)] {
            let theme = build(mode);
            // The metrics the app had before the theme, kept from the first install.
            let classic_key = egui::Id::new(("brep-theme-classic-metrics", mode == Mode::Dark));
            let classic = ctx.data(|d| d.get_temp::<ClassicMetrics>(classic_key)).unwrap_or_else(|| {
                let style = ctx.style_of(egui_theme);
                let classic = ClassicMetrics { spacing: style.spacing.clone(), text_sizes: style.text_styles.iter().map(|(k, font)| (k.clone(), font.size)).collect(), visuals: style.visuals.clone(), animation_time: style.animation_time };
                ctx.data_mut(|d| d.insert_temp(classic_key, classic.clone()));
                classic
            });
            ctx.style_mut_of(egui_theme, |style| {
                theme.apply(style);
                if want.density == Density::Compact {
                    classic.restore(style);
                }
                if !want.reduce_motion {
                    style.animation_time = classic.animation_time;
                }
            });
        }
        ctx.data_mut(|d| {
            d.insert_temp(key, want);
            // The touch layer keeps a copy of each mode's mouse spacing
            // (`viewport::touch`); it is out of date now.
            for egui_theme in [egui::Theme::Dark, egui::Theme::Light] {
                d.remove::<egui::style::Spacing>(egui::Id::new(("brep-touch-desktop-spacing", format!("{egui_theme:?}"))));
            }
        });
        set(ctx, Arc::new(build(mode)));
    } else if stored(ctx).is_none_or(|theme| theme.mode != mode) {
        set(ctx, Arc::new(build(mode)));
    }
}

/// The control metrics the top toolbar and the status bar were laid out with
/// before the theme (`ClassicMetrics`, whatever the density). The shell
/// draws those two bars with them until the chrome migration (rollout step 4)
/// gives them token metrics: their heights place the 3D view, and every script
/// that clicks in the view pins that rectangle. Colours, radii and fonts are
/// the theme's. On a touch browser the touch layer's sizes are left alone.
pub fn classic_bar_metrics(ctx: &egui::Context, style: &mut egui::Style) {
    if crate::viewport::touch::enabled(ctx) {
        return;
    }
    let dark = ctx.theme() == egui::Theme::Dark;
    if let Some(classic) = ctx.data(|d| d.get_temp::<ClassicMetrics>(egui::Id::new(("brep-theme-classic-metrics", dark)))) {
        classic.restore(style);
    }
}