Read mapped Type 1 fonts from PFA programs
This commit is contained in:
1 parent
868814288c
commit
60d67bbb7b
7 files changed
+211
-18
No files matched your search
@@ -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<Self, String> {
|
||||
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<Self, String> {
|
||||
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<Arc<DecodedType1>, 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();
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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<Vec<String>, 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<Self, String> {
|
||||
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<Self> {
|
||||
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<u8>, encrypted: &[u8], trailer: &[u8]) -> Option<Self> {
|
||||
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,
|
||||
|
||||
@@ -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>, &[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<u8> {
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -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<usize, String> {
|
||||
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<String, String> {
|
||||
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<usize, String> {
|
||||
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],
|
||||
|
||||
Reference in new issue
Block a user