use std::collections::{BTreeMap, HashMap};
use std::io::Write;
use f_office_fonts::{FontDb, FontId};
use pdf_writer::types::{CidFontType, FontFlags, SystemInfo, UnicodeCmap};
use pdf_writer::{Chunk, Filter, Finish, Name, Rect, Ref, Str};
use read_fonts::TableProvider;
use skrifa::FontRef;
use subsetter::GlyphRemapper;
use crate::Error;
use crate::outline_font;
use crate::stream::{StreamPdf, deflate};
const IDENTITY_SYSTEM_INFO: SystemInfo<'static> = SystemInfo {
registry: Str(b"Adobe"),
ordering: Str(b"Identity"),
supplement: 0,
};
pub(crate) struct UsedFonts<'a> {
db: &'a FontDb,
index_by_id: HashMap<FontId, usize>,
order: Vec<UsedFont>,
}
pub(crate) struct UsedFont {
id: FontId,
type0_ref: Ref,
units_per_em: f32,
right_edge: Option<i16>,
remapper: GlyphRemapper,
unicode: BTreeMap<u16, String>,
orig_gids: Vec<u16>,
}
pub(crate) struct MappedGlyph {
pub(crate) cid: u16,
pub(crate) needs_actual_text: bool,
}
impl<'a> UsedFonts<'a> {
pub(crate) fn new(db: &'a FontDb) -> Self {
Self {
db,
index_by_id: HashMap::new(),
order: Vec::new(),
}
}
pub(crate) fn db(&self) -> &'a FontDb {
self.db
}
pub(crate) fn validate(&self, id: FontId) -> Result<(), Error> {
let (data, index) = self.db.data(id).ok_or(Error::UnknownFont(id))?;
let font = FontRef::from_index(data, index).map_err(|_| Error::UnreadableFont(id))?;
let units = font
.head()
.map_err(|_| Error::UnreadableFont(id))?
.units_per_em();
if units == 0 {
return Err(Error::UnreadableFont(id));
}
Ok(())
}
pub(crate) fn get_or_register<W: Write>(
&mut self,
id: FontId,
pdf: &mut StreamPdf<'_, W>,
) -> Result<&mut UsedFont, Error> {
if let Some(&idx) = self.index_by_id.get(&id) {
return self.order.get_mut(idx).ok_or(Error::UnknownFont(id));
}
let (data, index) = self.db.data(id).ok_or(Error::UnknownFont(id))?;
let font = FontRef::from_index(data, index).map_err(|_| Error::UnreadableFont(id))?;
let units_per_em = f32::from(
font.head()
.map_err(|_| Error::UnreadableFont(id))?
.units_per_em(),
);
if units_per_em <= 0.0 {
return Err(Error::UnreadableFont(id));
}
let right_edge = outline_font::right_edge(data, index);
let type0_ref = pdf.alloc();
let mut remapper = GlyphRemapper::new();
remapper.remap(0);
let idx = self.order.len();
self.order.push(UsedFont {
id,
type0_ref,
units_per_em,
right_edge,
remapper,
unicode: BTreeMap::new(),
orig_gids: vec![0],
});
self.index_by_id.insert(id, idx);
self.order.get_mut(idx).ok_or(Error::UnknownFont(id))
}
pub(crate) fn emit_all<W: Write>(&self, pdf: &mut StreamPdf<'_, W>) -> Result<(), Error> {
for used in &self.order {
emit_font(self.db, used, pdf)?;
}
Ok(())
}
}
impl UsedFont {
pub(crate) const fn type0_ref(&self) -> Ref {
self.type0_ref
}
pub(crate) const fn units_per_em(&self) -> f32 {
self.units_per_em
}
pub(crate) const fn right_edge(&self) -> Option<i16> {
self.right_edge
}
pub(crate) fn record_glyph(&mut self, orig_gid: u32, text: &str) -> Result<MappedGlyph, Error> {
let orig_u16 = u16::try_from(orig_gid).map_err(|_| Error::UnknownGlyph {
font: self.id,
glyph: orig_gid,
})?;
let cid = self.remapper.remap(orig_u16);
let cid_idx = usize::from(cid);
if cid_idx >= self.orig_gids.len() {
self.orig_gids.resize(cid_idx + 1, 0);
}
if let Some(slot) = self.orig_gids.get_mut(cid_idx) {
*slot = orig_u16;
}
let needs_actual_text = if text.is_empty() {
false
} else if let Some(existing) = self.unicode.get(&cid) {
existing != text
} else {
self.unicode.insert(cid, text.to_owned());
false
};
Ok(MappedGlyph {
cid,
needs_actual_text,
})
}
}
fn emit_font<W: Write>(
db: &FontDb,
used: &UsedFont,
pdf: &mut StreamPdf<'_, W>,
) -> Result<(), Error> {
let (raw_data, raw_index) = db.data(used.id).ok_or(Error::UnknownFont(used.id))?;
let stripped = outline_font::without_color_tables(raw_data, raw_index);
let (font_bytes, face_index) = match stripped.as_deref() {
Some(clean) => (clean, 0_u32),
None => (raw_data.as_ref(), raw_index),
};
let subset_bytes = subsetter::subset(font_bytes, face_index, &used.remapper)
.map_err(|err| Error::Write(format!("failed to subset font: {err:?}")))?;
let parsed =
FontRef::from_index(font_bytes, face_index).map_err(|_| Error::UnreadableFont(used.id))?;
let is_cff = parsed.cff().is_ok();
let metrics = extract_metrics(&parsed, used.units_per_em);
let base_name = subset_font_name(used.id);
let font_file_ref = emit_font_file(&subset_bytes, is_cff, pdf)?;
let descriptor_ref = emit_descriptor(&base_name, &metrics, font_file_ref, is_cff, pdf)?;
let cmap_ref = emit_to_unicode(&used.unicode, pdf)?;
let cid_ref = emit_cid_font(db, used, (&base_name, descriptor_ref, is_cff), pdf)?;
let mut chunk = Chunk::new();
chunk
.type0_font(used.type0_ref)
.base_font(Name(base_name.as_bytes()))
.encoding_predefined(Name(b"Identity-H"))
.descendant_font(cid_ref)
.to_unicode(cmap_ref);
pdf.emit(used.type0_ref, &chunk)
}
struct DescriptorMetrics {
bbox: Rect,
ascent: f32,
descent: f32,
cap_height: f32,
italic_angle: f32,
}
fn extract_metrics(font: &FontRef<'_>, units_per_em: f32) -> DescriptorMetrics {
let scale = 1000.0 / units_per_em;
let bbox = font
.head()
.map_or(Rect::new(0.0, 0.0, 1000.0, 1000.0), |h| {
Rect::new(
f32::from(h.x_min()) * scale,
f32::from(h.y_min()) * scale,
f32::from(h.x_max()) * scale,
f32::from(h.y_max()) * scale,
)
});
let (ascent, descent) = font.hhea().map_or((800.0, -200.0), |h| {
(
f32::from(h.ascender().to_i16()) * scale,
f32::from(h.descender().to_i16()) * scale,
)
});
let cap_height = font
.os2()
.ok()
.and_then(|os2| os2.s_cap_height())
.map_or(ascent, |h| f32::from(h) * scale);
let italic_angle = font.post().map_or(0.0, |p| p.italic_angle().to_f32());
DescriptorMetrics {
bbox,
ascent,
descent,
cap_height,
italic_angle,
}
}
fn subset_font_name(id: FontId) -> String {
let idx = id.index();
let mut tag = [b'A'; 6];
let mut value = idx;
for slot in tag.iter_mut().rev() {
let letter = u8::try_from(value % 26).unwrap_or(0);
*slot = b'A' + letter;
value /= 26;
}
let prefix = std::str::from_utf8(&tag).unwrap_or("AAAAAA");
format!("{prefix}+F{idx}")
}
fn emit_font_file<W: Write>(
subset_bytes: &[u8],
is_cff: bool,
pdf: &mut StreamPdf<'_, W>,
) -> Result<Ref, Error> {
let file_ref = pdf.alloc();
if is_cff {
let sub_font = FontRef::from_index(subset_bytes, 0)
.map_err(|_| Error::Write("subset CFF font unreadable".into()))?;
let cff_table = sub_font
.cff()
.map_err(|_| Error::Write("subset missing CFF table".into()))?;
let compressed = deflate(cff_table.offset_data().as_bytes())?;
let mut chunk = Chunk::new();
let mut stream = chunk.stream(file_ref, &compressed);
stream.filter(Filter::FlateDecode);
stream.pair(Name(b"Subtype"), Name(b"CIDFontType0C"));
stream.finish();
pdf.emit(file_ref, &chunk)?;
} else {
let compressed = deflate(subset_bytes)?;
let mut chunk = Chunk::new();
let mut stream = chunk.stream(file_ref, &compressed);
stream.filter(Filter::FlateDecode);
stream.pair(
Name(b"Length1"),
i32::try_from(subset_bytes.len()).unwrap_or(i32::MAX),
);
stream.finish();
pdf.emit(file_ref, &chunk)?;
}
Ok(file_ref)
}
fn emit_descriptor<W: Write>(
base_name: &str,
metrics: &DescriptorMetrics,
font_file_ref: Ref,
is_cff: bool,
pdf: &mut StreamPdf<'_, W>,
) -> Result<Ref, Error> {
let desc_ref = pdf.alloc();
let mut chunk = Chunk::new();
let mut desc = chunk.font_descriptor(desc_ref);
desc.name(Name(base_name.as_bytes()))
.flags(FontFlags::SYMBOLIC)
.bbox(metrics.bbox)
.italic_angle(metrics.italic_angle)
.ascent(metrics.ascent)
.descent(metrics.descent)
.cap_height(metrics.cap_height)
.stem_v(80.0);
if is_cff {
desc.font_file3(font_file_ref);
} else {
desc.font_file2(font_file_ref);
}
desc.finish();
pdf.emit(desc_ref, &chunk)?;
Ok(desc_ref)
}
fn emit_to_unicode<W: Write>(
unicode: &BTreeMap<u16, String>,
pdf: &mut StreamPdf<'_, W>,
) -> Result<Ref, Error> {
let cmap_ref = pdf.alloc();
let mut cmap = UnicodeCmap::new(Name(b"FOfficeUnicode"), IDENTITY_SYSTEM_INFO);
for (&cid, text) in unicode {
let mut chars = text.chars();
if let Some(first) = chars.next() {
if chars.next().is_none() {
cmap.pair(cid, first);
} else {
cmap.pair_with_multiple(cid, text.chars());
}
}
}
let raw = cmap.finish();
let compressed = deflate(raw.as_slice())?;
let mut chunk = Chunk::new();
let mut stream = chunk.cmap(cmap_ref, &compressed);
stream.filter(Filter::FlateDecode);
stream.finish();
pdf.emit(cmap_ref, &chunk)?;
Ok(cmap_ref)
}
fn emit_cid_font<W: Write>(
db: &FontDb,
used: &UsedFont,
(base_name, descriptor_ref, is_cff): (&str, Ref, bool),
pdf: &mut StreamPdf<'_, W>,
) -> Result<Ref, Error> {
let cid_ref = pdf.alloc();
let widths: Vec<f32> = used
.orig_gids
.iter()
.map(|&orig| {
db.advance(used.id, u32::from(orig))
.map_or(0.0, |adv| f32::from(adv) / used.units_per_em * 1000.0)
})
.collect();
let mut chunk = Chunk::new();
let mut cid = chunk.cid_font(cid_ref);
cid.subtype(if is_cff {
CidFontType::Type0
} else {
CidFontType::Type2
})
.base_font(Name(base_name.as_bytes()))
.system_info(IDENTITY_SYSTEM_INFO)
.font_descriptor(descriptor_ref)
.default_width(0.0);
if !is_cff {
cid.cid_to_gid_map_predefined(Name(b"Identity"));
}
if !widths.is_empty() {
cid.widths().consecutive(0, widths);
}
cid.finish();
pdf.emit(cid_ref, &chunk)?;
Ok(cid_ref)
}