497 lines
17 KiB
Rust
497 lines
17 KiB
Rust
//! PDF font map entries, lookup bindings, and the lifetime of the default map.
|
|
use super::{MappedType1, NativeFont, verify_resource};
|
|
use crate::{
|
|
execution::{FontId, SourceProvider},
|
|
resources::{LoadedResource, ResourceKind, ResourceVersion},
|
|
type1::Type1Transform,
|
|
};
|
|
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>,
|
|
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
|
pub(super) subset: bool,
|
|
pub encoding: Option<String>,
|
|
postscript_name: bool,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
ps_name: Option<String>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub(super) descriptor_flags: Option<i32>,
|
|
#[serde(default, skip_serializing_if = "Type1Transform::is_identity")]
|
|
pub transform: Type1Transform,
|
|
}
|
|
|
|
type PostscriptKey = (String, i32, i32);
|
|
|
|
impl MapEntry {
|
|
fn postscript_key(&self) -> Option<PostscriptKey> {
|
|
Some((self.ps_name.clone()?, self.transform.slant, self.transform.extend))
|
|
}
|
|
fn is_scalable(&self) -> bool {
|
|
self.file.is_some() || self.postscript_name
|
|
}
|
|
|
|
pub(super) fn type1_file(&self, name: &str) -> Result<&str, String> {
|
|
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,
|
|
subset: false,
|
|
encoding: None,
|
|
postscript_name: false,
|
|
ps_name: None,
|
|
descriptor_flags: None,
|
|
transform: Type1Transform::default(),
|
|
};
|
|
for (index, (quote, value)) in fields.into_iter().skip(1).enumerate() {
|
|
if quote {
|
|
let mut previous = "";
|
|
for word in value.split_ascii_whitespace() {
|
|
let (operation, number) = if let Some(prefix) = word.strip_suffix("SlantFont") {
|
|
(&mut entry.transform.slant, prefix)
|
|
} else if let Some(prefix) = word.strip_suffix("ExtendFont") {
|
|
(&mut entry.transform.extend, prefix)
|
|
} else {
|
|
previous = word;
|
|
continue;
|
|
};
|
|
let number = if number.is_empty() { previous } else { number };
|
|
if let Ok(value) = number.parse::<f32>() {
|
|
if !value.is_finite() {
|
|
return Err(format!("invalid Type1 map transform for {name}"));
|
|
}
|
|
*operation = (value * 1000.).round() as i32;
|
|
}
|
|
previous = word;
|
|
}
|
|
} 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());
|
|
entry.subset = !value.starts_with("<<");
|
|
}
|
|
} else if index == 0 && !value.as_bytes()[0].is_ascii_digit() {
|
|
entry.postscript_name = true;
|
|
entry.ps_name = Some(value);
|
|
} else if index == usize::from(entry.postscript_name) {
|
|
entry.descriptor_flags = value.parse().ok();
|
|
}
|
|
}
|
|
if entry.transform.extend == 1000 {
|
|
entry.transform.extend = 0;
|
|
}
|
|
if entry.transform.slant.unsigned_abs() > 1000 || entry.transform.extend.unsigned_abs() > 2000 {
|
|
return Err(format!("Type1 map transform out of range for {name}"));
|
|
}
|
|
if !entry.transform.is_identity()
|
|
&& entry.file.as_deref().is_none_or(|file| {
|
|
let extension = Path::new(file)
|
|
.extension()
|
|
.and_then(|ext| ext.to_str())
|
|
.unwrap_or("");
|
|
["ttf", "ttc", "otf"]
|
|
.iter()
|
|
.any(|ext| extension.eq_ignore_ascii_case(ext))
|
|
})
|
|
{
|
|
return Err(format!(
|
|
"SlantFont/ExtendFont require an embedded Type1 program for {name}"
|
|
));
|
|
}
|
|
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>,
|
|
// PDF inclusion addresses the PostScript name independently of the TFM.
|
|
postscript_entries: Arc<BTreeMap<PostscriptKey, (String, Arc<MapEntry>)>>,
|
|
used_postscript: BTreeSet<PostscriptKey>,
|
|
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(())
|
|
}
|
|
|
|
pub(super) fn scalable_object(
|
|
&mut self, font: &NativeFont, files: &mut impl SourceProvider,
|
|
) -> Result<bool, String> {
|
|
if self.bindings.is_none() {
|
|
self.initialize(true, &font.resource.version.path, files)?;
|
|
}
|
|
self.bind(font.id, &font.name);
|
|
let entry = self.bindings.as_ref().expect("initialized font map").font(font)?;
|
|
Ok(selected_outline(font, entry.as_deref(), false)?.is_some())
|
|
}
|
|
|
|
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 let Some(entry) = &entry {
|
|
self.used_names.insert(name.into());
|
|
if let Some(key) = entry.postscript_key()
|
|
&& self.postscript_entries.get(&key).is_some_and(|(_, imported)| Arc::ptr_eq(imported, entry))
|
|
{
|
|
self.used_postscript.insert(key);
|
|
}
|
|
}
|
|
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 imported_type1_program(
|
|
&mut self, name: &str, from: &Path, files: &mut impl SourceProvider,
|
|
) -> Result<Option<MappedType1>, String> {
|
|
let (name, transform) = imported_postscript_name(name);
|
|
if self.bindings.is_none() {
|
|
self.initialize(true, from, files)?;
|
|
}
|
|
let key = (name.to_owned(), transform.slant, transform.extend);
|
|
let Some((tfm, entry)) = self.postscript_entries.get(&key) else { return Ok(None) };
|
|
let file = entry.type1_file(name)?;
|
|
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}"))?;
|
|
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());
|
|
}
|
|
self.used_postscript.insert(key);
|
|
Ok(Some(MappedType1 {
|
|
version: resource.version,
|
|
font: Arc::new(font),
|
|
flags: entry.descriptor_flags.unwrap_or(4),
|
|
subset: entry.subset,
|
|
}))
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|
|
let entry = Arc::new(entry);
|
|
if mode == MapMode::Delete {
|
|
Arc::make_mut(&mut self.entries).remove(&name);
|
|
} else {
|
|
Arc::make_mut(&mut self.entries).insert(name.clone(), entry.clone());
|
|
}
|
|
let Some(key) = entry.postscript_key() else { return };
|
|
if self.postscript_entries.contains_key(&key) {
|
|
if mode == MapMode::Add || self.used_postscript.contains(&key) {
|
|
return;
|
|
}
|
|
Arc::make_mut(&mut self.postscript_entries).remove(&key);
|
|
}
|
|
if mode != MapMode::Delete && entry.type1_file(&name).is_ok() {
|
|
Arc::make_mut(&mut self.postscript_entries).insert(key, (name, entry));
|
|
}
|
|
}
|
|
}
|
|
|
|
fn imported_postscript_name(name: &str) -> (&str, Type1Transform) {
|
|
let mut name = if name.as_bytes().get(6) == Some(&b'+')
|
|
&& name.as_bytes()[..6].iter().all(u8::is_ascii_uppercase)
|
|
{
|
|
&name[7..]
|
|
} else {
|
|
name
|
|
};
|
|
let mut transform = Type1Transform::default();
|
|
if let Some((base, value)) = name.rsplit_once("-Extend_")
|
|
&& let Ok(value) = value.parse()
|
|
{
|
|
name = base;
|
|
transform.extend = value;
|
|
}
|
|
if let Some((base, value)) = name.rsplit_once("-Slant_")
|
|
&& let Ok(value) = value.parse()
|
|
{
|
|
name = base;
|
|
transform.slant = value;
|
|
}
|
|
(name, transform)
|
|
}
|
|
|
|
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,
|
|
ps_name: None,
|
|
descriptor_flags: None,
|
|
transform: Type1Transform::default(),
|
|
subset: false,
|
|
}
|
|
}
|