Resolve imported PDF Type 1 device fonts in native previews
This commit is contained in:
1 parent
c0970bdbf6
commit
b640b26eff
12 files changed
+586
-106
No files matched your search
@@ -304,6 +304,17 @@ impl DecodedType1 {
|
||||
}
|
||||
|
||||
impl NativeFontCache {
|
||||
/// Resolve a PDF device font using the same exact program identity as native text.
|
||||
pub fn pdf_device_type1(
|
||||
&self,
|
||||
files: &mut impl crate::execution::SourceProvider,
|
||||
name: &str,
|
||||
from: &str,
|
||||
) -> Result<Option<Arc<Type1Font>>, String> {
|
||||
Ok(device_type1::find_program(files, self, name, None, from)?
|
||||
.map(|(_, decoded)| decoded.program.clone()))
|
||||
}
|
||||
|
||||
// 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> {
|
||||
@@ -429,7 +440,8 @@ fn resolve_physical_fonts(
|
||||
let Some((first, _, _)) = used.values().next() else {
|
||||
return Ok(());
|
||||
};
|
||||
let captured = pages.iter().rev().find_map(|page| page.pdf_font_bindings.as_deref());
|
||||
let captured_bindings = pages.iter().rev().filter_map(|page| page.pdf_font_bindings.as_deref());
|
||||
let captured = captured_bindings.clone().next();
|
||||
let default_map = if captured.is_none() {
|
||||
load_map(files, "pdftex.map", &first.resource.version.path)?
|
||||
} else {
|
||||
@@ -448,8 +460,11 @@ fn resolve_physical_fonts(
|
||||
for (id, (font, slots, expanded)) in used {
|
||||
let entry = if font.pdf_space_font && font.name == "pdftexspace" {
|
||||
Some(Arc::new(dedicated_space_map(&font)))
|
||||
} else if let Some(bindings) = captured {
|
||||
bindings.font(&font)?
|
||||
} else if captured.is_some() {
|
||||
// Pending Form lists may precede the last real page in execution
|
||||
// order, even when the host appends them for physical font painting.
|
||||
captured_bindings.clone().find_map(|bindings| bindings.font(&font).ok())
|
||||
.ok_or_else(|| format!("PDF font {} has no captured map binding", font.name))?
|
||||
} else if let Some(map) = &default_map {
|
||||
find_map_entry(map, &font.name, files, &mut subfonts)?.map(Arc::new)
|
||||
} else {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
//! Unembedded pdfTeX Type 1 fonts retain a device name and optional local outlines.
|
||||
use super::{
|
||||
NativeFont, NativeFontCache, NativeFontPaint, NativeFontProgram, actual_resource,
|
||||
DecodedType1, NativeFont, NativeFontCache, NativeFontPaint, NativeFontProgram, actual_resource,
|
||||
encoding_vector, map::MapEntry, verify_resource,
|
||||
};
|
||||
use crate::{
|
||||
execution::SourceProvider,
|
||||
resources::ResourceKind,
|
||||
resources::{ResourceKind, ResourceVersion},
|
||||
type1::{Type1Font, Type1Transform, standard_encoding},
|
||||
};
|
||||
use std::{
|
||||
@@ -46,6 +46,43 @@ fn standard_flags(name: &str) -> Option<i32> {
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn find_program(
|
||||
files: &mut impl SourceProvider,
|
||||
cache: &NativeFontCache,
|
||||
name: &str,
|
||||
tfm: Option<&str>,
|
||||
from: &str,
|
||||
) -> Result<Option<(ResourceVersion, Arc<DecodedType1>)>, String> {
|
||||
if name.is_empty()
|
||||
|| name
|
||||
.bytes()
|
||||
.any(|byte| matches!(byte, b'/' | b'\\' | b':' | 0))
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let lowercase = name.to_ascii_lowercase();
|
||||
let candidates = std::iter::once(name)
|
||||
.chain(tfm.filter(|tfm| *tfm != name))
|
||||
.chain(
|
||||
(lowercase != name && tfm != Some(lowercase.as_str())).then_some(lowercase.as_str()),
|
||||
);
|
||||
for candidate in candidates {
|
||||
for extension in ["pfb", "pfa"] {
|
||||
let file = format!("{candidate}.{extension}");
|
||||
let Some(resource) = files.optional_font_file(ResourceKind::Type1, &file, from)? else {
|
||||
continue;
|
||||
};
|
||||
let resource = verify_resource(resource, ResourceKind::Type1, &file)?;
|
||||
if let Ok(decoded) = cache.type1(&resource, Type1Transform::default())
|
||||
&& decoded.program.name == name
|
||||
{
|
||||
return Ok(Some((resource.version, decoded)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(super) fn resolve(
|
||||
files: &mut impl SourceProvider,
|
||||
cache: &NativeFontCache,
|
||||
@@ -56,31 +93,11 @@ pub(super) fn resolve(
|
||||
) -> Result<NativeFontPaint, String> {
|
||||
let from = entry.from.to_string_lossy();
|
||||
let mut resources: Vec<_> = entry.version.iter().cloned().collect();
|
||||
let mut preview = None;
|
||||
let candidates = [name, font.name.as_str()];
|
||||
for (index, candidate) in candidates.into_iter().enumerate() {
|
||||
if index == 1 && candidate == name {
|
||||
break;
|
||||
}
|
||||
for extension in ["pfb", "pfa"] {
|
||||
let file = format!("{candidate}.{extension}");
|
||||
let Some(resource) = files.optional_font_file(ResourceKind::Type1, &file, &from)?
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let resource = verify_resource(resource, ResourceKind::Type1, &file)?;
|
||||
if let Ok(decoded) = cache.type1(&resource, Type1Transform::default())
|
||||
&& decoded.program.name == name
|
||||
{
|
||||
resources.push(resource.version);
|
||||
preview = Some(decoded);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if preview.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let preview =
|
||||
find_program(files, cache, name, Some(&font.name), &from)?.map(|(version, decoded)| {
|
||||
resources.push(version);
|
||||
decoded
|
||||
});
|
||||
let encoding = if let Some(file) = &entry.encoding {
|
||||
let encoding = actual_resource(files, ResourceKind::Encoding, file, &from)?;
|
||||
let vector = encoding_vector(&encoding.data)?;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Native image XObjects and the resource objects reachable from their content.
|
||||
mod bmp;
|
||||
mod destinations;
|
||||
mod device_fonts;
|
||||
mod jpeg;
|
||||
mod icc;
|
||||
mod imported_fonts;
|
||||
@@ -56,6 +57,8 @@ pub struct PdfImage {
|
||||
pub(crate) color_space: Option<i32>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
imported_fonts: Vec<imported_fonts::ImportedType1>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
device_type1_fonts: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pdftex_source: Option<imports::SourceGraph>,
|
||||
}
|
||||
@@ -419,6 +422,7 @@ impl PdfImage {
|
||||
objects: Vec::new(),
|
||||
color_space: self.color_space,
|
||||
imported_fonts: Vec::new(),
|
||||
device_type1_fonts: Vec::new(),
|
||||
pdftex_source: None,
|
||||
}
|
||||
}
|
||||
@@ -558,6 +562,7 @@ impl PdfImage {
|
||||
objects,
|
||||
color_space,
|
||||
imported_fonts: Vec::new(),
|
||||
device_type1_fonts: Vec::new(),
|
||||
pdftex_source: None,
|
||||
}
|
||||
}
|
||||
@@ -607,6 +612,7 @@ impl PdfImage {
|
||||
objects: vec![vec![part]],
|
||||
color_space: None,
|
||||
imported_fonts: Vec::new(),
|
||||
device_type1_fonts: Vec::new(),
|
||||
pdftex_source: None,
|
||||
})
|
||||
}
|
||||
@@ -896,12 +902,18 @@ impl PdfImage {
|
||||
objects: graph.bodies,
|
||||
color_space: None,
|
||||
imported_fonts,
|
||||
device_type1_fonts: device_fonts::capture(&doc, inherited(b"Resources")),
|
||||
pdftex_source,
|
||||
},
|
||||
[left, bottom],
|
||||
))
|
||||
}
|
||||
|
||||
/// Unembedded Type 1 names recorded from this selected PDF page.
|
||||
pub fn device_type1_fonts(&self) -> &[String] {
|
||||
&self.device_type1_fonts
|
||||
}
|
||||
|
||||
pub(crate) fn extent(&self) -> [f64; 2] {
|
||||
self.extent.map(f64::from_bits)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
//! Device fonts reachable from the selected page's drawing resources.
|
||||
use super::resolved;
|
||||
use lopdf::{Dictionary, Document, Object};
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
|
||||
pub(super) fn capture(doc: &Document, resources: Option<&Object>) -> Vec<String> {
|
||||
let Some(resources) = resources.and_then(|value| resolved(doc, value).ok()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut pending = vec![resources];
|
||||
let mut seen = HashSet::new();
|
||||
let mut names = BTreeSet::new();
|
||||
while let Some(resources) = pending.pop() {
|
||||
let Ok(dict) = resources.as_dict() else {
|
||||
continue;
|
||||
};
|
||||
if !seen.insert(std::ptr::from_ref(dict)) {
|
||||
continue;
|
||||
}
|
||||
if let Some(fonts) = get(doc, dict, b"Font").and_then(|value| value.as_dict().ok()) {
|
||||
for (_, font) in fonts.iter() {
|
||||
if let Some(font) = resolved(doc, font)
|
||||
.ok()
|
||||
.and_then(|value| value.as_dict().ok())
|
||||
{
|
||||
capture_font(doc, font, &mut names, &mut pending);
|
||||
}
|
||||
}
|
||||
}
|
||||
for group in [b"XObject".as_slice(), b"Pattern"] {
|
||||
if let Some(objects) = get(doc, dict, group).and_then(|value| value.as_dict().ok()) {
|
||||
for (_, object) in objects.iter() {
|
||||
if let Ok(Object::Stream(stream)) = resolved(doc, object)
|
||||
&& let Some(resources) = get(doc, &stream.dict, b"Resources")
|
||||
{
|
||||
pending.push(resources);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(states) = get(doc, dict, b"ExtGState").and_then(|value| value.as_dict().ok()) {
|
||||
for (_, state) in states.iter() {
|
||||
let Some(state) = resolved(doc, state)
|
||||
.ok()
|
||||
.and_then(|value| value.as_dict().ok())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if let Some(values) =
|
||||
get(doc, state, b"Font").and_then(|value| value.as_array().ok())
|
||||
&& let Some(font) = values
|
||||
.first()
|
||||
.and_then(|value| resolved(doc, value).ok())
|
||||
.and_then(|value| value.as_dict().ok())
|
||||
{
|
||||
capture_font(doc, font, &mut names, &mut pending);
|
||||
}
|
||||
if let Some(mask) = get(doc, state, b"SMask").and_then(|value| value.as_dict().ok())
|
||||
&& let Some(Object::Stream(form)) = get(doc, mask, b"G")
|
||||
&& let Some(resources) = get(doc, &form.dict, b"Resources")
|
||||
{
|
||||
pending.push(resources);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
names.into_iter().collect()
|
||||
}
|
||||
|
||||
fn get<'a>(doc: &'a Document, dict: &'a Dictionary, key: &[u8]) -> Option<&'a Object> {
|
||||
resolved(doc, dict.get(key).ok()?).ok()
|
||||
}
|
||||
|
||||
fn capture_font<'a>(
|
||||
doc: &'a Document,
|
||||
font: &'a Dictionary,
|
||||
names: &mut BTreeSet<String>,
|
||||
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());
|
||||
}
|
||||
}
|
||||
Some(b"Type3") => {
|
||||
if let Some(resources) = get(doc, font, b"Resources") {
|
||||
pending.push(resources);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -147,6 +147,7 @@ pub(super) fn read(
|
||||
objects: vec![vec![Part::Png(image)]],
|
||||
color_space,
|
||||
imported_fonts: Vec::new(),
|
||||
device_type1_fonts: Vec::new(),
|
||||
pdftex_source: None,
|
||||
restored_pdf_origin: None,
|
||||
},
|
||||
|
||||
@@ -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 的 Type 1 设备字体
|
||||
|
||||
从已放置图像所选页面的实际资源及嵌套 Form 记录设备字体,并使用
|
||||
现有原生字体缓存和项目资源查找,核对实际 PFB/PFA 的 PostScript
|
||||
名。导出 PDF 按原版保留设备字体声明。预览在私有 PDF 中追加所需
|
||||
字体程序和引用,保留原 PDF 字节和坐标精度。原生 Form 输出与后续
|
||||
页面按字体 ID 各自查找已捕获的映射。[原版导入字体规则](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftoepdf.cc#L359-L412)
|
||||
|
||||
两项定向回归通过。两个真实选页中只放置第一页时,只读取该图的
|
||||
CMR10。七组预览的三个字形轮廓全部相同。覆盖 PFB、PFA、直接
|
||||
字体字典和间接字体名、旧版格式重载、对象流压缩、XeTeX profile
|
||||
以及真实整嵌字体对照。PFA、旧格式与压缩样例的 SVG 与可见
|
||||
PFB 样例逐字节一致。直接字体字典和 XeTeX 的绝对坐标保留各自
|
||||
输入的精度,最大变换系数差分别为 0.0021 和 0.0001。Poppler
|
||||
在原版与原生的直接字体字典样例均报告内部交叉引用提示。
|
||||
|
||||
四页会话更改实际 CMR10 轮廓时,导出 PDF 字节相同。修改轮廓、
|
||||
移动图像及恢复资源都只更新第 2 页。后两次各复用 109 步。
|
||||
成功版本的 PDF、测量页面、SVG、来源映射和 aux 与独立全量一致。
|
||||
缺字体时编辑器保留此前的成功预览和 aux。
|
||||
|
||||
回执在 target/p3-imported-device-type1。receipt.json 的 SHA-256 为
|
||||
a0057c8833e8ad26315b4a59da9700c1bff60929c025e460f6f6192e240aa4cb,
|
||||
revision.log 为 f3872ba1c987dc93c71314c1d35c84fd2320c096540fe7e70420115869fdb6c7。
|
||||
保留初次 Form 绑定失败和预览副本发生舍入的原始证据。
|
||||
下一入口为导入 PDF 中未嵌入的 TrueType 设备字体。原版与原生
|
||||
均保留 LiberationSerif 字体引用。当前预览未读取实际提供的
|
||||
LiberationSerif-Regular.ttf,只留下裁剪。复现在
|
||||
target/p3-imported-device-type1/next-imported-truetype。
|
||||
|
||||
### pdfTeX 的未嵌入 Type 1 设备字体
|
||||
|
||||
映射中只声明设备字体名时,原生 PDF 写出实际 TFM 字宽和字体描述符,
|
||||
|
||||
+19
-8
@@ -15,7 +15,7 @@ use crate::native_job::{
|
||||
DraftSyncQueue, EffectMode, Files, PreparedInputsCheck, PreparedOutput, absolute_output,
|
||||
file_modification_date,
|
||||
};
|
||||
use crate::native_preview::PreviewState;
|
||||
use crate::native_preview::{PreviewFonts, PreviewState};
|
||||
pub use crate::native_preview::{PreviewPage, PreviewUpdate};
|
||||
pub use crate::native_stream::{
|
||||
DescriptorIdentity, InputOpened, InputStorage, ReleaseCause, StreamEffect, StreamEvent,
|
||||
@@ -1124,7 +1124,9 @@ impl CompileJob {
|
||||
files.write_layout_manifest(path, e, &pages, &source_map)?;
|
||||
}
|
||||
evidence.phase = AttemptPhase::Fonts;
|
||||
if !draft_mode {
|
||||
let preview_fonts = if draft_mode {
|
||||
PreviewFonts::default()
|
||||
} else {
|
||||
let mut forms = pages.first_mut().map(|first| std::mem::take(&mut first.forms))
|
||||
.unwrap_or_default();
|
||||
let actual_pages = pages.len();
|
||||
@@ -1136,15 +1138,23 @@ impl CompileJob {
|
||||
if let Some(first) = pages.first_mut() {
|
||||
first.forms = forms;
|
||||
}
|
||||
let fonts = fonts.and_then(|_| PreviewFonts::resolve(
|
||||
&pages, files, &self.compiler.font_cache,
|
||||
));
|
||||
let reported = report(files, &request);
|
||||
if let Err(error) = fonts {
|
||||
if let Err(report) = reported {
|
||||
evidence.gaps.push(report.to_string());
|
||||
match fonts {
|
||||
Ok(preview) => {
|
||||
reported?;
|
||||
preview
|
||||
}
|
||||
Err(error) => {
|
||||
if let Err(report) = reported {
|
||||
evidence.gaps.push(report.to_string());
|
||||
}
|
||||
return Err(CompileError::Host(error));
|
||||
}
|
||||
return Err(CompileError::Host(error));
|
||||
}
|
||||
reported?;
|
||||
}
|
||||
};
|
||||
let source_map = self.compiler.session.source_map(&execution, &pages)?;
|
||||
notify(
|
||||
&request,
|
||||
@@ -1235,6 +1245,7 @@ impl CompileJob {
|
||||
)
|
||||
}),
|
||||
pdf_unchanged,
|
||||
preview_fonts,
|
||||
);
|
||||
let result = Arc::new(CompiledDocument {
|
||||
format_preparation,
|
||||
|
||||
@@ -386,6 +386,9 @@ fn original_a3_resume_uses_real_host_and_matches_independent_full_jobs() {
|
||||
RevisionExecution::from_execution(1, resumed, Some(files.resource_trace().clone()));
|
||||
let mut pages = execution.execution.shipout_display_lists().unwrap();
|
||||
texrra_tex_core::native_font::resolve_native_fonts(&mut pages, &mut files).unwrap();
|
||||
let fonts = PreviewFonts::resolve(
|
||||
&pages, &mut files, &texrra_tex_core::native_font::NativeFontCache::default(),
|
||||
).unwrap();
|
||||
let source_map = SourceMap::from_revision(&execution, &pages).unwrap();
|
||||
let pdf = texrra_tex_core::pdf::shipout_lists_to_native_pdf_document(
|
||||
&pages,
|
||||
@@ -410,7 +413,7 @@ fn original_a3_resume_uses_real_host_and_matches_independent_full_jobs() {
|
||||
let resumed_log = fs::read(cwd.join("main.log")).unwrap();
|
||||
assert_eq!(aux, resumed_aux);
|
||||
let pdf_for_preview: Arc<[u8]> = Arc::from(pdf.bytes.as_slice());
|
||||
let resumed_preview = PreviewState::new(&pages, None, false)
|
||||
let resumed_preview = PreviewState::new(&pages, None, false, fonts)
|
||||
.render(1, &pages, Some(&pdf_for_preview), None, || Ok(()))
|
||||
.unwrap();
|
||||
let full = NativeCompiler::default().compile(request.clone()).unwrap();
|
||||
|
||||
@@ -10,7 +10,7 @@ use texrra_tex_core::render::DisplayList;
|
||||
|
||||
mod device_fonts;
|
||||
mod pdf_dependencies;
|
||||
use device_fonts::PreviewFonts;
|
||||
pub(crate) use device_fonts::PreviewFonts;
|
||||
use pdf_dependencies::{Fingerprint, PdfDependencies};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
|
||||
@@ -136,11 +136,11 @@ impl PreviewState {
|
||||
pages: &[DisplayList],
|
||||
previous: Option<(u64, &[DisplayList], &Self)>,
|
||||
pdf_unchanged: bool,
|
||||
fonts: PreviewFonts,
|
||||
) -> Self {
|
||||
let mut changed = Vec::new();
|
||||
let mut slots = Vec::with_capacity(pages.len());
|
||||
let mut prior_pdf = BTreeMap::new();
|
||||
let fonts = PreviewFonts::collect(pages);
|
||||
let pdf_inputs_unchanged = pdf_unchanged
|
||||
&& previous.is_some_and(|(_, _, old)| old.fonts == fonts);
|
||||
for (index, page) in pages.iter().enumerate() {
|
||||
|
||||
@@ -1,53 +1,91 @@
|
||||
use lopdf::{Dictionary, Document, Stream};
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
use lopdf::{Dictionary, Document, Object, ObjectId, Stream};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
path::Path,
|
||||
sync::Arc,
|
||||
};
|
||||
use texrra_tex_core::{
|
||||
native_font::NativeFontProgram,
|
||||
execution::SourceProvider,
|
||||
native_font::{NativeFontCache, NativeFontProgram},
|
||||
render::{DisplayItem, DisplayList},
|
||||
type1::Type1Font,
|
||||
};
|
||||
|
||||
mod overlay;
|
||||
|
||||
#[derive(Default, PartialEq, Eq)]
|
||||
pub(super) struct PreviewFonts {
|
||||
pub(crate) struct PreviewFonts {
|
||||
programs: BTreeMap<String, Arc<Type1Font>>,
|
||||
missing: bool,
|
||||
conflict: Option<String>,
|
||||
}
|
||||
|
||||
impl PreviewFonts {
|
||||
pub(super) fn collect(pages: &[DisplayList]) -> Self {
|
||||
pub(crate) fn resolve(
|
||||
pages: &[DisplayList],
|
||||
files: &mut impl SourceProvider,
|
||||
cache: &NativeFontCache,
|
||||
) -> Result<Self, String> {
|
||||
let mut fonts = Self::default();
|
||||
if pages.iter().any(DisplayList::has_embedded_pdf) {
|
||||
for page in pages {
|
||||
fonts.collect_from(page);
|
||||
}
|
||||
if !pages.iter().any(DisplayList::has_embedded_pdf) {
|
||||
return Ok(fonts);
|
||||
}
|
||||
fonts
|
||||
}
|
||||
|
||||
fn collect_from(&mut self, page: &DisplayList) {
|
||||
for item in &page.items {
|
||||
let DisplayItem::NativeGlyph {
|
||||
paint: Some(paint), ..
|
||||
} = item
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if let NativeFontProgram::DeviceType1(device) = &paint.program {
|
||||
if let Some(program) = &device.preview_program {
|
||||
if let Some(captured) = self.programs.get(&device.name) {
|
||||
if !Arc::ptr_eq(captured, program) && captured != program {
|
||||
self.conflict = Some(device.name.clone());
|
||||
let forms: BTreeMap<_, _> = pages
|
||||
.iter()
|
||||
.flat_map(|page| &page.forms)
|
||||
.map(|form| (form.form.number, &form.list))
|
||||
.collect();
|
||||
let mut pending: Vec<_> = pages.iter().collect();
|
||||
let mut visited = BTreeSet::new();
|
||||
let mut required: BTreeSet<(&Path, &str)> = BTreeSet::new();
|
||||
while let Some(list) = pending.pop() {
|
||||
for item in &list.items {
|
||||
match item {
|
||||
DisplayItem::NativeGlyph {
|
||||
paint: Some(paint), ..
|
||||
} => {
|
||||
if let NativeFontProgram::DeviceType1(device) = &paint.program {
|
||||
fonts.record(&device.name, device.preview_program.as_ref());
|
||||
}
|
||||
} else {
|
||||
self.programs.insert(device.name.clone(), program.clone());
|
||||
}
|
||||
} else {
|
||||
self.missing = true;
|
||||
DisplayItem::PdfImage { image, .. } => {
|
||||
let source = &image.image;
|
||||
required.extend(
|
||||
source
|
||||
.device_type1_fonts()
|
||||
.iter()
|
||||
.map(|name| (source.version.path.as_path(), name.as_str())),
|
||||
);
|
||||
}
|
||||
DisplayItem::PdfForm { form, .. } => {
|
||||
if visited.insert(form.number)
|
||||
&& let Some(list) = forms.get(&form.number)
|
||||
{
|
||||
pending.push(list);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
for form in &page.forms {
|
||||
self.collect_from(&form.list);
|
||||
for (from, name) in required {
|
||||
let program = cache.pdf_device_type1(files, name, &from.to_string_lossy())?;
|
||||
fonts.record(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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,8 +93,7 @@ impl PreviewFonts {
|
||||
self.missing || !self.programs.is_empty()
|
||||
}
|
||||
|
||||
/// For PDF-backed previews, attach the same captured local font programs
|
||||
/// used by the native SVG path to an in-memory copy of the PDF.
|
||||
/// Attach the captured programs to a private copy for PDF-backed previews.
|
||||
pub(super) fn attach(&self, pdf: &[u8]) -> Result<Option<Vec<u8>>, String> {
|
||||
if let Some(name) = &self.conflict {
|
||||
return Err(format!(
|
||||
@@ -68,43 +105,133 @@ impl PreviewFonts {
|
||||
}
|
||||
let mut document = Document::load_mem(pdf)
|
||||
.map_err(|error| format!("could not read PDF device fonts for preview: {error}"))?;
|
||||
let descriptors: Vec<_> = document
|
||||
let names: BTreeMap<_, _> = document
|
||||
.objects
|
||||
.iter()
|
||||
.filter_map(|(&id, object)| {
|
||||
let descriptor = object.as_dict().ok()?;
|
||||
if descriptor.get(b"Type").ok()?.as_name().ok()? != b"FontDescriptor"
|
||||
|| [b"FontFile".as_slice(), b"FontFile2", b"FontFile3"]
|
||||
.into_iter()
|
||||
.any(|key| descriptor.has(key))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let name = descriptor.get(b"FontName").ok()?;
|
||||
let (_, name) = document.dereference(name).ok()?;
|
||||
let name = std::str::from_utf8(name.as_name().ok()?).ok()?;
|
||||
Some((id, self.programs.get(name)?))
|
||||
.filter_map(|(&id, value)| {
|
||||
let (_, value) = document.dereference(value).ok()?;
|
||||
Some((id, value.as_name().ok()?.to_vec()))
|
||||
})
|
||||
.collect();
|
||||
if descriptors.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut streams = BTreeMap::new();
|
||||
for (id, font) in descriptors {
|
||||
let stream = *streams.entry(&font.name).or_insert_with(|| {
|
||||
let descriptors: BTreeMap<_, _> = document
|
||||
.objects
|
||||
.iter()
|
||||
.filter_map(|(&id, value)| {
|
||||
let (_, value) = document.dereference(value).ok()?;
|
||||
let dict = value.as_dict().ok()?;
|
||||
dict.has(b"FontName").then(|| (id, dict.clone()))
|
||||
})
|
||||
.collect();
|
||||
let prior_max_id = document.max_id;
|
||||
let programs = self
|
||||
.programs
|
||||
.iter()
|
||||
.map(|(name, program)| {
|
||||
let mut dictionary = Dictionary::new();
|
||||
dictionary.set("Length1", font.length1 as i64);
|
||||
dictionary.set("Length2", font.length2 as i64);
|
||||
dictionary.set("Length3", font.length3 as i64);
|
||||
document.add_object(Stream::new(dictionary, font.program.clone()))
|
||||
});
|
||||
let descriptor = document.get_object_mut(id).unwrap().as_dict_mut().unwrap();
|
||||
descriptor.set("FontFile", stream);
|
||||
dictionary.set("Length1", program.length1 as i64);
|
||||
dictionary.set("Length2", program.length2 as i64);
|
||||
dictionary.set("Length3", program.length3 as i64);
|
||||
let stream = document.add_object(Stream::new(dictionary, program.program.clone()));
|
||||
(name.as_bytes(), (program, stream))
|
||||
})
|
||||
.collect();
|
||||
let attachment = Attachment {
|
||||
names,
|
||||
descriptors,
|
||||
programs,
|
||||
};
|
||||
let mut attached = false;
|
||||
let changes: Vec<_> = document
|
||||
.objects
|
||||
.iter_mut()
|
||||
.filter_map(|(&id, object)| {
|
||||
let patched = id.0 <= prior_max_id && attachment.apply(object, 0);
|
||||
attached |= patched;
|
||||
(patched || id.0 > prior_max_id).then_some(id)
|
||||
})
|
||||
.collect();
|
||||
if attached {
|
||||
Ok(Some(overlay::append_objects(
|
||||
pdf,
|
||||
&document,
|
||||
changes.into_iter(),
|
||||
)?))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
document
|
||||
.save_to(&mut bytes)
|
||||
.map_err(|error| format!("could not prepare PDF device fonts for preview: {error}"))?;
|
||||
Ok(Some(bytes))
|
||||
}
|
||||
}
|
||||
|
||||
struct Attachment<'a> {
|
||||
names: BTreeMap<ObjectId, Vec<u8>>,
|
||||
descriptors: BTreeMap<ObjectId, Dictionary>,
|
||||
programs: BTreeMap<&'a [u8], (&'a Arc<Type1Font>, ObjectId)>,
|
||||
}
|
||||
|
||||
impl Attachment<'_> {
|
||||
fn apply(&self, object: &mut Object, depth: usize) -> bool {
|
||||
if depth >= 64 {
|
||||
return false;
|
||||
}
|
||||
let dictionary = match object {
|
||||
Object::Dictionary(dict) => dict,
|
||||
Object::Stream(stream) => &mut stream.dict,
|
||||
Object::Array(entries) => {
|
||||
return entries.iter_mut().fold(false, |changed, object| {
|
||||
self.apply(object, depth + 1) | changed
|
||||
});
|
||||
}
|
||||
_ => return false,
|
||||
};
|
||||
let nested = dictionary.iter_mut().fold(false, |changed, (_, value)| {
|
||||
self.apply(value, depth + 1) | changed
|
||||
});
|
||||
self.attach_font(dictionary) || nested
|
||||
}
|
||||
|
||||
fn attach_font(&self, font: &mut Dictionary) -> bool {
|
||||
let name = |key| {
|
||||
let object = font.get(key).ok()?;
|
||||
match object {
|
||||
Object::Reference(id) => self.names.get(id).map(Vec::as_slice),
|
||||
_ => 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 {
|
||||
return false;
|
||||
};
|
||||
let mut descriptor = match font.get(b"FontDescriptor") {
|
||||
Ok(Object::Dictionary(dict)) => dict.clone(),
|
||||
Ok(Object::Reference(id)) => {
|
||||
let Some(dict) = self.descriptors.get(id) else {
|
||||
return false;
|
||||
};
|
||||
dict.clone()
|
||||
}
|
||||
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
|
||||
}
|
||||
_ => return false,
|
||||
};
|
||||
if [b"FontFile".as_slice(), b"FontFile2", b"FontFile3"]
|
||||
.into_iter()
|
||||
.any(|key| descriptor.has(key))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
descriptor.set("FontFile", *stream);
|
||||
font.set("FontDescriptor", descriptor);
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
//! Append private preview objects without rewriting the exported geometry.
|
||||
use lopdf::{
|
||||
Dictionary, Document, Object, ObjectId,
|
||||
content::{Content, Operation},
|
||||
};
|
||||
use std::io::Write;
|
||||
|
||||
pub(super) fn append_objects(
|
||||
pdf: &[u8],
|
||||
document: &Document,
|
||||
objects: impl Iterator<Item = ObjectId>,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let suffix = b"startxref";
|
||||
let start = pdf
|
||||
.windows(suffix.len())
|
||||
.rposition(|part| part == suffix)
|
||||
.ok_or("native PDF startxref missing")?
|
||||
+ suffix.len();
|
||||
let previous: usize = std::str::from_utf8(&pdf[start..])
|
||||
.ok()
|
||||
.and_then(|tail| tail.split_ascii_whitespace().next())
|
||||
.and_then(|value| value.parse().ok())
|
||||
.filter(|offset| *offset < start)
|
||||
.ok_or("invalid native PDF startxref")?;
|
||||
let mut bytes = pdf.to_vec();
|
||||
bytes.push(b'\n');
|
||||
let mut offsets = Vec::new();
|
||||
for id @ (number, generation) in objects {
|
||||
offsets.push((number, generation, bytes.len()));
|
||||
writeln!(bytes, "{number} {generation} obj").unwrap();
|
||||
write_value(&mut bytes, &document.objects[&id])?;
|
||||
bytes.extend_from_slice(b"\nendobj\n");
|
||||
}
|
||||
let xref = bytes.len();
|
||||
bytes.extend_from_slice(b"xref\n");
|
||||
for (number, generation, offset) in offsets {
|
||||
writeln!(bytes, "{number} 1\n{offset:010} {generation:05} n ").unwrap();
|
||||
}
|
||||
let mut trailer = Dictionary::new();
|
||||
for key in ["Root", "Info", "ID"] {
|
||||
if let Ok(value) = document.trailer.get(key.as_bytes()) {
|
||||
trailer.set(key, value.clone());
|
||||
}
|
||||
}
|
||||
trailer.set("Size", i64::from(document.max_id) + 1);
|
||||
trailer.set("Prev", previous as i64);
|
||||
bytes.extend_from_slice(b"trailer\n");
|
||||
write_dictionary(&mut bytes, &trailer)?;
|
||||
writeln!(bytes, "\nstartxref\n{xref}\n%%EOF").unwrap();
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn write_dictionary(bytes: &mut Vec<u8>, dictionary: &Dictionary) -> Result<(), String> {
|
||||
bytes.extend_from_slice(b"<<");
|
||||
for (name, value) in dictionary.iter() {
|
||||
write_value(bytes, &Object::Name(name.clone()))?;
|
||||
bytes.push(b' ');
|
||||
write_value(bytes, value)?;
|
||||
bytes.push(b' ');
|
||||
}
|
||||
bytes.extend_from_slice(b">>");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_value(bytes: &mut Vec<u8>, value: &Object) -> Result<(), String> {
|
||||
// lopdf 0.26's writer rounds all Real objects to two decimal places.
|
||||
match value {
|
||||
Object::Real(value) => write!(bytes, "{value}").unwrap(),
|
||||
Object::Dictionary(dictionary) => write_dictionary(bytes, dictionary)?,
|
||||
Object::Array(values) => {
|
||||
bytes.push(b'[');
|
||||
for value in values {
|
||||
write_value(bytes, value)?;
|
||||
bytes.push(b' ');
|
||||
}
|
||||
bytes.push(b']');
|
||||
}
|
||||
Object::Stream(stream) => {
|
||||
write_dictionary(bytes, &stream.dict)?;
|
||||
bytes.extend_from_slice(b"\nstream\n");
|
||||
bytes.extend_from_slice(&stream.content);
|
||||
bytes.extend_from_slice(b"\nendstream");
|
||||
}
|
||||
other => {
|
||||
let encoded = Content {
|
||||
operations: [Operation::new("", vec![other.clone()])],
|
||||
}
|
||||
.encode()
|
||||
.map_err(|error| format!("could not encode preview PDF object: {error}"))?;
|
||||
bytes.extend_from_slice(&encoded[..encoded.len() - 2]);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1888,6 +1888,71 @@ fn relocated_format_binds_packed_and_new_glyphs_to_the_current_tfm() {
|
||||
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();
|
||||
let fonts = root.join("fonts");
|
||||
fs::create_dir(&fonts).unwrap();
|
||||
let regular = fonts.join("cmr10.pfb");
|
||||
let other = fonts.join("cmtt10.pfb");
|
||||
let original = include_bytes!("../assets/fonts/cmr10.pfb");
|
||||
fs::write(®ular, original).unwrap();
|
||||
fs::write(&other, include_bytes!("../assets/fonts/cmtt10.pfb")).unwrap();
|
||||
fs::write(fonts.join("pdftex.map"), b"cmr10 CMR10 4\ncmtt10 CMTT10 4\n").unwrap();
|
||||
let mut job = request(&root);
|
||||
for kind in [ResourceKind::Map, ResourceKind::Type1] {
|
||||
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\roman=cmr10 \font\mono=cmtt10
|
||||
\setbox0=\hbox{\roman ABC}
|
||||
\pdfxform0
|
||||
\setbox0=\hbox{\pdfrefxform\pdflastxform}
|
||||
\pdfxform0
|
||||
\shipout\hbox{\pdfrefxform\pdflastxform}
|
||||
\shipout\hbox{\mono OUTSIDE THE SELECTED PAGE}
|
||||
\end
|
||||
").unwrap();
|
||||
let mut figure = job.clone();
|
||||
figure.input = root.join("figure.tex");
|
||||
figure.output = PathBuf::from("figure.pdf");
|
||||
NativeCompiler::default().compile(figure).unwrap();
|
||||
fs::write(root.join("main.tex"), br"\catcode123=1 \catcode125=2
|
||||
\pdfoutput=1 \pdfcompresslevel=0 \pdfpagewidth=240pt \pdfpageheight=200pt
|
||||
\immediate\pdfximage page2 {figure.pdf}
|
||||
\pdfximage width120pt page1 {figure.pdf}
|
||||
\shipout\hbox{\vrule height10pt width10pt}
|
||||
\shipout\hbox{\pdfrefximage\pdflastximage}
|
||||
\end
|
||||
").unwrap();
|
||||
let compiler = NativeCompiler::default();
|
||||
let first = compiler.compile(job.clone()).unwrap();
|
||||
let svg = first.preview_since(None).unwrap().pages[1].svg.clone();
|
||||
assert!(svg.contains(r#"viewBox="0 0 239.103 199.253""#), "{svg}");
|
||||
let (_, drawing) = svg.split_once("</defs>").unwrap();
|
||||
assert!(drawing.contains("<path") || drawing.contains("<use"), "{svg}");
|
||||
assert!(first.resources.trace.reads.contains(&file_version(®ular).unwrap().unwrap()));
|
||||
assert!(!first.resources.trace.reads.contains(&file_version(&other).unwrap().unwrap()));
|
||||
|
||||
let marker = b"/FontMatrix [0.001";
|
||||
let index = original.windows(marker.len()).position(|value| value == marker).unwrap();
|
||||
let mut changed = original.to_vec();
|
||||
changed[index + marker.len() - 1] = b'2';
|
||||
fs::write(®ular, changed).unwrap();
|
||||
let second = compiler.compile(job.clone()).unwrap();
|
||||
assert_eq!(first.pdf, second.pdf);
|
||||
let delta = second.preview_since(Some(first.revision())).unwrap();
|
||||
assert_eq!(delta.pages.iter().map(|page| page.index).collect::<Vec<_>>(), [1]);
|
||||
assert_ne!(svg, delta.pages[0].svg);
|
||||
|
||||
fs::remove_file(®ular).unwrap();
|
||||
let missing = compiler.compile(job).unwrap();
|
||||
assert_eq!(first.pdf, missing.pdf);
|
||||
assert!(missing.preview_since(None).unwrap_err().contains("actual device font"));
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapped_device_type1_uses_actual_preview_font_without_pdf_embedding() {
|
||||
use texrra_tex_core::{native_font::NativeFontProgram, render::DisplayItem};
|
||||
|
||||
Reference in new issue
Block a user