Skip to main content

brep_app/
theme.rs

1//! Theme tokens: the one place a colour, size, radius, shadow or duration of
2//! the refreshed UI is written (section 3).
3//!
4//! STATUS: rollout step 1. Nothing in the app reads these tokens except the
5//! developer gallery ([`crate::ui_kit::gallery`]) and its whole-app PREVIEW,
6//! which is off unless the gallery turns it on. With the gallery closed and the
7//! preview off the app makes no call into this module.
8//!
9//! A [`Theme`](crate::theme::Theme) is built per mode (dark, light), density (compact, comfortable)
10//! and accent. [`Theme::apply`](crate::theme::Theme::apply) writes it into an `egui::Style`, which restyles
11//! every default egui widget; the [`crate::ui_kit`] components read the tokens
12//! directly through [`Theme::of`](crate::theme::Theme::of).
13use eframe::egui::{self, Color32};
14use std::sync::Arc;
15
16/// Dark or light chrome. The 3D viewport's colours are render settings and are
17/// not part of the theme.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19pub enum Mode {
20    Dark,
21    Light,
22}
23
24impl Mode {
25    pub fn of(dark: bool) -> Self {
26        if dark { Mode::Dark } else { Mode::Light }
27    }
28    pub fn label(self) -> &'static str {
29        match self {
30            Mode::Dark => "Dark",
31            Mode::Light => "Light",
32        }
33    }
34}
35
36/// Control heights and spacing. Compact is the proposed default (spec section 2).
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38pub enum Density {
39    Compact,
40    Comfortable,
41}
42
43impl Density {
44    pub fn label(self) -> &'static str {
45        match self {
46            Density::Compact => "Compact",
47            Density::Comfortable => "Comfortable",
48        }
49    }
50}
51
52/// One accent the owner can choose between (spec section 9, decision 2).
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct Accent {
55    /// The key a command names it by.
56    pub key: &'static str,
57    pub label: &'static str,
58    pub color: Color32,
59}
60
61/// The accent candidates. The first is the spec's proposal.
62pub const ACCENTS: &[Accent] = &[
63    Accent { key: "blue", label: "Blue #3d8bfd (proposed)", color: Color32::from_rgb(0x3d, 0x8b, 0xfd) },
64    Accent { key: "brand", label: "Help-site blue #0b6bcb", color: Color32::from_rgb(0x0b, 0x6b, 0xcb) },
65    Accent { key: "teal", label: "Teal #14b8a6", color: Color32::from_rgb(0x14, 0xb8, 0xa6) },
66    Accent { key: "violet", label: "Violet #8b5cf6", color: Color32::from_rgb(0x8b, 0x5c, 0xf6) },
67    Accent { key: "orange", label: "Orange #f08c2e", color: Color32::from_rgb(0xf0, 0x8c, 0x2e) },
68    Accent { key: "green", label: "Green #2fb170", color: Color32::from_rgb(0x2f, 0xb1, 0x70) },
69];
70
71/// The accent with this key.
72pub fn accent(key: &str) -> Option<Accent> {
73    ACCENTS.iter().copied().find(|a| a.key == key)
74}
75
76/// The colour roles (spec section 3). Every colour is opaque except the three
77/// overlays, which are laid over whatever surface the control sits on.
78#[derive(Debug, Clone, Copy, PartialEq)]
79pub struct Palette {
80    /// The window background behind panels.
81    pub bg_app: Color32,
82    /// Panel surfaces.
83    pub bg_panel: Color32,
84    /// Cards, popups, menus.
85    pub bg_raised: Color32,
86    /// Text and number field fill.
87    pub bg_input: Color32,
88    /// Hover overlay (translucent).
89    pub hover: Color32,
90    /// Pressed overlay (translucent).
91    pub pressed: Color32,
92    /// Card and panel borders.
93    pub border_subtle: Color32,
94    /// Input borders.
95    pub border_strong: Color32,
96    /// The accent as chosen: focus rings, underlines, check marks, sliders.
97    pub accent: Color32,
98    /// The accent as a FILL under [`Palette::on_accent`] text: the accent
99    /// itself when white text reads on it at 4.5:1, else darkened until it does.
100    pub accent_fill: Color32,
101    /// The accent as TEXT on this mode's surfaces (4.5:1 on every one of them
102    /// and on [`Palette::accent_muted`] over them).
103    pub accent_text: Color32,
104    /// The accent as a focus RING or 2 px bar: 3:1 on every surface.
105    pub accent_ring: Color32,
106    /// Selected rows, active tab background (translucent: accent at 18 %).
107    /// Text on it is `text.primary` or `accent.text`, never `text.secondary`.
108    pub accent_muted: Color32,
109    /// Text on [`Palette::accent_fill`] and on the filled danger button.
110    pub on_accent: Color32,
111    pub text_primary: Color32,
112    pub text_secondary: Color32,
113    /// Disabled text. Exempt from the contrast rule (WCAG 1.4.3).
114    pub text_disabled: Color32,
115    pub danger: Color32,
116    /// The danger colour as a fill under [`Palette::on_accent`] text.
117    pub danger_fill: Color32,
118    pub warning: Color32,
119    pub success: Color32,
120    /// Informational text and marks: a blue that reads 4.5:1 on every
121    /// surface of the mode, whatever accent the user chose.
122    pub info: Color32,
123    /// Popup and window shadow colour (translucent).
124    pub shadow: Color32,
125}
126
127const fn rgb(hex: u32) -> Color32 {
128    Color32::from_rgb((hex >> 16) as u8, (hex >> 8) as u8, hex as u8)
129}
130
131/// WCAG relative luminance of an opaque colour.
132pub fn luminance(c: Color32) -> f32 {
133    let f = |v: u8| {
134        let v = f32::from(v) / 255.0;
135        if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
136    };
137    0.2126 * f(c.r()) + 0.7152 * f(c.g()) + 0.0722 * f(c.b())
138}
139
140/// WCAG contrast ratio of two opaque colours (1 to 21).
141pub fn contrast(a: Color32, b: Color32) -> f32 {
142    let (la, lb) = (luminance(a), luminance(b));
143    (la.max(lb) + 0.05) / (la.min(lb) + 0.05)
144}
145
146/// `top` laid over the opaque `base` at `top`'s own alpha.
147pub fn over(base: Color32, top: Color32) -> Color32 {
148    let [r, g, b, a] = top.to_srgba_unmultiplied();
149    mix(base, Color32::from_rgb(r, g, b), f32::from(a) / 255.0)
150}
151
152/// `a` moved `t` of the way to `b` (both opaque).
153pub fn mix(a: Color32, b: Color32, t: f32) -> Color32 {
154    let ch = |x: u8, y: u8| (f32::from(x) * (1.0 - t) + f32::from(y) * t).round() as u8;
155    Color32::from_rgb(ch(a.r(), b.r()), ch(a.g(), b.g()), ch(a.b(), b.b()))
156}
157
158fn alpha(c: Color32, a: f32) -> Color32 {
159    Color32::from_rgba_unmultiplied(c.r(), c.g(), c.b(), (a * 255.0).round() as u8)
160}
161
162/// `color` moved towards `toward` in 2 % steps until `ok` accepts it.
163/// Returns `toward` if nothing less does.
164fn moved_until(color: Color32, toward: Color32, ok: impl Fn(Color32) -> bool) -> Color32 {
165    (0..=50).map(|step| mix(color, toward, step as f32 * 0.02)).find(|c| ok(*c)).unwrap_or(toward)
166}
167
168impl Palette {
169    pub fn new(mode: Mode, accent: Color32) -> Self {
170        let white = Color32::WHITE;
171        let black = Color32::BLACK;
172        let mut p = match mode {
173            Mode::Dark => Palette {
174                bg_app: rgb(0x0f151c),
175                bg_panel: rgb(0x151d26),
176                bg_raised: rgb(0x1b2531),
177                bg_input: rgb(0x0f151c),
178                hover: alpha(white, 0.06),
179                pressed: alpha(white, 0.10),
180                border_subtle: rgb(0x263241),
181                border_strong: rgb(0x334255),
182                accent,
183                accent_fill: accent,
184                accent_text: accent,
185                accent_ring: accent,
186                accent_muted: alpha(accent, 0.18),
187                on_accent: white,
188                text_primary: rgb(0xe6edf3),
189                text_secondary: rgb(0x9fb0c0),
190                text_disabled: rgb(0x5c6b7a),
191                // The spec's #f05252 reads 4.45:1 on bg.raised; one step lighter passes.
192                danger: rgb(0xf26464),
193                danger_fill: rgb(0xf05252),
194                warning: rgb(0xf5a524),
195                success: rgb(0x3fb950),
196                info: ACCENTS[0].color,
197                shadow: alpha(black, 0.45),
198            },
199            Mode::Light => Palette {
200                bg_app: rgb(0xe9edf2),
201                bg_panel: rgb(0xf4f6f9),
202                bg_raised: rgb(0xffffff),
203                bg_input: rgb(0xffffff),
204                hover: alpha(black, 0.05),
205                pressed: alpha(black, 0.09),
206                border_subtle: rgb(0xd3dae3),
207                border_strong: rgb(0xaeb9c6),
208                accent,
209                accent_fill: accent,
210                accent_text: accent,
211                accent_ring: accent,
212                accent_muted: alpha(accent, 0.18),
213                on_accent: white,
214                text_primary: rgb(0x17212b),
215                text_secondary: rgb(0x4a5868),
216                text_disabled: rgb(0x8d99a6),
217                danger: rgb(0xc62828),
218                danger_fill: rgb(0xc62828),
219                warning: rgb(0x8f5d00),
220                success: rgb(0x177332),
221                info: ACCENTS[0].color,
222                shadow: alpha(black, 0.18),
223            },
224        };
225        // The accent's derived forms. The accent the owner picks stays the hue;
226        // each use moves it only as far as its contrast rule needs.
227        let surfaces = [p.bg_app, p.bg_panel, p.bg_raised, p.bg_input];
228        let away = if mode == Mode::Dark { white } else { black };
229        let (hover, pressed, muted) = (p.hover, p.pressed, p.accent_muted);
230        // A fill carries white text; hovered and pressed it only gets darker
231        // ([`Palette::fill_hover`], [`Palette::fill_pressed`]).
232        let carries_white = |fill: Color32| contrast(white, fill) >= 4.5;
233        p.accent_fill = moved_until(accent, black, carries_white);
234        p.danger_fill = moved_until(p.danger_fill, black, carries_white);
235        p.accent_ring = moved_until(accent, away, |c| surfaces.iter().all(|bg| contrast(c, *bg) >= 3.0));
236        // Accent text reads on every surface at rest, hovered, pressed and selected.
237        let states: Vec<Color32> = surfaces
238            .iter()
239            .flat_map(|s| [*s, over(*s, hover), over(*s, pressed), over(*s, muted), over(over(*s, muted), hover)])
240            .collect();
241        p.accent_text = moved_until(accent, away, |c| states.iter().all(|bg| contrast(c, *bg) >= 4.5));
242        p.info = moved_until(ACCENTS[0].color, away, |c| states.iter().all(|bg| contrast(c, *bg) >= 4.5));
243        p
244    }
245
246    /// A filled button's fill while hovered: 8 % towards black, in both
247    /// modes, so its white text never loses contrast.
248    pub fn fill_hover(fill: Color32) -> Color32 {
249        mix(fill, Color32::BLACK, 0.08)
250    }
251
252    /// A filled button's fill while pressed: 16 % towards black.
253    pub fn fill_pressed(fill: Color32) -> Color32 {
254        mix(fill, Color32::BLACK, 0.16)
255    }
256}
257
258/// The 4 px spacing scale (spec section 3).
259pub mod space {
260    pub const XXS: f32 = 2.0;
261    pub const XS: f32 = 4.0;
262    pub const SM: f32 = 6.0;
263    pub const MD: f32 = 8.0;
264    pub const LG: f32 = 12.0;
265    pub const XL: f32 = 16.0;
266    pub const XXL: f32 = 24.0;
267    pub const XXXL: f32 = 32.0;
268}
269
270/// Corner radii (spec section 3).
271pub mod radius {
272    /// Inputs and small buttons.
273    pub const INPUT: f32 = 4.0;
274    /// Buttons and tabs.
275    pub const BUTTON: f32 = 6.0;
276    /// Cards and popups.
277    pub const CARD: f32 = 8.0;
278}
279
280/// Every border is 1 px; a focus ring or an active bar is 2 px.
281pub const BORDER: f32 = 1.0;
282pub const RING: f32 = 2.0;
283
284/// The type scale (spec section 4).
285#[derive(Debug, Clone, Copy, PartialEq, Eq)]
286pub enum Text {
287    /// 11: captions, group labels, error messages.
288    Caption,
289    /// 13: body text and control text.
290    Body,
291    /// 12 semibold: field labels.
292    Label,
293    /// 14 semibold: section headers.
294    Section,
295    /// 16 semibold: panel and dialog titles.
296    Title,
297    /// 12 monospace: code, the console.
298    Code,
299    /// 12 monospace: tree, table and list rows (owner 2026-11-28: these
300    /// widgets need same-width characters so their columns line up, whichever
301    /// UI font is chosen).
302    Data,
303}
304
305/// The font families the theme draws with. The default is egui's own three, so
306/// a theme can always be drawn; [`install`] names the UI font's families (Inter,
307/// `crate::fonts`) for `text` and `strong` in a context that has them bound.
308#[derive(Debug, Clone, PartialEq, Eq)]
309pub struct Families {
310    pub text: egui::FontFamily,
311    /// The semibold face; the regular one where there is no semibold.
312    pub strong: egui::FontFamily,
313    pub mono: egui::FontFamily,
314}
315
316impl Default for Families {
317    fn default() -> Self {
318        Self {
319            text: egui::FontFamily::Proportional,
320            strong: egui::FontFamily::Proportional,
321            mono: egui::FontFamily::Monospace,
322        }
323    }
324}
325
326/// One theme: every token a component or the base egui style needs.
327#[derive(Debug, Clone, PartialEq)]
328pub struct Theme {
329    pub mode: Mode,
330    pub density: Density,
331    pub colors: Palette,
332    pub families: Families,
333    /// Turns every transition off.
334    pub reduce_motion: bool,
335    /// The smallest height a control or row may have: 0 with a mouse, the
336    /// touch target on a touch browser ([`install`] sets it), so `ui_kit`
337    /// controls grow there without their callers asking.
338    pub min_target: f32,
339}
340
341impl Default for Theme {
342    fn default() -> Self {
343        Theme::new(Mode::Dark, Density::Compact, ACCENTS[0].color)
344    }
345}
346
347impl Theme {
348    pub fn new(mode: Mode, density: Density, accent: Color32) -> Self {
349        Theme { mode, density, colors: Palette::new(mode, accent), families: Families::default(), reduce_motion: false, min_target: 0.0 }
350    }
351
352    pub fn with_families(mut self, families: Families) -> Self {
353        self.families = families;
354        self
355    }
356
357    pub fn with_min_target(mut self, min_target: f32) -> Self {
358        self.min_target = min_target;
359        self
360    }
361
362    pub fn with_reduce_motion(mut self, reduce: bool) -> Self {
363        self.reduce_motion = reduce;
364        self
365    }
366
367    /// The height of inputs, buttons and dropdowns: 24 compact, 28 comfortable.
368    pub fn control_height(&self) -> f32 {
369        let height: f32 = match self.density {
370            Density::Compact => 24.0,
371            Density::Comfortable => 28.0,
372        };
373        height.max(self.min_target)
374    }
375
376    /// The height of a small (`sm`) button; never under the 24 px hit target.
377    pub fn control_height_sm(&self) -> f32 {
378        24.0_f32.max(self.min_target)
379    }
380
381    /// The height of a list, menu or tree row.
382    pub fn row_height(&self) -> f32 {
383        let height: f32 = match self.density {
384            Density::Compact => 24.0,
385            Density::Comfortable => 28.0,
386        };
387        height.max(self.min_target)
388    }
389
390    /// Horizontal padding inside a control.
391    pub fn control_padding(&self) -> f32 {
392        match self.density {
393            Density::Compact => space::MD,
394            Density::Comfortable => space::LG,
395        }
396    }
397
398    pub fn font(&self, role: Text) -> egui::FontId {
399        let (size, family) = match role {
400            Text::Caption => (11.0, &self.families.text),
401            Text::Body => (13.0, &self.families.text),
402            Text::Label => (12.0, &self.families.strong),
403            Text::Section => (14.0, &self.families.strong),
404            Text::Title => (16.0, &self.families.strong),
405            Text::Code | Text::Data => (12.0, &self.families.mono),
406        };
407        egui::FontId::new(size, family.clone())
408    }
409
410    fn seconds(&self, s: f32) -> f32 {
411        if self.reduce_motion { 0.0 } else { s }
412    }
413    /// 80 ms: hover.
414    pub fn motion_fast(&self) -> f32 {
415        self.seconds(0.08)
416    }
417    /// 120 ms: press, focus, toggles.
418    pub fn motion_base(&self) -> f32 {
419        self.seconds(0.12)
420    }
421    /// 160 ms: the tab indicator, popups opening.
422    pub fn motion_slow(&self) -> f32 {
423        self.seconds(0.16)
424    }
425
426    /// The small shadow: popups and menus.
427    pub fn shadow_small(&self) -> egui::Shadow {
428        egui::Shadow { offset: [0, 2], blur: 8, spread: 0, color: self.colors.shadow }
429    }
430    /// The medium shadow: windows and dialogs.
431    pub fn shadow_medium(&self) -> egui::Shadow {
432        egui::Shadow { offset: [0, 6], blur: 20, spread: 0, color: self.colors.shadow }
433    }
434
435    /// The frame of a popup, menu or card on `bg.raised`.
436    pub fn raised_frame(&self) -> egui::Frame {
437        egui::Frame::new()
438            .fill(self.colors.bg_raised)
439            .stroke(egui::Stroke::new(BORDER, self.colors.border_subtle))
440            .corner_radius(radius::CARD)
441    }
442
443    /// Write the tokens into `style`: this alone restyles every default egui
444    /// widget (rollout step 2's foundation). Fields the theme has no token for
445    /// keep the value `style` came with.
446    pub fn apply(&self, style: &mut egui::Style) {
447        let c = &self.colors;
448        style.text_styles = [
449            (egui::TextStyle::Small, self.font(Text::Caption)),
450            (egui::TextStyle::Body, self.font(Text::Body)),
451            (egui::TextStyle::Button, self.font(Text::Body)),
452            (egui::TextStyle::Heading, self.font(Text::Title)),
453            (egui::TextStyle::Monospace, self.font(Text::Code)),
454        ]
455        .into();
456        style.animation_time = self.motion_base();
457
458        let s = &mut style.spacing;
459        let compact = self.density == Density::Compact;
460        s.item_spacing = if compact { egui::vec2(space::SM, space::XS) } else { egui::vec2(space::MD, space::SM) };
461        s.button_padding = egui::vec2(self.control_padding(), if compact { 3.0 } else { 5.0 });
462        s.interact_size = egui::vec2(40.0, self.control_height());
463        s.window_margin = egui::Margin::same(space::LG as i8);
464        s.menu_margin = egui::Margin::same(space::SM as i8);
465        s.indent = space::XL;
466        s.icon_width = 16.0;
467        s.icon_width_inner = 10.0;
468        s.icon_spacing = space::SM;
469        s.slider_rail_height = 4.0;
470        s.combo_height = 28.0 * 12.0;
471        // Solid bars stay (the app's own rule: overflow is visible without
472        // hovering); they only get thinner.
473        s.scroll.bar_width = 6.0;
474        s.scroll.handle_min_length = 24.0;
475
476        let v = &mut style.visuals;
477        *v = if self.mode == Mode::Dark { egui::Visuals::dark() } else { egui::Visuals::light() };
478        v.panel_fill = c.bg_panel;
479        v.window_fill = c.bg_raised;
480        v.extreme_bg_color = c.bg_input;
481        v.text_edit_bg_color = Some(c.bg_input);
482        v.faint_bg_color = over(c.bg_panel, c.hover);
483        v.code_bg_color = c.bg_input;
484        v.hyperlink_color = c.accent_text;
485        v.warn_fg_color = c.warning;
486        v.error_fg_color = c.danger;
487        v.weak_text_color = Some(c.text_secondary);
488        v.window_corner_radius = egui::CornerRadius::same(radius::CARD as u8);
489        v.menu_corner_radius = egui::CornerRadius::same(radius::CARD as u8);
490        v.window_stroke = egui::Stroke::new(BORDER, c.border_subtle);
491        v.window_shadow = self.shadow_medium();
492        v.popup_shadow = self.shadow_small();
493        // egui writes a selected label's text in `selection.stroke`'s colour
494        // on `selection.bg_fill`: the pair the palette tests for 4.5:1.
495        v.selection.bg_fill = over(c.bg_panel, c.accent_muted);
496        v.selection.stroke = egui::Stroke::new(BORDER, c.accent_text);
497        v.text_cursor.stroke = egui::Stroke::new(RING, c.accent_ring);
498        v.slider_trailing_fill = true;
499        v.handle_shape = egui::style::HandleShape::Circle;
500        v.striped = false;
501
502        let button = egui::CornerRadius::same(radius::BUTTON as u8);
503        let w = &mut v.widgets;
504        // Labels, separators, frames.
505        w.noninteractive.bg_fill = c.bg_panel;
506        w.noninteractive.weak_bg_fill = c.bg_panel;
507        w.noninteractive.bg_stroke = egui::Stroke::new(BORDER, c.border_subtle);
508        w.noninteractive.fg_stroke = egui::Stroke::new(BORDER, c.text_primary);
509        w.noninteractive.corner_radius = button;
510        // A control at rest: the secondary button. `bg_fill` is what egui
511        // fills a checkbox's box and a slider's rail and handle with: the
512        // input fill, so an unticked box reads as empty.
513        w.inactive.bg_fill = c.bg_input;
514        w.inactive.weak_bg_fill = c.bg_raised;
515        w.inactive.bg_stroke = egui::Stroke::new(BORDER, c.border_strong);
516        w.inactive.fg_stroke = egui::Stroke::new(BORDER, c.text_primary);
517        w.inactive.corner_radius = button;
518        w.inactive.expansion = 0.0;
519        w.hovered.bg_fill = over(c.bg_input, c.hover);
520        w.hovered.weak_bg_fill = over(c.bg_raised, c.hover);
521        w.hovered.bg_stroke = egui::Stroke::new(BORDER, c.border_strong);
522        w.hovered.fg_stroke = egui::Stroke::new(BORDER, c.text_primary);
523        w.hovered.corner_radius = button;
524        w.hovered.expansion = 0.0;
525        w.active.bg_fill = over(c.bg_input, c.pressed);
526        w.active.weak_bg_fill = over(c.bg_raised, c.pressed);
527        w.active.bg_stroke = egui::Stroke::new(BORDER, c.accent_ring);
528        w.active.fg_stroke = egui::Stroke::new(BORDER, c.text_primary);
529        w.active.corner_radius = button;
530        w.active.expansion = 0.0;
531        w.open.bg_fill = over(c.bg_raised, c.pressed);
532        w.open.weak_bg_fill = over(c.bg_raised, c.pressed);
533        w.open.bg_stroke = egui::Stroke::new(BORDER, c.accent_ring);
534        w.open.fg_stroke = egui::Stroke::new(BORDER, c.text_primary);
535        w.open.corner_radius = button;
536        w.open.expansion = 0.0;
537    }
538
539    /// `base` with this theme applied.
540    pub fn style(&self, base: &egui::Style) -> egui::Style {
541        let mut style = base.clone();
542        self.apply(&mut style);
543        style
544    }
545
546    /// The theme the components under `ui` draw with: the one [`set`] stored,
547    /// or the default (dark, compact, the proposed accent).
548    pub fn of(ui: &egui::Ui) -> Arc<Theme> {
549        current(ui.ctx())
550    }
551}
552
553fn slot() -> egui::Id {
554    egui::Id::new("brep-theme")
555}
556
557/// Make `theme` the one [`Theme::of`] answers for this context.
558pub fn set(ctx: &egui::Context, theme: Arc<Theme>) {
559    ctx.data_mut(|d| d.insert_temp(slot(), theme));
560}
561
562/// Forget the stored theme.
563pub fn clear(ctx: &egui::Context) {
564    ctx.data_mut(|d| d.remove::<Arc<Theme>>(slot()));
565}
566
567/// The stored theme, if one is stored.
568pub fn stored(ctx: &egui::Context) -> Option<Arc<Theme>> {
569    ctx.data(|d| d.get_temp::<Arc<Theme>>(slot()))
570}
571
572/// The stored theme, or the default.
573pub fn current(ctx: &egui::Context) -> Arc<Theme> {
574    stored(ctx).unwrap_or_default()
575}
576
577/// What the app's installed style was built from: the three Appearance
578/// settings. The styles of both modes are rewritten only when this changes.
579#[derive(Debug, Clone, Copy, PartialEq)]
580struct Installed {
581    accent: Color32,
582    density: Density,
583    reduce_motion: bool,
584    min_target: f32,
585    /// Whether the UI font (Inter) is bound in the context (`fonts::install`).
586    ui_font: bool,
587}
588
589/// The spacing and text sizes of a style before the theme was installed.
590///
591/// COMPACT density keeps them for widgets that are still plain egui: compact is
592/// "as dense as the app was", so an unconverted panel keeps its layout (and the
593/// scripts that pin it keep passing) while it takes the theme's colours, radii
594/// and fonts. A panel gets the 24 px token metrics when it is converted to
595/// `ui_kit` controls, which size from [`Theme::control_height`]. COMFORTABLE
596/// applies the token metrics to everything.
597#[derive(Debug, Clone)]
598struct ClassicMetrics {
599    spacing: egui::style::Spacing,
600    text_sizes: Vec<(egui::TextStyle, f32)>,
601    /// For the widths that take part in layout: strokes and expansions.
602    visuals: egui::Visuals,
603    /// egui's own animations (a window opening, a list scrolling to a row)
604    /// keep their pace: a longer one leaves a dialog moving for more frames,
605    /// and scripts that click a row as soon as it is published then miss it.
606    animation_time: f32,
607}
608
609impl ClassicMetrics {
610    fn restore(&self, style: &mut egui::Style) {
611        style.spacing = self.spacing.clone();
612        for (text_style, size) in &self.text_sizes {
613            if let Some(font) = style.text_styles.get_mut(text_style) {
614                font.size = *size;
615            }
616        }
617        let (v, classic) = (&mut style.visuals, &self.visuals);
618        v.window_stroke.width = classic.window_stroke.width;
619        v.selection.stroke.width = classic.selection.stroke.width;
620        v.text_cursor.stroke.width = classic.text_cursor.stroke.width;
621        v.handle_shape = classic.handle_shape;
622        let states = |w: &mut egui::style::Widgets, c: &egui::style::Widgets| {
623            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)] {
624                state.bg_stroke.width = classic.bg_stroke.width;
625                state.fg_stroke.width = classic.fg_stroke.width;
626                state.expansion = classic.expansion;
627            }
628        };
629        states(&mut v.widgets, &classic.widgets);
630    }
631}
632
633/// Make the Appearance settings the app's style (rollout step 2): write the
634/// tokens into the context's dark and light styles when a setting changed, and
635/// store the theme of the mode now showing for the `ui_kit` components. Called
636/// once per frame, before any panel draws; a frame with nothing changed only
637/// compares three values.
638pub fn install(ctx: &egui::Context, settings: &brep_render::style::RenderSettings) {
639    let want = Installed {
640        accent: accent(settings.ui_accent).unwrap_or(ACCENTS[0]).color,
641        density: match settings.ui_density {
642            brep_render::style::UiDensity::Compact => Density::Compact,
643            brep_render::style::UiDensity::Comfortable => Density::Comfortable,
644        },
645        reduce_motion: settings.reduce_motion,
646        min_target: crate::viewport::touch::target_size(ctx, egui::Vec2::ZERO).y,
647        ui_font: matches!(crate::fonts::families(ctx).0, egui::FontFamily::Name(_)),
648    };
649    let (text, strong) = crate::fonts::families(ctx);
650    let families = Families { text, strong, mono: egui::FontFamily::Monospace };
651    let key = egui::Id::new("brep-theme-installed");
652    let mode = if ctx.theme() == egui::Theme::Dark { Mode::Dark } else { Mode::Light };
653    let build = |mode| Theme::new(mode, want.density, want.accent).with_families(families.clone()).with_reduce_motion(want.reduce_motion).with_min_target(want.min_target);
654    if ctx.data(|d| d.get_temp::<Installed>(key)) != Some(want) {
655        for (egui_theme, mode) in [(egui::Theme::Dark, Mode::Dark), (egui::Theme::Light, Mode::Light)] {
656            let theme = build(mode);
657            // The metrics the app had before the theme, kept from the first install.
658            let classic_key = egui::Id::new(("brep-theme-classic-metrics", mode == Mode::Dark));
659            let classic = ctx.data(|d| d.get_temp::<ClassicMetrics>(classic_key)).unwrap_or_else(|| {
660                let style = ctx.style_of(egui_theme);
661                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 };
662                ctx.data_mut(|d| d.insert_temp(classic_key, classic.clone()));
663                classic
664            });
665            ctx.style_mut_of(egui_theme, |style| {
666                theme.apply(style);
667                if want.density == Density::Compact {
668                    classic.restore(style);
669                }
670                if !want.reduce_motion {
671                    style.animation_time = classic.animation_time;
672                }
673                number_text(style);
674            });
675        }
676        ctx.data_mut(|d| {
677            d.insert_temp(key, want);
678            // The touch layer keeps a copy of each mode's mouse spacing
679            // (`viewport::touch`); it is out of date now.
680            for egui_theme in [egui::Theme::Dark, egui::Theme::Light] {
681                d.remove::<egui::style::Spacing>(egui::Id::new(("brep-touch-desktop-spacing", format!("{egui_theme:?}"))));
682            }
683        });
684        set(ctx, Arc::new(build(mode)));
685    } else if stored(ctx).is_none_or(|theme| theme.mode != mode) {
686        set(ctx, Arc::new(build(mode)));
687    }
688}
689
690/// The text style of egui's own number fields (`DragValue`, a slider's value):
691/// the monospace family at the size of button text, so digits line up and a
692/// field is as wide as it was before the interface font was proportional.
693pub const NUMBER_TEXT: &str = "brep-number";
694
695fn number_text(style: &mut egui::Style) {
696    let size = style.text_styles.get(&egui::TextStyle::Button).map_or(13.0, |font| font.size);
697    let number = egui::TextStyle::Name(NUMBER_TEXT.into());
698    style.text_styles.insert(number.clone(), egui::FontId::new(size, egui::FontFamily::Monospace));
699    style.drag_value_text_style = number;
700}
701
702/// The text of one tree, table or list row that is still a plain egui widget,
703/// in the monospace family at the size the widget's style gives it (owner
704/// 2026-11-28: those widgets need same-width characters, whatever the UI
705/// font). `ui_kit` rows use [`Text::Data`] and need neither this nor
706/// [`data_rows`].
707pub fn data(text: impl Into<String>) -> egui::RichText {
708    egui::RichText::new(text).family(egui::FontFamily::Monospace)
709}
710
711/// [`data`] for everything a scope draws: the plain egui text under `ui`
712/// (labels, selectable rows, grid cells) in the monospace family, at the sizes
713/// it had. For a table or list whose cells are many separate widgets.
714pub fn data_rows(ui: &mut egui::Ui) {
715    for font in ui.style_mut().text_styles.values_mut() {
716        font.family = egui::FontFamily::Monospace;
717    }
718}
719
720/// The control metrics the top toolbar and the status bar were laid out with
721/// before the theme (`ClassicMetrics`, whatever the density). The shell
722/// draws those two bars with them until the chrome migration (rollout step 4)
723/// gives them token metrics: their heights place the 3D view, and every script
724/// that clicks in the view pins that rectangle. Colours, radii and fonts are
725/// the theme's. On a touch browser the touch layer's sizes are left alone.
726pub fn classic_bar_metrics(ctx: &egui::Context, style: &mut egui::Style) {
727    if crate::viewport::touch::enabled(ctx) {
728        return;
729    }
730    let dark = ctx.theme() == egui::Theme::Dark;
731    if let Some(classic) = ctx.data(|d| d.get_temp::<ClassicMetrics>(egui::Id::new(("brep-theme-classic-metrics", dark)))) {
732        classic.restore(style);
733    }
734}
735