591 lines
21 KiB
Rust
591 lines
21 KiB
Rust
//! Immutable font identity retained by native character lists and geometry.
|
|
//! Font parameters remain in the job's catalog; painting never reselects a
|
|
//! master from a font name, Unicode label, or the current execution state.
|
|
use crate::{
|
|
execution::{FontId, FontResource},
|
|
resources::{LoadedResource, ResourceVersion},
|
|
tfm::TfmMetrics,
|
|
type1::Type1Font,
|
|
type1_outline::Type1Outlines,
|
|
};
|
|
use std::{
|
|
collections::{BTreeMap, VecDeque},
|
|
sync::{Arc, Mutex},
|
|
};
|
|
mod virtual_paint;
|
|
pub(crate) use virtual_paint::{JobVirtualFonts, VirtualGlyphs, VirtualPaintState};
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub struct NativeFontPaint {
|
|
pub program: NativeFontProgram,
|
|
pub encoding: Vec<String>,
|
|
pub glyph_paths: BTreeMap<u8, String>,
|
|
pub bbox: [i32; 4],
|
|
pub stem_v: i32,
|
|
pub resources: Vec<crate::resources::ResourceVersion>,
|
|
}
|
|
|
|
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.encoding[32] == "space"
|
|
&& font.metrics().width(' ') > 65_782
|
|
}
|
|
pub(crate) fn type1_resource(&self) -> Option<&crate::resources::ResourceVersion> {
|
|
match &self.program {
|
|
NativeFontProgram::Type1(_) => {
|
|
// The physical font follows the map, before any encoding resource.
|
|
self.resources.get(1)
|
|
}
|
|
NativeFontProgram::Pk(_) => None,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub enum NativeFontProgram {
|
|
Type1(crate::type1::Type1Font),
|
|
Pk(crate::pk_font::PkFontProgram),
|
|
}
|
|
impl NativeFontProgram {
|
|
pub fn name(&self) -> &str {
|
|
match self {
|
|
Self::Type1(p) => &p.name,
|
|
Self::Pk(p) => &p.name,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub struct NativeFont {
|
|
pub id: FontId,
|
|
pub name: String,
|
|
pub metrics: Arc<TfmMetrics>,
|
|
pub resource: FontResource,
|
|
/// Horizontal font adjustment in thousandths. The backing TFM and
|
|
/// outline program are the original font at the original point size.
|
|
#[serde(default, skip_serializing_if = "unexpanded")]
|
|
pub expansion: i32,
|
|
/// Metrics from a TFM loaded before it joined an automatic expansion
|
|
/// family. The device embeds the base program but moves by these widths.
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub(crate) layout_metrics: Option<Arc<TfmMetrics>>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub letter_spacing: Option<LetterspaceProgram>,
|
|
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
|
pub(crate) pdf_space_font: bool,
|
|
}
|
|
|
|
/// Virtual character packets use the selected font and an encoded right move.
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub struct LetterspaceProgram {
|
|
pub base: Arc<NativeFont>,
|
|
pub right: i32,
|
|
}
|
|
pub(crate) fn unexpanded(amount: &i32) -> bool {
|
|
*amount == 0
|
|
}
|
|
|
|
impl NativeFont {
|
|
pub fn metrics(&self) -> &TfmMetrics {
|
|
&self.metrics
|
|
}
|
|
pub fn size_sp(&self) -> i64 {
|
|
self.metrics.size_sp()
|
|
}
|
|
pub(crate) fn layout_metrics(&self) -> &TfmMetrics {
|
|
self.layout_metrics.as_deref().unwrap_or(&self.metrics)
|
|
}
|
|
pub fn advance(&self, slot: u8) -> i64 {
|
|
let width = self.layout_metrics().width(char::from(slot));
|
|
if self.layout_metrics.is_some() {
|
|
width
|
|
} else {
|
|
self.horizontal(width)
|
|
}
|
|
}
|
|
pub(crate) fn horizontal(&self, value: i64) -> i64 {
|
|
if self.expansion == 0 {
|
|
value
|
|
} else {
|
|
crate::pdf_device::magnify(value, 1000 + self.expansion)
|
|
}
|
|
}
|
|
pub(crate) fn same_base(&self, other: &Self) -> bool {
|
|
std::ptr::eq(self, other)
|
|
|| (self.id == other.id
|
|
&& self.name == other.name
|
|
&& (Arc::ptr_eq(&self.metrics, &other.metrics) || self.metrics == other.metrics)
|
|
&& self.letter_spacing == other.letter_spacing
|
|
&& self.resource.version == other.resource.version
|
|
&& (Arc::ptr_eq(&self.resource.data, &other.resource.data)
|
|
|| self.resource.data == other.resource.data))
|
|
}
|
|
pub fn has_slot(&self, slot: u8) -> bool {
|
|
self.metrics.has_slot(slot)
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
struct MapEntry {
|
|
file: String,
|
|
encoding: Option<String>,
|
|
}
|
|
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 file, mut encoding) = (None, None);
|
|
for (quote, value) in fields.into_iter().skip(1) {
|
|
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"))
|
|
{
|
|
return Err(format!(
|
|
"native font map transform is not implemented: {value}"
|
|
));
|
|
}
|
|
} else if value.starts_with('<') {
|
|
let path = value.trim_start_matches('<').trim_start_matches('[');
|
|
if path.ends_with(".enc") {
|
|
encoding = Some(path.to_owned());
|
|
} else if path.ends_with(".pfb") {
|
|
file = Some(path.to_owned());
|
|
} else {
|
|
return Err(format!(
|
|
"native font program format is not implemented: {path}"
|
|
));
|
|
}
|
|
}
|
|
}
|
|
return Ok(Some(MapEntry { file: file.ok_or_else(||format!("font map {name} has no embedded Type1 program; mapped device fonts require their actual support"))?, encoding }));
|
|
}
|
|
Ok(None)
|
|
}
|
|
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
|
|
.lines()
|
|
.map(|s| s.split('%').next().unwrap_or(""))
|
|
.collect::<Vec<_>>()
|
|
.join("\n");
|
|
let vector = text
|
|
.split_once('[')
|
|
.ok_or("missing encoding vector")?
|
|
.1
|
|
.split_once(']')
|
|
.ok_or("unterminated encoding vector")?
|
|
.0;
|
|
let names: Result<Vec<_>, _> = vector
|
|
.split_whitespace()
|
|
.map(|n| {
|
|
n.strip_prefix('/')
|
|
.map(str::to_owned)
|
|
.ok_or("invalid encoding glyph name")
|
|
})
|
|
.collect();
|
|
let names = names?;
|
|
if names.len() != 256 {
|
|
return Err("encoding vector must contain exactly 256 slots".into());
|
|
}
|
|
Ok(names)
|
|
}
|
|
fn actual_resource(
|
|
files: &mut impl crate::execution::SourceProvider,
|
|
kind: crate::resources::ResourceKind,
|
|
name: &str,
|
|
from: &str,
|
|
) -> Result<crate::resources::LoadedResource, String> {
|
|
let resource = files.resource(kind, name, from)?;
|
|
verify_resource(resource, kind, name)
|
|
}
|
|
fn verify_resource(
|
|
resource: crate::resources::LoadedResource,
|
|
kind: crate::resources::ResourceKind,
|
|
name: &str,
|
|
) -> Result<crate::resources::LoadedResource, String> {
|
|
use sha2::{Digest, Sha256};
|
|
if resource.version.bytes != resource.data.len() as u64
|
|
|| resource.version.sha256 != format!("{:x}", Sha256::digest(&resource.data))
|
|
{
|
|
return Err(format!(
|
|
"{kind:?} resource version does not match actual bytes: {name}"
|
|
));
|
|
}
|
|
Ok(resource)
|
|
}
|
|
|
|
const MAX_TYPE1_PROGRAMS: usize = 16;
|
|
const MAX_CACHED_PFB_BYTES: usize = 256 * 1024;
|
|
|
|
/// Decoded Type 1 programs shared across revisions in one compiler.
|
|
#[derive(Default)]
|
|
pub struct NativeFontCache {
|
|
type1: Mutex<VecDeque<(ResourceVersion, Arc<DecodedType1>)>>,
|
|
}
|
|
|
|
struct DecodedType1 {
|
|
program: Type1Font,
|
|
outlines: Type1Outlines,
|
|
bbox: [i32; 4],
|
|
stem_v: i32,
|
|
}
|
|
|
|
impl DecodedType1 {
|
|
fn from_pfb(resource: &LoadedResource) -> Result<Self, String> {
|
|
let program = Type1Font::from_pfb(&resource.data).ok_or_else(|| {
|
|
format!(
|
|
"invalid Type1 PFB program: {}",
|
|
resource.version.path.display()
|
|
)
|
|
})?;
|
|
let outlines = Type1Outlines::parse(&program)?;
|
|
let bbox = outlines.normalized_bbox(program.bbox);
|
|
let stem_v = outlines.stem_v();
|
|
Ok(Self {
|
|
program,
|
|
outlines,
|
|
bbox,
|
|
stem_v,
|
|
})
|
|
}
|
|
}
|
|
|
|
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) -> Result<Arc<DecodedType1>, String> {
|
|
if resource.data.len() > MAX_CACHED_PFB_BYTES {
|
|
return DecodedType1::from_pfb(resource).map(Arc::new);
|
|
}
|
|
let mut entries = self.type1.lock().expect("native Type 1 cache poisoned");
|
|
if let Some(index) = entries
|
|
.iter()
|
|
.position(|(version, _)| *version == resource.version)
|
|
{
|
|
let entry = entries.remove(index).expect("cached Type 1 index exists");
|
|
let decoded = entry.1.clone();
|
|
entries.push_back(entry);
|
|
return Ok(decoded);
|
|
}
|
|
let decoded = Arc::new(DecodedType1::from_pfb(resource)?);
|
|
if entries.len() == MAX_TYPE1_PROGRAMS {
|
|
entries.pop_front();
|
|
}
|
|
entries.push_back((resource.version.clone(), decoded.clone()));
|
|
Ok(decoded)
|
|
}
|
|
|
|
/// Resolve the current revision's fonts and record its actual reads.
|
|
pub fn resolve(
|
|
&self,
|
|
pages: &mut [crate::render::DisplayList],
|
|
files: &mut impl crate::execution::SourceProvider,
|
|
) -> Result<(), String> {
|
|
let mut virtuals = virtual_paint::VirtualPaintState::default();
|
|
let expanded = virtual_paint::expand_pages(&mut virtuals, pages, files)?;
|
|
if expanded.is_none() && !pages.iter().any(|page| page.pdf_text_spaces.is_some()) {
|
|
return resolve_physical_fonts(pages, files, self);
|
|
}
|
|
let mut resolved = expanded.unwrap_or_else(|| pages.to_vec());
|
|
resolve_physical_fonts(&mut resolved, files, self)?;
|
|
crate::pdf::prepare_text_spaces(&mut resolved, |font, device| {
|
|
self.space_font(font, device, files)
|
|
})?;
|
|
for (original, resolved) in pages.iter_mut().zip(resolved) {
|
|
*original = resolved;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub(crate) fn resolve_space_probe(
|
|
&self,
|
|
pages: &mut [crate::render::DisplayList],
|
|
virtuals: &mut VirtualPaintState,
|
|
files: &mut impl crate::execution::SourceProvider,
|
|
) -> Result<(), String> {
|
|
if let Some(expanded) = virtual_paint::expand_pages(virtuals, pages, files)? {
|
|
for (original, expanded) in pages.iter_mut().zip(expanded) {
|
|
*original = expanded;
|
|
}
|
|
}
|
|
resolve_physical_fonts(pages, files, self)
|
|
}
|
|
|
|
pub(crate) fn space_font(
|
|
&self,
|
|
font: Arc<NativeFont>,
|
|
device: Option<crate::pdf_device::PdfPageData>,
|
|
files: &mut impl crate::execution::SourceProvider,
|
|
) -> Result<crate::pdf_device::text_spaces::ResolvedSpaceFont, String> {
|
|
use crate::pdf_device::text_spaces::ResolvedSpaceFont;
|
|
use crate::render::{DisplayItem, DisplayList, DisplayUnits};
|
|
let mut page = DisplayList {
|
|
units: DisplayUnits::TeX,
|
|
pdf: device,
|
|
items: vec![DisplayItem::NativeGlyph {
|
|
x: 0,
|
|
y: 0,
|
|
size: font.size_sp(),
|
|
font: font.clone(),
|
|
slot: b' ',
|
|
character: ' ',
|
|
paint: None,
|
|
}],
|
|
..DisplayList::default()
|
|
};
|
|
resolve_physical_fonts(std::slice::from_mut(&mut page), files, self)?;
|
|
let DisplayItem::NativeGlyph { paint: Some(paint), .. } = page.items.pop().unwrap() else {
|
|
unreachable!("space font slot must be resolved");
|
|
};
|
|
Ok(ResolvedSpaceFont { font, paint })
|
|
}
|
|
}
|
|
|
|
/// Resolve only fonts used by actual output lists. TFM-only execution and
|
|
/// unshipped boxes do not require any font program. Errors leave lists intact.
|
|
/// SVG executes the requested glyph programs; PDF embeds the same actual PFB.
|
|
pub fn resolve_native_fonts(
|
|
pages: &mut [crate::render::DisplayList],
|
|
files: &mut impl crate::execution::SourceProvider,
|
|
) -> Result<(), String> {
|
|
NativeFontCache::default().resolve(pages, files)
|
|
}
|
|
fn resolve_physical_fonts(
|
|
pages: &mut [crate::render::DisplayList],
|
|
files: &mut impl crate::execution::SourceProvider,
|
|
font_cache: &NativeFontCache,
|
|
) -> Result<(), String> {
|
|
use crate::{render::DisplayItem, resources::ResourceKind};
|
|
use std::collections::BTreeSet;
|
|
let mut used: BTreeMap<FontId, (Arc<NativeFont>, BTreeSet<u8>)> = BTreeMap::new();
|
|
for page in pages.iter() {
|
|
for item in &page.items {
|
|
if let DisplayItem::NativeGlyph { font, slot, .. } = item {
|
|
let entry = used
|
|
.entry(font.id)
|
|
.or_insert_with(|| (font.clone(), BTreeSet::new()));
|
|
if !Arc::ptr_eq(&entry.0, font) && !entry.0.same_base(font) {
|
|
return Err("native font ids from different jobs cannot share output".into());
|
|
}
|
|
entry.1.insert(*slot);
|
|
}
|
|
}
|
|
}
|
|
let Some((first, _)) = used.values().next() else {
|
|
return Ok(());
|
|
};
|
|
let map = actual_resource(
|
|
files,
|
|
ResourceKind::Map,
|
|
"pdftex.map",
|
|
&first.resource.version.path.to_string_lossy(),
|
|
)?;
|
|
let mut resolved = BTreeMap::new();
|
|
let mut pk_resolved = BTreeMap::new();
|
|
let device = pages
|
|
.iter()
|
|
.find_map(|p| p.pdf.as_ref())
|
|
.map(|p| p.file.clone());
|
|
let mut cache: BTreeMap<_, (NativeFontPaint, Arc<DecodedType1>)> = BTreeMap::new();
|
|
for (id, (font, slots)) in used {
|
|
let entry = if font.pdf_space_font && font.name == "pdftexspace" {
|
|
// The pdfTeX device adds its own map entry on first use.
|
|
Some(MapEntry { file: "pdftexspace.pfb".into(), encoding: None })
|
|
} else {
|
|
map_entry(&map.data, &font.name)?
|
|
};
|
|
let Some(entry) = entry else {
|
|
let (resolution, digits) = if let Some(device) = &device {
|
|
(device.pk_resolution, device.decimal_digits)
|
|
} else {
|
|
(files.default_pk_resolution()?.clamp(72, 8000) as u32, 3)
|
|
};
|
|
let dpi = crate::pk_font::requested_dpi(
|
|
resolution,
|
|
crate::pdf_device::divide_scaled(font.size_sp(), 6_578_176, 6).1,
|
|
font.metrics.design_size_sp(),
|
|
)?;
|
|
let resource = files.pk_font(
|
|
&font.name,
|
|
dpi,
|
|
&font.resource.version.path.to_string_lossy(),
|
|
)?;
|
|
{
|
|
use sha2::{Digest, Sha256};
|
|
if resource.version.bytes != resource.data.len() as u64
|
|
|| resource.version.sha256 != format!("{:x}", Sha256::digest(&resource.data))
|
|
{
|
|
return Err(format!(
|
|
"PK resource version does not match actual bytes: {}",
|
|
font.name
|
|
));
|
|
}
|
|
}
|
|
let pk = crate::pk::PkFont::parse(&resource.data)?;
|
|
let program = crate::pk_font::PkFontProgram::new(
|
|
font.name.clone(),
|
|
pk,
|
|
font.metrics(),
|
|
resolution,
|
|
digits,
|
|
)?;
|
|
let mut glyph_paths = BTreeMap::new();
|
|
let mut bbox = None;
|
|
for slot in slots {
|
|
let b = program.glyph_bbox(slot).ok_or_else(|| {
|
|
format!("PK font {} at {dpi} dpi has no glyph {slot}", font.name)
|
|
})?;
|
|
bbox = Some(bbox.map_or(b, |old: [i32; 4]| {
|
|
[
|
|
old[0].min(b[0]),
|
|
old[1].min(b[1]),
|
|
old[2].max(b[2]),
|
|
old[3].max(b[3]),
|
|
]
|
|
}));
|
|
glyph_paths.insert(slot, program.glyph_path(slot)?);
|
|
}
|
|
pk_resolved.insert(
|
|
id,
|
|
Arc::new(NativeFontPaint {
|
|
program: NativeFontProgram::Pk(program),
|
|
encoding: (0..=255).map(|slot| format!("a{slot}")).collect(),
|
|
glyph_paths,
|
|
bbox: bbox.unwrap(),
|
|
stem_v: 0,
|
|
resources: vec![map.version.clone(), resource.version],
|
|
}),
|
|
);
|
|
continue;
|
|
};
|
|
let file = entry.file;
|
|
let key = (file.clone(), entry.encoding.clone());
|
|
if !cache.contains_key(&key) {
|
|
let resource = actual_resource(
|
|
files,
|
|
ResourceKind::Type1,
|
|
&file,
|
|
&map.version.path.to_string_lossy(),
|
|
)?;
|
|
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 enc = actual_resource(
|
|
files,
|
|
ResourceKind::Encoding,
|
|
&name,
|
|
&map.version.path.to_string_lossy(),
|
|
)?;
|
|
let encoding = encoding_vector(&enc.data)?;
|
|
resources.push(enc.version);
|
|
encoding
|
|
} else {
|
|
(0..=255u8)
|
|
.map(|slot| program.name_for_code(slot).unwrap_or(".notdef").to_owned())
|
|
.collect()
|
|
};
|
|
cache.insert(
|
|
key.clone(),
|
|
(
|
|
NativeFontPaint {
|
|
program: NativeFontProgram::Type1(program.clone()),
|
|
encoding,
|
|
glyph_paths: BTreeMap::new(),
|
|
bbox: decoded.bbox,
|
|
stem_v: decoded.stem_v,
|
|
resources,
|
|
},
|
|
decoded,
|
|
),
|
|
);
|
|
}
|
|
let (paint, decoded) = cache.get_mut(&key).unwrap();
|
|
let outlines = &decoded.outlines;
|
|
for slot in slots {
|
|
if paint.glyph_paths.contains_key(&slot) {
|
|
continue;
|
|
}
|
|
let name = &paint.encoding[slot as usize];
|
|
if name == ".notdef" || !outlines.has_glyph(name) {
|
|
return Err(format!(
|
|
"native font {} has no glyph program for TFM slot {slot} ({name})",
|
|
font.name
|
|
));
|
|
}
|
|
paint.glyph_paths.insert(slot, outlines.glyph_path(name)?);
|
|
}
|
|
resolved.insert(id, key);
|
|
}
|
|
let cache: BTreeMap<_, _> = cache
|
|
.into_iter()
|
|
.map(|(key, (paint, _))| (key, Arc::new(paint)))
|
|
.collect();
|
|
let mut resolved: BTreeMap<_, _> = resolved
|
|
.into_iter()
|
|
.map(|(id, key)| (id, cache[&key].clone()))
|
|
.collect();
|
|
resolved.extend(pk_resolved);
|
|
for page in pages {
|
|
for item in &mut page.items {
|
|
if let DisplayItem::NativeGlyph {
|
|
font,
|
|
paint,
|
|
slot,
|
|
character,
|
|
..
|
|
} = item
|
|
{
|
|
let p = resolved[&font.id].clone();
|
|
*character = match &p.program {
|
|
NativeFontProgram::Type1(_) => {
|
|
crate::type1::glyph_unicode_text(&p.encoding[*slot as usize])
|
|
.and_then(|text| text.chars().next())
|
|
.unwrap_or('�')
|
|
}
|
|
NativeFontProgram::Pk(_) => '�',
|
|
};
|
|
*paint = Some(p);
|
|
}
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|