From 60d67bbb7b0e0f8de21706843e6c722290ee172b Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 28 Nov 2026 03:19:37 +0800 Subject: [PATCH] Read mapped Type 1 fonts from PFA programs --- crates/texrra-tex-core/src/native_font.rs | 18 +++--- crates/texrra-tex-core/src/native_font/map.rs | 6 +- crates/texrra-tex-core/src/type1.rs | 23 +++++-- crates/texrra-tex-core/src/type1/pfa.rs | 56 +++++++++++++++++ crates/texrra-tex-core/src/type1_outline.rs | 39 ++++++++++++ docs/P2_M1_PROGRESS.md | 27 +++++++++ tests/native_pipeline.rs | 60 +++++++++++++++++++ 7 files changed, 211 insertions(+), 18 deletions(-) create mode 100644 crates/texrra-tex-core/src/type1/pfa.rs diff --git a/crates/texrra-tex-core/src/native_font.rs b/crates/texrra-tex-core/src/native_font.rs index c867a61..5f6a6b8 100644 --- a/crates/texrra-tex-core/src/native_font.rs +++ b/crates/texrra-tex-core/src/native_font.rs @@ -257,7 +257,7 @@ fn verify_resource( } const MAX_TYPE1_PROGRAMS: usize = 16; -const MAX_CACHED_PFB_BYTES: usize = 256 * 1024; +const MAX_CACHED_TYPE1_BYTES: usize = 256 * 1024; /// Decoded Type 1 programs shared across revisions in one compiler. #[derive(Default)] @@ -274,13 +274,9 @@ struct DecodedType1 { } impl DecodedType1 { - fn from_pfb(resource: &LoadedResource, transform: Type1Transform) -> Result { - let mut program = Type1Font::from_pfb(&resource.data).ok_or_else(|| { - format!( - "invalid Type1 PFB program: {}", - resource.version.path.display() - ) - })?; + fn from_resource(resource: &LoadedResource, transform: Type1Transform) -> Result { + let mut program = Type1Font::from_file(&resource.data) + .map_err(|error| format!("{error}: {}", resource.version.path.display()))?; program.apply_map_transform(transform)?; let outlines = Type1Outlines::parse(&program)?; let (bbox, stem_v) = if transform.is_identity() { @@ -303,8 +299,8 @@ impl NativeFontCache { // 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> { - if resource.data.len() > MAX_CACHED_PFB_BYTES { - return DecodedType1::from_pfb(resource, transform).map(Arc::new); + if resource.data.len() > MAX_CACHED_TYPE1_BYTES { + return DecodedType1::from_resource(resource, transform).map(Arc::new); } let mut entries = self.type1.lock().expect("native Type 1 cache poisoned"); if let Some(index) = entries @@ -316,7 +312,7 @@ impl NativeFontCache { entries.push_back(entry); return Ok(decoded); } - let decoded = Arc::new(DecodedType1::from_pfb(resource, transform)?); + let decoded = Arc::new(DecodedType1::from_resource(resource, transform)?); if entries.len() == MAX_TYPE1_PROGRAMS { entries.pop_front(); } diff --git a/crates/texrra-tex-core/src/native_font/map.rs b/crates/texrra-tex-core/src/native_font/map.rs index 166dfcc..5fa4c71 100644 --- a/crates/texrra-tex-core/src/native_font/map.rs +++ b/crates/texrra-tex-core/src/native_font/map.rs @@ -132,7 +132,7 @@ impl MapEntry { let file = self.file.as_deref().ok_or_else(|| { format!("font map {name} has no embedded Type1 program; mapped device fonts require their actual support") })?; - if !file.ends_with(".pfb") { + if self.outline_file(&["pfb", "pfa"]).is_none() { return Err(format!( "native font program format is not implemented: {file}" )); @@ -405,8 +405,8 @@ impl JobFontMap { let Some(resource) = files.optional_font_file(ResourceKind::Type1, file, &entry.from.to_string_lossy())? else { return Ok(None) }; let resource = verify_resource(resource, ResourceKind::Type1, file)?; - let mut font = crate::type1::Type1Font::from_pfb(&resource.data) - .ok_or_else(|| format!("invalid Type1 PFB program: {file}"))?; + let mut font = crate::type1::Type1Font::from_file(&resource.data) + .map_err(|error| format!("{error}: {}", resource.version.path.display()))?; font.apply_map_transform(transform)?; if self.entries.get(tfm).is_some_and(|direct| Arc::ptr_eq(direct, entry)) { self.used_names.insert(tfm.clone()); diff --git a/crates/texrra-tex-core/src/type1.rs b/crates/texrra-tex-core/src/type1.rs index 66c7e13..5744fb9 100644 --- a/crates/texrra-tex-core/src/type1.rs +++ b/crates/texrra-tex-core/src/type1.rs @@ -1,14 +1,16 @@ -//! Type1 (PFB) loading for TeX's Computer Modern outlines. +//! Type1 loading for TeX's Computer Modern outlines. //! //! Route-D used to embed Liberation TrueType outlines while taking widths from //! the Computer Modern TFMs, so the PDF glyph shapes never matched the metrics. -//! This module parses Knuth's Type1 programs directly: PFB segment lengths for +//! This module parses the actual Type1 programs: segment lengths for //! the PDF `/FontFile` entry and the font's built-in encoding so callers can map //! characters to the codes the program expects. use crate::type1_outline::Tokens; use std::{collections::BTreeMap, ops::Range}; +mod pfa; + pub(crate) fn builtin_encoding(header: &[u8]) -> Result, String> { let mut tokens = Tokens::new(header); while tokens.required()? != "/Encoding" {} @@ -194,6 +196,15 @@ pub struct Type1Font { } impl Type1Font { + pub(crate) fn from_file(bytes: &[u8]) -> Result { + if bytes.first() == Some(&0x80) { + return Self::from_pfb(bytes).ok_or_else(|| "invalid Type1 PFB program".into()); + } + let (header, encrypted, trailer) = pfa::segments(bytes)?; + Self::from_segments(header.to_vec(), &encrypted, trailer) + .ok_or_else(|| "invalid Type1 PFA header or encoding".into()) + } + /// Parse a PFB container into a PDF-ready program plus its encoding. pub fn from_pfb(bytes: &[u8]) -> Option { let mut header = Vec::new(); @@ -230,6 +241,10 @@ impl Type1Font { if !ended || header.is_empty() || encrypted.is_empty() { return None; } + Self::from_segments(header, &encrypted, &trailer) + } + + fn from_segments(header: Vec, encrypted: &[u8], trailer: &[u8]) -> Option { let text = String::from_utf8_lossy(&header); let bbox_text = text.split("/FontBBox").nth(1)?.trim_start(); let close = match bbox_text.as_bytes().first()? { @@ -296,8 +311,8 @@ impl Type1Font { let length2 = encrypted.len(); let length3 = trailer.len(); let mut program = header; - program.extend_from_slice(&encrypted); - program.extend_from_slice(&trailer); + program.extend_from_slice(encrypted); + program.extend_from_slice(trailer); Some(Self { bbox, italic_angle, diff --git a/crates/texrra-tex-core/src/type1/pfa.rs b/crates/texrra-tex-core/src/type1/pfa.rs new file mode 100644 index 0000000..8cedd77 --- /dev/null +++ b/crates/texrra-tex-core/src/type1/pfa.rs @@ -0,0 +1,56 @@ +//! Split the clear PostScript and ASCII-hex eexec data of a PFA file. +use crate::type1_outline::{Tokens, encrypted_eexec_length}; + +pub(super) fn segments(bytes: &[u8]) -> Result<(&[u8], Vec, &[u8]), String> { + let eexec = Tokens::new(bytes).after_currentfile("eexec")?; + let header_end = eexec + + bytes[eexec..] + .iter() + .take_while(|byte| byte.is_ascii_whitespace()) + .count(); + let tail = &bytes[header_end..]; + let mut encrypted = Vec::new(); + let mut digits = tail + .iter() + .enumerate() + .filter(|(_, byte)| !byte.is_ascii_whitespace()); + while let Some((offset, &first)) = digits.next() { + if tail[offset..].starts_with(b"cleartomark") || first == b'%' { + if Tokens::new(&tail[offset..]).required()? != "cleartomark" { + return Err("invalid Type1 PFA trailer".into()); + } + break; + } + let high = hex_digit(first).ok_or("invalid hexadecimal digit in Type1 PFA eexec")?; + let (_, &second) = digits + .next() + .ok_or("truncated Type1 PFA hexadecimal byte")?; + let low = hex_digit(second).ok_or("invalid hexadecimal digit in Type1 PFA eexec")?; + encrypted.push(high << 4 | low); + } + + let length = encrypted_eexec_length(&encrypted)?; + if encrypted[length..].iter().any(|&byte| byte != 0) { + return Err("nonzero Type1 PFA padding after eexec".into()); + } + encrypted.truncate(length); + // Keep the original clear trailer from the exact end of the cipher. + let trailer = tail + .iter() + .enumerate() + .filter(|(_, byte)| !byte.is_ascii_whitespace()) + .nth(length * 2 - 1) + .ok_or("truncated Type1 PFA eexec")? + .0 + + 1; + Ok((&bytes[..header_end], encrypted, &tail[trailer..])) +} + +fn hex_digit(byte: u8) -> Option { + match byte { + b'0'..=b'9' => Some(byte - b'0'), + b'a'..=b'f' => Some(byte - b'a' + 10), + b'A'..=b'F' => Some(byte - b'A' + 10), + _ => None, + } +} diff --git a/crates/texrra-tex-core/src/type1_outline.rs b/crates/texrra-tex-core/src/type1_outline.rs index 0fc2fb9..525690e 100644 --- a/crates/texrra-tex-core/src/type1_outline.rs +++ b/crates/texrra-tex-core/src/type1_outline.rs @@ -91,6 +91,27 @@ impl<'a> Tokens<'a> { .map_err(|_| "unsupported non-UTF8 Type1 private token")?; Ok(Some(token.into())) } + /// Locate a top-level file operator without interpreting the font. + pub(super) fn after_currentfile(&mut self, operator: &str) -> Result { + let mut previous = String::new(); + let mut depth = 0usize; + while let Some(token) = self.next()? { + if depth == 0 && previous == "currentfile" && token == operator { + return Ok(self.at); + } + match token.as_str() { + "{" => depth += 1, + "}" => depth = depth.saturating_sub(1), + "RD" | "-|" if let Ok(length) = previous.parse() => { + self.binary_data(length)?; + } + _ => {} + } + previous = token; + } + Err(format!("missing Type1 currentfile {operator}")) + } + pub(super) fn required(&mut self) -> Result { self.next()? .ok_or_else(|| "truncated Type1 private dictionary".into()) @@ -132,6 +153,24 @@ impl<'a> Tokens<'a> { Ok(bytes) } } +pub(super) fn encrypted_eexec_length(encrypted: &[u8]) -> Result { + const PREFIX: usize = 4; + let private = decrypt(encrypted, 55665, PREFIX)?; + let offset = Tokens::new(&private).after_currentfile("closefile")?; + // Include the line terminator when it was encrypted with the program. + let rest = &private[offset..]; + let horizontal = rest + .iter() + .take_while(|&&byte| matches!(byte, b' ' | b'\t')) + .count(); + let newline = match &rest[horizontal..] { + [b'\r', b'\n', ..] => 2, + [b'\r' | b'\n', ..] => 1, + _ => 0, + }; + Ok(PREFIX + offset + if newline != 0 { horizontal + newline } else { 0 }) +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub(crate) struct XdvDescriptor { metrics: [u64; 4], diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index de99b49..e09a159 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -819,6 +819,33 @@ 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) +### pdfTeX 映射的 Type 1 PFA 字体 + +原生从实际映射和版本化资源读取 PFA,解码十六进制 eexec,使用 +私有程序中真实的文件关闭指令定位加密段末尾。与 PFB 共用字体 +度量、字形、整嵌、子集和字体映射变换。导入 PDF 的 Type 1 字体替换 +也读取同一物理 PFA。定向回归验证了 PFA 整嵌的密文与原 CMR10 +PFB 逐字节相同,并复验同路径 PFB 更换后更新 PDF 与预览。 + +五组 pdfTeX 1.40.29 对照覆盖整嵌、子集、CRLF、斜切拉伸和导入。 +字体名、字符宽度、描述符数值、词框、文字和 144 DPI 灰度图一致。 +导入时两份字体字典共用同一个实际字体程序。原样保留的 PFA +明文尾部、嵌入程序段长、编码字典和 PDF 对象号仍与参考有差异。 +[原版的 PFA 解码](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/writet1.c#L266-L316) +[原版的整嵌写出](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/writet1.c#L875-L902) + +三页会话中修改 PFA FontMatrix 后重新执行,随后正文修改和恢复 +字体各复用 104 步。三次只发布第 2 页,PDF、测量页面、完整 SVG、 +来源映射及 aux 与同版本独立全量一致。无效十六进制使作业失败, +上一个已发布预览和 aux 保持可用。 + +回执在 target/p3-type1-pfa。receipt.json 的 SHA-256 为 +649e43e2ad8380fccefd9a5ad6af9644ff7498d57459da601bec41ec6972af84, +revision.log 为 1f1e8505039d24c4d540eeb2f3ca433f367be1247a893725a800a8fe21b4f1e0。 +保留实现前的同源失败。下一处实际缺口在 next-unembedded-type1。 +相同 ptmr8r.tfm、8r.enc 与 Times-Roman 设备字体映射,原版 +生成未嵌入字体的 PDF,本版明确报告映射未提供物理 Type 1 程序。 + ### pdfTeX 的 TrueType SFD 子字体 字体映射读取实际 SFD,按定义展开子字体条目。偏移、字符范围及 diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index 0d7f032..43a3cc8 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -1888,6 +1888,66 @@ fn relocated_format_binds_packed_and_new_glyphs_to_the_current_tfm() { fs::remove_dir_all(root).unwrap(); } +#[test] +fn mapped_type1_pfa_embeds_original_cipher_and_tracks_its_input() { + use std::io::Write; + use texrra_tex_core::{native_font::NativeFontProgram, render::DisplayItem, type1::Type1Font}; + + let root = directory("mapped-type1-pfa").canonicalize().unwrap(); + let outline = root.join("face.pfa"); + let font = Type1Font::from_pfb(include_bytes!("../assets/fonts/cmr10.pfb")).unwrap(); + let cipher = &font.program[font.length1..font.length1 + font.length2]; + let mut pfa = font.program[..font.length1].to_vec(); + for line in cipher.chunks(32) { + for byte in line { + write!(pfa, "{byte:02X}").unwrap(); + } + pfa.extend_from_slice(b"\r\n"); + } + pfa.extend_from_slice(&font.program[font.length1 + font.length2..]); + fs::write(&outline, &pfa).unwrap(); + fs::write(root.join("pdftex.map"), b"cmr10 CMR10 < { + assert!(matches!(paint.program, NativeFontProgram::Type1(_))); + assert!(!paint.glyph_paths[slot].is_empty()); + Some(*character) + } + _ => None, + }).collect(); + assert_eq!(glyphs, "ABC"); + assert!(first.resources.trace.reads.contains(&file_version(&outline).unwrap().unwrap())); + + let pdf = lopdf::Document::load_mem(first.pdf.as_deref().unwrap()).unwrap(); + let embedded = pdf.objects.values().filter_map(|object| object.as_stream().ok()) + .find(|stream| stream.dict.has(b"Length2")).unwrap(); + let length1 = embedded.dict.get(b"Length1").unwrap().as_i64().unwrap() as usize; + let length2 = embedded.dict.get(b"Length2").unwrap().as_i64().unwrap() as usize; + assert_eq!(&embedded.content[length1..length1 + length2], cipher); + + pfa[font.length1 + 6] = b'Z'; + fs::write(&outline, pfa).unwrap(); + let error = compiler.compile_detailed(job).err().unwrap().error.to_string(); + assert!(error.contains("face.pfa") && error.contains("hexadecimal"), "{error}"); + assert!(Arc::ptr_eq(&first, &compiler.latest().unwrap())); + fs::remove_dir_all(root).unwrap(); +} + #[test] fn mapped_opentype_cff_paints_reencoded_glyphs_and_embeds_the_original_table() { use texrra_tex_core::{native_font::NativeFontProgram, render::DisplayItem};