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
@@ -0,0 +1,365 @@
|
||||
//! PDF font map entries, lookup bindings, and the lifetime of the default map.
|
||||
use super::{NativeFont, verify_resource};
|
||||
use crate::{
|
||||
execution::{FontId, SourceProvider},
|
||||
resources::{LoadedResource, ResourceKind, ResourceVersion},
|
||||
};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub(super) struct MapEntry {
|
||||
pub from: PathBuf,
|
||||
pub version: Option<ResourceVersion>,
|
||||
file: Option<String>,
|
||||
pub encoding: Option<String>,
|
||||
postscript_name: bool,
|
||||
unsupported_transform: Option<String>,
|
||||
}
|
||||
|
||||
impl MapEntry {
|
||||
fn is_scalable(&self) -> bool {
|
||||
self.file.is_some() || self.postscript_name
|
||||
}
|
||||
|
||||
pub(super) 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)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_map_line(
|
||||
line: &str,
|
||||
from: &Path,
|
||||
version: Option<&ResourceVersion>,
|
||||
) -> Result<Option<(String, MapEntry)>, String> {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with(['%', '#', ';', '*']) {
|
||||
return Ok(None);
|
||||
}
|
||||
let name = line.split_ascii_whitespace().next().unwrap().to_owned();
|
||||
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 {
|
||||
from: from.to_path_buf(),
|
||||
version: version.cloned(),
|
||||
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 && !value.as_bytes()[0].is_ascii_digit() {
|
||||
entry.postscript_name = true;
|
||||
}
|
||||
}
|
||||
Ok(Some((name, entry)))
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PdfFontBindings {
|
||||
fonts: BTreeMap<FontId, Option<Arc<MapEntry>>>,
|
||||
pub(super) default_map: Option<ResourceVersion>,
|
||||
}
|
||||
|
||||
impl PdfFontBindings {
|
||||
pub(super) fn font(&self, font: &NativeFont) -> Result<Option<Arc<MapEntry>>, String> {
|
||||
self.fonts
|
||||
.get(&font.id)
|
||||
.cloned()
|
||||
.ok_or_else(|| format!("PDF font {} has no captured map binding", font.name))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum MapMode {
|
||||
Add,
|
||||
Replace,
|
||||
Delete,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct JobFontMap {
|
||||
// Ordinary unevaluated pages can retain raw lists for hosts that only
|
||||
// need TeX layout. A map command or actual autoexpanded glyph activates
|
||||
// the table and materializes all earlier first-use bindings in order.
|
||||
first_font_source: Option<PathBuf>,
|
||||
pending_fonts: Vec<(FontId, String)>,
|
||||
pending_ids: BTreeSet<FontId>,
|
||||
entries: Arc<BTreeMap<String, Arc<MapEntry>>>,
|
||||
used_names: BTreeSet<String>,
|
||||
bindings: Option<Arc<PdfFontBindings>>,
|
||||
}
|
||||
|
||||
impl JobFontMap {
|
||||
pub(super) fn bindings(&self) -> Option<Arc<PdfFontBindings>> {
|
||||
self.bindings.clone()
|
||||
}
|
||||
|
||||
pub(super) fn observe(
|
||||
&mut self,
|
||||
font: &NativeFont,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<(), String> {
|
||||
let from = &font.resource.version.path;
|
||||
self.first_font_source.get_or_insert_with(|| from.clone());
|
||||
if self.bindings.is_none() && font.expansion == 0 {
|
||||
if self.pending_ids.insert(font.id) {
|
||||
self.pending_fonts.push((font.id, font.name.clone()));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if self.bindings.is_none() {
|
||||
self.initialize(true, from, files)?;
|
||||
}
|
||||
self.bind(font.id, &font.name);
|
||||
let entry = self.bindings.as_ref().unwrap().font(font)?;
|
||||
selected_outline(font, entry.as_deref(), font.expansion != 0)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn bind(&mut self, id: FontId, name: &str) {
|
||||
let bindings = self.bindings.as_mut().unwrap();
|
||||
if bindings.fonts.contains_key(&id) {
|
||||
return;
|
||||
}
|
||||
let entry = self.entries.get(name).cloned();
|
||||
if entry.is_some() {
|
||||
self.used_names.insert(name.into());
|
||||
}
|
||||
Arc::make_mut(bindings).fonts.insert(id, entry);
|
||||
}
|
||||
|
||||
fn initialize(
|
||||
&mut self,
|
||||
default_pending: bool,
|
||||
from: &Path,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<(), String> {
|
||||
let mut bindings = PdfFontBindings::default();
|
||||
if default_pending || self.first_font_source.is_some() {
|
||||
let from = self.first_font_source.as_deref().unwrap_or(from);
|
||||
if let Some(read) = load_map(files, "pdftex.map", from)? {
|
||||
let mut ignored = Vec::new();
|
||||
self.apply_file(&read, MapMode::Add, true, &mut ignored)?;
|
||||
bindings.default_map = Some(read.version);
|
||||
}
|
||||
}
|
||||
self.bindings = Some(Arc::new(bindings));
|
||||
for (id, name) in std::mem::take(&mut self.pending_fonts) {
|
||||
self.bind(id, &name);
|
||||
}
|
||||
self.pending_ids.clear();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn command(
|
||||
&mut self,
|
||||
input: &[u8],
|
||||
map_file: bool,
|
||||
from: &Path,
|
||||
suppress_duplicates: bool,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let text =
|
||||
std::str::from_utf8(input).map_err(|_| "PDF font map command is not UTF-8/ASCII")?;
|
||||
let text = text.trim_start_matches(' ');
|
||||
let (sign, item) = match text.as_bytes().first() {
|
||||
Some(b'+' | b'=' | b'-') => (text.as_bytes().first().copied(), &text[1..]),
|
||||
_ => (None, text),
|
||||
};
|
||||
let mode = match sign {
|
||||
Some(b'=') => MapMode::Replace,
|
||||
Some(b'-') => MapMode::Delete,
|
||||
_ => MapMode::Add,
|
||||
};
|
||||
if self.bindings.is_none() {
|
||||
self.initialize(sign.is_some(), from, files)?;
|
||||
}
|
||||
let item = item.trim_start_matches(' ');
|
||||
let mut warnings = Vec::new();
|
||||
if map_file {
|
||||
if let Some(name) = item.split_ascii_whitespace().next() {
|
||||
let name = if name.ends_with(".map") {
|
||||
name.to_owned()
|
||||
} else {
|
||||
format!("{name}.map")
|
||||
};
|
||||
match load_map(files, &name, from)? {
|
||||
Some(read) => {
|
||||
self.apply_file(&read, mode, suppress_duplicates, &mut warnings)?
|
||||
}
|
||||
None => warnings.push(format!("cannot open font map file {name}")),
|
||||
}
|
||||
}
|
||||
} else {
|
||||
self.apply_line(item, from, None, mode, suppress_duplicates, &mut warnings);
|
||||
}
|
||||
Ok(warnings)
|
||||
}
|
||||
|
||||
fn apply_file(
|
||||
&mut self,
|
||||
read: &LoadedResource,
|
||||
mode: MapMode,
|
||||
suppress_duplicates: bool,
|
||||
warnings: &mut Vec<String>,
|
||||
) -> Result<(), String> {
|
||||
let text = std::str::from_utf8(&read.data).map_err(|_| "font map is not UTF-8/ASCII")?;
|
||||
for line in text.lines() {
|
||||
self.apply_line(
|
||||
line,
|
||||
&read.version.path,
|
||||
Some(&read.version),
|
||||
mode,
|
||||
suppress_duplicates,
|
||||
warnings,
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_line(
|
||||
&mut self,
|
||||
line: &str,
|
||||
from: &Path,
|
||||
version: Option<&ResourceVersion>,
|
||||
mode: MapMode,
|
||||
suppress_duplicates: bool,
|
||||
warnings: &mut Vec<String>,
|
||||
) {
|
||||
let (name, entry) = match parse_map_line(line, from, version) {
|
||||
Ok(Some(entry)) => entry,
|
||||
Ok(None) => return,
|
||||
Err(error) => {
|
||||
warnings.push(error);
|
||||
return;
|
||||
}
|
||||
};
|
||||
if self.entries.contains_key(&name) {
|
||||
if mode == MapMode::Add {
|
||||
if !suppress_duplicates {
|
||||
warnings.push(format!(
|
||||
"fontmap entry for '{name}' already exists, duplicates ignored"
|
||||
));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.used_names.contains(&name) {
|
||||
warnings.push(format!(
|
||||
"fontmap entry for '{name}' has been used, replace/delete not allowed"
|
||||
));
|
||||
return;
|
||||
}
|
||||
}
|
||||
if mode == MapMode::Delete {
|
||||
Arc::make_mut(&mut self.entries).remove(&name);
|
||||
} else {
|
||||
Arc::make_mut(&mut self.entries).insert(name, Arc::new(entry));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn load_map(
|
||||
files: &mut impl SourceProvider,
|
||||
name: &str,
|
||||
from: &Path,
|
||||
) -> Result<Option<LoadedResource>, String> {
|
||||
files
|
||||
.optional_font_map(name, &from.to_string_lossy())?
|
||||
.map(|map| verify_resource(map, ResourceKind::Map, name))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub(super) fn find_map_entry(map: &LoadedResource, name: &str) -> Result<Option<MapEntry>, String> {
|
||||
let text = std::str::from_utf8(&map.data).map_err(|_| "font map is not UTF-8/ASCII")?;
|
||||
let Some(line) = text
|
||||
.lines()
|
||||
.find(|line| line.split_ascii_whitespace().next() == Some(name))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(parse_map_line(line, &map.version.path, Some(&map.version))?.map(|(_, entry)| entry))
|
||||
}
|
||||
|
||||
pub(super) fn selected_outline<'a>(
|
||||
font: &NativeFont,
|
||||
entry: Option<&'a MapEntry>,
|
||||
auto_expanded: bool,
|
||||
) -> Result<Option<&'a MapEntry>, String> {
|
||||
let outline = entry.filter(|entry| entry.is_scalable());
|
||||
if auto_expanded && outline.is_none() && !font.pdf_space_font {
|
||||
return Err("font expansion: auto expansion is only possible with scalable fonts".into());
|
||||
}
|
||||
Ok(outline)
|
||||
}
|
||||
|
||||
pub(super) fn dedicated_space_map(font: &NativeFont) -> MapEntry {
|
||||
MapEntry {
|
||||
from: font.resource.version.path.clone(),
|
||||
version: None,
|
||||
file: Some("pdftexspace.pfb".into()),
|
||||
encoding: None,
|
||||
postscript_name: false,
|
||||
unsupported_transform: None,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user