use std::collections::HashMap;
use std::sync::Mutex;
use skrifa::instance::{LocationRef, Size};
use skrifa::outline::{
DrawSettings, Engine, HintingInstance, HintingOptions, OutlinePen, SmoothMode, Target,
};
use skrifa::{FontRef, GlyphId, MetadataProvider};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum GlyphRendering {
#[default]
Natural,
Crisp,
}
const MAX_INSTANCES: usize = 8;
#[derive(Default)]
pub(crate) struct HintCache {
inner: Mutex<Vec<HintedSize>>,
}
struct HintedSize {
ppem_bits: u32,
weight: u16,
instance: HintingInstance,
advances: HashMap<u16, Option<f32>>,
linear: HashMap<u16, Option<f32>>,
}
fn hinting_options() -> HintingOptions {
HintingOptions {
engine: Engine::Auto(None),
target: Target::Smooth {
mode: SmoothMode::Normal,
symmetric_rendering: true,
preserve_linear_metrics: false,
},
}
}
fn location(font: &FontRef<'_>, weight: u16) -> skrifa::instance::Location {
font.axes().location([("wght", f32::from(weight))])
}
impl HintCache {
fn with_size<R>(
&self,
font: &FontRef<'_>,
ppem: f32,
weight: u16,
f: impl FnOnce(&mut HintedSize) -> R,
) -> Option<R> {
let mut sizes = self.inner.lock().unwrap_or_else(|e| e.into_inner());
let ppem_bits = ppem.to_bits();
let index = match sizes
.iter()
.position(|s| s.ppem_bits == ppem_bits && s.weight == weight)
{
Some(index) => index,
None => {
let outlines = font.outline_glyphs();
let location = location(font, weight);
let instance = HintingInstance::new(
&outlines,
Size::new(ppem),
LocationRef::from(&location),
hinting_options(),
)
.ok()?;
if sizes.len() >= MAX_INSTANCES {
sizes.remove(0);
}
sizes.push(HintedSize {
ppem_bits,
weight,
instance,
advances: HashMap::new(),
linear: HashMap::new(),
});
sizes.len() - 1
}
};
Some(f(&mut sizes[index]))
}
pub(crate) fn advances(
&self,
font_data: &[u8],
face_index: u32,
glyph_id: u16,
ppem: f32,
weight: u16,
) -> Option<(f32, f32)> {
let font = FontRef::from_index(font_data, face_index).ok()?;
self.with_size(&font, ppem, weight, |size| {
let hinted = *size.advances.entry(glyph_id).or_insert_with(|| {
let outlines = font.outline_glyphs();
let glyph = outlines.get(GlyphId::new(u32::from(glyph_id)))?;
let metrics = glyph
.draw(
DrawSettings::hinted(&size.instance, false),
&mut skrifa::outline::pen::NullPen,
)
.ok()?;
metrics.advance_width
});
let linear = *size.linear.entry(glyph_id).or_insert_with(|| {
let location = location(&font, weight);
font.glyph_metrics(Size::new(ppem), LocationRef::from(&location))
.advance_width(GlyphId::new(u32::from(glyph_id)))
});
Some((hinted?, linear?))
})
.flatten()
}
pub(crate) fn draw(
&self,
font_data: &[u8],
face_index: u32,
glyph_id: u16,
ppem: f32,
weight: u16,
pen: &mut impl OutlinePen,
) -> bool {
let Ok(font) = FontRef::from_index(font_data, face_index) else {
return false;
};
self.with_size(&font, ppem, weight, |size| {
let outlines = font.outline_glyphs();
outlines
.get(GlyphId::new(u32::from(glyph_id)))
.is_some_and(|glyph| {
glyph
.draw(DrawSettings::hinted(&size.instance, false), pen)
.is_ok()
})
})
.unwrap_or(false)
}
}
pub(crate) fn crisp_advance(
shaped: f32,
hinted_device: f32,
linear_device: f32,
scale_factor: f32,
) -> f32 {
let shaped_device = shaped * scale_factor;
let adjustment = (shaped_device - linear_device).round();
(hinted_device + adjustment).max(0.0) / scale_factor
}
pub(crate) fn crisp_offset(offset: f32, scale_factor: f32) -> f32 {
(offset * scale_factor).round() / scale_factor
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_advance_keeps_its_kerning_rounded() {
assert_eq!(crisp_advance(6.7, 7.0, 7.3, 1.0), 6.0);
assert_eq!(crisp_advance(7.3, 7.0, 7.3, 1.0), 7.0);
assert!((crisp_advance(4.8, 7.0, 7.2, 1.5) - 7.0 / 1.5).abs() < 1e-6);
assert_eq!(crisp_advance(0.0, 0.0, 0.0, 1.0), 0.0);
}
#[test]
fn an_offset_lands_on_a_device_pixel() {
assert_eq!(crisp_offset(1.4, 1.0), 1.0);
assert!((crisp_offset(1.4, 1.5) * 1.5 - 2.0).abs() < 1e-6);
}
}