use super::{
cff, AdjustedMetrics, DrawError, Hinting, LocationRef, NormalizedCoord, OutlineCollectionKind,
OutlineGlyph, OutlineGlyphCollection, OutlineKind, OutlinePen, Size,
};
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum EmbeddedHinting {
Full,
Light,
LightSubpixel,
VerticalSubpixel,
}
#[derive(Clone)]
pub struct EmbeddedHintingInstance {
size: Size,
coords: Vec<NormalizedCoord>,
mode: EmbeddedHinting,
kind: HinterKind,
}
impl EmbeddedHintingInstance {
pub fn new<'a>(
outline_glyphs: &OutlineGlyphCollection,
size: Size,
location: impl Into<LocationRef<'a>>,
mode: EmbeddedHinting,
) -> Result<Self, DrawError> {
let mut hinter = Self {
size: Size::unscaled(),
coords: vec![],
mode,
kind: HinterKind::None,
};
hinter.reconfigure(outline_glyphs, size, location, mode)?;
Ok(hinter)
}
pub fn size(&self) -> Size {
self.size
}
pub fn location(&self) -> LocationRef {
LocationRef::new(&self.coords)
}
pub fn mode(&self) -> EmbeddedHinting {
self.mode
}
pub fn reconfigure<'a>(
&mut self,
outlines: &OutlineGlyphCollection,
size: Size,
location: impl Into<LocationRef<'a>>,
mode: EmbeddedHinting,
) -> Result<(), DrawError> {
self.size = size;
self.coords.clear();
self.coords.extend_from_slice(location.into().coords());
self.mode = mode;
let current_kind = core::mem::replace(&mut self.kind, HinterKind::None);
match &outlines.kind {
OutlineCollectionKind::Glyf(_) => {
self.kind = HinterKind::Glyf;
}
OutlineCollectionKind::Cff(cff) => {
let mut subfonts = match current_kind {
HinterKind::Cff(subfonts) => subfonts,
_ => vec![],
};
subfonts.clear();
let size = size.ppem().unwrap_or_default();
for i in 0..cff.subfont_count() {
subfonts.push(cff.subfont(i, size, &self.coords)?);
}
self.kind = HinterKind::Cff(subfonts);
}
OutlineCollectionKind::None => {}
}
Ok(())
}
pub(super) fn draw(
&self,
glyph: &OutlineGlyph,
memory: Option<&mut [u8]>,
pen: &mut impl OutlinePen,
) -> Result<AdjustedMetrics, DrawError> {
let ppem = self.size.ppem().unwrap_or_default();
let coords = self.coords.as_slice();
match (&self.kind, &glyph.kind) {
(HinterKind::Glyf, OutlineKind::Glyf(glyf, outline)) => {
super::with_glyf_memory(outline, Hinting::Embedded, memory, |buf| {
let mem = outline
.memory_from_buffer(buf, Hinting::Embedded)
.ok_or(DrawError::InsufficientMemory)?;
let scaled_outline = glyf.draw(mem, outline, ppem, coords)?;
scaled_outline.to_path(pen)?;
Ok(AdjustedMetrics {
has_overlaps: outline.has_overlaps,
lsb: Some(scaled_outline.adjusted_lsb().to_f32()),
advance_width: Some(scaled_outline.adjusted_advance_width().to_f32()),
})
})
}
(HinterKind::Cff(subfonts), OutlineKind::Cff(cff, glyph_id, subfont_ix)) => {
let Some(subfont) = subfonts.get(*subfont_ix as usize) else {
return Err(DrawError::NoSources);
};
cff.draw(subfont, *glyph_id, &self.coords, true, pen)?;
Ok(AdjustedMetrics::default())
}
_ => Err(DrawError::NoSources),
}
}
}
#[derive(Clone)]
enum HinterKind {
None,
Glyf,
Cff(Vec<cff::Subfont>),
}