mod error;
mod hinting;
mod postscript;
mod truetype;
#[cfg(test)]
mod tests;
pub use crate::outline::glyf::{DropoutControl, RasterPolicy};
pub use error::ScaleError;
use hinting::EngineRequest;
pub use hinting::{HintEngine, HintOptions, RasterTarget};
pub use raw::model::glyph::outline::{DrawMemory, DrawnMetrics, OutlineSource, PathSink};
pub use raw::model::glyph::{GlyphSource, GlyphSourceOrder};
use crate::{
font::Font,
instance::Size,
outline::{autohint, pen::PathStyle, AdjustedMetrics},
};
use alloc::boxed::Box;
#[cfg(feature = "libm")]
#[allow(unused_imports)]
use core_maths::CoreFloat;
use raw::{
model::glyph::outline::{DrawOptions, OutlineGlyph, OutlineGlyphs, PathContourStart},
model::metrics::{ScaleF32, ScaledGlyphMetrics, ScaledMetrics, ScaledStyleMetrics},
ps::cff::CffFontRef,
types::{Fixed, GlyphId},
};
use yoke::Yoke;
const _: () = {
fn shared<T: Send + Sync>() {}
let _ = shared::<ScalerFont>;
};
impl From<AdjustedMetrics> for DrawnMetrics {
fn from(metrics: AdjustedMetrics) -> Self {
let mut computed = Self::default();
computed.h_advance = metrics.advance_width;
computed.x_bearing = metrics.lsb;
computed.has_overlaps = metrics.has_overlaps;
computed
}
}
pub struct ScalerFont {
outlines: Yoke<OutlineGlyphs<'static>, Box<Font>>,
order: GlyphSourceOrder,
ppem: Option<f32>,
hint_options: Option<HintOptions>,
state: State,
}
#[derive(Clone)]
pub struct ScalerSource {
font: Font,
order: GlyphSourceOrder,
}
impl ScalerSource {
pub fn new(font: Font, order: GlyphSourceOrder) -> Self {
Self { font, order }
}
}
impl core::fmt::Debug for ScalerSource {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("ScalerSource")
.field("order", &self.order)
.finish_non_exhaustive()
}
}
impl From<Font> for ScalerSource {
fn from(font: Font) -> Self {
Self::new(font, GlyphSourceOrder::DEFAULT)
}
}
impl core::fmt::Debug for ScalerFont {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("ScalerFont")
.field("outline_source", &self.outline_source())
.field("ppem", &self.ppem)
.field("hint_options", &self.hint_options)
.field("hint_engine", &self.hint_engine())
.finish_non_exhaustive()
}
}
enum State {
Unhinted,
Failed(Box<ScaleError>),
TrueType(Box<truetype::TrueTypeHinter>),
PostScript(postscript::PostScriptHinter),
Auto(autohint::Instance),
}
impl ScalerFont {
pub fn unhinted(font: impl Into<ScalerSource>, ppem: Option<f32>) -> Self {
let source = font.into();
let tricky = ppem.is_some() && source.font.is_hint_reliant();
let mut scaler = Self {
order: source.order,
outlines: resolve_outlines(source),
ppem,
hint_options: tricky.then(HintOptions::interpreter),
state: State::Unhinted,
};
scaler.configure();
scaler
}
pub fn force_unhinted(font: impl Into<ScalerSource>, ppem: Option<f32>) -> Self {
let source = font.into();
Self {
order: source.order,
outlines: resolve_outlines(source),
ppem,
hint_options: None,
state: State::Unhinted,
}
}
pub fn hinted(font: impl Into<ScalerSource>, ppem: f32, hint_options: HintOptions) -> Self {
let source = font.into();
let mut scaler = Self {
order: source.order,
outlines: resolve_outlines(source),
ppem: Some(ppem),
hint_options: Some(hint_options),
state: State::Unhinted,
};
scaler.configure();
scaler
}
pub fn reconfigure(
&mut self,
font: impl Into<ScalerSource>,
ppem: f32,
hint_options: HintOptions,
) {
let source = font.into();
self.order = source.order;
self.outlines = resolve_outlines(source);
self.ppem = Some(ppem);
self.hint_options = Some(hint_options);
self.configure();
}
pub fn font(&self) -> &Font {
self.outlines.backing_cart()
}
pub fn outline_source(&self) -> Option<OutlineSource> {
self.outlines.get().source()
}
pub fn underlying_outline_source(&self) -> Option<OutlineSource> {
self.outlines.get().underlying_source()
}
pub fn ppem(&self) -> Option<f32> {
self.ppem
}
pub fn hinted_ppem(&self) -> Option<f32> {
match &self.state {
State::TrueType(hinter) => hinter.ppem().or(self.ppem),
_ => self.ppem,
}
}
pub fn hint_engine(&self) -> Option<HintEngine> {
match &self.state {
State::TrueType(_) => Some(HintEngine::TrueType),
State::PostScript(_) => Some(HintEngine::PostScript),
State::Auto(_) => Some(HintEngine::Auto),
State::Unhinted | State::Failed(_) => None,
}
}
pub fn hint_options(&self) -> Option<HintOptions> {
self.hint_options
}
pub fn is_hinted(&self) -> bool {
match &self.state {
State::TrueType(hinter) => hinter.is_enabled(),
State::PostScript(_) | State::Auto(_) => true,
State::Unhinted | State::Failed(_) => false,
}
}
pub fn hinting_error(&self) -> Option<&ScaleError> {
match &self.state {
State::Failed(error) => Some(error),
_ => None,
}
}
pub fn raster_policy(&self) -> Option<RasterPolicy> {
match &self.state {
State::TrueType(hinter) => Some(hinter.raster_policy()),
_ => None,
}
}
pub fn metrics(&self) -> ScaledMetrics<'_, ScaleF32> {
let metrics = self.font().metrics();
metrics.scaled_f32(self.ppem.unwrap_or(metrics.units_per_em as f32))
}
pub fn style_metrics(&self) -> ScaledStyleMetrics<'_, ScaleF32> {
let style = self.font().style_metrics();
style.scaled_f32(self.ppem.unwrap_or(style.units_per_em as f32))
}
pub fn linear_glyph_metrics(&self) -> ScaledGlyphMetrics<'_, 'static, ScaleF32> {
let font = self.font();
let ppem = self.ppem.unwrap_or(font.units_per_em() as f32);
font.glyph_metrics()
.with_extents_source_order(self.order)
.scaled_f32(ppem)
}
pub fn outline(&self, glyph: GlyphId) -> Option<ScalerOutline<'_>> {
let outline = self.outlines.get().get(glyph)?;
Some(ScalerOutline {
scaler: self,
outline,
})
}
fn configure(&mut self) {
let previous = core::mem::replace(&mut self.state, State::Unhinted);
let (Some(hinting), Some(ppem)) = (&self.hint_options, self.ppem) else {
return;
};
self.state = match EngineChoice::new(self.font(), self.outlines.get(), hinting) {
EngineChoice::TrueType => {
let mut hinter = match previous {
State::TrueType(hinter) => hinter,
_ => Box::default(),
};
match hinter.reconfigure(self.font(), ppem, hinting) {
Ok(()) => State::TrueType(hinter),
Err(error) => State::Failed(Box::new(error)),
}
}
EngineChoice::PostScript(cff) => {
let mut hinter = match previous {
State::PostScript(hinter) => hinter,
_ => Default::default(),
};
hinter.reconfigure(cff, self.font().normalized_coords(), ppem);
State::PostScript(hinter)
}
EngineChoice::Auto => State::Auto(autohint::Instance::from_state(
autohint::LocatedState::of_outlines(self.font(), *self.outlines.get()),
hinting.outline_target(),
)),
EngineChoice::None => State::Unhinted,
};
}
fn draw_unhinted(
&self,
outline: &OutlineGlyph<'_>,
ppem: Option<f32>,
memory: Option<&mut [u8]>,
sink: &mut dyn PathSink,
) -> Result<DrawnMetrics, ScaleError> {
let glyph = outline.glyph();
let options = draw_options(ppem);
let supplied = memory.as_ref().map_or(0, |memory| memory.len());
let memory = memory.map_or(DrawMemory::Scratch, DrawMemory::Buffer);
let metrics = outline.draw(&options, memory, sink).map_err(|error| {
ScaleError::from_outline(error, outline.required_memory_size(), supplied)
})?;
let mut h_advance = metrics.h_advance;
if let (None, OutlineGlyph::Cff(charstring)) = (h_advance, outline) {
let advance = self.font().glyph_metrics().h_advance_exact(glyph).round();
let advance = Fixed::from_i32(advance.to_i32());
let transform = charstring
.cff_font()
.transform(charstring.subfont(), options.ppem);
h_advance = Some(transform.transform_h_metric(advance).to_f32());
}
if let OutlineGlyph::Cff(_) = outline {
h_advance = h_advance.filter(|advance| *advance >= 0.0);
}
if self.hint_options.is_some() && !matches!(outline, OutlineGlyph::Varc(_)) {
h_advance = h_advance.map(|advance| advance.round());
}
let mut metrics = metrics;
metrics.h_advance = h_advance;
Ok(metrics)
}
}
enum EngineChoice<'a> {
TrueType,
PostScript(&'a CffFontRef<'a>),
Auto,
None,
}
impl<'a> EngineChoice<'a> {
fn new(font: &'a Font, outlines: &OutlineGlyphs<'a>, hinting: &HintOptions) -> Self {
let source = outlines.underlying_source();
if source == Some(OutlineSource::Glyf) && font.is_hint_reliant() {
return Self::TrueType;
}
let instructions = match hinting.engine() {
EngineRequest::Interpreter => true,
EngineRequest::Auto => false,
EngineRequest::AutoFallback => match source {
Some(OutlineSource::Glyf) => truetype::prefer_interpreter(font.tables()),
_ => true,
},
};
if !instructions {
return Self::Auto;
}
match source {
Some(OutlineSource::Glyf) => Self::TrueType,
Some(OutlineSource::Cff2 | OutlineSource::Cff) => {
outlines.cff_font().map_or(Self::None, Self::PostScript)
}
_ => Self::None,
}
}
}
#[derive(Clone)]
pub struct ScalerOutline<'a> {
scaler: &'a ScalerFont,
outline: OutlineGlyph<'a>,
}
impl core::fmt::Debug for ScalerOutline<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("ScalerOutline")
.field("glyph", &self.glyph())
.field("source", &self.source())
.finish()
}
}
impl ScalerOutline<'_> {
pub fn glyph(&self) -> GlyphId {
self.outline.glyph()
}
pub fn source(&self) -> OutlineSource {
self.outline.source()
}
pub fn required_memory_size(&self) -> usize {
match (&self.scaler.state, &self.outline) {
(State::Auto(_), _) => 0,
(State::TrueType(hinter), OutlineGlyph::Glyf(glyf)) if hinter.is_enabled() => {
hinter.required_memory_size(glyf)
}
_ => self.outline.required_memory_size(),
}
}
pub fn draw(
&self,
memory: DrawMemory<'_>,
sink: &mut impl PathSink,
) -> Result<DrawnMetrics, ScaleError> {
let memory = match memory {
DrawMemory::Buffer(buffer) => Some(buffer),
_ => None,
};
self.draw_dyn(memory, sink)
}
fn draw_dyn(
&self,
memory: Option<&mut [u8]>,
sink: &mut dyn PathSink,
) -> Result<DrawnMetrics, ScaleError> {
let scaler = self.scaler;
match (&scaler.state, &self.outline) {
(State::Failed(error), _) => Err(ScaleError::clone(error)),
(State::Auto(instance), _) => {
let context = autohint::FontContext::for_glyph(
scaler.font(),
*scaler.outlines.get(),
&self.outline,
);
let size = scaler.ppem.map_or_else(Size::unscaled, Size::new);
let mut sink = sink;
let mut metrics = DrawnMetrics::from(
instance
.draw(&context, size, self.glyph(), PathStyle::FreeType, &mut sink)
.map_err(|error| {
let supplied = memory.as_ref().map_or(0, |memory| memory.len());
ScaleError::from_draw_error(error, 0, supplied)
})?,
);
if matches!(self.outline, OutlineGlyph::Varc(_)) {
metrics.h_advance = None;
}
Ok(metrics)
}
(State::TrueType(hinter), OutlineGlyph::Glyf(glyf)) if hinter.is_enabled() => {
hinter.draw(glyf, memory, sink)
}
(State::PostScript(hinter), OutlineGlyph::Cff(charstring)) => {
hinter.draw(scaler.font(), charstring, sink)
}
(State::TrueType(hinter), OutlineGlyph::Glyf(_)) => {
let ppem = hinter.program_unhinted_ppem().or(scaler.ppem);
scaler.draw_unhinted(&self.outline, ppem, memory, sink)
}
_ => scaler.draw_unhinted(&self.outline, scaler.ppem, memory, sink),
}
}
}
fn resolve_outlines(source: ScalerSource) -> Yoke<OutlineGlyphs<'static>, Box<Font>> {
let order = source.order;
Yoke::attach_to_cart(Box::new(source.font), |font| {
font.outline_glyphs_with(order)
})
}
fn draw_options(ppem: Option<f32>) -> DrawOptions {
DrawOptions {
ppem,
contour_start: PathContourStart::ScanBackward,
}
}