use crate::{AsFaceRef, FaceMut, OwnedFace};
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use core::fmt;
use ttf_parser::{cmap, kern, Face, GlyphId};
#[derive(Clone)]
pub struct PreParsedSubtables<'face, F> {
pub face: F,
pub(crate) subtables: FaceSubtables<'face>,
}
impl<'face> From<Face<'face>> for PreParsedSubtables<'face, Face<'face>> {
fn from(face: Face<'face>) -> Self {
let subtables = FaceSubtables::from(&face);
Self { face, subtables }
}
}
impl From<OwnedFace> for PreParsedSubtables<'static, OwnedFace> {
fn from(face: OwnedFace) -> Self {
face.pre_parse_subtables()
}
}
impl<F> fmt::Debug for PreParsedSubtables<'_, F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "PreParsedSubtables")
}
}
#[derive(Clone)]
pub(crate) struct FaceSubtables<'face> {
cmap: Vec<cmap::Subtable<'face>>,
h_kern: Vec<kern::Subtable<'face>>,
}
impl<'face> From<&Face<'face>> for FaceSubtables<'face> {
fn from(face: &Face<'face>) -> Self {
let cmap = face
.tables()
.cmap
.iter()
.flat_map(|cmap| cmap.subtables)
.filter(|st| st.is_unicode())
.collect();
let h_kern = face
.tables()
.kern
.iter()
.flat_map(|c| c.subtables)
.filter(|st| st.horizontal && !st.variable)
.collect();
Self { cmap, h_kern }
}
}
impl<F> PreParsedSubtables<'_, F> {
#[inline]
pub fn glyph_index(&self, c: char) -> Option<GlyphId> {
self.subtables
.cmap
.iter()
.find_map(|t| t.glyph_index(c.into()))
}
#[inline]
pub fn glyph_variation_index(&self, c: char, v: char) -> Option<GlyphId> {
self.subtables
.cmap
.iter()
.find_map(|t| t.glyph_variation_index(c.into(), v.into()))
.and_then(|r| match r {
cmap::GlyphVariationResult::Found(v) => Some(v),
cmap::GlyphVariationResult::UseDefault => self.glyph_index(c),
})
}
#[inline]
pub fn glyphs_hor_kerning(&self, first: GlyphId, second: GlyphId) -> Option<i16> {
self.subtables
.h_kern
.iter()
.find_map(|st| st.glyphs_kerning(first, second))
}
}
impl<F> AsFaceRef for PreParsedSubtables<'_, F>
where
F: AsFaceRef,
{
#[inline]
fn as_face_ref(&self) -> &ttf_parser::Face<'_> {
self.face.as_face_ref()
}
}
impl<F> AsFaceRef for &PreParsedSubtables<'_, F>
where
F: AsFaceRef,
{
#[inline]
fn as_face_ref(&self) -> &ttf_parser::Face<'_> {
(*self).as_face_ref()
}
}
impl<F> FaceMut for PreParsedSubtables<'_, F>
where
F: FaceMut,
{
#[inline]
fn set_variation(&mut self, axis: ttf_parser::Tag, value: f32) -> Option<()> {
self.face.set_variation(axis, value)
}
}
impl<F> FaceMut for &mut PreParsedSubtables<'_, F>
where
F: FaceMut,
{
#[inline]
fn set_variation(&mut self, axis: ttf_parser::Tag, value: f32) -> Option<()> {
(*self).set_variation(axis, value)
}
}