use std::collections::BTreeSet;
use std::sync::Arc;
use laminapdf_cos::{Dict, ObjRef, Object, Result};
use crate::document::Document;
use crate::page::{Page, Pages};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct FontResource {
pub name: Option<String>,
pub subtype: Option<String>,
pub embedded: bool,
pub subset: bool,
pub encoding: Option<FontEncoding>,
pub object: Option<ObjRef>,
pub to_unicode: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum FontEncoding {
Named(String),
Custom,
}
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct SimpleEncoding {
pub base: Option<Vec<u8>>,
pub differences: Option<Arc<Object>>,
pub malformed: bool,
}
impl SimpleEncoding {
pub fn read(font: &Dict, mut resolve: impl FnMut(&Object) -> Result<Option<Arc<Object>>>) -> Result<Self> {
let Some(value) = font.get("Encoding") else {
return Ok(Self::default());
};
let Some(encoding) = resolve(value)? else {
return Ok(Self::default());
};
Ok(match &*encoding {
Object::Name(n) => Self {
base: Some(n.as_bytes().to_vec()),
..Self::default()
},
Object::Dict(d) => {
let base = match d.get("BaseEncoding") {
Some(base) => match resolve(base)?.as_deref() {
Some(Object::Name(n)) => Some(n.as_bytes().to_vec()),
_ => None,
},
None => None,
};
let differences = match d.get("Differences") {
Some(list) => resolve(list)?,
None => None,
};
Self {
base,
differences,
malformed: false,
}
}
_ => Self {
malformed: true,
..Self::default()
},
})
}
}
pub fn to_unicode_cmap(
font: &Dict,
mut resolve: impl FnMut(&Object) -> Result<Option<Arc<Object>>>,
) -> Result<Option<Arc<Object>>> {
let Some(value) = font.get("ToUnicode") else {
return Ok(None);
};
Ok(resolve(value)?.filter(|cmap| matches!(**cmap, Object::Stream(_))))
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
enum FontKey {
Object(u32),
Direct(Option<String>, Option<String>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum FontScope {
Content,
WithAppearances,
}
impl Pages<'_> {
pub fn fonts(&self) -> Result<Vec<FontResource>> {
self.fonts_in(FontScope::Content)
}
pub fn fonts_in(&self, scope: FontScope) -> Result<Vec<FontResource>> {
let mut walk = Walk::new(self.document());
for page in self.iter() {
walk.page(&page, scope)?;
}
Ok(walk.out)
}
}
impl Page<'_> {
pub fn fonts(&self) -> Result<Vec<FontResource>> {
self.fonts_in(FontScope::Content)
}
pub fn fonts_in(&self, scope: FontScope) -> Result<Vec<FontResource>> {
let mut walk = Walk::new(self.doc());
walk.page(self, scope)?;
Ok(walk.out)
}
}
struct Walk<'d> {
doc: &'d Document,
max_depth: usize,
seen_containers: BTreeSet<u32>,
seen_fonts: BTreeSet<FontKey>,
out: Vec<FontResource>,
}
impl<'d> Walk<'d> {
fn new(doc: &'d Document) -> Self {
Self {
doc,
max_depth: doc.limits().max_tree_depth(),
seen_containers: BTreeSet::new(),
seen_fonts: BTreeSet::new(),
out: Vec::new(),
}
}
fn page(&mut self, page: &Page<'_>, scope: FontScope) -> Result<()> {
if let Some(resources) = page.resources() {
self.resources(resources, 0)?;
}
if scope == FontScope::Content {
return Ok(());
}
for annot in page.annots()? {
let Some(annot) = self.dict(Some(&Object::Ref(annot)))? else {
continue;
};
let Some(appearances) = self.dict(annot.get("AP"))? else {
continue;
};
for (_, value) in appearances.iter() {
self.appearance(value)?;
}
}
Ok(())
}
fn appearance(&mut self, value: &Object) -> Result<()> {
let Some(object) = self.doc.read(value)? else {
return Ok(());
};
match &*object {
Object::Stream(_) => self.container(value, 0, |_| true),
Object::Dict(states) => {
for (_, state) in states.iter() {
if matches!(self.doc.read(state)?.as_deref(), Some(Object::Stream(_))) {
self.container(state, 0, |_| true)?;
}
}
Ok(())
}
_ => Ok(()),
}
}
fn resources(&mut self, resources: &Dict, depth: usize) -> Result<()> {
if depth > self.max_depth {
return Ok(());
}
if let Some(fonts) = self.dict(resources.get("Font"))? {
for (_, value) in fonts.iter() {
self.font(value, depth)?;
}
}
if let Some(xobjects) = self.dict(resources.get("XObject"))? {
for (_, value) in xobjects.iter() {
self.container(value, depth, |dict| dict.get_name("Subtype") == Some(b"Form"))?;
}
}
if let Some(patterns) = self.dict(resources.get("Pattern"))? {
for (_, value) in patterns.iter() {
self.container(value, depth, |dict| dict.get_int("PatternType") == Some(1))?;
}
}
if let Some(states) = self.dict(resources.get("ExtGState"))? {
for (_, value) in states.iter() {
let Some(state) = self.dict(Some(value))? else { continue };
let Some(mask) = self.dict(state.get("SMask"))? else {
continue;
};
if let Some(group) = mask.get("G") {
self.container(group, depth, |_| true)?;
}
}
}
Ok(())
}
fn container(&mut self, value: &Object, depth: usize, wanted: impl Fn(&Dict) -> bool) -> Result<()> {
if let Some(r) = value.as_ref()
&& !self.seen_containers.insert(r.num)
{
return Ok(());
}
let Some(object) = self.doc.read(value)? else {
return Ok(());
};
let Object::Stream(stream) = &*object else {
return Ok(());
};
if !wanted(&stream.dict) {
return Ok(());
}
if let Some(inner) = self.dict(stream.dict.get("Resources"))? {
self.resources(&inner, depth + 1)?;
}
Ok(())
}
fn font(&mut self, value: &Object, depth: usize) -> Result<()> {
if let Some(r) = value.as_ref()
&& self.seen_fonts.contains(&FontKey::Object(r.num))
{
return Ok(());
}
let Some(object) = self.doc.read(value)? else {
return Ok(());
};
let Some(font) = object.as_dict() else { return Ok(()) };
let subtype = font.get_name("Subtype").map(lossy);
let type3 = subtype.as_deref() == Some("Type3");
let composite = subtype.as_deref() == Some("Type0");
let descriptor_font = if composite { self.descendant(font)? } else { None };
let descriptor = self.dict(descriptor_font.as_ref().unwrap_or(font).get("FontDescriptor"))?;
let full_name = self.full_name(font, descriptor.as_ref(), type3)?;
let key = match value.as_ref() {
Some(r) => FontKey::Object(r.num),
None => FontKey::Direct(subtype.clone(), full_name.clone()),
};
if !self.seen_fonts.insert(key) {
return Ok(());
}
let subset = full_name.as_deref().is_some_and(has_subset_tag);
let name = full_name.map(|b| {
if subset {
b.get(7..).unwrap_or_default().to_owned()
} else {
b
}
});
let embedded = type3 || embeds(descriptor.as_ref());
let encoding = self.encoding(font, composite)?;
let to_unicode = to_unicode_cmap(font, |o| self.doc.read(o))?.is_some();
self.out.push(FontResource {
name,
subtype,
embedded,
subset,
encoding,
object: value.as_ref(),
to_unicode,
});
if type3 {
if let Some(r) = value.as_ref()
&& !self.seen_containers.insert(r.num)
{
return Ok(());
}
if let Some(inner) = self.dict(font.get("Resources"))? {
self.resources(&inner, depth + 1)?;
}
}
Ok(())
}
fn descendant(&self, font: &Dict) -> Result<Option<Dict>> {
let Some(list) = font.get("DescendantFonts") else {
return Ok(None);
};
let Some(list) = self.doc.read(list)? else {
return Ok(None);
};
let Some(first) = list.as_array().and_then(<[Object]>::first) else {
return Ok(None);
};
self.dict(Some(first))
}
fn full_name(&self, font: &Dict, descriptor: Option<&Dict>, type3: bool) -> Result<Option<String>> {
if let Some(name) = self.name(font.get("BaseFont"))? {
return Ok(Some(name));
}
if let Some(name) = self.name(descriptor.and_then(|d| d.get("FontName")))? {
return Ok(Some(name));
}
if type3 {
return self.name(font.get("Name"));
}
Ok(None)
}
fn name(&self, value: Option<&Object>) -> Result<Option<String>> {
let Some(value) = value else { return Ok(None) };
Ok(match self.doc.read(value)?.as_deref() {
Some(Object::Name(n)) => Some(lossy(n.as_bytes())),
_ => None,
})
}
fn encoding(&self, font: &Dict, composite: bool) -> Result<Option<FontEncoding>> {
if composite {
let Some(value) = font.get("Encoding") else {
return Ok(None);
};
return Ok(match self.doc.read(value)?.as_deref() {
Some(Object::Name(n)) => Some(FontEncoding::Named(lossy(n.as_bytes()))),
Some(Object::Stream(_)) => Some(FontEncoding::Custom),
_ => None,
});
}
let declared = SimpleEncoding::read(font, |o| self.doc.read(o))?;
Ok(if matches!(declared.differences.as_deref(), Some(Object::Array(_))) {
Some(FontEncoding::Custom)
} else {
declared.base.map(|b| FontEncoding::Named(lossy(&b)))
})
}
fn dict(&self, value: Option<&Object>) -> Result<Option<Dict>> {
let Some(value) = value else { return Ok(None) };
Ok(match self.doc.read(value)?.as_deref() {
Some(Object::Dict(d)) => Some(d.clone()),
Some(Object::Stream(s)) => Some(s.dict.clone()),
_ => None,
})
}
}
fn embeds(descriptor: Option<&Dict>) -> bool {
descriptor.is_some_and(|d| {
["FontFile", "FontFile2", "FontFile3"]
.iter()
.any(|key| d.get(key).is_some())
})
}
fn lossy(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes).into_owned()
}
fn has_subset_tag(name: &str) -> bool {
let bytes = name.as_bytes();
bytes.len() > 7 && bytes.get(6) == Some(&b'+') && bytes.iter().take(6).all(u8::is_ascii_uppercase)
}
#[cfg(test)]
mod tests {
use super::has_subset_tag;
#[test]
fn a_subset_tag_is_six_capitals_and_a_plus() {
assert!(has_subset_tag("ABCDEF+NotoSans-Regular"));
assert!(!has_subset_tag("ABCDEf+NotoSans"));
assert!(!has_subset_tag("ABCDEF+"));
assert!(!has_subset_tag("Helvetica"));
}
}