Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

7.2 KB
Raw Blame
//! Pure-Rust font management and CSS `font` shorthand parsing over `cosmic-text` (`fontdb`).
use std::path::PathBuf;
use std::sync::{Mutex, OnceLock};

use cosmic_text::{Family, FontSystem, Style, Weight};

static FONT_DIR: Mutex<Option<PathBuf>> = Mutex::new(None);
static FONT_SYSTEM: OnceLock<Mutex<FontSystem>> = OnceLock::new();
static LOADED_DIR: Mutex<Option<PathBuf>> = Mutex::new(None);

/// Directory of bundled `.ttf`/`.otf`/`.ttc` faces (`<bundle>/fonts`).
pub fn set_dir(dir: PathBuf) {
    *FONT_DIR.lock().unwrap_or_else(|e| e.into_inner()) = Some(dir);
    register();
}

/// Ensure bundled fonts (if configured) are loaded into the shared `FontSystem`.
pub fn register() {
    let dir = FONT_DIR.lock().unwrap_or_else(|e| e.into_inner()).clone();
    let Some(dir) = dir else { return };
    let mut loaded = LOADED_DIR.lock().unwrap_or_else(|e| e.into_inner());
    if loaded.as_ref() == Some(&dir) {
        return;
    }
    with_font_system(|fs| {
        if dir.is_dir() {
            fs.db_mut().load_fonts_dir(&dir);
        }
    });
    *loaded = Some(dir);
}

pub(crate) fn with_font_system<R>(f: impl FnOnce(&mut FontSystem) -> R) -> R {
    let lock = FONT_SYSTEM.get_or_init(|| Mutex::new(FontSystem::new()));
    let mut fs = lock.lock().unwrap_or_else(|e| e.into_inner());
    f(&mut fs)
}

#[derive(Clone, Debug)]
pub struct ParsedFont {
    pub families: Vec<String>,
    pub weight: u16,
    pub italic: bool,
    pub size: f64,
    pub line_height: Option<f64>,
    pub small_caps: bool,
    pub stretch: Option<String>,
    pub oblique: bool,
}

impl Default for ParsedFont {
    fn default() -> Self {
        Self {
            families: vec!["sans-serif".into()],
            weight: 400,
            italic: false,
            size: 10.0,
            line_height: None,
            small_caps: false,
            stretch: None,
            oblique: false,
        }
    }
}

impl ParsedFont {
    pub fn to_css(&self) -> String {
        let mut out = String::new();
        if self.italic {
            out.push_str("italic ");
        } else if self.oblique {
            out.push_str("oblique ");
        }
        if self.small_caps {
            out.push_str("small-caps ");
        }
        if self.weight != 400 {
            out.push_str(&format!("{} ", self.weight));
        }
        out.push_str(&format!("{}px ", self.size));
        for (i, fam) in self.families.iter().enumerate() {
            if i > 0 {
                out.push_str(", ");
            }
            if fam.contains(' ') {
                out.push('"');
                out.push_str(fam);
                out.push('"');
            } else {
                out.push_str(fam);
            }
        }
        out
    }

    pub fn cosmic_weight(&self) -> Weight {
        Weight(self.weight.clamp(100, 900))
    }

    pub fn cosmic_style(&self) -> Style {
        if self.italic {
            Style::Italic
        } else if self.oblique {
            Style::Oblique
        } else {
            Style::Normal
        }
    }
}

/// Pick the first CSS family present in `fontdb`, falling back to generic `SansSerif` / `Serif` / `Monospace`.
pub(crate) fn resolve_family<'a>(fs: &FontSystem, families: &'a [String]) -> Family<'a> {
    let db = fs.db();
    for raw in families {
        let name = raw.trim().trim_matches('"').trim_matches('\'');
        if name.is_empty() {
            continue;
        }
        match name.to_ascii_lowercase().as_str() {
            "sans-serif" | "system-ui" | "-apple-system" | "blinkmacsystemfont" | "ui-sans-serif" => return Family::SansSerif,
            "serif" | "ui-serif" => return Family::Serif,
            "monospace" | "ui-monospace" => return Family::Monospace,
            "cursive" => return Family::Cursive,
            "fantasy" => return Family::Fantasy,
            _ => {
                if db.faces().any(|f| f.families.iter().any(|(fam, _)| fam.eq_ignore_ascii_case(name))) {
                    return Family::Name(name);
                }
            }
        }
    }
    Family::SansSerif
}

fn parse_size(tok: &str) -> Option<(f64, Option<f64>)> {
    let (sz_s, lh_s) = match tok.split_once('/') {
        Some((a, b)) => (a, Some(b)),
        None => (tok, None),
    };
    let lower = sz_s.to_ascii_lowercase();
    let px = if let Some(v) = lower.strip_suffix("px") {
        v.parse::<f64>().ok()?
    } else if let Some(v) = lower.strip_suffix("pt") {
        v.parse::<f64>().ok()? * (4.0 / 3.0)
    } else if let Some(v) = lower.strip_suffix("em").or_else(|| lower.strip_suffix("rem")) {
        v.parse::<f64>().ok()? * 16.0
    } else if let Some(v) = lower.strip_suffix('%') {
        v.parse::<f64>().ok()? * 0.16
    } else {
        return None;
    };
    if !px.is_finite() || px <= 0.0 {
        return None;
    }
    let lh = lh_s.and_then(|s| {
        let l = s.to_ascii_lowercase();
        if let Some(v) = l.strip_suffix("px") {
            v.parse::<f64>().ok()
        } else {
            l.parse::<f64>().ok().map(|m| m * px)
        }
    });
    Some((px, lh))
}

/// Parse a CSS `font` shorthand (`[style] [variant] [weight] <size>[/<line-height>] <family-list>`).
pub fn parse_shorthand(css: &str) -> Option<ParsedFont> {
    let s = css.trim();
    if s.is_empty() {
        return None;
    }
    let mut weight = 400u16;
    let mut italic = false;
    let mut oblique = false;
    let mut small_caps = false;

    let mut rest = s;
    let (size, line_height) = loop {
        let trimmed = rest.trim_start();
        if trimmed.is_empty() {
            return None;
        }
        let end = trimmed.find(|c: char| c.is_ascii_whitespace()).unwrap_or(trimmed.len());
        let tok = &trimmed[..end];
        rest = &trimmed[end..];
        if let Some(sz) = parse_size(tok) {
            break sz;
        }
        match tok.to_ascii_lowercase().as_str() {
            "italic" => italic = true,
            "oblique" => oblique = true,
            "normal" => {}
            "small-caps" => small_caps = true,
            "bold" | "bolder" => weight = 700,
            "lighter" => weight = 300,
            other => {
                if let Ok(w) = other.parse::<u16>() {
                    if (1..=1000).contains(&w) {
                        weight = w;
                        continue;
                    }
                }
                return None;
            }
        }
    };

    let fam_str = rest.trim();
    if fam_str.is_empty() {
        return None;
    }
    let families: Vec<String> = fam_str
        .split(',')
        .map(|f| f.trim().trim_matches('"').trim_matches('\'').to_string())
        .filter(|f| !f.is_empty())
        .collect();
    if families.is_empty() {
        return None;
    }
    Some(ParsedFont { families, weight, italic, size, line_height, small_caps, stretch: None, oblique })
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn families() {
        let p = parse_shorthand("700 16px \"Nunito\", sans-serif").unwrap();
        assert_eq!(p.weight, 700);
        assert_eq!(p.size, 16.0);
        assert_eq!(p.families, vec!["Nunito", "sans-serif"]);
        assert!(parse_shorthand("not a font").is_none());
    }
    #[test]
    fn set_dir_does_not_deadlock() {
        set_dir(std::env::temp_dir());
        register();
    }
}