use std::{borrow::Cow, collections::BTreeMap, fmt, str::FromStr};
use allsorts::{
binary::read::ReadScope,
error::{ParseError, ReadWriteError},
font_data::{DynamicFontTableProvider, FontData},
subset::{subset, whole_font, CmapTarget, SubsetProfile},
tables::{
variable_fonts::fvar::FvarTable, Fixed, FontTableProvider, MaxpTable, OpenTypeData,
},
tag,
variations::{axis_names, instance, VariationError},
};
use serde_derive::{Deserialize, Serialize};
use crate::{FontId, ParsedFont, PdfDocument, PdfWarnMsg};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(into = "String", try_from = "String")]
pub struct FontVariationTag([u8; 4]);
impl FontVariationTag {
pub const WGHT: Self = Self(*b"wght");
pub const WDTH: Self = Self(*b"wdth");
pub const OPSZ: Self = Self(*b"opsz");
pub const SLNT: Self = Self(*b"slnt");
pub const ITAL: Self = Self(*b"ital");
pub fn new(bytes: [u8; 4]) -> Result<Self, VariableFontError> {
let [first, rest @ ..] = &bytes;
let mut padding = false;
let rest_is_valid = rest.iter().all(|byte| {
padding |= *byte == b' ';
if padding {
*byte == b' '
} else {
byte.is_ascii_alphanumeric()
}
});
if first.is_ascii_alphabetic() && rest_is_valid {
Ok(Self(bytes))
} else {
Err(VariableFontError::InvalidTag(
String::from_utf8_lossy(&bytes).into_owned(),
))
}
}
pub const fn as_bytes(&self) -> &[u8; 4] {
&self.0
}
pub const fn as_u32(&self) -> u32 {
u32::from_be_bytes(self.0)
}
}
impl TryFrom<&str> for FontVariationTag {
type Error = VariableFontError;
fn try_from(text: &str) -> Result<Self, Self::Error> {
let bytes = <[u8; 4]>::try_from(text.as_bytes())
.map_err(|_| VariableFontError::InvalidTag(text.to_string()))?;
Self::new(bytes)
}
}
impl TryFrom<String> for FontVariationTag {
type Error = VariableFontError;
fn try_from(text: String) -> Result<Self, Self::Error> {
Self::try_from(text.as_str())
}
}
impl FromStr for FontVariationTag {
type Err = VariableFontError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
Self::try_from(text)
}
}
impl From<FontVariationTag> for String {
fn from(tag: FontVariationTag) -> Self {
tag.to_string()
}
}
impl fmt::Display for FontVariationTag {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let text: String = self.0.iter().copied().map(char::from).collect();
f.pad(&text)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FontVariationAxis {
pub tag: FontVariationTag,
pub name: Option<String>,
pub min: f32,
pub default: f32,
pub max: f32,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct FontVariationSettings {
pub coordinates: BTreeMap<FontVariationTag, f32>,
}
impl FontVariationSettings {
pub fn new() -> Self {
Self::default()
}
pub fn insert(&mut self, tag: FontVariationTag, value: f32) -> Option<f32> {
self.coordinates.insert(tag, value)
}
pub fn with(mut self, tag: FontVariationTag, value: f32) -> Self {
self.insert(tag, value);
self
}
pub fn get(&self, tag: FontVariationTag) -> Option<f32> {
self.coordinates.get(&tag).copied()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum VariableFontError {
InvalidFont(String),
InvalidFaceIndex {
index: usize,
},
NotVariable,
InvalidTag(String),
UnknownAxis(FontVariationTag),
NonFiniteValue {
tag: FontVariationTag,
},
UnsupportedOutlineFormat(String),
Instancing(String),
StaticFontParse(String),
PdfConversion(String),
}
impl fmt::Display for VariableFontError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidFont(reason) => write!(f, "invalid font: {reason}"),
Self::InvalidFaceIndex { index } => write!(f, "the font file has no face {index}"),
Self::NotVariable => f.write_str("the font has no variation axes (no fvar table)"),
Self::InvalidTag(text) => write!(
f,
"{text:?} is not an axis tag (four letters or digits, starting with a letter)"
),
Self::UnknownAxis(tag) => write!(f, "the font has no variation axis {tag}"),
Self::NonFiniteValue { tag } => {
write!(f, "the value for variation axis {tag} is not a finite number")
}
Self::UnsupportedOutlineFormat(reason) => {
write!(f, "unsupported variable font outlines: {reason}")
}
Self::Instancing(reason) => write!(f, "cannot create the instance: {reason}"),
Self::StaticFontParse(reason) => {
write!(f, "the created instance does not parse as a font: {reason}")
}
Self::PdfConversion(reason) => {
write!(f, "cannot convert the instance for embedding in a PDF: {reason}")
}
}
}
}
impl std::error::Error for VariableFontError {}
fn invalid_font(error: impl fmt::Display) -> VariableFontError {
VariableFontError::InvalidFont(error.to_string())
}
fn conversion_error(error: impl fmt::Display) -> VariableFontError {
VariableFontError::PdfConversion(error.to_string())
}
struct Axis {
tag: FontVariationTag,
min: Fixed,
default: Fixed,
max: Fixed,
}
fn face_provider<'a>(
font_file: &FontData<'a>,
face_index: usize,
) -> Result<DynamicFontTableProvider<'a>, VariableFontError> {
let one_face = match font_file {
FontData::OpenType(font) => matches!(font.data, OpenTypeData::Single(_)),
FontData::Woff(_) => true,
FontData::Woff2(font) => font.collection_directory.is_none(),
};
if one_face && face_index != 0 {
return Err(VariableFontError::InvalidFaceIndex { index: face_index });
}
font_file.table_provider(face_index).map_err(|error| match error {
ReadWriteError::Read(ParseError::BadIndex) => {
VariableFontError::InvalidFaceIndex { index: face_index }
}
other => invalid_font(other),
})
}
fn read_axes(provider: &impl FontTableProvider) -> Result<Vec<Axis>, VariableFontError> {
let Some(data) = provider.table_data(tag::FVAR).map_err(invalid_font)? else {
return Ok(Vec::new());
};
let fvar = ReadScope::new(&data)
.read::<FvarTable<'_>>()
.map_err(invalid_font)?;
fvar.axes()
.map(|axis| {
let tag = FontVariationTag::new(axis.axis_tag.to_be_bytes()).map_err(|_| {
invalid_font(format!("the fvar axis tag {:#010x} is not valid", axis.axis_tag))
})?;
if !(axis.min_value <= axis.default_value && axis.default_value <= axis.max_value) {
return Err(invalid_font(format!(
"the range of variation axis {tag} is not in order (minimum, default, maximum)"
)));
}
Ok(Axis {
tag,
min: axis.min_value,
default: axis.default_value,
max: axis.max_value,
})
})
.collect()
}
pub fn font_variation_axes(
bytes: &[u8],
face_index: usize,
) -> Result<Vec<FontVariationAxis>, VariableFontError> {
let font_file = ReadScope::new(bytes)
.read::<FontData<'_>>()
.map_err(invalid_font)?;
let provider = face_provider(&font_file, face_index)?;
let axes = read_axes(&provider)?;
if axes.is_empty() {
return Ok(Vec::new());
}
let names = axis_names(&provider).unwrap_or_default();
Ok(axes
.into_iter()
.map(|axis| FontVariationAxis {
name: names
.iter()
.find(|named| named.tag == axis.tag.as_u32())
.map(|named| named.name.to_string()),
tag: axis.tag,
min: f32::from(axis.min),
default: f32::from(axis.default),
max: f32::from(axis.max),
})
.collect())
}
fn to_fixed(value: f32, min: Fixed, max: Fixed) -> Fixed {
let raw = (f64::from(value) * 65536.0).round() as i32;
Fixed::from_raw(raw.max(min.raw_value()).min(max.raw_value()))
}
pub fn instantiate_variable_font_bytes(
bytes: &[u8],
face_index: usize,
settings: &FontVariationSettings,
) -> Result<(Vec<u8>, FontVariationSettings), VariableFontError> {
let font_file = ReadScope::new(bytes)
.read::<FontData<'_>>()
.map_err(invalid_font)?;
let provider = face_provider(&font_file, face_index)?;
let axes = read_axes(&provider)?;
if axes.is_empty() {
return Err(VariableFontError::NotVariable);
}
for (&tag, &value) in &settings.coordinates {
if !axes.iter().any(|axis| axis.tag == tag) {
return Err(VariableFontError::UnknownAxis(tag));
}
if !value.is_finite() {
return Err(VariableFontError::NonFiniteValue { tag });
}
}
let mut user_instance = Vec::with_capacity(axes.len());
let mut resolved = FontVariationSettings::new();
for axis in &axes {
let value = match settings.get(axis.tag) {
Some(requested) => to_fixed(requested, axis.min, axis.max),
None => axis.default,
};
resolved.insert(axis.tag, f32::from(value));
user_instance.push(value);
}
let (static_bytes, _) = instance(&provider, &user_instance).map_err(|error| match error {
VariationError::NotVariableFont => VariableFontError::NotVariable,
VariationError::NotImplemented => VariableFontError::UnsupportedOutlineFormat(
"expected TrueType outlines with a gvar table, or CFF2 outlines".to_string(),
),
other => VariableFontError::Instancing(other.to_string()),
})?;
let static_bytes = if has_cff2_outlines(&static_bytes)? {
cff2_to_cff1(&static_bytes)?
} else {
static_bytes
};
Ok((static_bytes, resolved))
}
fn has_cff2_outlines(bytes: &[u8]) -> Result<bool, VariableFontError> {
let font_file = ReadScope::new(bytes)
.read::<FontData<'_>>()
.map_err(conversion_error)?;
let provider = font_file.table_provider(0).map_err(conversion_error)?;
Ok(provider.has_table(tag::CFF2) && !provider.has_table(tag::GLYF))
}
struct WithCff<'a, P> {
font: &'a P,
cff: Vec<u8>,
}
impl<P: FontTableProvider> FontTableProvider for WithCff<'_, P> {
fn table_data(&self, table: u32) -> Result<Option<Cow<'_, [u8]>>, ParseError> {
match table {
tag::CFF => Ok(Some(Cow::Borrowed(self.cff.as_slice()))),
tag::CFF2 => Ok(None),
_ => self.font.table_data(table),
}
}
fn has_table(&self, table: u32) -> bool {
match table {
tag::CFF => true,
tag::CFF2 => false,
_ => self.font.has_table(table),
}
}
fn table_tags(&self) -> Option<Vec<u32>> {
let mut tags: Vec<u32> = self
.font
.table_tags()?
.into_iter()
.filter(|&table| table != tag::CFF && table != tag::CFF2)
.collect();
tags.push(tag::CFF);
Some(tags)
}
}
fn cff2_to_cff1(bytes: &[u8]) -> Result<Vec<u8>, VariableFontError> {
let font_file = ReadScope::new(bytes)
.read::<FontData<'_>>()
.map_err(conversion_error)?;
let provider = font_file.table_provider(0).map_err(conversion_error)?;
let maxp = ReadScope::new(&provider.read_table_data(tag::MAXP).map_err(conversion_error)?)
.read::<MaxpTable>()
.map_err(conversion_error)?;
let glyph_ids: Vec<u16> = (0..maxp.num_glyphs).collect();
let converted = subset(
&provider,
&glyph_ids,
&SubsetProfile::Minimal,
CmapTarget::Unicode,
)
.map_err(conversion_error)?;
let converted_file = ReadScope::new(&converted)
.read::<FontData<'_>>()
.map_err(conversion_error)?;
let converted_provider = converted_file.table_provider(0).map_err(conversion_error)?;
let converted_glyphs = ReadScope::new(
&converted_provider
.read_table_data(tag::MAXP)
.map_err(conversion_error)?,
)
.read::<MaxpTable>()
.map_err(conversion_error)?
.num_glyphs;
if converted_glyphs != maxp.num_glyphs {
return Err(conversion_error(format!(
"the converted outlines have {converted_glyphs} glyphs, the font has {}",
maxp.num_glyphs
)));
}
let cff = converted_provider
.read_table_data(tag::CFF)
.map_err(conversion_error)?
.into_owned();
let with_cff = WithCff {
font: &provider,
cff,
};
let tags = with_cff
.table_tags()
.ok_or_else(|| conversion_error("the list of tables of the font is not available"))?;
whole_font(&with_cff, &tags).map_err(conversion_error)
}
pub(crate) fn unresolved_variation_warning(font_id: &FontId, font: &ParsedFont) -> Option<PdfWarnMsg> {
let bytes = font.source_bytes()?;
let font_file = ReadScope::new(bytes.as_slice()).read::<FontData<'_>>().ok()?;
let provider = font_file.table_provider(font.original_index).ok()?;
if !provider.has_table(tag::FVAR) {
return None;
}
let name = font.font_name.as_deref().unwrap_or(&font_id.0);
Some(PdfWarnMsg::warning(
0,
0,
format!(
"font {name} is a variable font (it has an fvar table) and is embedded at its default \
instance, because a PDF has no variable fonts; PdfDocument::add_variable_font embeds \
an instance at chosen axis values"
),
))
}
impl PdfDocument {
pub fn add_variable_font(
&mut self,
bytes: &[u8],
face_index: usize,
settings: &FontVariationSettings,
) -> Result<FontId, VariableFontError> {
let (static_bytes, _) = instantiate_variable_font_bytes(bytes, face_index, settings)?;
let mut warnings = Vec::new();
let font = ParsedFont::from_bytes(&static_bytes, 0, &mut warnings).ok_or_else(|| {
let reasons: Vec<&str> = warnings.iter().map(|w| w.message.as_str()).collect();
VariableFontError::StaticFontParse(reasons.join("; "))
})?;
Ok(self.add_font(&font))
}
}