BREP_app 0.35.0

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
//! The four open decisions (spec section 9) as values, the fonts each font
//! option draws with, and the whole-app PREVIEW of the theme.
//!
//! The preview is developer-only and never saved: it is off at start-up, and
//! with it off (and the gallery closed) nothing here runs. Turning it on
//! snapshots egui's dark and light styles and installs the themed ones;
//! turning it off puts the snapshot back, so the app returns to exactly the
//! style it had.
//!
//! FONTS. The repo ships no font file, and which font the refresh uses is the
//! owner's decision, so neither option adds one here:
//! - option A (ship a UI font) is previewed from a font file OUTSIDE the repo,
//!   named by `BREP_UI_PREVIEW_FONT` (a variable font supplies its own
//!   semibold; `BREP_UI_PREVIEW_FONT_SEMIBOLD` names a static one), or from an
//!   installed "Inter" family;
//! - option B (the OS's UI font) is whatever fontconfig answers `sans-serif`.
//! The faces are bound to two EXTRA font families, [`UI_FAMILY`] and
//! [`UI_STRONG_FAMILY`]; egui's own Proportional and Monospace families are
//! not touched, so text outside the gallery and the preview lays out as before.
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";

/// Decision 1: the font.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "automation", derive(schemars::JsonSchema))]
pub enum FontChoice {
    /// Ship a UI font (Inter or similar): the same look everywhere.
    A,
    /// Keep the no-font-file rule: the OS's proportional UI font.
    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)",
        }
    }
}

/// Decision 4: whether the light theme is in the first release of the refresh.
#[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 {
    /// Dark and light together in the first release.
    Now,
    /// Dark only first; light keeps today's look until a later release.
    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)",
        }
    }
}

/// Which theme the gallery window itself is drawn in.
#[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 {
    /// The app's current theme (Settings: theme).
    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",
        }
    }
}

/// The four decisions as currently chosen in the gallery. The defaults are the
/// spec's proposals; the font has no proposal, so it starts on B (today's
/// no-font-file rule).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Choices {
    pub font: FontChoice,
    /// Index into [`ACCENTS`].
    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 {
    /// The choices on one line, for the owner to read back.
    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())
    }
}

/// One loaded face.
struct Face {
    bytes: Vec<u8>,
    index: u32,
    /// Variable-font weight to select, when the file is a variable font.
    weight: Option<f32>,
}

/// What a font option resolved to on this machine.
struct Loaded {
    regular: Option<Face>,
    strong: Option<Face>,
    /// One line for the gallery and the command's reply.
    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 }
        }
    }
}

/// The browser cannot read font files: both options draw with egui's bundled
/// font there, which is what option B means on the web.
#[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)
}

/// The preview's fonts: the two extra families, bound on demand and removed
/// again when neither the gallery nor the preview needs them.
#[derive(Default)]
pub struct PreviewFonts {
    /// The font definitions as they were before the first change.
    base: Option<egui::FontDefinitions>,
    installed: Option<FontChoice>,
    description: String,
}

impl PreviewFonts {
    /// Whether this ever changed the context's fonts (and has not restored them).
    pub fn touched(&self) -> bool {
        self.base.is_some()
    }

    pub fn description(&self) -> &str {
        &self.description
    }

    /// Bind `choice`'s faces to the two extra families. The new definitions
    /// take effect at the start of the next pass; [`PreviewFonts::families`]
    /// answers egui's own families until then.
    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);
    }

    /// The families a theme draws with: the two extra ones once they are
    /// bound in the context's CURRENT definitions, egui's own until then (a
    /// family that is named but not bound cannot be laid out).
    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()
        }
    }

    /// Put the context's fonts back as they were.
    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();
    }
}

/// What the preview installed, and what to put back.
struct Applied {
    key: (Choices, Families, bool),
    dark: Arc<egui::Style>,
    light: Arc<egui::Style>,
}

/// The whole-app preview: the theme written into egui's global styles.
#[derive(Default)]
pub struct Preview {
    applied: Option<Applied>,
}

impl Preview {
    pub fn active(&self) -> bool {
        self.applied.is_some()
    }

    /// Install (or re-install after a change of `choices`) the themed styles.
    /// The first install snapshots the styles it replaces.
    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)),
            // Dark only first: light keeps today's look.
            super::preview::LightScope::Later => ctx.set_style_of(egui::Theme::Light, light.clone()),
        }
        self.applied = Some(Applied { key, dark, light });
    }

    /// Put back the styles the preview replaced.
    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);
        }
    }
}

/// The theme `choices` describe, in `mode`.
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)
}