use eframe::egui;
pub const UI_FAMILY: &str = "brep-inter";
pub const UI_STRONG_FAMILY: &str = "brep-inter-semibold";
static INTER: &[u8] = include_bytes!("../assets/fonts/Inter/InterVariable.ttf");
fn ui_font_bound() -> egui::Id {
egui::Id::new("brep-ui-font-bound")
}
fn sfnt_table(font: &[u8], tag: &[u8; 4]) -> Option<std::ops::Range<usize>> {
let u16_at = |at: usize| Some(u16::from_be_bytes(font.get(at..at + 2)?.try_into().ok()?));
let u32_at = |at: usize| Some(u32::from_be_bytes(font.get(at..at + 4)?.try_into().ok()?) as usize);
(0..usize::from(u16_at(4)?)).map(|i| 12 + 16 * i).find(|record| font.get(*record..*record + 4) == Some(&tag[..])).and_then(|record| {
let (start, length) = (u32_at(record + 8)?, u32_at(record + 12)?);
(start.checked_add(length)? <= font.len()).then_some(start..start + length)
})
}
fn line_metrics(font: &[u8]) -> Option<(f32, f32, f32, f32)> {
let i16_at = |at: usize| Some(f32::from(i16::from_be_bytes(font.get(at..at + 2)?.try_into().ok()?)));
let head = sfnt_table(font, b"head")?.start;
let hhea = sfnt_table(font, b"hhea")?.start;
let units = f32::from(u16::from_be_bytes(font.get(head + 18..head + 20)?.try_into().ok()?));
(units > 0.0).then_some(())?;
Some((units, i16_at(hhea + 4)?, i16_at(hhea + 6)?, i16_at(hhea + 8)?))
}
fn with_line_metrics_of(font: &[u8], like: &[u8]) -> Option<Vec<u8>> {
let (units, ..) = line_metrics(font)?;
let (like_units, ascender, descender, gap) = line_metrics(like)?;
let scaled = |v: f32| (v * units / like_units).round();
let (ascender, descender, gap) = (scaled(ascender), scaled(descender), scaled(gap));
let hhea = sfnt_table(font, b"hhea")?;
let os2 = sfnt_table(font, b"OS/2")?;
(hhea.len() >= 10 && os2.len() >= 78).then_some(())?;
let mut out = font.to_vec();
let mut put_i16 = |at: usize, v: f32| out[at..at + 2].copy_from_slice(&(v as i16).to_be_bytes());
put_i16(hhea.start + 4, ascender);
put_i16(hhea.start + 6, descender);
put_i16(hhea.start + 8, gap);
put_i16(os2.start + 68, ascender);
put_i16(os2.start + 70, descender);
put_i16(os2.start + 72, gap);
out[os2.start + 74..os2.start + 76].copy_from_slice(&(ascender.max(0.0) as u16).to_be_bytes());
out[os2.start + 76..os2.start + 78].copy_from_slice(&((-descender).max(0.0) as u16).to_be_bytes());
Some(out)
}
fn inter(mono: Option<&[u8]>) -> &'static [u8] {
static PATCHED: std::sync::OnceLock<Option<Vec<u8>>> = std::sync::OnceLock::new();
PATCHED.get_or_init(|| with_line_metrics_of(INTER, mono?)).as_deref().unwrap_or(INTER)
}
fn with_ui_font(mut fonts: egui::FontDefinitions) -> egui::FontDefinitions {
let fallback = fonts.families.get(&egui::FontFamily::Proportional).cloned().unwrap_or_default();
let mono = fonts.families.get(&egui::FontFamily::Monospace).and_then(|faces| fonts.font_data.get(faces.first()?)).cloned();
let inter = inter(mono.as_ref().map(|data| data.font.as_ref()));
for (family, weight) in [(UI_FAMILY, 400.0), (UI_STRONG_FAMILY, 600.0)] {
let mut data = egui::FontData::from_static(inter);
data.tweak.coords = egui::epaint::text::VariationCoords::new([(*b"wght", weight)]);
fonts.font_data.insert(family.to_owned(), data.into());
let mut faces = vec![family.to_owned()];
faces.extend(fallback.iter().cloned());
fonts.families.insert(egui::FontFamily::Name(family.into()), faces);
}
fonts
}
pub fn families(ctx: &egui::Context) -> (egui::FontFamily, egui::FontFamily) {
if ctx.data(|d| d.get_temp::<bool>(ui_font_bound())).unwrap_or(false) {
(egui::FontFamily::Name(UI_FAMILY.into()), egui::FontFamily::Name(UI_STRONG_FAMILY.into()))
} else {
(egui::FontFamily::Proportional, egui::FontFamily::Proportional)
}
}
pub fn install(ctx: &egui::Context) {
install_matching(ctx, "monospace");
}
pub fn install_matching(ctx: &egui::Context, pattern: &str) -> Option<String> {
let os_font = font_matching(pattern);
let path = os_font.as_ref().map(|(_, _, path)| path.clone());
ctx.set_fonts(with_ui_font(base_defs(os_font.map(|(bytes, index, _)| (bytes, index)))));
ctx.data_mut(|d| d.insert_temp(ui_font_bound(), true));
ctx.add_plugin(RestoreAtlasAfterHiddenPass::default());
path
}
fn base_defs(os_font: Option<(Vec<u8>, u32)>) -> egui::FontDefinitions {
let mut fonts = egui::FontDefinitions::default();
let mono = fonts.families.get(&egui::FontFamily::Monospace).cloned().unwrap_or_default();
let mut faces = mono.clone();
for face in fonts.families.get(&egui::FontFamily::Proportional).cloned().unwrap_or_default() {
if !faces.contains(&face) {
faces.push(face);
}
}
if let Some((bytes, index)) = os_font {
let mut data = egui::FontData::from_owned(bytes);
data.index = index; fonts.font_data.insert("os_mono".to_owned(), data.into());
faces.push("os_mono".to_owned());
}
for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] {
fonts.families.insert(family, faces.clone());
}
fonts
}
#[cfg(not(target_arch = "wasm32"))]
fn font_matching(pattern: &str) -> Option<(Vec<u8>, u32, String)> {
let out = std::process::Command::new("fc-match")
.args(["--format=%{file}\n%{index}", 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();
if path.is_empty() {
return None;
}
let index = lines.next().and_then(|l| l.trim().parse().ok()).unwrap_or(0);
let bytes = std::fs::read(path).ok()?; Some((bytes, index, path.to_string()))
}
#[cfg(target_arch = "wasm32")]
fn font_matching(_pattern: &str) -> Option<(Vec<u8>, u32, String)> {
None
}
#[derive(Default)]
struct RestoreAtlasAfterHiddenPass {
hidden: bool,
restore: bool,
}
impl egui::Plugin for RestoreAtlasAfterHiddenPass {
fn debug_name(&self) -> &'static str {
"brep-restore-font-atlas"
}
fn input_hook(&mut self, _ctx: &egui::Context, input: &mut egui::RawInput) {
self.hidden = input.viewport().visible() == Some(false);
self.restore |= self.hidden;
}
fn output_hook(&mut self, ctx: &egui::Context, output: &mut egui::FullOutput) {
if self.hidden || !self.restore {
return;
}
self.restore = false;
let image = ctx.fonts(|fonts| fonts.image());
output.textures_delta.set.retain(|(id, _)| *id != egui::TextureId::default());
output.textures_delta.set.push((
egui::TextureId::default(),
egui::epaint::ImageDelta::full(image, egui::TextureOptions::LINEAR),
));
}
}