BREP_app 0.36.1

The next.BREP.io CAD application on the Rust B-rep kernel: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame, native + wasm from one codebase.
Documentation
//! Font setup: Inter for the interface text, Hack for data rows, code and the
//! canvas, the same faces on every device (owner decision 2026-11-29: "I want
//! the font the same on all devices").
//!
//! THE UI FONT. This crate ships one font file,
//! `assets/fonts/Inter/InterVariable.ttf` (Inter 4.1, SIL OFL 1.1, licence text
//! beside it and in THIRD-PARTY-NOTICES.md). It is compiled in and bound to two
//! NAMED families, [`UI_FAMILY`] (weight 400) and [`UI_STRONG_FAMILY`] (weight
//! 600, from the same file's weight axis), on native, in the browser and on
//! mobile alike. The theme's text roles for buttons, labels, menus and headings
//! name those families ([`families`], `theme::install`). The file is the
//! unmodified upstream one; at load its LINE METRICS are overridden with the
//! monospace face's, so a row of text is as tall as it always was (`inter`).
//!
//! THE MONOSPACE FONT is Hack, one of the four faces eframe's `default_fonts`
//! feature compiles in. It leads egui's own `Monospace` AND `Proportional`
//! families on every platform: tree, table and list rows (`theme::Text::Data`),
//! code, and every caller of `FontId::proportional` or `FontId::monospace`
//! (canvas text among them) draw with it. Until 2026-11-29 native drew all text
//! with the OS's default monospace font and the browser drew proportional text
//! with Ubuntu Light, so the two looked different. Hack has the metrics of
//! DejaVu Sans Mono (same advance, ascent and descent), the face the layouts
//! were recorded in.
//!
//! FALLBACKS, in order, for a character the leading face lacks: the other
//! bundled faces (Ubuntu Light, Noto Emoji, emoji-icon-font), then, on native
//! only, the OS's default monospace font read at runtime via fontconfig. That
//! last one is the only per-device part: it draws the few symbols no bundled
//! face has (`⌂`, a `⌀` inside a text run) where the OS has them; the browser
//! has no OS font access.
//!
//! ICONS are not a font. The repo used to ship `BrepIcons.ttf`, a monoline icon
//! face; every icon is now drawn from its SVG ([`crate::icons`] +
//! [`crate::icon_text`]), and an icon character is only ever a KEY into the
//! icon catalog, never something a font renders.
//!
//! LICENCES. The four `default_fonts` faces are `include_bytes!` constants of
//! `epaint_default_fonts`, linked into every native binary and wasm module. Two
//! are conjoined OFL-1.1 / Ubuntu-font-1.0, and Inter is OFL-1.1, so a binary
//! release must carry their notices. See THIRD-PARTY-NOTICES.md.
//!
//! Installed at app creation from each shell entry point (`lib.rs` wasm `start`,
//! `main.rs` native `run_native`).

use eframe::egui;

/// The family of the interface text (Inter, weight 400).
pub const UI_FAMILY: &str = "brep-inter";
/// The family of headings and strong labels (Inter, weight 600).
pub const UI_STRONG_FAMILY: &str = "brep-inter-semibold";

/// Inter 4.1, the variable file: one file holds every weight.
static INTER: &[u8] = include_bytes!("../assets/fonts/Inter/InterVariable.ttf");

fn ui_font_bound() -> egui::Id {
    egui::Id::new("brep-ui-font-bound")
}

/// One table of an sfnt font file: its byte range, from the table directory.
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)
    })
}

/// `font`'s line metrics in font units: (units per em, ascender, descender,
/// line gap) of its `hhea` table.
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)?))
}

/// A copy of `font` whose line metrics (ascender, descender, line gap, in
/// `hhea` and in `OS/2`'s typographic and Windows fields) are `like`'s, scaled
/// to `font`'s units per em. Glyphs, advances and everything else are untouched.
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)
}

/// Inter as the app draws it: the shipped file with the line metrics of
/// `mono`, the face that leads the monospace family (Hack).
///
/// WHY. A row of Inter is taller than a row of Hack at the same size (1.21 em
/// against 1.16 em), about one pixel per row of text. Every layout the app had
/// was made with the monospace row: with Inter's own, the ribbon grows a pixel
/// and moves the 3D view, and a long panel pushes its last rows out of reach.
/// With the monospace row, a label takes the height it always took, and an
/// Inter label and a monospace value on one line share a baseline. The file on
/// disk and in the crate is the unmodified Inter; this is an override at load.
/// One copy, shared by both families; the unpatched bytes if a table is not
/// where it is expected.
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)
}

/// Bind Inter to the two named families, followed by the faces `fonts` already
/// draws proportional text with (for the characters Inter lacks).
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
}

/// The (text, strong) families the theme names for interface text: Inter once
/// [`install`] bound it in `ctx`, egui's `Proportional` in a context it was
/// never installed in (a family that is named but not bound cannot be laid out).
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)
    }
}

/// Install fonts into `ctx`. Call once, at app creation.
pub fn install(ctx: &egui::Context) {
    // The OS monospace is only the last fallback (native, when it can be read).
    install_matching(ctx, "monospace");
}

/// Install the app's fonts: Inter for the interface text, Hack leading both of
/// egui's families, and the OS font fontconfig matches for `pattern` (a family
/// name or `monospace`) as the last fallback where it can be read. Returns that
/// font's file. The headless MCP host names one family here instead of
/// `monospace`, so the fallback is the same face on every machine too.
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
}

/// egui's bundled faces with Hack leading BOTH families (egui's own default
/// leads `Proportional` with Ubuntu Light), and the OS font, when there is
/// one, last in both.
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; // honor a .ttc collection face index from fontconfig
        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
}

/// Locate and read the OS font fontconfig matches for `pattern` (bytes,
/// collection index, path). Native only, via fontconfig's `fc-match`; returns
/// `None` on any failure: the bundled faces then draw alone.
#[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()?; // read failure => None => default fallback
    Some((bytes, index, path.to_string()))
}

/// wasm has no OS font access: the bundled faces draw alone.
#[cfg(target_arch = "wasm32")]
fn font_matching(_pattern: &str) -> Option<(Vec<u8>, u32, String)> {
    None
}

/// eframe 0.35 runs egui for hidden native windows but skips
/// `paint_and_update_textures`, consuming (and losing) that pass's atlas delta.
/// Atlas recycling in such a pass leaves the GPU sampling an
/// older atlas. Restore the current image once visibility returns, after all
/// layout has finished. This also covers a hidden pass run by another host;
/// ordinary visible passes retain egui's incremental uploads.
#[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());
        // Replace this pass's partial updates too: the full image already
        // includes them, and it establishes the correct GPU texture dimensions.
        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),
        ));
    }
}