Apply job-local PDF font maps at execution and shipout
This commit is contained in:
1 parent
9527d3bbec
commit
28dfba5a5e
15 files changed
+583
-187
No files matched your search
@@ -12,7 +12,10 @@ use std::{
|
||||
collections::{BTreeMap, VecDeque},
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
mod map;
|
||||
mod virtual_paint;
|
||||
pub use map::PdfFontBindings;
|
||||
use map::{dedicated_space_map, find_map_entry, load_map, selected_outline};
|
||||
pub(crate) use virtual_paint::{JobVirtualFonts, VirtualGlyphs, VirtualPaintState};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
@@ -23,13 +26,15 @@ pub struct NativeFontPaint {
|
||||
pub bbox: [i32; 4],
|
||||
pub stem_v: i32,
|
||||
pub resources: Vec<crate::resources::ResourceVersion>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
program_index: Option<usize>,
|
||||
}
|
||||
|
||||
impl NativeFontPaint {
|
||||
pub(crate) fn has_pdf_space(&self, font: &NativeFont) -> bool {
|
||||
// pdfTeX requires the space name in an actual map re-encoding.
|
||||
matches!(self.program, NativeFontProgram::Type1(_))
|
||||
&& self.resources.len() == 3
|
||||
&& self.resources.len() == self.program_index.unwrap_or(1) + 2
|
||||
&& self.encoding[32] == "space"
|
||||
&& font.metrics().width(' ') > 65_782
|
||||
}
|
||||
@@ -37,7 +42,7 @@ impl NativeFontPaint {
|
||||
match &self.program {
|
||||
NativeFontProgram::Type1(_) => {
|
||||
// The physical font follows the map, before any encoding resource.
|
||||
self.resources.get(1)
|
||||
self.resources.get(self.program_index.unwrap_or(1))
|
||||
}
|
||||
NativeFontProgram::Pk(_) => None,
|
||||
}
|
||||
@@ -128,135 +133,6 @@ impl NativeFont {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct MapEntry {
|
||||
file: Option<String>,
|
||||
encoding: Option<String>,
|
||||
postscript_name: bool,
|
||||
unsupported_transform: Option<String>,
|
||||
}
|
||||
|
||||
impl MapEntry {
|
||||
fn is_scalable(&self) -> bool {
|
||||
self.file.is_some() || self.postscript_name
|
||||
}
|
||||
|
||||
fn type1_file(&self, name: &str) -> Result<&str, String> {
|
||||
if let Some(value) = &self.unsupported_transform {
|
||||
return Err(format!("native font map transform is not implemented: {value}"));
|
||||
}
|
||||
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") {
|
||||
return Err(format!("native font program format is not implemented: {file}"));
|
||||
}
|
||||
Ok(file)
|
||||
}
|
||||
}
|
||||
|
||||
/// Version and lookup context of the PDF map read during shipout.
|
||||
#[doc(hidden)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PdfFontMapInput {
|
||||
pub(crate) from: std::path::PathBuf,
|
||||
pub(crate) version: ResourceVersion,
|
||||
}
|
||||
fn map_entry(data: &[u8], name: &str) -> Result<Option<MapEntry>, String> {
|
||||
let text = std::str::from_utf8(data).map_err(|_| "font map is not UTF-8/ASCII")?;
|
||||
for line in text.lines() {
|
||||
if line.split_whitespace().next() != Some(name) {
|
||||
continue;
|
||||
}
|
||||
let mut fields = Vec::new();
|
||||
let mut current = String::new();
|
||||
let mut quoted = false;
|
||||
for c in line.chars() {
|
||||
match c {
|
||||
'%' if !quoted => break,
|
||||
'"' => {
|
||||
if quoted {
|
||||
fields.push((true, std::mem::take(&mut current)));
|
||||
} else if !current.is_empty() {
|
||||
fields.push((false, std::mem::take(&mut current)));
|
||||
}
|
||||
quoted = !quoted;
|
||||
}
|
||||
c if c.is_ascii_whitespace() && !quoted => {
|
||||
if !current.is_empty() {
|
||||
fields.push((false, std::mem::take(&mut current)));
|
||||
}
|
||||
}
|
||||
_ => current.push(c),
|
||||
}
|
||||
}
|
||||
if quoted {
|
||||
return Err(format!("unterminated font map operation for {name}"));
|
||||
}
|
||||
if !current.is_empty() {
|
||||
fields.push((false, current));
|
||||
}
|
||||
let mut entry = MapEntry {
|
||||
file: None,
|
||||
encoding: None,
|
||||
postscript_name: false,
|
||||
unsupported_transform: None,
|
||||
};
|
||||
for (index, (quote, value)) in fields.into_iter().skip(1).enumerate() {
|
||||
if quote {
|
||||
let words: Vec<_> = value.split_whitespace().collect();
|
||||
// pdfTeX ignores PostScript names and ReEncodeFont words;
|
||||
// the actual .enc file supplies the encoding vector.
|
||||
if words
|
||||
.iter()
|
||||
.any(|w| matches!(*w, "SlantFont" | "ExtendFont"))
|
||||
{
|
||||
entry.unsupported_transform.get_or_insert(value);
|
||||
}
|
||||
} else if value.starts_with('<') {
|
||||
let path = value.trim_start_matches('<').trim_start_matches('[');
|
||||
if path.ends_with(".enc") {
|
||||
entry.encoding = Some(path.to_owned());
|
||||
} else if !path.is_empty() {
|
||||
entry.file = Some(path.to_owned());
|
||||
}
|
||||
} else if index == 0 {
|
||||
entry.postscript_name = true;
|
||||
}
|
||||
}
|
||||
return Ok(Some(entry));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
fn mapped_font(
|
||||
map: &LoadedResource,
|
||||
font: &NativeFont,
|
||||
auto_expanded: bool,
|
||||
) -> Result<Option<MapEntry>, String> {
|
||||
let entry = if font.pdf_space_font && font.name == "pdftexspace" {
|
||||
// pdfTeX installs the dedicated spacing font on first use.
|
||||
Some(MapEntry {
|
||||
file: Some("pdftexspace.pfb".into()),
|
||||
encoding: None,
|
||||
postscript_name: false,
|
||||
unsupported_transform: None,
|
||||
})
|
||||
} else {
|
||||
map_entry(&map.data, &font.name)?.filter(MapEntry::is_scalable)
|
||||
};
|
||||
if auto_expanded && entry.is_none() {
|
||||
return Err("font expansion: auto expansion is only possible with scalable fonts".into());
|
||||
}
|
||||
Ok(entry)
|
||||
}
|
||||
|
||||
fn load_font_map(
|
||||
files: &mut impl crate::execution::SourceProvider,
|
||||
from: &std::path::Path,
|
||||
) -> Result<LoadedResource, String> {
|
||||
actual_resource(files, crate::resources::ResourceKind::Map, "pdftex.map", &from.to_string_lossy())
|
||||
}
|
||||
|
||||
fn encoding_vector(data: &[u8]) -> Result<Vec<String>, String> {
|
||||
let text = std::str::from_utf8(data).map_err(|_| "font encoding is not UTF-8/ASCII")?;
|
||||
let text = text
|
||||
@@ -418,6 +294,7 @@ impl NativeFontCache {
|
||||
let mut page = DisplayList {
|
||||
units: DisplayUnits::TeX,
|
||||
pdf: device,
|
||||
pdf_font_bindings: Some(Arc::new(PdfFontBindings::default())),
|
||||
items: vec![DisplayItem::NativeGlyph {
|
||||
x: 0,
|
||||
y: 0,
|
||||
@@ -471,12 +348,14 @@ fn resolve_physical_fonts(
|
||||
let Some((first, _, _)) = used.values().next() else {
|
||||
return Ok(());
|
||||
};
|
||||
let captured_map = pages.iter().find_map(|page| page.pdf_font_map.as_deref());
|
||||
let from = captured_map.map_or(first.resource.version.path.as_path(), |map| map.from.as_path());
|
||||
let map = load_font_map(files, from)?;
|
||||
if captured_map.is_some_and(|captured| captured.version != map.version) {
|
||||
return Err("PDF font map changed after shipout".into());
|
||||
}
|
||||
let captured = pages.iter().rev().find_map(|page| page.pdf_font_bindings.as_deref());
|
||||
let default_map = if captured.is_none() {
|
||||
load_map(files, "pdftex.map", &first.resource.version.path)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let default_version = captured.and_then(|bindings| bindings.default_map.as_ref())
|
||||
.or_else(|| default_map.as_ref().map(|map| &map.version));
|
||||
let mut resolved = BTreeMap::new();
|
||||
let mut pk_resolved = BTreeMap::new();
|
||||
let device = pages
|
||||
@@ -485,7 +364,16 @@ fn resolve_physical_fonts(
|
||||
.map(|p| p.file.clone());
|
||||
let mut cache: BTreeMap<_, (NativeFontPaint, Arc<DecodedType1>)> = BTreeMap::new();
|
||||
for (id, (font, slots, expanded)) in used {
|
||||
let Some(entry) = mapped_font(&map, &font, expanded)? else {
|
||||
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 let Some(map) = &default_map {
|
||||
find_map_entry(map, &font.name)?.map(Arc::new)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let Some(outline) = selected_outline(&font, entry.as_deref(), expanded)? else {
|
||||
let (resolution, digits) = if let Some(device) = &device {
|
||||
(device.pk_resolution, device.decimal_digits)
|
||||
} else {
|
||||
@@ -544,29 +432,36 @@ fn resolve_physical_fonts(
|
||||
glyph_paths,
|
||||
bbox: bbox.unwrap(),
|
||||
stem_v: 0,
|
||||
resources: vec![map.version.clone(), resource.version],
|
||||
resources: entry.as_ref().and_then(|entry| entry.version.as_ref())
|
||||
.or(default_version).cloned().into_iter()
|
||||
.chain(std::iter::once(resource.version)).collect(),
|
||||
program_index: None,
|
||||
}),
|
||||
);
|
||||
continue;
|
||||
};
|
||||
let file = entry.type1_file(&font.name)?;
|
||||
let key = (file.to_owned(), entry.encoding.clone());
|
||||
let file = outline.type1_file(&font.name)?;
|
||||
let version = outline.version.as_ref();
|
||||
let key = (
|
||||
outline.from.clone(),
|
||||
version.map(|version| version.sha256.clone()),
|
||||
file.to_owned(),
|
||||
outline.encoding.clone(),
|
||||
);
|
||||
if !cache.contains_key(&key) {
|
||||
let resource = actual_resource(
|
||||
files,
|
||||
ResourceKind::Type1,
|
||||
file,
|
||||
&map.version.path.to_string_lossy(),
|
||||
)?;
|
||||
let from = outline.from.to_string_lossy();
|
||||
let resource = actual_resource(files, ResourceKind::Type1, file, &from)?;
|
||||
let decoded = font_cache.type1(&resource)?;
|
||||
let program = &decoded.program;
|
||||
let mut resources = vec![map.version.clone(), resource.version];
|
||||
let encoding = if let Some(name) = entry.encoding {
|
||||
let mut resources: Vec<_> = version.cloned().into_iter().collect();
|
||||
let program_index = Some(resources.len());
|
||||
resources.push(resource.version);
|
||||
let encoding = if let Some(name) = &outline.encoding {
|
||||
let enc = actual_resource(
|
||||
files,
|
||||
ResourceKind::Encoding,
|
||||
&name,
|
||||
&map.version.path.to_string_lossy(),
|
||||
name,
|
||||
&from,
|
||||
)?;
|
||||
let encoding = encoding_vector(&enc.data)?;
|
||||
resources.push(enc.version);
|
||||
@@ -586,6 +481,7 @@ fn resolve_physical_fonts(
|
||||
bbox: decoded.bbox,
|
||||
stem_v: decoded.stem_v,
|
||||
resources,
|
||||
program_index,
|
||||
},
|
||||
decoded,
|
||||
),
|
||||
|
||||
Reference in new issue
Block a user