use std::collections::HashMap;
use std::path::Path;
use anyhow::{Context, Result};
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum FontRole {
Thin,
Light,
Regular,
Medium,
SemiBold,
}
pub const ALL_ROLES: [FontRole; 5] = [
FontRole::Thin,
FontRole::Light,
FontRole::Regular,
FontRole::Medium,
FontRole::SemiBold,
];
impl FontRole {
pub fn index(self) -> usize {
match self {
FontRole::Thin => 0,
FontRole::Light => 1,
FontRole::Regular => 2,
FontRole::Medium => 3,
FontRole::SemiBold => 4,
}
}
pub fn file_name(self) -> &'static str {
match self {
FontRole::Thin => "Montserrat-Thin.ttf",
FontRole::Light => "Montserrat-Light.ttf",
FontRole::Regular => "Montserrat-Regular.ttf",
FontRole::Medium => "Montserrat-Medium.ttf",
FontRole::SemiBold => "Montserrat-SemiBold.ttf",
}
}
pub fn postscript_name(self) -> &'static str {
match self {
FontRole::Thin => "Montserrat-Thin",
FontRole::Light => "Montserrat-Light",
FontRole::Regular => "Montserrat-Regular",
FontRole::Medium => "Montserrat-Medium",
FontRole::SemiBold => "Montserrat-SemiBold",
}
}
pub fn resource_name(self) -> [u8; 2] {
[b'F', b'0' + self.index() as u8]
}
pub fn styled(self, bold: bool, italic: bool) -> FontRole {
if bold {
FontRole::SemiBold
} else if italic {
FontRole::Medium
} else {
self
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct GlyphInfo {
pub gid: u16,
pub advance: u16,
}
pub struct Font {
pub data: Vec<u8>,
pub units_per_em: f32,
pub ascender: f32,
pub descender: f32,
pub cap_height: f32,
pub bbox: [f32; 4],
cmap: HashMap<char, GlyphInfo>,
gid_to_char: HashMap<u16, char>,
}
impl Font {
pub fn parse(data: Vec<u8>) -> Result<Font> {
let face = ttf_parser::Face::parse(&data, 0)
.map_err(|e| anyhow::anyhow!("failed to parse font: {e}"))?;
let mut cmap = HashMap::new();
let mut gid_to_char = HashMap::new();
if let Some(table) = face.tables().cmap {
for sub in table.subtables {
if !sub.is_unicode() {
continue;
}
sub.codepoints(|cp| {
let Some(ch) = char::from_u32(cp) else { return };
if cmap.contains_key(&ch) {
return;
}
if let Some(gid) = face.glyph_index(ch) {
let advance = face.glyph_hor_advance(gid).unwrap_or(0);
cmap.insert(
ch,
GlyphInfo {
gid: gid.0,
advance,
},
);
gid_to_char.entry(gid.0).or_insert(ch);
}
});
}
}
let bb = face.global_bounding_box();
Ok(Font {
units_per_em: face.units_per_em() as f32,
ascender: face.ascender() as f32,
descender: face.descender() as f32,
cap_height: face.capital_height().unwrap_or(700) as f32,
bbox: [
bb.x_min as f32,
bb.y_min as f32,
bb.x_max as f32,
bb.y_max as f32,
],
cmap,
gid_to_char,
data,
})
}
pub fn glyph(&self, ch: char) -> Option<GlyphInfo> {
self.cmap.get(&ch).copied()
}
pub fn char_for_gid(&self, gid: u16) -> Option<char> {
self.gid_to_char.get(&gid).copied()
}
pub fn measure(&self, text: &str, size: f32) -> f32 {
let units: f32 = text
.chars()
.map(|c| match self.glyph(c) {
Some(g) => g.advance as f32,
None => self.units_per_em * 0.5,
})
.sum();
units * size / self.units_per_em
}
}
pub struct FontBook {
fonts: HashMap<FontRole, Font>,
}
impl FontBook {
pub fn embedded() -> Result<FontBook> {
let mut fonts = HashMap::new();
macro_rules! load {
($role:expr, $file:literal) => {
fonts.insert(
$role,
Font::parse(include_bytes!(concat!("../assets/fonts/", $file)).to_vec())
.context(concat!("embedded font ", $file))?,
);
};
}
load!(FontRole::Thin, "Montserrat-Thin.ttf");
load!(FontRole::Light, "Montserrat-Light.ttf");
load!(FontRole::Regular, "Montserrat-Regular.ttf");
load!(FontRole::Medium, "Montserrat-Medium.ttf");
load!(FontRole::SemiBold, "Montserrat-SemiBold.ttf");
Ok(FontBook { fonts })
}
pub fn from_dir(dir: &Path) -> Result<FontBook> {
let mut fonts = HashMap::new();
for role in ALL_ROLES {
let path = dir.join(role.file_name());
let data =
std::fs::read(&path).with_context(|| format!("reading font {}", path.display()))?;
fonts.insert(role, Font::parse(data)?);
}
Ok(FontBook { fonts })
}
pub fn get(&self, role: FontRole) -> &Font {
&self.fonts[&role]
}
pub fn measure(&self, role: FontRole, text: &str, size: f32) -> f32 {
self.get(role).measure(text, size)
}
pub fn bullet_char(&self) -> char {
let regular = self.get(FontRole::Regular);
for c in ['\u{25C6}', '\u{2022}', '-'] {
if regular.glyph(c).is_some() {
return c;
}
}
'-'
}
pub fn missing_chars(&self, role: FontRole, text: &str) -> Vec<char> {
let font = self.get(role);
text.chars().filter(|&c| font.glyph(c).is_none()).collect()
}
}