Render imported PDF TrueType device fonts from exact SFNT faces

This commit is contained in:
gloamxun committed 2026-11-28 04:21:30 +08:00
1 parent b640b26eff
commit 84d6f3ae51
14 files changed
+504 -76

No files matched your search

@@ -277,6 +277,14 @@ pub trait SourceProvider {
) -> Result<Option<crate::resources::NamedFont>, String> {
Ok(None)
}
/// Resolve the exact PostScript name of a PDF TrueType device font.
fn pdf_truetype(
&mut self,
_name: &str,
_from: &str,
) -> Result<Option<crate::resources::NamedFont>, String> {
Ok(None)
}
/// An exact lookup that can report a missing font file before trying another format.
fn optional_font_file(
&mut self, kind: crate::resources::ResourceKind, name: &str, from: &str,
@@ -315,6 +315,15 @@ impl NativeFontCache {
.map(|(_, decoded)| decoded.program.clone()))
}
/// Resolve the real standalone glyph program for a PDF TrueType device font.
pub fn pdf_device_truetype(
files: &mut impl crate::execution::SourceProvider,
name: &str,
from: &str,
) -> Result<Option<Arc<[u8]>>, String> {
truetype::device_program(files, name, from)
}
// The caller reads the actual resource and verifies its bytes on this
// revision before asking for the decoded representation.
fn type1(&self, resource: &LoadedResource, transform: Type1Transform) -> Result<Arc<DecodedType1>, String> {
@@ -80,6 +80,25 @@ impl TrueTypeProgram {
}
}
pub(super) fn device_program(
files: &mut impl SourceProvider,
name: &str,
from: &str,
) -> Result<Option<Arc<[u8]>>, String> {
let Some(selected) = files.pdf_truetype(name, from)? else { return Ok(None) };
let resource = super::verify_resource(selected.resource, ResourceKind::TrueType, name)?;
if crate::resources::exact_truetype_name(&resource.data, selected.index, name).is_none() {
return Err(format!("PDF device font {name} does not match the selected TrueType face"));
}
let data = if resource.data.starts_with(b"ttcf") {
let face = RawFace::parse(&resource.data, selected.index).map_err(|error| error.to_string())?;
build_sfnt(tables(&face)?)?
} else {
resource.data
};
Ok(Some(data.into()))
}
pub(super) fn resolve(
files: &mut impl SourceProvider,
outlines: &mut OutlineFiles,
+14 -1
View File
@@ -59,6 +59,8 @@ pub struct PdfImage {
imported_fonts: Vec<imported_fonts::ImportedType1>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
device_type1_fonts: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
device_truetype_fonts: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pdftex_source: Option<imports::SourceGraph>,
}
@@ -423,6 +425,7 @@ impl PdfImage {
color_space: self.color_space,
imported_fonts: Vec::new(),
device_type1_fonts: Vec::new(),
device_truetype_fonts: Vec::new(),
pdftex_source: None,
}
}
@@ -563,6 +566,7 @@ impl PdfImage {
color_space,
imported_fonts: Vec::new(),
device_type1_fonts: Vec::new(),
device_truetype_fonts: Vec::new(),
pdftex_source: None,
}
}
@@ -613,6 +617,7 @@ impl PdfImage {
color_space: None,
imported_fonts: Vec::new(),
device_type1_fonts: Vec::new(),
device_truetype_fonts: Vec::new(),
pdftex_source: None,
})
}
@@ -891,6 +896,8 @@ impl PdfImage {
Vec::new()
};
let pdftex_source = pdftex.then(|| imports::SourceGraph::capture(&mut graph)).transpose()?;
let (device_type1_fonts, device_truetype_fonts) =
device_fonts::capture(&doc, inherited(b"Resources"));
Ok((
Self {
version: resource.version,
@@ -902,7 +909,8 @@ impl PdfImage {
objects: graph.bodies,
color_space: None,
imported_fonts,
device_type1_fonts: device_fonts::capture(&doc, inherited(b"Resources")),
device_type1_fonts,
device_truetype_fonts,
pdftex_source,
},
[left, bottom],
@@ -914,6 +922,11 @@ impl PdfImage {
&self.device_type1_fonts
}
/// Unembedded TrueType names recorded from this selected PDF page.
pub fn device_truetype_fonts(&self) -> &[String] {
&self.device_truetype_fonts
}
pub(crate) fn extent(&self) -> [f64; 2] {
self.extent.map(f64::from_bits)
}
@@ -3,13 +3,19 @@ use super::resolved;
use lopdf::{Dictionary, Document, Object};
use std::collections::{BTreeSet, HashSet};
pub(super) fn capture(doc: &Document, resources: Option<&Object>) -> Vec<String> {
#[derive(Default)]
struct Names {
type1: BTreeSet<String>,
truetype: BTreeSet<String>,
}
pub(super) fn capture(doc: &Document, resources: Option<&Object>) -> (Vec<String>, Vec<String>) {
let Some(resources) = resources.and_then(|value| resolved(doc, value).ok()) else {
return Vec::new();
return (Vec::new(), Vec::new());
};
let mut pending = vec![resources];
let mut seen = HashSet::new();
let mut names = BTreeSet::new();
let mut names = Names::default();
while let Some(resources) = pending.pop() {
let Ok(dict) = resources.as_dict() else {
continue;
@@ -64,7 +70,10 @@ pub(super) fn capture(doc: &Document, resources: Option<&Object>) -> Vec<String>
}
}
}
names.into_iter().collect()
(
names.type1.into_iter().collect(),
names.truetype.into_iter().collect(),
)
}
fn get<'a>(doc: &'a Document, dict: &'a Dictionary, key: &[u8]) -> Option<&'a Object> {
@@ -74,25 +83,33 @@ fn get<'a>(doc: &'a Document, dict: &'a Dictionary, key: &[u8]) -> Option<&'a Ob
fn capture_font<'a>(
doc: &'a Document,
font: &'a Dictionary,
names: &mut BTreeSet<String>,
names: &mut Names,
pending: &mut Vec<&'a Object>,
) {
match get(doc, font, b"Subtype").and_then(|value| value.as_name().ok()) {
Some(b"Type1") => {
let Some(name) = get(doc, font, b"BaseFont")
.and_then(|value| value.as_name().ok())
.and_then(|bytes| std::str::from_utf8(bytes).ok())
else {
return;
};
let descriptor =
get(doc, font, b"FontDescriptor").and_then(|value| value.as_dict().ok());
if !descriptor.is_some_and(|dict| {
[b"FontFile".as_slice(), b"FontFile2", b"FontFile3"]
.into_iter()
.any(|key| dict.has(key))
}) {
names.insert(name.to_owned());
let subtype = get(doc, font, b"Subtype").and_then(|value| value.as_name().ok());
match subtype {
Some(b"Type1" | b"TrueType") => {
capture_name(
doc,
font,
if subtype == Some(b"Type1") {
&mut names.type1
} else {
&mut names.truetype
},
);
}
Some(b"Type0") => {
if let Some(descendants) =
get(doc, font, b"DescendantFonts").and_then(|value| value.as_array().ok())
&& let Some(descendant) = descendants
.first()
.and_then(|value| resolved(doc, value).ok())
.and_then(|value| value.as_dict().ok())
&& get(doc, descendant, b"Subtype").and_then(|value| value.as_name().ok())
== Some(b"CIDFontType2")
{
capture_name(doc, descendant, &mut names.truetype);
}
}
Some(b"Type3") => {
@@ -103,3 +120,20 @@ fn capture_font<'a>(
_ => {}
}
}
fn capture_name(doc: &Document, font: &Dictionary, names: &mut BTreeSet<String>) {
let Some(name) = get(doc, font, b"BaseFont")
.and_then(|value| value.as_name().ok())
.and_then(|bytes| std::str::from_utf8(bytes).ok())
else {
return;
};
let descriptor = get(doc, font, b"FontDescriptor").and_then(|value| value.as_dict().ok());
if !descriptor.is_some_and(|dict| {
[b"FontFile".as_slice(), b"FontFile2", b"FontFile3"]
.into_iter()
.any(|key| dict.has(key))
}) {
names.insert(name.to_owned());
}
}
@@ -148,6 +148,7 @@ pub(super) fn read(
color_space,
imported_fonts: Vec::new(),
device_type1_fonts: Vec::new(),
device_truetype_fonts: Vec::new(),
pdftex_source: None,
restored_pdf_origin: None,
},
+37 -14
View File
@@ -2,6 +2,7 @@
mod deferred;
mod named_fonts;
pub use named_fonts::{FontStyle, NamedFont};
pub(crate) use named_fonts::exact_truetype_name;
mod project;
pub use deferred::{
DeferredProbe, DirectoryAbsence, GeneratedLookup, GeneratedLookupOrigin, GeneratedLookupRole,
@@ -316,12 +317,21 @@ pub struct WorldFailure {
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
struct DirectoryIndex {
#[serde(default = "recursive_index", skip_serializing_if = "recursive_index_value")]
recursive: bool,
directories: Vec<(PathBuf, SystemTime)>,
#[serde(default)]
directory_aliases: BTreeMap<PathBuf, PathBuf>,
#[serde(with = "index_names")]
names: BTreeMap<std::ffi::OsString, Vec<PathBuf>>,
}
fn recursive_index() -> bool {
true
}
fn recursive_index_value(recursive: &bool) -> bool {
*recursive
}
// OsString has a platform-tagged serde representation, so it cannot be a JSON
// object key. Preserve exact filename values as entries rather than lossy text.
mod index_names {
@@ -1349,32 +1359,40 @@ impl FileWorld {
}
}
fn index(&mut self, root: &Path) -> Result<&DirectoryIndex, String> {
self.index_at(root, true)
}
fn index_at(&mut self, root: &Path, recursive: bool) -> Result<&DirectoryIndex, String> {
if let Some(project) = &self.project {
// The index tracks the logical namespace. Each candidate's live
// existence and staged bytes are still checked by probe().
if !self.current_project_indexes.contains(root) {
if !self.current_project_indexes.contains(root)
|| (recursive && !self.indexes[root].recursive)
{
let index =
project.index(root, &self.project_paths(), self.config.max_index_entries)?;
project.index(root, &self.project_paths(), self.config.max_index_entries, recursive)?;
self.indexes.insert(root.into(), Arc::new(index));
self.current_project_indexes.insert(root.into());
}
return Ok(&self.indexes[root]);
}
if self.pinned {
if let Some(failure) = self.index_failures.get(root) {
return Err(failure.error.clone());
}
if self.pinned
&& let Some(failure) = self.index_failures.get(root)
&& (recursive || !failure.partial.recursive)
{
return Err(failure.error.clone());
}
// Live worlds revalidate directory timestamps; captured worlds freeze
// observed enumeration. Neither mode authorizes execution/layout reuse.
let fresh = self.indexes.get(root).is_some_and(|index| {
self.pinned
|| (!index.directories.is_empty()
&& index.directories.iter().all(|(p, t)| {
p.metadata()
.and_then(|m| m.modified())
.is_ok_and(|v| v == *t)
}))
(!recursive || index.recursive)
&& (self.pinned
|| (!index.directories.is_empty()
&& index.directories.iter().all(|(p, t)| {
p.metadata()
.and_then(|m| m.modified())
.is_ok_and(|v| v == *t)
})))
});
if !fresh {
if self.replay {
@@ -1384,6 +1402,7 @@ impl FileWorld {
));
}
let mut index = DirectoryIndex {
recursive,
directories: Vec::new(),
directory_aliases: BTreeMap::new(),
names: BTreeMap::new(),
@@ -1427,7 +1446,11 @@ impl FileWorld {
}
let path = child.path();
match path.metadata() {
Ok(m) if m.is_dir() => queue.push((path, ancestors.clone())),
Ok(m) if m.is_dir() => {
if recursive {
queue.push((path, ancestors.clone()));
}
}
Ok(_) => index.names.entry(child.file_name()).or_default().push(path),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
if path
@@ -85,6 +85,24 @@ impl NamedFace {
}
}
pub(crate) fn exact_truetype_name(data: &[u8], index: u32, requested: &str) -> Option<String> {
let face = ttf_parser::Face::parse(data, index).ok()?;
face.tables().glyf.as_ref()?;
let mut names = face.names().into_iter();
names
.any(|name| {
name.name_id == name_id::POST_SCRIPT_NAME
&& name.to_string().is_some_and(|name| name == requested)
})
.then(|| {
face.names()
.into_iter()
.filter(|name| name.name_id == name_id::FULL_NAME)
.find_map(|name| name.to_string())
.unwrap_or_else(|| requested.to_owned())
})
}
fn is_outline(path: &Path) -> bool {
path.extension()
.and_then(|ext| ext.to_str())
@@ -197,6 +215,136 @@ impl FileWorld {
result
}
/// PDF device name lookup requires the exact PostScript name and glyf outlines.
pub fn read_pdf_truetype(
&mut self,
name: &str,
from: &Path,
) -> Result<Option<NamedFont>, String> {
let mut candidates = Vec::new();
let result = self.select_pdf_truetype(name, from, &mut candidates);
self.trace.lookups.push(ResourceLookup {
kind: ResourceKind::TrueType,
name: name.into(),
from: from.into(),
candidates,
resolved: result
.as_ref()
.ok()
.and_then(|font| font.as_ref())
.map(|font| font.resource.version.path.clone()),
lookup_path: None,
error: result.as_ref().err().cloned(),
});
result
}
fn select_pdf_truetype(
&mut self,
name: &str,
from: &Path,
candidates: &mut Vec<PathBuf>,
) -> Result<Option<NamedFont>, String> {
let mut scoped_paths = self.paths(ResourceKind::TrueType, from);
scoped_paths.extend(self.paths(ResourceKind::OpenType, from));
let mut seen = BTreeSet::new();
for (entry, _) in scoped_paths {
let SearchPath::Directory {
path,
recursive,
suffix,
} = entry
else {
continue;
};
let root = self.config.cwd.join(path);
let prefix = root.join(&suffix);
let index = self.index_at(if recursive { &root } else { &prefix }, recursive)?;
let mut paths: Vec<_> = index
.names
.values()
.flatten()
.filter(|candidate| is_outline(candidate))
.filter(|candidate| {
candidate.parent().is_some_and(|parent| {
if recursive {
parent
.strip_prefix(&root)
.is_ok_and(|part| part.ends_with(&suffix))
} else {
parent == prefix
}
})
})
.cloned()
.collect();
// Try the matching basename first, then discover arbitrary filenames
// by inspecting the versioned program's name table.
let priority = |path: &Path| !path.file_stem().is_some_and(|stem| stem == name);
paths.sort_by(|left, right| (priority(left), left).cmp(&(priority(right), right)));
for candidate in paths {
candidates.push(candidate.clone());
let Some(path) = self.probe(&candidate)? else {
continue;
};
if !seen.insert(path.clone()) {
continue;
}
let data = self.input_file(path.clone())?;
let count = ttf_parser::fonts_in_collection(&data.data).unwrap_or(1) as usize;
if count > self.config.max_index_entries
|| (count > 1 && count > data.data.len().saturating_sub(12) / 4)
{
continue;
}
for index in 0..count as u32 {
if let Some(full_name) = exact_truetype_name(&data.data, index, name) {
let resource = self.read_path(path)?;
return Ok(Some(NamedFont {
resource,
index,
full_name,
}));
}
}
}
}
if self.project.is_some() {
return Ok(None);
}
if self.system_fonts.is_none() && !self.replay {
self.system_fonts = Some(system_faces(self.config.max_index_entries));
}
let Some(faces) = &self.system_fonts else {
return Ok(None);
};
let mut matching: Vec<_> = faces
.as_ref()
.map_err(Clone::clone)?
.iter()
.filter(|face| face.postscript == name)
.map(|face| (face.path.clone(), face.index))
.collect();
matching.sort();
matching.dedup();
for (candidate, index) in matching {
candidates.push(candidate.clone());
let Some(path) = self.probe(&candidate)? else {
continue;
};
let data = self.input_file(path.clone())?;
if let Some(full_name) = exact_truetype_name(&data.data, index, name) {
let resource = self.read_path(path)?;
return Ok(Some(NamedFont {
resource,
index,
full_name,
}));
}
}
Ok(None)
}
fn select_named_face(
&mut self,
name: &str,
@@ -215,7 +363,9 @@ impl FileWorld {
let mut remaining = self.config.max_index_entries;
for (path, file) in project.files() {
if !is_outline(path)
|| !paths.iter().any(|(scope, _)| self.font_path_in(scope, path))
|| !paths
.iter()
.any(|(scope, _)| self.font_path_in(scope, path))
{
continue;
}
@@ -475,8 +475,10 @@ impl ProjectSnapshot {
root: &Path,
live: &BTreeSet<PathBuf>,
limit: usize,
recursive: bool,
) -> Result<DirectoryIndex, String> {
let mut index = DirectoryIndex {
recursive,
directories: Vec::new(),
directory_aliases: BTreeMap::new(),
names: BTreeMap::new(),
@@ -511,9 +513,9 @@ impl ProjectSnapshot {
let child = logical.join(&name);
let location = self.locate(&child, live)?;
match location.kind {
Some(NodeKind::Directory) => pending.push((child, ancestors.clone())),
Some(NodeKind::Directory) if recursive => pending.push((child, ancestors.clone())),
Some(NodeKind::File) => index.names.entry(name).or_default().push(child),
None => {}
_ => {}
}
}
}