Resolve imported PDF Type 1 device fonts in native previews
This commit is contained in:
1 parent
c0970bdbf6
commit
b640b26eff
12 files changed
+586
-106
No files matched your search
@@ -1,53 +1,91 @@
|
||||
use lopdf::{Dictionary, Document, Stream};
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
use lopdf::{Dictionary, Document, Object, ObjectId, Stream};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
path::Path,
|
||||
sync::Arc,
|
||||
};
|
||||
use texrra_tex_core::{
|
||||
native_font::NativeFontProgram,
|
||||
execution::SourceProvider,
|
||||
native_font::{NativeFontCache, NativeFontProgram},
|
||||
render::{DisplayItem, DisplayList},
|
||||
type1::Type1Font,
|
||||
};
|
||||
|
||||
mod overlay;
|
||||
|
||||
#[derive(Default, PartialEq, Eq)]
|
||||
pub(super) struct PreviewFonts {
|
||||
pub(crate) struct PreviewFonts {
|
||||
programs: BTreeMap<String, Arc<Type1Font>>,
|
||||
missing: bool,
|
||||
conflict: Option<String>,
|
||||
}
|
||||
|
||||
impl PreviewFonts {
|
||||
pub(super) fn collect(pages: &[DisplayList]) -> Self {
|
||||
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) {
|
||||
for page in pages {
|
||||
fonts.collect_from(page);
|
||||
}
|
||||
if !pages.iter().any(DisplayList::has_embedded_pdf) {
|
||||
return Ok(fonts);
|
||||
}
|
||||
fonts
|
||||
}
|
||||
|
||||
fn collect_from(&mut self, page: &DisplayList) {
|
||||
for item in &page.items {
|
||||
let DisplayItem::NativeGlyph {
|
||||
paint: Some(paint), ..
|
||||
} = item
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if let NativeFontProgram::DeviceType1(device) = &paint.program {
|
||||
if let Some(program) = &device.preview_program {
|
||||
if let Some(captured) = self.programs.get(&device.name) {
|
||||
if !Arc::ptr_eq(captured, program) && captured != program {
|
||||
self.conflict = Some(device.name.clone());
|
||||
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: BTreeSet<(&Path, &str)> = 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 {
|
||||
fonts.record(&device.name, device.preview_program.as_ref());
|
||||
}
|
||||
} else {
|
||||
self.programs.insert(device.name.clone(), program.clone());
|
||||
}
|
||||
} else {
|
||||
self.missing = true;
|
||||
DisplayItem::PdfImage { image, .. } => {
|
||||
let source = &image.image;
|
||||
required.extend(
|
||||
source
|
||||
.device_type1_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 form in &page.forms {
|
||||
self.collect_from(&form.list);
|
||||
for (from, name) in required {
|
||||
let program = cache.pdf_device_type1(files, name, &from.to_string_lossy())?;
|
||||
fonts.record(name, program.as_ref());
|
||||
}
|
||||
Ok(fonts)
|
||||
}
|
||||
|
||||
fn record(&mut self, name: &str, program: Option<&Arc<Type1Font>>) {
|
||||
let Some(program) = program else {
|
||||
self.missing = true;
|
||||
return;
|
||||
};
|
||||
if let Some(captured) = self.programs.get(name) {
|
||||
if !Arc::ptr_eq(captured, program) && captured != program {
|
||||
self.conflict = Some(name.to_owned());
|
||||
}
|
||||
} else {
|
||||
self.programs.insert(name.to_owned(), program.clone());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,8 +93,7 @@ impl PreviewFonts {
|
||||
self.missing || !self.programs.is_empty()
|
||||
}
|
||||
|
||||
/// For PDF-backed previews, attach the same captured local font programs
|
||||
/// used by the native SVG path to an in-memory copy of the PDF.
|
||||
/// 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!(
|
||||
@@ -68,43 +105,133 @@ impl PreviewFonts {
|
||||
}
|
||||
let mut document = Document::load_mem(pdf)
|
||||
.map_err(|error| format!("could not read PDF device fonts for preview: {error}"))?;
|
||||
let descriptors: Vec<_> = document
|
||||
let names: BTreeMap<_, _> = document
|
||||
.objects
|
||||
.iter()
|
||||
.filter_map(|(&id, object)| {
|
||||
let descriptor = object.as_dict().ok()?;
|
||||
if descriptor.get(b"Type").ok()?.as_name().ok()? != b"FontDescriptor"
|
||||
|| [b"FontFile".as_slice(), b"FontFile2", b"FontFile3"]
|
||||
.into_iter()
|
||||
.any(|key| descriptor.has(key))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let name = descriptor.get(b"FontName").ok()?;
|
||||
let (_, name) = document.dereference(name).ok()?;
|
||||
let name = std::str::from_utf8(name.as_name().ok()?).ok()?;
|
||||
Some((id, self.programs.get(name)?))
|
||||
.filter_map(|(&id, value)| {
|
||||
let (_, value) = document.dereference(value).ok()?;
|
||||
Some((id, value.as_name().ok()?.to_vec()))
|
||||
})
|
||||
.collect();
|
||||
if descriptors.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut streams = BTreeMap::new();
|
||||
for (id, font) in descriptors {
|
||||
let stream = *streams.entry(&font.name).or_insert_with(|| {
|
||||
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 programs = self
|
||||
.programs
|
||||
.iter()
|
||||
.map(|(name, program)| {
|
||||
let mut dictionary = Dictionary::new();
|
||||
dictionary.set("Length1", font.length1 as i64);
|
||||
dictionary.set("Length2", font.length2 as i64);
|
||||
dictionary.set("Length3", font.length3 as i64);
|
||||
document.add_object(Stream::new(dictionary, font.program.clone()))
|
||||
});
|
||||
let descriptor = document.get_object_mut(id).unwrap().as_dict_mut().unwrap();
|
||||
descriptor.set("FontFile", stream);
|
||||
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 attachment = Attachment {
|
||||
names,
|
||||
descriptors,
|
||||
programs,
|
||||
};
|
||||
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)
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
document
|
||||
.save_to(&mut bytes)
|
||||
.map_err(|error| format!("could not prepare PDF device fonts for preview: {error}"))?;
|
||||
Ok(Some(bytes))
|
||||
}
|
||||
}
|
||||
|
||||
struct Attachment<'a> {
|
||||
names: BTreeMap<ObjectId, Vec<u8>>,
|
||||
descriptors: BTreeMap<ObjectId, Dictionary>,
|
||||
programs: BTreeMap<&'a [u8], (&'a Arc<Type1Font>, 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(),
|
||||
}
|
||||
};
|
||||
if name(b"Subtype") != Some(b"Type1") {
|
||||
return false;
|
||||
}
|
||||
let Some((program, stream)) = name(b"BaseFont").and_then(|base| self.programs.get(base))
|
||||
else {
|
||||
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(program.name.as_bytes().to_vec()));
|
||||
dict.set(
|
||||
"FontBBox",
|
||||
Object::Array(program.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("FontFile", *stream);
|
||||
font.set("FontDescriptor", descriptor);
|
||||
true
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user