374 lines
13 KiB
Rust
374 lines
13 KiB
Rust
use lopdf::{Dictionary, Document, Object, ObjectId, Stream};
|
|
use std::{
|
|
collections::{BTreeMap, BTreeSet},
|
|
path::Path,
|
|
sync::Arc,
|
|
};
|
|
use texrra_tex_core::{
|
|
execution::SourceProvider,
|
|
native_font::{NativeFontCache, NativeFontProgram},
|
|
render::{DisplayItem, DisplayList},
|
|
type1::Type1Font,
|
|
};
|
|
|
|
mod overlay;
|
|
|
|
#[derive(Default, PartialEq, Eq)]
|
|
pub(crate) struct PreviewFonts {
|
|
type1: BTreeMap<String, Arc<Type1Font>>,
|
|
truetype: BTreeMap<String, Arc<[u8]>>,
|
|
cff: BTreeMap<String, Arc<[u8]>>,
|
|
cid_cff: BTreeMap<String, Arc<[u8]>>,
|
|
missing: bool,
|
|
conflict: Option<String>,
|
|
}
|
|
|
|
impl PreviewFonts {
|
|
pub(crate) fn resolve(
|
|
pages: &[DisplayList],
|
|
files: &mut impl SourceProvider,
|
|
cache: &NativeFontCache,
|
|
) -> Result<Self, String> {
|
|
let mut fonts = Self::default();
|
|
if !pages.iter().any(DisplayList::has_embedded_pdf) {
|
|
return Ok(fonts);
|
|
}
|
|
let forms: BTreeMap<_, _> = pages
|
|
.iter()
|
|
.flat_map(|page| &page.forms)
|
|
.map(|form| (form.form.number, &form.list))
|
|
.collect();
|
|
let mut pending: Vec<_> = pages.iter().collect();
|
|
let mut visited = BTreeSet::new();
|
|
let mut required_type1: BTreeSet<(&Path, &str)> = BTreeSet::new();
|
|
let mut required_truetype = BTreeSet::new();
|
|
let mut required_cid_cff = BTreeSet::new();
|
|
while let Some(list) = pending.pop() {
|
|
for item in &list.items {
|
|
match item {
|
|
DisplayItem::NativeGlyph {
|
|
paint: Some(paint), ..
|
|
} => {
|
|
if let NativeFontProgram::DeviceType1(device) = &paint.program {
|
|
record(
|
|
&mut fonts.type1,
|
|
&mut fonts.missing,
|
|
&mut fonts.conflict,
|
|
&device.name,
|
|
device.preview_program.as_ref(),
|
|
);
|
|
}
|
|
}
|
|
DisplayItem::PdfImage { image, .. } => {
|
|
let source = &image.image;
|
|
required_type1.extend(
|
|
source
|
|
.device_type1_fonts()
|
|
.iter()
|
|
.map(|name| (source.version.path.as_path(), name.as_str())),
|
|
);
|
|
required_truetype.extend(
|
|
source
|
|
.device_truetype_fonts()
|
|
.iter()
|
|
.map(|name| (source.version.path.as_path(), name.as_str())),
|
|
);
|
|
required_cid_cff.extend(
|
|
source
|
|
.device_cid_cff_fonts()
|
|
.iter()
|
|
.map(|name| (source.version.path.as_path(), name.as_str())),
|
|
);
|
|
}
|
|
DisplayItem::PdfForm { form, .. } => {
|
|
if visited.insert(form.number)
|
|
&& let Some(list) = forms.get(&form.number)
|
|
{
|
|
pending.push(list);
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
for (from, name) in required_type1 {
|
|
let from = from.to_string_lossy();
|
|
let program = cache.pdf_device_type1(files, name, &from)?;
|
|
if let Some(program) = &program {
|
|
record(
|
|
&mut fonts.type1,
|
|
&mut fonts.missing,
|
|
&mut fonts.conflict,
|
|
name,
|
|
Some(program),
|
|
);
|
|
} else {
|
|
let program = NativeFontCache::pdf_device_cff(files, name, &from, false)?;
|
|
record(
|
|
&mut fonts.cff,
|
|
&mut fonts.missing,
|
|
&mut fonts.conflict,
|
|
name,
|
|
program.as_ref(),
|
|
);
|
|
}
|
|
}
|
|
for (from, name) in required_truetype {
|
|
let program =
|
|
NativeFontCache::pdf_device_truetype(files, name, &from.to_string_lossy())?;
|
|
record(
|
|
&mut fonts.truetype,
|
|
&mut fonts.missing,
|
|
&mut fonts.conflict,
|
|
name,
|
|
program.as_ref(),
|
|
);
|
|
}
|
|
for (from, name) in required_cid_cff {
|
|
let program =
|
|
NativeFontCache::pdf_device_cff(files, name, &from.to_string_lossy(), true)?;
|
|
record(
|
|
&mut fonts.cid_cff,
|
|
&mut fonts.missing,
|
|
&mut fonts.conflict,
|
|
name,
|
|
program.as_ref(),
|
|
);
|
|
}
|
|
if let Some(name) = fonts
|
|
.type1
|
|
.keys()
|
|
.find(|name| fonts.cff.contains_key(*name))
|
|
{
|
|
fonts.conflict = Some(name.clone());
|
|
}
|
|
Ok(fonts)
|
|
}
|
|
|
|
pub(super) fn includes_device_fonts(&self) -> bool {
|
|
self.missing || !self.programs_empty()
|
|
}
|
|
|
|
fn programs_empty(&self) -> bool {
|
|
self.type1.is_empty()
|
|
&& self.truetype.is_empty()
|
|
&& self.cff.is_empty()
|
|
&& self.cid_cff.is_empty()
|
|
}
|
|
|
|
/// Attach the captured programs to a private copy for PDF-backed previews.
|
|
pub(super) fn attach(&self, pdf: &[u8]) -> Result<Option<Vec<u8>>, String> {
|
|
if let Some(name) = &self.conflict {
|
|
return Err(format!(
|
|
"conflicting actual fonts for PDF preview device name {name}"
|
|
));
|
|
}
|
|
if self.programs_empty() {
|
|
return Ok(None);
|
|
}
|
|
let mut document = Document::load_mem(pdf)
|
|
.map_err(|error| format!("could not read PDF device fonts for preview: {error}"))?;
|
|
let names: BTreeMap<_, _> = document
|
|
.objects
|
|
.iter()
|
|
.filter_map(|(&id, value)| {
|
|
let (_, value) = document.dereference(value).ok()?;
|
|
Some((id, value.as_name().ok()?.to_vec()))
|
|
})
|
|
.collect();
|
|
let descriptors: BTreeMap<_, _> = document
|
|
.objects
|
|
.iter()
|
|
.filter_map(|(&id, value)| {
|
|
let (_, value) = document.dereference(value).ok()?;
|
|
let dict = value.as_dict().ok()?;
|
|
dict.has(b"FontName").then(|| (id, dict.clone()))
|
|
})
|
|
.collect();
|
|
let prior_max_id = document.max_id;
|
|
let type1 = self
|
|
.type1
|
|
.iter()
|
|
.map(|(name, program)| {
|
|
let mut dictionary = Dictionary::new();
|
|
dictionary.set("Length1", program.length1 as i64);
|
|
dictionary.set("Length2", program.length2 as i64);
|
|
dictionary.set("Length3", program.length3 as i64);
|
|
let stream = document.add_object(Stream::new(dictionary, program.program.clone()));
|
|
(name.as_bytes(), (program, stream))
|
|
})
|
|
.collect();
|
|
let truetype = self
|
|
.truetype
|
|
.iter()
|
|
.map(|(name, program)| {
|
|
let mut dictionary = Dictionary::new();
|
|
dictionary.set("Length1", program.len() as i64);
|
|
let stream = document.add_object(Stream::new(dictionary, program.to_vec()));
|
|
(name.as_bytes(), stream)
|
|
})
|
|
.collect();
|
|
let cff = cff_streams(&mut document, &self.cff, b"Type1C");
|
|
let cid_cff = cff_streams(&mut document, &self.cid_cff, b"CIDFontType0C");
|
|
let attachment = Attachment {
|
|
names,
|
|
descriptors,
|
|
type1,
|
|
truetype,
|
|
cff,
|
|
cid_cff,
|
|
};
|
|
let mut attached = false;
|
|
let changes: Vec<_> = document
|
|
.objects
|
|
.iter_mut()
|
|
.filter_map(|(&id, object)| {
|
|
let patched = id.0 <= prior_max_id && attachment.apply(object, 0);
|
|
attached |= patched;
|
|
(patched || id.0 > prior_max_id).then_some(id)
|
|
})
|
|
.collect();
|
|
if attached {
|
|
Ok(Some(overlay::append_objects(
|
|
pdf,
|
|
&document,
|
|
changes.into_iter(),
|
|
)?))
|
|
} else {
|
|
Ok(None)
|
|
}
|
|
}
|
|
}
|
|
|
|
fn cff_streams<'a>(
|
|
document: &mut Document,
|
|
programs: &'a BTreeMap<String, Arc<[u8]>>,
|
|
subtype: &[u8],
|
|
) -> BTreeMap<&'a [u8], ObjectId> {
|
|
programs
|
|
.iter()
|
|
.map(|(name, bytes)| {
|
|
let mut dictionary = Dictionary::new();
|
|
dictionary.set("Subtype", Object::Name(subtype.to_vec()));
|
|
let stream = document.add_object(Stream::new(dictionary, bytes.to_vec()));
|
|
(name.as_bytes(), stream)
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
fn record<T: PartialEq + ?Sized>(
|
|
programs: &mut BTreeMap<String, Arc<T>>,
|
|
missing: &mut bool,
|
|
conflict: &mut Option<String>,
|
|
name: &str,
|
|
program: Option<&Arc<T>>,
|
|
) {
|
|
let Some(program) = program else {
|
|
*missing = true;
|
|
return;
|
|
};
|
|
if let Some(captured) = programs.get(name) {
|
|
if !Arc::ptr_eq(captured, program) && captured != program {
|
|
*conflict = Some(name.to_owned());
|
|
}
|
|
} else {
|
|
programs.insert(name.to_owned(), program.clone());
|
|
}
|
|
}
|
|
|
|
struct Attachment<'a> {
|
|
names: BTreeMap<ObjectId, Vec<u8>>,
|
|
descriptors: BTreeMap<ObjectId, Dictionary>,
|
|
type1: BTreeMap<&'a [u8], (&'a Arc<Type1Font>, ObjectId)>,
|
|
truetype: BTreeMap<&'a [u8], ObjectId>,
|
|
cff: BTreeMap<&'a [u8], ObjectId>,
|
|
cid_cff: BTreeMap<&'a [u8], ObjectId>,
|
|
}
|
|
|
|
impl Attachment<'_> {
|
|
fn apply(&self, object: &mut Object, depth: usize) -> bool {
|
|
if depth >= 64 {
|
|
return false;
|
|
}
|
|
let dictionary = match object {
|
|
Object::Dictionary(dict) => dict,
|
|
Object::Stream(stream) => &mut stream.dict,
|
|
Object::Array(entries) => {
|
|
return entries.iter_mut().fold(false, |changed, object| {
|
|
self.apply(object, depth + 1) | changed
|
|
});
|
|
}
|
|
_ => return false,
|
|
};
|
|
let nested = dictionary.iter_mut().fold(false, |changed, (_, value)| {
|
|
self.apply(value, depth + 1) | changed
|
|
});
|
|
self.attach_font(dictionary) || nested
|
|
}
|
|
|
|
fn attach_font(&self, font: &mut Dictionary) -> bool {
|
|
let name = |key| {
|
|
let object = font.get(key).ok()?;
|
|
match object {
|
|
Object::Reference(id) => self.names.get(id).map(Vec::as_slice),
|
|
_ => object.as_name().ok(),
|
|
}
|
|
};
|
|
let Some(base) = name(b"BaseFont") else {
|
|
return false;
|
|
};
|
|
let (file_key, stream, bbox) = match name(b"Subtype") {
|
|
Some(b"Type1") => {
|
|
if let Some((program, stream)) = self.type1.get(base) {
|
|
("FontFile", stream, Some(program.bbox))
|
|
} else if let Some(stream) = self.cff.get(base) {
|
|
("FontFile3", stream, None)
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
Some(b"CIDFontType0") => {
|
|
let Some(stream) = self.cid_cff.get(base) else {
|
|
return false;
|
|
};
|
|
("FontFile3", stream, None)
|
|
}
|
|
Some(b"TrueType" | b"CIDFontType2") => {
|
|
let Some(stream) = self.truetype.get(base) else {
|
|
return false;
|
|
};
|
|
("FontFile2", stream, None)
|
|
}
|
|
_ => return false,
|
|
};
|
|
let mut descriptor = match font.get(b"FontDescriptor") {
|
|
Ok(Object::Dictionary(dict)) => dict.clone(),
|
|
Ok(Object::Reference(id)) => {
|
|
let Some(dict) = self.descriptors.get(id) else {
|
|
return false;
|
|
};
|
|
dict.clone()
|
|
}
|
|
Err(_) | Ok(Object::Null) => {
|
|
let mut dict = Dictionary::new();
|
|
dict.set("Type", Object::Name(b"FontDescriptor".to_vec()));
|
|
dict.set("FontName", Object::Name(base.to_vec()));
|
|
if let Some(bbox) = bbox {
|
|
dict.set("FontBBox", Object::Array(bbox.map(Object::from).into()));
|
|
}
|
|
dict
|
|
}
|
|
_ => return false,
|
|
};
|
|
if [b"FontFile".as_slice(), b"FontFile2", b"FontFile3"]
|
|
.into_iter()
|
|
.any(|key| descriptor.has(key))
|
|
{
|
|
return false;
|
|
}
|
|
descriptor.set(file_key, *stream);
|
|
font.set("FontDescriptor", descriptor);
|
|
true
|
|
}
|
|
}
|