use crate::fonts::{
DEFAULT_FAMILY, FontBook, FontData, FontError, FontFamily, FontId, FontPreferences,
FontSelection, GlyphMatch,
};
use crate::resources::ResourceResolver;
use std::sync::OnceLock;
use ttf_parser::Face;
const FALLBACK_X_HEIGHT_EM: f32 = 0.5;
const LOWERCASE_X: char = 'x';
const CAPITAL_H: char = 'H';
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct FaceMetrics {
pub ascent: f32,
pub descent: f32,
pub line_gap: f32,
pub x_height: f32,
pub cap_height: f32,
}
impl FaceMetrics {
pub(crate) fn of(face: &Face<'_>) -> Self {
let units_per_em = f32::from(face.units_per_em());
let glyph_top = |ch| {
face.glyph_index(ch)
.and_then(|glyph| face.glyph_bounding_box(glyph))
.map(|bounds| bounds.y_max)
};
let ascent = f32::from(face.ascender()) / units_per_em;
Self {
ascent,
descent: -f32::from(face.descender()) / units_per_em,
line_gap: f32::from(face.line_gap()) / units_per_em,
x_height: face
.x_height()
.filter(|height| *height > 0)
.or_else(|| glyph_top(LOWERCASE_X))
.map_or(FALLBACK_X_HEIGHT_EM, |height| {
f32::from(height) / units_per_em
}),
cap_height: face
.capital_height()
.filter(|height| *height > 0)
.or_else(|| glyph_top(CAPITAL_H))
.map_or(ascent, |height| f32::from(height) / units_per_em),
}
}
pub(crate) fn normal_line_height(&self) -> f32 {
self.ascent + self.descent + self.line_gap
}
}
pub(crate) fn advance(face: &Face<'_>, ch: char) -> Option<f32> {
let glyph = face.glyph_index(ch).filter(|glyph| glyph.0 != 0)?;
Some(f32::from(face.glyph_hor_advance(glyph)?) / f32::from(face.units_per_em()))
}
impl FontBook {
pub(crate) fn first_available_metrics(
&self,
candidates: &[FontId],
selection: FontSelection,
resolver: &dyn ResourceResolver,
) -> Result<FaceMetrics, FontError> {
for &id in candidates {
if let Some(instance) = self.instance(id, selection, resolver)? {
return Ok(FaceMetrics::of(&instance.face));
}
}
Err(FontError::NoAvailableFace)
}
pub(crate) fn advance(
&self,
candidates: &[FontId],
selection: FontSelection,
ch: char,
resolver: &dyn ResourceResolver,
) -> Result<Option<f32>, FontError> {
self.find_glyph(candidates, |id| -> Result<_, FontError> {
let Some(instance) = self.instance(id, selection, resolver)? else {
return Ok(GlyphMatch::Unavailable);
};
Ok(advance(&instance.face, ch).map_or(GlyphMatch::Missing, GlyphMatch::Found))
})
.map(|found| found.map(|(_, advance)| advance))
}
}
pub(crate) struct InitialFont {
faces: Vec<Face<'static>>,
}
impl InitialFont {
pub(crate) fn from_preferences(preferences: &FontPreferences) -> Self {
let book = FontBook::with_preferences(preferences.clone());
let candidates = book.candidates(
&[FontFamily::Generic(DEFAULT_FAMILY)],
FontSelection::default(),
);
Self {
faces: candidates
.iter()
.filter_map(|id| match book.face(*id)?.data {
FontData::Bundled(data) => Some(data),
#[cfg(test)]
FontData::Loaded(_) => None,
FontData::Lazy { .. } => None,
})
.map(|data| parse(data).expect("bundled fonts are valid"))
.collect(),
}
}
pub(crate) fn metrics(&self) -> FaceMetrics {
FaceMetrics::of(&self.faces[0])
}
pub(crate) fn advance(&self, ch: char) -> Option<f32> {
self.faces.iter().find_map(|face| advance(face, ch))
}
}
pub(crate) fn initial_font() -> &'static InitialFont {
static INITIAL: OnceLock<InitialFont> = OnceLock::new();
INITIAL.get_or_init(|| InitialFont::from_preferences(&FontPreferences::default()))
}
fn parse(data: &[u8]) -> Result<Face<'_>, FontError> {
Face::parse(data, 0).map_err(FontError::InvalidFont)
}