Skip to main content

brep_app/ui_kit/
preview.rs

1//! The four open decisions (spec section 9) as values, the fonts each font
2//! option draws with, and the whole-app PREVIEW of the theme.
3//!
4//! The preview is developer-only and never saved: it is off at start-up, and
5//! with it off (and the gallery closed) nothing here runs. Turning it on
6//! snapshots egui's dark and light styles and installs the themed ones;
7//! turning it off puts the snapshot back, so the app returns to exactly the
8//! style it had.
9//!
10//! FONTS. The repo ships no font file, and which font the refresh uses is the
11//! owner's decision, so neither option adds one here:
12//! - option A (ship a UI font) is previewed from a font file OUTSIDE the repo,
13//!   named by `BREP_UI_PREVIEW_FONT` (a variable font supplies its own
14//!   semibold; `BREP_UI_PREVIEW_FONT_SEMIBOLD` names a static one), or from an
15//!   installed "Inter" family;
16//! - option B (the OS's UI font) is whatever fontconfig answers `sans-serif`.
17//! The faces are bound to two EXTRA font families, [`UI_FAMILY`] and
18//! [`UI_STRONG_FAMILY`]; egui's own Proportional and Monospace families are
19//! not touched, so text outside the gallery and the preview lays out as before.
20use crate::theme::{Density, Families, Mode, Theme, ACCENTS};
21use eframe::egui;
22use std::sync::Arc;
23
24pub const UI_FAMILY: &str = "brep-ui";
25pub const UI_STRONG_FAMILY: &str = "brep-ui-semibold";
26
27/// Decision 1: the font.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
29#[cfg_attr(feature = "automation", derive(schemars::JsonSchema))]
30pub enum FontChoice {
31    /// Ship a UI font (Inter or similar): the same look everywhere.
32    A,
33    /// Keep the no-font-file rule: the OS's proportional UI font.
34    B,
35}
36
37impl FontChoice {
38    pub const ALL: [FontChoice; 2] = [FontChoice::A, FontChoice::B];
39    pub fn label(self) -> &'static str {
40        match self {
41            FontChoice::A => "A: ship a UI font (Inter or similar)",
42            FontChoice::B => "B: the OS's UI font (no font file)",
43        }
44    }
45}
46
47/// Decision 4: whether the light theme is in the first release of the refresh.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
49#[cfg_attr(feature = "automation", derive(schemars::JsonSchema))]
50#[serde(rename_all = "lowercase")]
51pub enum LightScope {
52    /// Dark and light together in the first release.
53    Now,
54    /// Dark only first; light keeps today's look until a later release.
55    Later,
56}
57
58impl LightScope {
59    pub const ALL: [LightScope; 2] = [LightScope::Now, LightScope::Later];
60    pub fn label(self) -> &'static str {
61        match self {
62            LightScope::Now => "In the first release (dark and light)",
63            LightScope::Later => "Later (dark only first)",
64        }
65    }
66}
67
68/// Which theme the gallery window itself is drawn in.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
70#[cfg_attr(feature = "automation", derive(schemars::JsonSchema))]
71#[serde(rename_all = "lowercase")]
72pub enum View {
73    /// The app's current theme (Settings: theme).
74    App,
75    Dark,
76    Light,
77}
78
79impl View {
80    pub const ALL: [View; 3] = [View::App, View::Dark, View::Light];
81    pub fn label(self) -> &'static str {
82        match self {
83            View::App => "The app's theme",
84            View::Dark => "Dark",
85            View::Light => "Light",
86        }
87    }
88}
89
90/// The four decisions as currently chosen in the gallery. The defaults are the
91/// spec's proposals; the font has no proposal, so it starts on B (today's
92/// no-font-file rule).
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
94pub struct Choices {
95    pub font: FontChoice,
96    /// Index into [`ACCENTS`].
97    pub accent: usize,
98    pub density: Density,
99    pub light: LightScope,
100}
101
102impl Default for Choices {
103    fn default() -> Self {
104        Choices { font: FontChoice::B, accent: 0, density: Density::Compact, light: LightScope::Now }
105    }
106}
107
108impl Choices {
109    /// The choices on one line, for the owner to read back.
110    pub fn summary(&self) -> String {
111        let font = match self.font {
112            FontChoice::A => "font A (ship a UI font)",
113            FontChoice::B => "font B (OS UI font)",
114        };
115        let light = match self.light {
116            LightScope::Now => "light theme in the first release",
117            LightScope::Later => "light theme later",
118        };
119        format!("{font} · accent {} · {} density · {light}", ACCENTS[self.accent].label, self.density.label().to_lowercase())
120    }
121}
122
123/// One loaded face.
124struct Face {
125    bytes: Vec<u8>,
126    index: u32,
127    /// Variable-font weight to select, when the file is a variable font.
128    weight: Option<f32>,
129}
130
131/// What a font option resolved to on this machine.
132struct Loaded {
133    regular: Option<Face>,
134    strong: Option<Face>,
135    /// One line for the gallery and the command's reply.
136    description: String,
137}
138
139#[cfg(not(target_arch = "wasm32"))]
140fn fc_match(pattern: &str) -> Option<(String, u32, String)> {
141    let out = std::process::Command::new("fc-match").args(["--format=%{file}\n%{index}\n%{family}", pattern]).output().ok()?;
142    if !out.status.success() {
143        return None;
144    }
145    let text = String::from_utf8_lossy(&out.stdout);
146    let mut lines = text.lines();
147    let path = lines.next()?.trim().to_string();
148    let index = lines.next().and_then(|l| l.trim().parse().ok()).unwrap_or(0);
149    let family = lines.next().unwrap_or("").trim().to_string();
150    (!path.is_empty()).then_some((path, index, family))
151}
152
153#[cfg(not(target_arch = "wasm32"))]
154fn has_weight_axis(bytes: &[u8], index: u32) -> bool {
155    let mut data = egui::FontData::from_owned(bytes.to_vec());
156    data.index = index;
157    data.variation_axes().iter().any(|axis| axis.tag.to_string() == "wght")
158}
159
160#[cfg(not(target_arch = "wasm32"))]
161fn file_name(path: &str) -> &str {
162    std::path::Path::new(path).file_name().and_then(|n| n.to_str()).unwrap_or(path)
163}
164
165#[cfg(not(target_arch = "wasm32"))]
166fn load(choice: FontChoice) -> Loaded {
167    let none = |description: String| Loaded { regular: None, strong: None, description };
168    match choice {
169        FontChoice::A => {
170            let named = std::env::var("BREP_UI_PREVIEW_FONT").ok().filter(|p| !p.is_empty()).map(|p| (p, 0, String::new()));
171            let found = named.or_else(|| fc_match("Inter").filter(|(_, _, family)| family.to_lowercase().contains("inter")));
172            let Some((path, index, _)) = found else {
173                return none("option A: no UI font file to preview (set BREP_UI_PREVIEW_FONT to a .ttf outside the repo, or install Inter); drawn with the current font".into());
174            };
175            let Ok(bytes) = std::fs::read(&path) else {
176                return none(format!("option A: {path} could not be read; drawn with the current font"));
177            };
178            let variable = has_weight_axis(&bytes, index);
179            let strong = if variable {
180                Some(Face { bytes: bytes.clone(), index, weight: Some(600.0) })
181            } else {
182                std::env::var("BREP_UI_PREVIEW_FONT_SEMIBOLD").ok().and_then(|p| std::fs::read(p).ok()).map(|bytes| Face { bytes, index: 0, weight: None })
183            };
184            let description = format!(
185                "option A: {} (preview file, not shipped){}",
186                file_name(&path),
187                match (&strong, variable) {
188                    (Some(_), true) => ", semibold from its weight axis",
189                    (Some(_), false) => ", with a static semibold",
190                    (None, _) => ", no semibold face (headings drawn regular)",
191                }
192            );
193            Loaded { regular: Some(Face { bytes, index, weight: variable.then_some(400.0) }), strong, description }
194        }
195        FontChoice::B => {
196            let Some((path, index, family)) = fc_match("sans-serif") else {
197                return none("option B: fontconfig has no sans-serif; drawn with the current font".into());
198            };
199            let Ok(bytes) = std::fs::read(&path) else {
200                return none(format!("option B: {path} could not be read; drawn with the current font"));
201            };
202            let strong = fc_match("sans-serif:semibold")
203                .or_else(|| fc_match("sans-serif:bold"))
204                .filter(|(strong_path, _, _)| *strong_path != path)
205                .and_then(|(p, i, _)| std::fs::read(p).ok().map(|bytes| Face { bytes, index: i, weight: None }));
206            let description = format!(
207                "option B: this machine's UI font, {family} ({}){}; it differs per OS",
208                file_name(&path),
209                if strong.is_some() { "" } else { ", no bolder face found" }
210            );
211            Loaded { regular: Some(Face { bytes, index, weight: None }), strong, description }
212        }
213    }
214}
215
216/// The browser cannot read font files: both options draw with egui's bundled
217/// font there, which is what option B means on the web.
218#[cfg(target_arch = "wasm32")]
219fn load(choice: FontChoice) -> Loaded {
220    let description = match choice {
221        FontChoice::A => "option A cannot be previewed in the browser build (no font file is shipped yet); drawn with egui's bundled font",
222        FontChoice::B => "option B: egui's bundled font in the browser build",
223    };
224    Loaded { regular: None, strong: None, description: description.into() }
225}
226
227fn font_data(face: Face) -> Arc<egui::FontData> {
228    let mut data = egui::FontData::from_owned(face.bytes);
229    data.index = face.index;
230    if let Some(weight) = face.weight {
231        data.tweak.coords = egui::epaint::text::VariationCoords::new([(*b"wght", weight)]);
232    }
233    Arc::new(data)
234}
235
236/// The preview's fonts: the two extra families, bound on demand and removed
237/// again when neither the gallery nor the preview needs them.
238#[derive(Default)]
239pub struct PreviewFonts {
240    /// The font definitions as they were before the first change.
241    base: Option<egui::FontDefinitions>,
242    installed: Option<FontChoice>,
243    description: String,
244}
245
246impl PreviewFonts {
247    /// Whether this ever changed the context's fonts (and has not restored them).
248    pub fn touched(&self) -> bool {
249        self.base.is_some()
250    }
251
252    pub fn description(&self) -> &str {
253        &self.description
254    }
255
256    /// Bind `choice`'s faces to the two extra families. The new definitions
257    /// take effect at the start of the next pass; [`PreviewFonts::families`]
258    /// answers egui's own families until then.
259    pub fn ensure(&mut self, ctx: &egui::Context, choice: FontChoice) {
260        if self.installed == Some(choice) {
261            return;
262        }
263        let base = self.base.get_or_insert_with(|| ctx.fonts(|f| f.definitions().clone()));
264        let mut defs = base.clone();
265        let loaded = load(choice);
266        let fallback = defs.families.get(&egui::FontFamily::Proportional).cloned().unwrap_or_default();
267        let mut bind = |family: &str, face: Option<Face>, also: Option<&str>| {
268            let mut names = Vec::new();
269            if let Some(face) = face {
270                let name = format!("{family}-{choice:?}");
271                defs.font_data.insert(name.clone(), font_data(face));
272                names.push(name);
273            } else if let Some(other) = also {
274                names.push(other.to_owned());
275            }
276            names.extend(fallback.iter().cloned());
277            defs.families.insert(egui::FontFamily::Name(family.into()), names);
278        };
279        let regular_name = loaded.regular.is_some().then(|| format!("{UI_FAMILY}-{choice:?}"));
280        bind(UI_FAMILY, loaded.regular, None);
281        bind(UI_STRONG_FAMILY, loaded.strong, regular_name.as_deref());
282        self.description = loaded.description;
283        self.installed = Some(choice);
284        ctx.set_fonts(defs);
285    }
286
287    /// The families a theme draws with: the two extra ones once they are
288    /// bound in the context's CURRENT definitions, egui's own until then (a
289    /// family that is named but not bound cannot be laid out).
290    pub fn families(&self, ctx: &egui::Context) -> Families {
291        let bound = self.installed.is_some()
292            && ctx.fonts(|f| {
293                let families = &f.definitions().families;
294                families.contains_key(&egui::FontFamily::Name(UI_FAMILY.into())) && families.contains_key(&egui::FontFamily::Name(UI_STRONG_FAMILY.into()))
295            });
296        if bound {
297            Families { text: egui::FontFamily::Name(UI_FAMILY.into()), strong: egui::FontFamily::Name(UI_STRONG_FAMILY.into()), mono: egui::FontFamily::Monospace }
298        } else {
299            Families::default()
300        }
301    }
302
303    /// Put the context's fonts back as they were.
304    pub fn restore(&mut self, ctx: &egui::Context) {
305        if let Some(base) = self.base.take() {
306            ctx.set_fonts(base);
307        }
308        self.installed = None;
309        self.description.clear();
310    }
311}
312
313/// What the preview installed, and what to put back.
314struct Applied {
315    key: (Choices, Families, bool),
316    dark: Arc<egui::Style>,
317    light: Arc<egui::Style>,
318}
319
320/// The whole-app preview: the theme written into egui's global styles.
321#[derive(Default)]
322pub struct Preview {
323    applied: Option<Applied>,
324}
325
326impl Preview {
327    pub fn active(&self) -> bool {
328        self.applied.is_some()
329    }
330
331    /// Install (or re-install after a change of `choices`) the themed styles.
332    /// The first install snapshots the styles it replaces.
333    pub fn apply(&mut self, ctx: &egui::Context, choices: Choices, families: &Families, reduce_motion: bool) {
334        let key = (choices, families.clone(), reduce_motion);
335        if self.applied.as_ref().is_some_and(|a| a.key == key) {
336            return;
337        }
338        let (dark, light) = match self.applied.take() {
339            Some(a) => (a.dark, a.light),
340            None => (ctx.style_of(egui::Theme::Dark), ctx.style_of(egui::Theme::Light)),
341        };
342        let theme = |mode| theme_for(choices, mode, families, reduce_motion);
343        ctx.set_style_of(egui::Theme::Dark, theme(Mode::Dark).style(&dark));
344        match choices.light {
345            super::preview::LightScope::Now => ctx.set_style_of(egui::Theme::Light, theme(Mode::Light).style(&light)),
346            // Dark only first: light keeps today's look.
347            super::preview::LightScope::Later => ctx.set_style_of(egui::Theme::Light, light.clone()),
348        }
349        self.applied = Some(Applied { key, dark, light });
350    }
351
352    /// Put back the styles the preview replaced.
353    pub fn remove(&mut self, ctx: &egui::Context) {
354        if let Some(a) = self.applied.take() {
355            ctx.set_style_of(egui::Theme::Dark, a.dark);
356            ctx.set_style_of(egui::Theme::Light, a.light);
357        }
358    }
359}
360
361/// The theme `choices` describe, in `mode`.
362pub fn theme_for(choices: Choices, mode: Mode, families: &Families, reduce_motion: bool) -> Theme {
363    Theme::new(mode, choices.density, ACCENTS[choices.accent.min(ACCENTS.len() - 1)].color).with_families(families.clone()).with_reduce_motion(reduce_motion)
364}