use crate::theme::{Density, Families, Mode, Theme, ACCENTS};
use eframe::egui;
use std::sync::Arc;
pub const UI_FAMILY: &str = "brep-ui";
pub const UI_STRONG_FAMILY: &str = "brep-ui-semibold";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "automation", derive(schemars::JsonSchema))]
pub enum FontChoice {
A,
B,
}
impl FontChoice {
pub const ALL: [FontChoice; 2] = [FontChoice::A, FontChoice::B];
pub fn label(self) -> &'static str {
match self {
FontChoice::A => "A: ship a UI font (Inter or similar)",
FontChoice::B => "B: the OS's UI font (no font file)",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "automation", derive(schemars::JsonSchema))]
#[serde(rename_all = "lowercase")]
pub enum LightScope {
Now,
Later,
}
impl LightScope {
pub const ALL: [LightScope; 2] = [LightScope::Now, LightScope::Later];
pub fn label(self) -> &'static str {
match self {
LightScope::Now => "In the first release (dark and light)",
LightScope::Later => "Later (dark only first)",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "automation", derive(schemars::JsonSchema))]
#[serde(rename_all = "lowercase")]
pub enum View {
App,
Dark,
Light,
}
impl View {
pub const ALL: [View; 3] = [View::App, View::Dark, View::Light];
pub fn label(self) -> &'static str {
match self {
View::App => "The app's theme",
View::Dark => "Dark",
View::Light => "Light",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Choices {
pub font: FontChoice,
pub accent: usize,
pub density: Density,
pub light: LightScope,
}
impl Default for Choices {
fn default() -> Self {
Choices { font: FontChoice::B, accent: 0, density: Density::Compact, light: LightScope::Now }
}
}
impl Choices {
pub fn summary(&self) -> String {
let font = match self.font {
FontChoice::A => "font A (ship a UI font)",
FontChoice::B => "font B (OS UI font)",
};
let light = match self.light {
LightScope::Now => "light theme in the first release",
LightScope::Later => "light theme later",
};
format!("{font} · accent {} · {} density · {light}", ACCENTS[self.accent].label, self.density.label().to_lowercase())
}
}
struct Face {
bytes: Vec<u8>,
index: u32,
weight: Option<f32>,
}
struct Loaded {
regular: Option<Face>,
strong: Option<Face>,
description: String,
}
#[cfg(not(target_arch = "wasm32"))]
fn fc_match(pattern: &str) -> Option<(String, u32, String)> {
let out = std::process::Command::new("fc-match").args(["--format=%{file}\n%{index}\n%{family}", pattern]).output().ok()?;
if !out.status.success() {
return None;
}
let text = String::from_utf8_lossy(&out.stdout);
let mut lines = text.lines();
let path = lines.next()?.trim().to_string();
let index = lines.next().and_then(|l| l.trim().parse().ok()).unwrap_or(0);
let family = lines.next().unwrap_or("").trim().to_string();
(!path.is_empty()).then_some((path, index, family))
}
#[cfg(not(target_arch = "wasm32"))]
fn has_weight_axis(bytes: &[u8], index: u32) -> bool {
let mut data = egui::FontData::from_owned(bytes.to_vec());
data.index = index;
data.variation_axes().iter().any(|axis| axis.tag.to_string() == "wght")
}
#[cfg(not(target_arch = "wasm32"))]
fn file_name(path: &str) -> &str {
std::path::Path::new(path).file_name().and_then(|n| n.to_str()).unwrap_or(path)
}
#[cfg(not(target_arch = "wasm32"))]
fn load(choice: FontChoice) -> Loaded {
let none = |description: String| Loaded { regular: None, strong: None, description };
match choice {
FontChoice::A => {
let named = std::env::var("BREP_UI_PREVIEW_FONT").ok().filter(|p| !p.is_empty()).map(|p| (p, 0, String::new()));
let found = named.or_else(|| fc_match("Inter").filter(|(_, _, family)| family.to_lowercase().contains("inter")));
let Some((path, index, _)) = found else {
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());
};
let Ok(bytes) = std::fs::read(&path) else {
return none(format!("option A: {path} could not be read; drawn with the current font"));
};
let variable = has_weight_axis(&bytes, index);
let strong = if variable {
Some(Face { bytes: bytes.clone(), index, weight: Some(600.0) })
} else {
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 })
};
let description = format!(
"option A: {} (preview file, not shipped){}",
file_name(&path),
match (&strong, variable) {
(Some(_), true) => ", semibold from its weight axis",
(Some(_), false) => ", with a static semibold",
(None, _) => ", no semibold face (headings drawn regular)",
}
);
Loaded { regular: Some(Face { bytes, index, weight: variable.then_some(400.0) }), strong, description }
}
FontChoice::B => {
let Some((path, index, family)) = fc_match("sans-serif") else {
return none("option B: fontconfig has no sans-serif; drawn with the current font".into());
};
let Ok(bytes) = std::fs::read(&path) else {
return none(format!("option B: {path} could not be read; drawn with the current font"));
};
let strong = fc_match("sans-serif:semibold")
.or_else(|| fc_match("sans-serif:bold"))
.filter(|(strong_path, _, _)| *strong_path != path)
.and_then(|(p, i, _)| std::fs::read(p).ok().map(|bytes| Face { bytes, index: i, weight: None }));
let description = format!(
"option B: this machine's UI font, {family} ({}){}; it differs per OS",
file_name(&path),
if strong.is_some() { "" } else { ", no bolder face found" }
);
Loaded { regular: Some(Face { bytes, index, weight: None }), strong, description }
}
}
}
#[cfg(target_arch = "wasm32")]
fn load(choice: FontChoice) -> Loaded {
let description = match choice {
FontChoice::A => "option A cannot be previewed in the browser build (no font file is shipped yet); drawn with egui's bundled font",
FontChoice::B => "option B: egui's bundled font in the browser build",
};
Loaded { regular: None, strong: None, description: description.into() }
}
fn font_data(face: Face) -> Arc<egui::FontData> {
let mut data = egui::FontData::from_owned(face.bytes);
data.index = face.index;
if let Some(weight) = face.weight {
data.tweak.coords = egui::epaint::text::VariationCoords::new([(*b"wght", weight)]);
}
Arc::new(data)
}
#[derive(Default)]
pub struct PreviewFonts {
base: Option<egui::FontDefinitions>,
installed: Option<FontChoice>,
description: String,
}
impl PreviewFonts {
pub fn touched(&self) -> bool {
self.base.is_some()
}
pub fn description(&self) -> &str {
&self.description
}
pub fn ensure(&mut self, ctx: &egui::Context, choice: FontChoice) {
if self.installed == Some(choice) {
return;
}
let base = self.base.get_or_insert_with(|| ctx.fonts(|f| f.definitions().clone()));
let mut defs = base.clone();
let loaded = load(choice);
let fallback = defs.families.get(&egui::FontFamily::Proportional).cloned().unwrap_or_default();
let mut bind = |family: &str, face: Option<Face>, also: Option<&str>| {
let mut names = Vec::new();
if let Some(face) = face {
let name = format!("{family}-{choice:?}");
defs.font_data.insert(name.clone(), font_data(face));
names.push(name);
} else if let Some(other) = also {
names.push(other.to_owned());
}
names.extend(fallback.iter().cloned());
defs.families.insert(egui::FontFamily::Name(family.into()), names);
};
let regular_name = loaded.regular.is_some().then(|| format!("{UI_FAMILY}-{choice:?}"));
bind(UI_FAMILY, loaded.regular, None);
bind(UI_STRONG_FAMILY, loaded.strong, regular_name.as_deref());
self.description = loaded.description;
self.installed = Some(choice);
ctx.set_fonts(defs);
}
pub fn families(&self, ctx: &egui::Context) -> Families {
let bound = self.installed.is_some()
&& ctx.fonts(|f| {
let families = &f.definitions().families;
families.contains_key(&egui::FontFamily::Name(UI_FAMILY.into())) && families.contains_key(&egui::FontFamily::Name(UI_STRONG_FAMILY.into()))
});
if bound {
Families { text: egui::FontFamily::Name(UI_FAMILY.into()), strong: egui::FontFamily::Name(UI_STRONG_FAMILY.into()), mono: egui::FontFamily::Monospace }
} else {
Families::default()
}
}
pub fn restore(&mut self, ctx: &egui::Context) {
if let Some(base) = self.base.take() {
ctx.set_fonts(base);
}
self.installed = None;
self.description.clear();
}
}
struct Applied {
key: (Choices, Families, bool),
dark: Arc<egui::Style>,
light: Arc<egui::Style>,
}
#[derive(Default)]
pub struct Preview {
applied: Option<Applied>,
}
impl Preview {
pub fn active(&self) -> bool {
self.applied.is_some()
}
pub fn apply(&mut self, ctx: &egui::Context, choices: Choices, families: &Families, reduce_motion: bool) {
let key = (choices, families.clone(), reduce_motion);
if self.applied.as_ref().is_some_and(|a| a.key == key) {
return;
}
let (dark, light) = match self.applied.take() {
Some(a) => (a.dark, a.light),
None => (ctx.style_of(egui::Theme::Dark), ctx.style_of(egui::Theme::Light)),
};
let theme = |mode| theme_for(choices, mode, families, reduce_motion);
ctx.set_style_of(egui::Theme::Dark, theme(Mode::Dark).style(&dark));
match choices.light {
super::preview::LightScope::Now => ctx.set_style_of(egui::Theme::Light, theme(Mode::Light).style(&light)),
super::preview::LightScope::Later => ctx.set_style_of(egui::Theme::Light, light.clone()),
}
self.applied = Some(Applied { key, dark, light });
}
pub fn remove(&mut self, ctx: &egui::Context) {
if let Some(a) = self.applied.take() {
ctx.set_style_of(egui::Theme::Dark, a.dark);
ctx.set_style_of(egui::Theme::Light, a.light);
}
}
}
pub fn theme_for(choices: Choices, mode: Mode, families: &Families, reduce_motion: bool) -> Theme {
Theme::new(mode, choices.density, ACCENTS[choices.accent.min(ACCENTS.len() - 1)].color).with_families(families.clone()).with_reduce_motion(reduce_motion)
}