use read_fonts::{
tables::{glyf::Glyf, hmtx::LongMetric, hvar::Hvar, loca::Loca, os2::SelectionFlags},
types::{BigEndian, GlyphId},
TableProvider,
};
use super::instance::{LocationRef, NormalizedCoord, Size};
pub type BoundingBox = read_fonts::types::BoundingBox<f32>;
#[derive(Copy, Clone, PartialEq, Default, Debug)]
pub struct Decoration {
pub offset: f32,
pub thickness: f32,
}
#[derive(Copy, Clone, PartialEq, Default, Debug)]
pub struct Metrics {
pub units_per_em: u16,
pub glyph_count: u16,
pub is_monospace: bool,
pub italic_angle: f32,
pub ascent: f32,
pub descent: f32,
pub leading: f32,
pub cap_height: Option<f32>,
pub x_height: Option<f32>,
pub average_width: Option<f32>,
pub max_width: Option<f32>,
pub underline: Option<Decoration>,
pub strikeout: Option<Decoration>,
pub bounds: Option<BoundingBox>,
}
impl Metrics {
pub fn new<'a>(
font: &impl TableProvider<'a>,
size: Size,
location: impl Into<LocationRef<'a>>,
) -> Self {
let head = font.head();
let mut metrics = Metrics {
units_per_em: head.map(|head| head.units_per_em()).unwrap_or_default(),
..Default::default()
};
let coords = location.into().coords();
let scale = size.linear_scale(metrics.units_per_em);
if let Ok(head) = font.head() {
metrics.bounds = Some(BoundingBox {
x_min: head.x_min() as f32 * scale,
y_min: head.y_min() as f32 * scale,
x_max: head.x_max() as f32 * scale,
y_max: head.y_max() as f32 * scale,
});
}
if let Ok(maxp) = font.maxp() {
metrics.glyph_count = maxp.num_glyphs();
}
if let Ok(post) = font.post() {
metrics.is_monospace = post.is_fixed_pitch() != 0;
metrics.italic_angle = post.italic_angle().to_f64() as f32;
metrics.underline = Some(Decoration {
offset: post.underline_position().to_i16() as f32 * scale,
thickness: post.underline_thickness().to_i16() as f32 * scale,
});
}
let hhea = font.hhea();
if let Ok(hhea) = &hhea {
metrics.max_width = Some(hhea.advance_width_max().to_u16() as f32 * scale);
}
let os2 = font.os2().ok();
let mut used_typo_metrics = false;
if let Some(os2) = &os2 {
if os2
.fs_selection()
.contains(SelectionFlags::USE_TYPO_METRICS)
{
metrics.ascent = os2.s_typo_ascender() as f32 * scale;
metrics.descent = os2.s_typo_descender() as f32 * scale;
metrics.leading = os2.s_typo_line_gap() as f32 * scale;
used_typo_metrics = true;
}
metrics.average_width = Some(os2.x_avg_char_width() as f32 * scale);
metrics.cap_height = os2.s_cap_height().map(|v| v as f32 * scale);
metrics.x_height = os2.sx_height().map(|v| v as f32 * scale);
metrics.strikeout = Some(Decoration {
offset: os2.y_strikeout_position() as f32 * scale,
thickness: os2.y_strikeout_size() as f32 * scale,
});
}
if !used_typo_metrics {
if let Ok(hhea) = font.hhea() {
metrics.ascent = hhea.ascender().to_i16() as f32 * scale;
metrics.descent = hhea.descender().to_i16() as f32 * scale;
metrics.leading = hhea.line_gap().to_i16() as f32 * scale;
}
if metrics.ascent == 0.0 && metrics.descent == 0.0 {
if let Some(os2) = &os2 {
if os2.s_typo_ascender() != 0 || os2.s_typo_descender() != 0 {
metrics.ascent = os2.s_typo_ascender() as f32 * scale;
metrics.descent = os2.s_typo_descender() as f32 * scale;
metrics.leading = os2.s_typo_line_gap() as f32 * scale;
} else {
metrics.ascent = os2.us_win_ascent() as f32 * scale;
metrics.descent = -(os2.us_win_descent() as f32 * scale);
}
}
}
}
if let (Ok(mvar), true) = (font.mvar(), !coords.is_empty()) {
use read_fonts::tables::mvar::tags::*;
let metric_delta =
|tag| mvar.metric_delta(tag, coords).unwrap_or_default().to_f64() as f32 * scale;
metrics.ascent += metric_delta(HASC);
metrics.descent += metric_delta(HDSC);
metrics.leading += metric_delta(HLGP);
if let Some(cap_height) = &mut metrics.cap_height {
*cap_height += metric_delta(CPHT);
}
if let Some(x_height) = &mut metrics.x_height {
*x_height += metric_delta(XHGT);
}
if let Some(underline) = &mut metrics.underline {
underline.offset += metric_delta(UNDO);
underline.thickness += metric_delta(UNDS);
}
if let Some(strikeout) = &mut metrics.strikeout {
strikeout.offset += metric_delta(STRO);
strikeout.thickness += metric_delta(STRS);
}
}
metrics
}
}
#[derive(Clone)]
pub struct GlyphMetrics<'a> {
glyph_count: u16,
scale: f32,
h_metrics: &'a [LongMetric],
default_advance_width: u16,
lsbs: &'a [BigEndian<i16>],
hvar: Option<Hvar<'a>>,
loca_glyf: Option<(Loca<'a>, Glyf<'a>)>,
coords: &'a [NormalizedCoord],
}
impl<'a> GlyphMetrics<'a> {
pub fn new(
font: &impl TableProvider<'a>,
size: Size,
location: impl Into<LocationRef<'a>>,
) -> Self {
let glyph_count = font
.maxp()
.map(|maxp| maxp.num_glyphs())
.unwrap_or_default();
let upem = font
.head()
.map(|head| head.units_per_em())
.unwrap_or_default();
let scale = size.linear_scale(upem);
let coords = location.into().coords();
let (h_metrics, default_advance_width, lsbs) = font
.hmtx()
.map(|hmtx| {
let h_metrics = hmtx.h_metrics();
let default_advance_width = h_metrics.last().map(|m| m.advance.get()).unwrap_or(0);
let lsbs = hmtx.left_side_bearings();
(h_metrics, default_advance_width, lsbs)
})
.unwrap_or_default();
let hvar = font.hvar().ok();
let loca_glyf = if let (Ok(loca), Ok(glyf)) = (font.loca(None), font.glyf()) {
Some((loca, glyf))
} else {
None
};
Self {
glyph_count,
scale,
h_metrics,
default_advance_width,
lsbs,
hvar,
loca_glyf,
coords,
}
}
pub fn glyph_count(&self) -> u16 {
self.glyph_count
}
pub fn advance_width(&self, glyph_id: GlyphId) -> Option<f32> {
if glyph_id.to_u16() >= self.glyph_count {
return None;
}
let mut advance = self
.h_metrics
.get(glyph_id.to_u16() as usize)
.map(|metric| metric.advance())
.unwrap_or(self.default_advance_width) as i32;
if let Some(hvar) = &self.hvar {
advance += hvar
.advance_width_delta(glyph_id, self.coords)
.map(|delta| delta.to_f64() as i32)
.unwrap_or(0);
}
Some(advance as f32 * self.scale)
}
pub fn left_side_bearing(&self, glyph_id: GlyphId) -> Option<f32> {
if glyph_id.to_u16() >= self.glyph_count {
return None;
}
let gid_index = glyph_id.to_u16() as usize;
let mut lsb = self
.h_metrics
.get(gid_index)
.map(|metric| metric.side_bearing())
.unwrap_or_else(|| {
self.lsbs
.get(gid_index.saturating_sub(self.h_metrics.len()))
.map(|lsb| lsb.get())
.unwrap_or_default()
}) as i32;
if let Some(hvar) = &self.hvar {
lsb += hvar
.lsb_delta(glyph_id, self.coords)
.map(|delta| delta.to_f64() as i32)
.unwrap_or(0);
}
Some(lsb as f32 * self.scale)
}
pub fn bounds(&self, glyph_id: GlyphId) -> Option<BoundingBox> {
let (loca, glyf) = self.loca_glyf.as_ref()?;
Some(match loca.get_glyf(glyph_id, glyf).ok()? {
Some(glyph) => BoundingBox {
x_min: glyph.x_min() as f32 * self.scale,
y_min: glyph.y_min() as f32 * self.scale,
x_max: glyph.x_max() as f32 * self.scale,
y_max: glyph.y_max() as f32 * self.scale,
},
None => BoundingBox::default(),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::MetadataProvider as _;
use font_test_data::{SIMPLE_GLYF, VAZIRMATN_VAR};
use read_fonts::FontRef;
#[test]
fn metrics() {
let font = FontRef::new(SIMPLE_GLYF).unwrap();
let metrics = font.metrics(Size::unscaled(), LocationRef::default());
let expected = Metrics {
units_per_em: 1024,
glyph_count: 3,
bounds: Some(BoundingBox {
x_min: 51.0,
y_min: -250.0,
x_max: 998.0,
y_max: 950.0,
}),
average_width: Some(1275.0),
max_width: None,
x_height: Some(512.0),
cap_height: Some(717.0),
is_monospace: false,
italic_angle: 0.0,
ascent: 950.0,
descent: -250.0,
leading: 0.0,
underline: None,
strikeout: Some(Decoration {
offset: 307.0,
thickness: 51.0,
}),
};
assert_eq!(metrics, expected);
}
#[test]
fn metrics_missing_os2() {
let font = FontRef::new(VAZIRMATN_VAR).unwrap();
let metrics = font.metrics(Size::unscaled(), LocationRef::default());
let expected = Metrics {
units_per_em: 2048,
glyph_count: 4,
bounds: Some(BoundingBox {
x_min: 29.0,
y_min: 0.0,
x_max: 1310.0,
y_max: 1847.0,
}),
average_width: None,
max_width: Some(1336.0),
x_height: None,
cap_height: None,
is_monospace: false,
italic_angle: 0.0,
ascent: 2100.0,
descent: -1100.0,
leading: 0.0,
underline: None,
strikeout: None,
};
assert_eq!(metrics, expected);
}
#[test]
fn glyph_metrics() {
let font = FontRef::new(VAZIRMATN_VAR).unwrap();
let glyph_metrics = font.glyph_metrics(Size::unscaled(), LocationRef::default());
let expected = &[
(908.0, 100.0),
(1336.0, 29.0),
(1336.0, 29.0),
(633.0, 57.0),
];
let result = (0..4)
.map(|i| {
let gid = GlyphId::new(i as u16);
let advance_width = glyph_metrics.advance_width(gid).unwrap();
let lsb = glyph_metrics.left_side_bearing(gid).unwrap();
(advance_width, lsb)
})
.collect::<Vec<_>>();
assert_eq!(expected, &result[..]);
}
#[test]
fn glyph_metrics_var() {
let font = FontRef::new(VAZIRMATN_VAR).unwrap();
let coords = &[NormalizedCoord::from_f32(-0.8)];
let glyph_metrics = font.glyph_metrics(Size::unscaled(), LocationRef::new(coords));
let expected = &[
(908.0, 100.0),
(1246.0, 29.0),
(1246.0, 29.0),
(556.0, 57.0),
];
let result = (0..4)
.map(|i| {
let gid = GlyphId::new(i as u16);
let advance_width = glyph_metrics.advance_width(gid).unwrap();
let lsb = glyph_metrics.left_side_bearing(gid).unwrap();
(advance_width, lsb)
})
.collect::<Vec<_>>();
assert_eq!(expected, &result[..]);
}
}