diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index 8453360..c040b75 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -277,6 +277,14 @@ pub trait SourceProvider { ) -> Result, String> { Ok(None) } + /// Resolve the exact PostScript name of a PDF TrueType device font. + fn pdf_truetype( + &mut self, + _name: &str, + _from: &str, + ) -> Result, 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, diff --git a/crates/texrra-tex-core/src/native_font.rs b/crates/texrra-tex-core/src/native_font.rs index 69689cb..34d4208 100644 --- a/crates/texrra-tex-core/src/native_font.rs +++ b/crates/texrra-tex-core/src/native_font.rs @@ -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>, 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, String> { diff --git a/crates/texrra-tex-core/src/native_font/truetype.rs b/crates/texrra-tex-core/src/native_font/truetype.rs index 5458a57..40dff6b 100644 --- a/crates/texrra-tex-core/src/native_font/truetype.rs +++ b/crates/texrra-tex-core/src/native_font/truetype.rs @@ -80,6 +80,25 @@ impl TrueTypeProgram { } } +pub(super) fn device_program( + files: &mut impl SourceProvider, + name: &str, + from: &str, +) -> Result>, 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, diff --git a/crates/texrra-tex-core/src/pdf_image.rs b/crates/texrra-tex-core/src/pdf_image.rs index ef5d491..5a18c25 100644 --- a/crates/texrra-tex-core/src/pdf_image.rs +++ b/crates/texrra-tex-core/src/pdf_image.rs @@ -59,6 +59,8 @@ pub struct PdfImage { imported_fonts: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] device_type1_fonts: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + device_truetype_fonts: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pdftex_source: Option, } @@ -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) } diff --git a/crates/texrra-tex-core/src/pdf_image/device_fonts.rs b/crates/texrra-tex-core/src/pdf_image/device_fonts.rs index e11e982..8b9e9b3 100644 --- a/crates/texrra-tex-core/src/pdf_image/device_fonts.rs +++ b/crates/texrra-tex-core/src/pdf_image/device_fonts.rs @@ -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 { +#[derive(Default)] +struct Names { + type1: BTreeSet, + truetype: BTreeSet, +} + +pub(super) fn capture(doc: &Document, resources: Option<&Object>) -> (Vec, Vec) { 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 } } } - 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, + 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) { + 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()); + } +} diff --git a/crates/texrra-tex-core/src/pdf_image/png.rs b/crates/texrra-tex-core/src/pdf_image/png.rs index eadd28b..6edc25f 100644 --- a/crates/texrra-tex-core/src/pdf_image/png.rs +++ b/crates/texrra-tex-core/src/pdf_image/png.rs @@ -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, }, diff --git a/crates/texrra-tex-core/src/resources.rs b/crates/texrra-tex-core/src/resources.rs index e1a8cd2..1d1af67 100644 --- a/crates/texrra-tex-core/src/resources.rs +++ b/crates/texrra-tex-core/src/resources.rs @@ -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, #[serde(with = "index_names")] names: BTreeMap>, } +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 diff --git a/crates/texrra-tex-core/src/resources/named_fonts.rs b/crates/texrra-tex-core/src/resources/named_fonts.rs index 25fb39c..0b5bf1c 100644 --- a/crates/texrra-tex-core/src/resources/named_fonts.rs +++ b/crates/texrra-tex-core/src/resources/named_fonts.rs @@ -85,6 +85,24 @@ impl NamedFace { } } +pub(crate) fn exact_truetype_name(data: &[u8], index: u32, requested: &str) -> Option { + 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, 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, + ) -> Result, 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; } diff --git a/crates/texrra-tex-core/src/resources/project.rs b/crates/texrra-tex-core/src/resources/project.rs index 9d59dc2..bbfb500 100644 --- a/crates/texrra-tex-core/src/resources/project.rs +++ b/crates/texrra-tex-core/src/resources/project.rs @@ -475,8 +475,10 @@ impl ProjectSnapshot { root: &Path, live: &BTreeSet, limit: usize, + recursive: bool, ) -> Result { 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 => {} + _ => {} } } } diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index abb1457..1e6218b 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -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 记录设备字体,并使用 diff --git a/src/native_checkpoint_probe.rs b/src/native_checkpoint_probe.rs index 0759ad5..9d6bc8f 100644 --- a/src/native_checkpoint_probe.rs +++ b/src/native_checkpoint_probe.rs @@ -156,6 +156,16 @@ impl SourceProvider for RecordingHost<'_> { })).map_err(Clone::clone) }) } + fn pdf_truetype( + &mut self, name: &str, from: &str, + ) -> Result, 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, String> { let (name, from) = (name.to_owned(), from.to_owned()); call!(self, optional_font_file(kind, &name, &from); |result| { diff --git a/src/native_job.rs b/src/native_job.rs index a861a29..2286391 100644 --- a/src/native_job.rs +++ b/src/native_job.rs @@ -1676,6 +1676,15 @@ impl SourceProvider for Files { } Ok(selected) } + fn pdf_truetype( + &mut self, name: &str, from: &str, + ) -> Result, 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, String> { let resource = self.world.read_optional(kind, name, Path::new(from))?; if let Some(resource) = &resource { diff --git a/src/native_preview/device_fonts.rs b/src/native_preview/device_fonts.rs index 6923864..70119d5 100644 --- a/src/native_preview/device_fonts.rs +++ b/src/native_preview/device_fonts.rs @@ -15,7 +15,8 @@ mod overlay; #[derive(Default, PartialEq, Eq)] pub(crate) struct PreviewFonts { - programs: BTreeMap>, + type1: BTreeMap>, + truetype: BTreeMap>, missing: bool, conflict: Option, } @@ -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>) { - 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( + programs: &mut BTreeMap>, + missing: &mut bool, + conflict: &mut Option, + name: &str, + program: Option<&Arc>, +) { + 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>, descriptors: BTreeMap, - programs: BTreeMap<&'a [u8], (&'a Arc, ObjectId)>, + type1: BTreeMap<&'a [u8], (&'a Arc, 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 } diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index 4fc06d9..1505d78 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -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 <