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 => {}
_ => {}
}
}
}
+30
View File
@@ -819,6 +819,36 @@ letterspace-fresh.log 和 device-pdftex-spaced-moved.log。
[原版字距虚拟字体构造](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L16400-L16492)
[原版格式所写字体字段](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L30627-L30696)
### 导入 PDF 的 TrueType 设备字体
选页资源中的 TrueType 和 CIDFontType2 按 SFNT 内部的 PostScript
名匹配。查找使用配置的字体根目录、原子项目或主机真实目录,
记录所选程序的版本。TTC 按实际字面索引提取独立 SFNT。预览
追加实际 FontFile2,读取原 PDF 的编码、Differences、CIDToGIDMap、
字宽和位置。导出继续保留原版的设备字体引用。
[PDF 字体与编码参考](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/pdfreference1.5_v6.pdf)
两项定向回归通过。目录中有文件名符合请求但内部名称不同的候选,
实际选择文件名不同但 PostScript 名一致的字体。删除源 PDF 和字体后,捕获的输入
可离线生成同字节 PDF 和 SVG。八组真实字形试验包含 WinAnsi、
Differences、TTC 的第二个字面、显式 CIDToGIDMap 和 XeTeX。
常规 TrueType、Differences 与 CID 各自的设备字体和整嵌对照,
以及 TTC 与普通 TTF 对照,字形路径和位置完全相同。XeTeX
与 pdfTeX 样例使用同一组字形轮廓。
四页项目更改字体的设计单位、移动插图及恢复资源,均只更新第 2
页。仅更改字体时导出 PDF 字节相同,正文编辑和恢复各复用 109 步。
成功的三个修订,PDF、测量页面、SVG、来源映射和 aux 与同版本
独立全量一致。字体缺失时编辑器保留上次成功的预览和 aux。
回执在 target/p3-imported-truetype。receipt.json 的 SHA-256 为
6c35d3f6f8ba09e8d42fde468dba517f769ae64e0a28d31813bda65c79623667,
revision.log 为 f3872ba1c987dc93c71314c1d35c84fd2320c096540fe7e70420115869fdb6c7。
下一入口为导入 PDF 的未嵌入 OpenType CFF。原版与原生均保留
LMRoman10-Regular 的设备字体引用。当前预览未读取实际提供的
lmroman10-regular.otf,并报告缺少设备字体。复现在
target/p3-imported-truetype/next-imported-cff。
### 导入 PDF 的 Type 1 设备字体
从已放置图像所选页面的实际资源及嵌套 Form 记录设备字体,并使用
+10
View File
@@ -156,6 +156,16 @@ impl SourceProvider for RecordingHost<'_> {
})).map_err(Clone::clone)
})
}
fn pdf_truetype(
&mut self, name: &str, from: &str,
) -> Result<Option<texrra_tex_core::resources::NamedFont>, String> {
let (name, from) = (name.to_owned(), from.to_owned());
call!(self, pdf_truetype(&name, &from); |result| {
result.as_ref().map(|result| result.as_ref().map(|font| {
(font.resource.version.clone(), font.index, font.full_name.clone())
})).map_err(Clone::clone)
})
}
fn optional_font_file(&mut self, kind: ResourceKind, name: &str, from: &str) -> Result<Option<LoadedResource>, String> {
let (name, from) = (name.to_owned(), from.to_owned());
call!(self, optional_font_file(kind, &name, &from); |result| {
+9
View File
@@ -1676,6 +1676,15 @@ impl SourceProvider for Files {
}
Ok(selected)
}
fn pdf_truetype(
&mut self, name: &str, from: &str,
) -> Result<Option<texrra_tex_core::resources::NamedFont>, String> {
let selected = self.world.read_pdf_truetype(name, Path::new(from))?;
if let Some(font) = &selected {
self.observe_resource(ResourceKind::TrueType, &font.resource);
}
Ok(selected)
}
fn optional_font_file(&mut self, kind: ResourceKind, name: &str, from: &str) -> Result<Option<LoadedResource>, String> {
let resource = self.world.read_optional(kind, name, Path::new(from))?;
if let Some(resource) = &resource {
+96 -37
View File
@@ -15,7 +15,8 @@ mod overlay;
#[derive(Default, PartialEq, Eq)]
pub(crate) struct PreviewFonts {
programs: BTreeMap<String, Arc<Type1Font>>,
type1: BTreeMap<String, Arc<Type1Font>>,
truetype: BTreeMap<String, Arc<[u8]>>,
missing: bool,
conflict: Option<String>,
}
@@ -37,7 +38,8 @@ impl PreviewFonts {
.collect();
let mut pending: Vec<_> = pages.iter().collect();
let mut visited = BTreeSet::new();
let mut required: BTreeSet<(&Path, &str)> = BTreeSet::new();
let mut required_type1: BTreeSet<(&Path, &str)> = BTreeSet::new();
let mut required_truetype = BTreeSet::new();
while let Some(list) = pending.pop() {
for item in &list.items {
match item {
@@ -45,17 +47,29 @@ impl PreviewFonts {
paint: Some(paint), ..
} => {
if let NativeFontProgram::DeviceType1(device) = &paint.program {
fonts.record(&device.name, device.preview_program.as_ref());
record(
&mut fonts.type1,
&mut fonts.missing,
&mut fonts.conflict,
&device.name,
device.preview_program.as_ref(),
);
}
}
DisplayItem::PdfImage { image, .. } => {
let source = &image.image;
required.extend(
required_type1.extend(
source
.device_type1_fonts()
.iter()
.map(|name| (source.version.path.as_path(), name.as_str())),
);
required_truetype.extend(
source
.device_truetype_fonts()
.iter()
.map(|name| (source.version.path.as_path(), name.as_str())),
);
}
DisplayItem::PdfForm { form, .. } => {
if visited.insert(form.number)
@@ -68,29 +82,32 @@ impl PreviewFonts {
}
}
}
for (from, name) in required {
for (from, name) in required_type1 {
let program = cache.pdf_device_type1(files, name, &from.to_string_lossy())?;
fonts.record(name, program.as_ref());
record(
&mut fonts.type1,
&mut fonts.missing,
&mut fonts.conflict,
name,
program.as_ref(),
);
}
for (from, name) in required_truetype {
let program =
NativeFontCache::pdf_device_truetype(files, name, &from.to_string_lossy())?;
record(
&mut fonts.truetype,
&mut fonts.missing,
&mut fonts.conflict,
name,
program.as_ref(),
);
}
Ok(fonts)
}
fn record(&mut self, name: &str, program: Option<&Arc<Type1Font>>) {
let Some(program) = program else {
self.missing = true;
return;
};
if let Some(captured) = self.programs.get(name) {
if !Arc::ptr_eq(captured, program) && captured != program {
self.conflict = Some(name.to_owned());
}
} else {
self.programs.insert(name.to_owned(), program.clone());
}
}
pub(super) fn includes_device_fonts(&self) -> bool {
self.missing || !self.programs.is_empty()
self.missing || !self.type1.is_empty() || !self.truetype.is_empty()
}
/// Attach the captured programs to a private copy for PDF-backed previews.
@@ -100,7 +117,7 @@ impl PreviewFonts {
"conflicting actual fonts for PDF preview device name {name}"
));
}
if self.programs.is_empty() {
if self.type1.is_empty() && self.truetype.is_empty() {
return Ok(None);
}
let mut document = Document::load_mem(pdf)
@@ -123,8 +140,8 @@ impl PreviewFonts {
})
.collect();
let prior_max_id = document.max_id;
let programs = self
.programs
let type1 = self
.type1
.iter()
.map(|(name, program)| {
let mut dictionary = Dictionary::new();
@@ -135,10 +152,21 @@ impl PreviewFonts {
(name.as_bytes(), (program, stream))
})
.collect();
let truetype = self
.truetype
.iter()
.map(|(name, program)| {
let mut dictionary = Dictionary::new();
dictionary.set("Length1", program.len() as i64);
let stream = document.add_object(Stream::new(dictionary, program.to_vec()));
(name.as_bytes(), stream)
})
.collect();
let attachment = Attachment {
names,
descriptors,
programs,
type1,
truetype,
};
let mut attached = false;
let changes: Vec<_> = document
@@ -162,10 +190,31 @@ impl PreviewFonts {
}
}
fn record<T: PartialEq + ?Sized>(
programs: &mut BTreeMap<String, Arc<T>>,
missing: &mut bool,
conflict: &mut Option<String>,
name: &str,
program: Option<&Arc<T>>,
) {
let Some(program) = program else {
*missing = true;
return;
};
if let Some(captured) = programs.get(name) {
if !Arc::ptr_eq(captured, program) && captured != program {
*conflict = Some(name.to_owned());
}
} else {
programs.insert(name.to_owned(), program.clone());
}
}
struct Attachment<'a> {
names: BTreeMap<ObjectId, Vec<u8>>,
descriptors: BTreeMap<ObjectId, Dictionary>,
programs: BTreeMap<&'a [u8], (&'a Arc<Type1Font>, ObjectId)>,
type1: BTreeMap<&'a [u8], (&'a Arc<Type1Font>, ObjectId)>,
truetype: BTreeMap<&'a [u8], ObjectId>,
}
impl Attachment<'_> {
@@ -197,13 +246,24 @@ impl Attachment<'_> {
_ => object.as_name().ok(),
}
};
if name(b"Subtype") != Some(b"Type1") {
return false;
}
let Some((program, stream)) = name(b"BaseFont").and_then(|base| self.programs.get(base))
else {
let Some(base) = name(b"BaseFont") else {
return false;
};
let (file_key, stream, bbox) = match name(b"Subtype") {
Some(b"Type1") => {
let Some((program, stream)) = self.type1.get(base) else {
return false;
};
("FontFile", stream, Some(program.bbox))
}
Some(b"TrueType" | b"CIDFontType2") => {
let Some(stream) = self.truetype.get(base) else {
return false;
};
("FontFile2", stream, None)
}
_ => return false,
};
let mut descriptor = match font.get(b"FontDescriptor") {
Ok(Object::Dictionary(dict)) => dict.clone(),
Ok(Object::Reference(id)) => {
@@ -215,11 +275,10 @@ impl Attachment<'_> {
Err(_) | Ok(Object::Null) => {
let mut dict = Dictionary::new();
dict.set("Type", Object::Name(b"FontDescriptor".to_vec()));
dict.set("FontName", Object::Name(program.name.as_bytes().to_vec()));
dict.set(
"FontBBox",
Object::Array(program.bbox.map(Object::from).into()),
);
dict.set("FontName", Object::Name(base.to_vec()));
if let Some(bbox) = bbox {
dict.set("FontBBox", Object::Array(bbox.map(Object::from).into()));
}
dict
}
_ => return false,
@@ -230,7 +289,7 @@ impl Attachment<'_> {
{
return false;
}
descriptor.set("FontFile", *stream);
descriptor.set(file_key, *stream);
font.set("FontDescriptor", descriptor);
true
}
+61
View File
@@ -1888,6 +1888,67 @@ fn relocated_format_binds_packed_and_new_glyphs_to_the_current_tfm() {
fs::remove_dir_all(root).unwrap();
}
#[test]
fn imported_device_truetype_uses_its_actual_postscript_name_offline() {
let root = directory("imported-device-truetype").canonicalize().unwrap();
let fonts = root.join("fonts");
fs::create_dir(&fonts).unwrap();
let selected = fonts.join("local-font-with-an-unrelated-filename.ttf");
let wrong_font = fonts.join("LiberationSerif.ttf");
fs::write(&selected, include_bytes!("../assets/fonts-subset/LiberationSerif-Regular.ttf")).unwrap();
fs::write(&wrong_font, include_bytes!("../assets/fonts-subset/LiberationSans-Regular.ttf")).unwrap();
fs::write(
fonts.join("pdftex.map"),
b"cmr10 LiberationSerif <<local-font-with-an-unrelated-filename.ttf\n",
).unwrap();
let mut job = request(&root);
for kind in [ResourceKind::Map, ResourceKind::TrueType] {
job.world.paths.insert(kind, vec![SearchPath::directory(&fonts, false)]);
}
fs::write(root.join("figure.tex"), br"\catcode123=1 \catcode125=2
\pdfoutput=1 \pdfcompresslevel=0 \pdfpagewidth=200pt \pdfpageheight=180pt
\font\face=cmr10
\shipout\hbox{\face AV}
\end
").unwrap();
let mut figure = job.clone();
figure.input = root.join("figure.tex");
figure.output = PathBuf::from("embedded.pdf");
NativeCompiler::default().compile(figure).unwrap();
let mut asset = lopdf::Document::load(root.join("embedded.pdf")).unwrap();
let mut detached = 0;
for objects in asset.objects.values_mut() {
if let Ok(dict) = objects.as_dict_mut() && dict.has(b"FontFile2") {
dict.remove(b"FontFile2");
detached += 1;
}
}
assert_eq!(detached, 1);
asset.prune_objects();
let image = root.join("figure.pdf");
asset.save(&image).unwrap();
fs::write(root.join("main.tex"), br"\catcode123=1 \catcode125=2
\pdfoutput=1 \pdfcompresslevel=0 \pdfpagewidth=240pt \pdfpageheight=200pt
\pdfximage width120pt {figure.pdf}
\shipout\hbox{\pdfrefximage\pdflastximage}
\end
").unwrap();
let compiler = NativeCompiler::default();
let original = compiler.compile(job.clone()).unwrap();
let svg = original.preview_since(None).unwrap().pages[0].svg.clone();
assert!(svg.contains("<use"));
assert!(original.resources.trace.reads.contains(&file_version(&selected).unwrap().unwrap()));
assert!(!original.resources.trace.reads.contains(&file_version(&wrong_font).unwrap().unwrap()));
let pdf = lopdf::Document::load_mem(original.pdf.as_deref().unwrap()).unwrap();
assert!(!pdf.objects.values().any(|object| object.as_dict().is_ok_and(|dict| dict.has(b"FontFile2"))));
for path in [&selected, &wrong_font, &image] { fs::remove_file(path).unwrap(); }
let replay = NativeCompiler::default().compile(job.with_inputs(original.inputs.clone())).unwrap();
assert_eq!(replay.pdf, original.pdf);
assert_eq!(replay.preview_since(None).unwrap().pages[0].svg, svg);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn imported_device_type1_tracks_the_selected_pages_local_outline() {
let root = directory("imported-device-type1").canonicalize().unwrap();