819 lines
32 KiB
Rust
819 lines
32 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, Type1Transform},
|
|
type1_outline::{Type1Outlines, XdvDescriptor},
|
|
};
|
|
use std::{
|
|
collections::{BTreeMap, VecDeque},
|
|
sync::{Arc, Mutex, OnceLock},
|
|
};
|
|
mod cff;
|
|
mod composite;
|
|
mod composite_type1;
|
|
mod device_type1;
|
|
mod map;
|
|
mod sfd;
|
|
mod truetype;
|
|
mod type1_cache;
|
|
mod virtual_paint;
|
|
pub use cff::OpenTypeCffProgram;
|
|
pub use composite_type1::CompositeType1Program;
|
|
pub use device_type1::DeviceType1Program;
|
|
pub use truetype::TrueTypeProgram;
|
|
pub use type1_cache::Type1FontWork;
|
|
pub(crate) use truetype::cid_width;
|
|
pub use map::PdfFontBindings;
|
|
pub(crate) use map::XdvFontMatrix;
|
|
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)]
|
|
pub struct NativeFontPaint {
|
|
pub program: NativeFontProgram,
|
|
pub encoding: Vec<String>,
|
|
pub glyph_paths: BTreeMap<u8, String>,
|
|
pub bbox: [i32; 4],
|
|
pub stem_v: i32,
|
|
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
|
pub(crate) subset: bool,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub(crate) descriptor_flags: Option<i32>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub(crate) xdv_descriptor: Option<XdvDescriptor>,
|
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
|
pub(crate) xdv_widths: BTreeMap<u8, i64>,
|
|
#[serde(default, skip_serializing_if = "XdvFontMatrix::is_identity")]
|
|
pub(crate) xdv_matrix: XdvFontMatrix,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub(crate) xdv_unicode: Option<Arc<XdvFontUnicode>>,
|
|
pub resources: Vec<crate::resources::ResourceVersion>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
program_index: Option<usize>,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub(crate) struct XdvFontUnicode {
|
|
pub(crate) texts: BTreeMap<u8, String>,
|
|
resources: Vec<ResourceVersion>,
|
|
}
|
|
|
|
struct MappedOutline {
|
|
data: Arc<[u8]>,
|
|
encoding: Option<Vec<String>>,
|
|
resources: Vec<ResourceVersion>,
|
|
program_index: usize,
|
|
}
|
|
|
|
pub(crate) type Type1ProgramKey<'a> = (&'a ResourceVersion, Type1Transform);
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub(crate) struct MappedType1 {
|
|
pub version: ResourceVersion,
|
|
pub font: Arc<Type1Font>,
|
|
pub flags: i32,
|
|
pub subset: bool,
|
|
}
|
|
|
|
impl MappedType1 {
|
|
pub(crate) fn key(&self) -> Type1ProgramKey<'_> {
|
|
(&self.version, self.font.transform)
|
|
}
|
|
}
|
|
|
|
impl NativeFontPaint {
|
|
pub(crate) fn program_version(&self) -> Option<&ResourceVersion> {
|
|
self.resources.get(self.program_index?)
|
|
}
|
|
|
|
pub(crate) fn legacy_cid_font(&self) -> Option<&composite::CompositeFont> {
|
|
match &self.program {
|
|
NativeFontProgram::TrueType(program) => program.composite.as_ref(),
|
|
NativeFontProgram::OpenTypeCff(program) => program.composite.as_ref(),
|
|
NativeFontProgram::CompositeType1(program) => Some(&program.mapping),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
pub(crate) fn mapped_text(&self, slot: u8) -> Option<&str> {
|
|
self.xdv_unicode.as_ref().and_then(|map| map.texts.get(&slot)).map(String::as_str)
|
|
.or_else(|| self.legacy_cid_font()?.unicode(slot))
|
|
}
|
|
|
|
pub(crate) fn has_pdf_space(&self, font: &NativeFont) -> bool {
|
|
// pdfTeX requires the space name in an actual map re-encoding.
|
|
self.encoding_version().is_some()
|
|
&& matches!(self.program, NativeFontProgram::Type1(_) | NativeFontProgram::DeviceType1(_))
|
|
&& self.encoding[32] == "space"
|
|
&& font.metrics().width(' ') > 65_782
|
|
}
|
|
pub(crate) fn encoding_version(&self) -> Option<&ResourceVersion> {
|
|
if let NativeFontProgram::DeviceType1(program) = &self.program {
|
|
return if program.reencoded { self.resources.last() } else { None };
|
|
}
|
|
self.resources.get(self.program_index? + 1)
|
|
}
|
|
|
|
pub(crate) fn type1_program_key(&self) -> Option<Type1ProgramKey<'_>> {
|
|
match &self.program {
|
|
NativeFontProgram::Type1(font) => self.resources.get(self.program_index.unwrap_or(1))
|
|
.map(|version| (version, font.transform)),
|
|
NativeFontProgram::Pk(_) | NativeFontProgram::TrueType(_)
|
|
| NativeFontProgram::OpenTypeCff(_) | NativeFontProgram::DeviceType1(_)
|
|
| NativeFontProgram::CompositeType1(_) => None,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub enum NativeFontProgram {
|
|
Type1(crate::type1::Type1Font),
|
|
Pk(crate::pk_font::PkFontProgram),
|
|
TrueType(TrueTypeProgram),
|
|
OpenTypeCff(OpenTypeCffProgram),
|
|
CompositeType1(CompositeType1Program),
|
|
DeviceType1(DeviceType1Program),
|
|
}
|
|
impl NativeFontProgram {
|
|
pub fn name(&self) -> &str {
|
|
match self {
|
|
Self::Type1(p) => &p.name,
|
|
Self::Pk(p) => &p.name,
|
|
Self::TrueType(p) => &p.name,
|
|
Self::OpenTypeCff(p) => &p.name,
|
|
Self::CompositeType1(p) => &p.font.name,
|
|
Self::DeviceType1(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(crate) fn discard_letterspace_program(font: &mut Arc<Self>) -> bool {
|
|
if font.letter_spacing.is_none() {
|
|
return false;
|
|
}
|
|
Arc::make_mut(font).letter_spacing = None;
|
|
true
|
|
}
|
|
|
|
pub(crate) fn rebind_resource_path(
|
|
font: &mut Arc<Self>,
|
|
bindings: &BTreeMap<std::path::PathBuf, std::path::PathBuf>,
|
|
) -> bool {
|
|
let path = bindings.get(&font.resource.version.path);
|
|
let base = font.letter_spacing.as_ref().and_then(|spacing| {
|
|
let mut base = spacing.base.clone();
|
|
Self::rebind_resource_path(&mut base, bindings).then_some(base)
|
|
});
|
|
if path.is_none() && base.is_none() {
|
|
return false;
|
|
}
|
|
let font = Arc::make_mut(font);
|
|
if let Some(path) = path {
|
|
font.resource.version.path.clone_from(path);
|
|
}
|
|
if let Some(base) = base {
|
|
font.letter_spacing.as_mut().expect("relocated letterspace base").base = base;
|
|
}
|
|
true
|
|
}
|
|
|
|
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 xdv_advance(&self, slot: u8) -> i64 {
|
|
self.horizontal(self.metrics().xdv_width(slot))
|
|
}
|
|
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)
|
|
}
|
|
}
|
|
|
|
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)
|
|
}
|
|
pub(crate) 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_TYPE1_BYTES: usize = 256 * 1024;
|
|
|
|
/// Verified Type 1 programs and derived device data shared across revisions.
|
|
#[derive(Default)]
|
|
pub struct NativeFontCache {
|
|
type1: Mutex<VecDeque<((ResourceVersion, Type1Transform), Arc<DecodedType1>)>>,
|
|
type1_output: type1_cache::Type1OutputCache,
|
|
}
|
|
|
|
struct DecodedType1 {
|
|
program: Arc<Type1Font>,
|
|
outlines: Type1Outlines,
|
|
glyphs: Mutex<type1_cache::GlyphMeasurements>,
|
|
bbox: [i32; 4],
|
|
stem_v: i32,
|
|
xdv_descriptor: OnceLock<Result<XdvDescriptor, String>>,
|
|
}
|
|
|
|
impl DecodedType1 {
|
|
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() {
|
|
(outlines.normalized_bbox(program.bbox), outlines.stem_v())
|
|
} else {
|
|
// The PDF descriptor keeps the Type1 program's own font units.
|
|
(program.bbox, outlines.raw_stem_v())
|
|
};
|
|
Ok(Self {
|
|
program: Arc::new(program),
|
|
outlines,
|
|
glyphs: Mutex::default(),
|
|
bbox,
|
|
stem_v,
|
|
xdv_descriptor: OnceLock::new(),
|
|
})
|
|
}
|
|
}
|
|
|
|
impl NativeFontCache {
|
|
/// Resolve a PDF device font using the same exact program identity as native text.
|
|
pub fn pdf_device_type1(
|
|
&self,
|
|
files: &mut impl crate::execution::SourceProvider,
|
|
name: &str,
|
|
from: &str,
|
|
) -> Result<Option<Arc<Type1Font>>, String> {
|
|
Ok(device_type1::find_program(files, self, name, None, from)?
|
|
.map(|(_, decoded)| decoded.program.clone()))
|
|
}
|
|
|
|
/// Resolve the real standalone glyph program for a PDF TrueType device font.
|
|
pub fn pdf_device_truetype(
|
|
files: &mut impl crate::execution::SourceProvider,
|
|
name: &str,
|
|
from: &str,
|
|
) -> Result<Option<Arc<[u8]>>, String> {
|
|
truetype::device_program(files, name, from)
|
|
}
|
|
|
|
/// Resolve the actual CFF table for a PDF device font.
|
|
pub fn pdf_device_cff(
|
|
files: &mut impl crate::execution::SourceProvider,
|
|
name: &str,
|
|
from: &str,
|
|
cid_keyed: bool,
|
|
) -> Result<Option<Arc<[u8]>>, String> {
|
|
cff::device_program(files, name, from, cid_keyed)
|
|
}
|
|
|
|
// 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_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
|
|
.iter()
|
|
.position(|((version, cached_transform), _)| *version == resource.version && *cached_transform == transform)
|
|
{
|
|
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_resource(resource, transform)?);
|
|
if entries.len() == MAX_TYPE1_PROGRAMS {
|
|
entries.pop_front();
|
|
}
|
|
entries.push_back(((resource.version.clone(), transform), 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,
|
|
pdf_font_bindings: Some(Arc::new(PdfFontBindings::default())),
|
|
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 draws the requested outlines; PDF embeds the same actual font programs.
|
|
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_xdv_unicode(
|
|
pages: &[crate::render::DisplayList],
|
|
resolved: &mut BTreeMap<FontId, Arc<NativeFontPaint>>,
|
|
bindings: &PdfFontBindings,
|
|
files: &mut impl crate::execution::SourceProvider,
|
|
) -> Result<(), String> {
|
|
use crate::render::DisplayItem;
|
|
let used: BTreeMap<_, _> = pages.iter().flat_map(|page| &page.items).filter_map(|item| {
|
|
match item {
|
|
DisplayItem::NativeGlyph { font, .. } => Some((font.id, &font.name)),
|
|
_ => None,
|
|
}
|
|
}).collect();
|
|
let mut maps = std::collections::HashMap::new();
|
|
let mut owners: std::collections::HashMap<_, Option<Arc<XdvFontUnicode>>> = std::collections::HashMap::new();
|
|
for (id, font_name) in used {
|
|
let paint = resolved.get_mut(&id).expect("resolved device font");
|
|
if paint.legacy_cid_font().is_some() {
|
|
continue;
|
|
}
|
|
// The PDF writer shares one Type 1 resource and encoding among all
|
|
// sizes and aliases of the same physical program.
|
|
let owner_key = paint.xdv_descriptor.and_then(|_| paint.type1_program_key())
|
|
.map(|(version, transform)| (version.clone(), transform, paint.encoding_version().cloned()));
|
|
let texts = if let Some(texts) = owner_key.as_ref().and_then(|key| owners.get(key)) {
|
|
texts.clone()
|
|
} else {
|
|
let texts = if let Some(entry) = bindings.xdv_unicode.get(font_name) {
|
|
let name = entry.xdv_to_unicode.as_deref().expect("explicit XDV font CMap");
|
|
let key = (&entry.from, name, &entry.version);
|
|
let map = match maps.entry(key) {
|
|
std::collections::hash_map::Entry::Occupied(existing) => existing.into_mut(),
|
|
std::collections::hash_map::Entry::Vacant(vacant) => {
|
|
let from = entry.from.to_string_lossy();
|
|
let map = crate::pdf_device::cmap::CMap::load(name, &from, files)?;
|
|
let texts = map.simple_unicode();
|
|
let resources = entry.version.iter().cloned().chain(map.resources).collect();
|
|
vacant.insert(Arc::new(XdvFontUnicode { texts, resources }))
|
|
}
|
|
};
|
|
Some(map.clone())
|
|
} else {
|
|
None
|
|
};
|
|
if let Some(key) = owner_key {
|
|
owners.insert(key, texts.clone());
|
|
}
|
|
texts
|
|
};
|
|
if texts.is_some() {
|
|
Arc::make_mut(paint).xdv_unicode = texts;
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
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>, bool)> = 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(), false));
|
|
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);
|
|
entry.2 |= font.expansion != 0;
|
|
}
|
|
}
|
|
}
|
|
let Some((first, _, _)) = used.values().next() else {
|
|
return Ok(());
|
|
};
|
|
let captured_bindings = pages.iter().rev().filter_map(|page| page.pdf_font_bindings.as_deref());
|
|
let captured = captured_bindings.clone().next();
|
|
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 direct_resolved = BTreeMap::new();
|
|
let mut subfonts = sfd::Files::default();
|
|
let mut outlines = map::OutlineFiles::default();
|
|
let device = pages.iter().find_map(|page| page.pdf.as_ref());
|
|
let xdv = device.is_some_and(|pdf| pdf.driver == crate::pdf_device::PdfDriver::Xdv);
|
|
let device = device.map(|pdf| pdf.file.clone());
|
|
let mut cache: BTreeMap<_, (NativeFontPaint, Arc<DecodedType1>)> = BTreeMap::new();
|
|
for (id, (font, slots, expanded)) in used {
|
|
let entry = if font.pdf_space_font && font.name == "pdftexspace" {
|
|
Some(Arc::new(dedicated_space_map(&font)))
|
|
} else if captured.is_some() {
|
|
// Pending Form lists may precede the last real page in execution
|
|
// order, even when the host appends them for physical font painting.
|
|
captured_bindings.clone().find_map(|bindings| bindings.font(&font).ok())
|
|
.ok_or_else(|| format!("PDF font {} has no captured map binding", font.name))?
|
|
} else if let Some(map) = &default_map {
|
|
find_map_entry(map, &font.name, files, &mut subfonts)?.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 {
|
|
(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)?);
|
|
}
|
|
direct_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,
|
|
subset: false,
|
|
descriptor_flags: None,
|
|
xdv_descriptor: None,
|
|
xdv_widths: BTreeMap::new(),
|
|
xdv_matrix: Default::default(),
|
|
xdv_unicode: None,
|
|
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;
|
|
};
|
|
if !xdv && let Some(name) = outline.device_type1_name() {
|
|
let paint = device_type1::resolve(files, font_cache, outline, name, &font, slots)?;
|
|
direct_resolved.insert(id, Arc::new(paint));
|
|
continue;
|
|
}
|
|
let matrix = if xdv { outline.xdv_text_matrix() } else { XdvFontMatrix::default() };
|
|
if let Some(file) = outline.true_type_file() {
|
|
let mut paint = truetype::resolve(files, &mut outlines, outline, file, &font, slots)?;
|
|
paint.xdv_matrix = matrix;
|
|
direct_resolved.insert(id, Arc::new(paint));
|
|
continue;
|
|
}
|
|
if let Some(file) = outline.open_type_file() {
|
|
let mut paint = cff::resolve(files, &mut outlines, outline, file, &font, slots)?;
|
|
paint.xdv_matrix = matrix;
|
|
direct_resolved.insert(id, Arc::new(paint));
|
|
continue;
|
|
}
|
|
let file = outline.type1_file(&font.name)?;
|
|
if let Some(encoding) = &outline.xdv_encoding
|
|
&& let Some(codes) = composite::Codes::load(encoding, outline, files)?
|
|
{
|
|
let paint = composite_type1::resolve(files, font_cache, outline, file, slots, encoding, codes)?;
|
|
direct_resolved.insert(id, Arc::new(paint));
|
|
continue;
|
|
}
|
|
let version = outline.version.as_ref();
|
|
let transform = outline.transform;
|
|
let key = (
|
|
outline.from.clone(),
|
|
version.map(|version| version.sha256.clone()),
|
|
file.to_owned(),
|
|
outline.encoding.clone(),
|
|
transform,
|
|
matrix,
|
|
outline.subset,
|
|
outline.descriptor_flags,
|
|
);
|
|
if !cache.contains_key(&key) {
|
|
let from = outline.from.to_string_lossy();
|
|
let resource = actual_resource(files, ResourceKind::Type1, file, &from)?;
|
|
let decoded = font_cache.type1(&resource, transform)?;
|
|
let program = &decoded.program;
|
|
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,
|
|
&from,
|
|
)?;
|
|
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.as_ref().clone()),
|
|
encoding,
|
|
glyph_paths: BTreeMap::new(),
|
|
bbox: decoded.bbox,
|
|
stem_v: decoded.stem_v,
|
|
subset: outline.subset && !xdv,
|
|
descriptor_flags: outline.descriptor_flags,
|
|
xdv_descriptor: if xdv {
|
|
Some(decoded.xdv_descriptor.get_or_init(|| {
|
|
decoded.outlines.xdv_descriptor()
|
|
}).clone()?)
|
|
} else {
|
|
None
|
|
},
|
|
xdv_widths: BTreeMap::new(),
|
|
xdv_matrix: matrix,
|
|
xdv_unicode: None,
|
|
resources,
|
|
program_index,
|
|
},
|
|
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
|
|
));
|
|
}
|
|
let (path, width) = font_cache.type1_glyph(decoded, name)?;
|
|
paint.glyph_paths.insert(slot, path);
|
|
if paint.xdv_descriptor.is_some() {
|
|
paint.xdv_widths.insert(slot, width);
|
|
}
|
|
}
|
|
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(direct_resolved);
|
|
if xdv && let Some(bindings) = captured && !bindings.xdv_unicode.is_empty() {
|
|
resolve_xdv_unicode(pages, &mut resolved, bindings, files)?;
|
|
}
|
|
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 = p.mapped_text(*slot)
|
|
.and_then(|text| text.chars().next()).unwrap_or_else(|| match &p.program {
|
|
NativeFontProgram::Type1(_)
|
|
| NativeFontProgram::DeviceType1(_)
|
|
| NativeFontProgram::TrueType(_)
|
|
| NativeFontProgram::OpenTypeCff(_)
|
|
| NativeFontProgram::CompositeType1(_) => {
|
|
crate::type1::glyph_unicode_text(&p.encoding[*slot as usize])
|
|
.and_then(|text| text.chars().next())
|
|
.unwrap_or('�')
|
|
}
|
|
NativeFontProgram::Pk(_) => '�',
|
|
});
|
|
*paint = Some(p);
|
|
}
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|