pub use super::outline::{AdjustedMetrics as ScalerMetrics, DrawError as Error};
pub use read_fonts::types::Pen;
use core::borrow::Borrow;
use read_fonts::{
types::{Fixed, GlyphId},
TableProvider,
};
use super::{
font::UniqueId,
instance::{NormalizedCoord, Size},
outline,
setting::VariationSetting,
};
pub type Result<T> = core::result::Result<T, Error>;
#[derive(Copy, Clone, PartialEq, Eq, Default, Debug)]
pub enum Hinting {
#[default]
None,
Full,
Light,
LightSubpixel,
VerticalSubpixel,
}
#[derive(Clone, Default, Debug)]
pub struct Context {
coords: Vec<NormalizedCoord>,
variations: Vec<VariationSetting>,
}
impl Context {
pub fn new() -> Self {
Self::default()
}
pub fn new_scaler(&mut self) -> ScalerBuilder {
ScalerBuilder::new(self)
}
}
pub struct ScalerBuilder<'a> {
context: &'a mut Context,
cache_key: Option<UniqueId>,
size: Size,
hint: Option<Hinting>,
}
impl<'a> ScalerBuilder<'a> {
pub fn new(context: &'a mut Context) -> Self {
context.coords.clear();
context.variations.clear();
Self {
context,
cache_key: None,
size: Size::unscaled(),
hint: None,
}
}
pub fn cache_key(mut self, key: Option<UniqueId>) -> Self {
self.cache_key = key;
self
}
pub fn size(mut self, size: Size) -> Self {
self.size = size;
self
}
pub fn hint(mut self, hint: Option<Hinting>) -> Self {
self.hint = hint;
self
}
pub fn normalized_coords<I>(self, coords: I) -> Self
where
I: IntoIterator,
I::Item: Borrow<NormalizedCoord>,
{
self.context.variations.clear();
self.context.coords.clear();
self.context
.coords
.extend(coords.into_iter().map(|v| *v.borrow()));
self
}
pub fn variation_settings<I>(self, settings: I) -> Self
where
I: IntoIterator,
I::Item: Into<VariationSetting>,
{
self.context.coords.clear();
self.context
.variations
.extend(settings.into_iter().map(|v| v.into()));
self
}
pub fn build(mut self, font: &impl TableProvider<'a>) -> Scaler<'a> {
self.resolve_variations(font);
let coords = &self.context.coords[..];
let outlines = outline::OutlineGlyphCollection::new(font);
Scaler {
outlines,
size: self.size,
coords,
}
}
fn resolve_variations(&mut self, font: &impl TableProvider<'a>) {
if self.context.variations.is_empty() {
return; }
let Ok(fvar) = font.fvar() else {
return; };
let Ok(axes) = fvar.axes() else {
return; };
let avar_mappings = font.avar().ok().map(|avar| avar.axis_segment_maps());
let axis_count = fvar.axis_count() as usize;
self.context.coords.clear();
self.context
.coords
.resize(axis_count, NormalizedCoord::default());
for variation in &self.context.variations {
for (i, axis) in axes
.iter()
.enumerate()
.filter(|(_, axis)| axis.axis_tag() == variation.selector)
{
let coord = axis.normalize(Fixed::from_f64(variation.value as f64));
let coord = avar_mappings
.as_ref()
.and_then(|mappings| mappings.get(i).transpose().ok())
.flatten()
.map(|mapping| mapping.apply(coord))
.unwrap_or(coord);
self.context.coords[i] = coord.to_f2dot14();
}
}
}
}
pub struct Scaler<'a> {
outlines: outline::OutlineGlyphCollection<'a>,
size: Size,
coords: &'a [NormalizedCoord],
}
impl<'a> Scaler<'a> {
pub fn normalized_coords(&self) -> &[NormalizedCoord] {
self.coords
}
pub fn has_outlines(&self) -> bool {
self.outlines.format().is_some()
}
pub fn outline(&mut self, glyph_id: GlyphId, pen: &mut impl Pen) -> Result<ScalerMetrics> {
let outline = self
.outlines
.get(glyph_id)
.ok_or(Error::GlyphNotFound(glyph_id))?;
outline.draw((self.size, self.coords), pen)
}
}
#[cfg(test)]
mod tests {
use super::{Context, Size};
use read_fonts::{scaler_test, types::GlyphId, FontRef, TableProvider};
#[test]
fn vazirmatin_var() {
compare_glyphs(
font_test_data::VAZIRMATN_VAR,
font_test_data::VAZIRMATN_VAR_GLYPHS,
);
}
#[test]
fn cantarell_vf() {
compare_glyphs(
font_test_data::CANTARELL_VF_TRIMMED,
font_test_data::CANTARELL_VF_TRIMMED_GLYPHS,
);
}
#[test]
fn noto_serif_display() {
compare_glyphs(
font_test_data::NOTO_SERIF_DISPLAY_TRIMMED,
font_test_data::NOTO_SERIF_DISPLAY_TRIMMED_GLYPHS,
);
}
#[test]
fn overlap_flags() {
let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
let mut cx = Context::new();
let mut path = scaler_test::Path::default();
let mut scaler = cx.new_scaler().build(&font);
let glyph_count = font.maxp().unwrap().num_glyphs();
let expected_gids_with_overlap = vec![2, 3];
assert_eq!(
expected_gids_with_overlap,
(0..glyph_count)
.filter(|gid| scaler
.outline(GlyphId::new(*gid), &mut path)
.unwrap()
.has_overlaps)
.collect::<Vec<_>>()
);
}
fn compare_glyphs(font_data: &[u8], expected_outlines: &str) {
let font = FontRef::new(font_data).unwrap();
let outlines = scaler_test::parse_glyph_outlines(expected_outlines);
let mut cx = Context::new();
let mut path = scaler_test::Path::default();
for expected_outline in &outlines {
if expected_outline.size == 0.0 && !expected_outline.coords.is_empty() {
continue;
}
path.elements.clear();
let mut scaler = cx
.new_scaler()
.size(Size::new(expected_outline.size))
.normalized_coords(&expected_outline.coords)
.build(&font);
scaler
.outline(expected_outline.glyph_id, &mut path)
.unwrap();
if path.elements != expected_outline.path {
panic!(
"mismatch in glyph path for id {} (size: {}, coords: {:?}): path: {:?} expected_path: {:?}",
expected_outline.glyph_id,
expected_outline.size,
expected_outline.coords,
&path.elements,
&expected_outline.path
);
}
}
}
}