1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
29#[cfg_attr(feature = "automation", derive(schemars::JsonSchema))]
30pub enum FontChoice {
31 A,
33 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#[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 Now,
54 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#[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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
94pub struct Choices {
95 pub font: FontChoice,
96 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 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
123struct Face {
125 bytes: Vec<u8>,
126 index: u32,
127 weight: Option<f32>,
129}
130
131struct Loaded {
133 regular: Option<Face>,
134 strong: Option<Face>,
135 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#[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#[derive(Default)]
239pub struct PreviewFonts {
240 base: Option<egui::FontDefinitions>,
242 installed: Option<FontChoice>,
243 description: String,
244}
245
246impl PreviewFonts {
247 pub fn touched(&self) -> bool {
249 self.base.is_some()
250 }
251
252 pub fn description(&self) -> &str {
253 &self.description
254 }
255
256 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 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 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
313struct Applied {
315 key: (Choices, Families, bool),
316 dark: Arc<egui::Style>,
317 light: Arc<egui::Style>,
318}
319
320#[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 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 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 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
361pub 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}