Support unembedded pdfTeX Type 1 device fonts in export and preview
This commit is contained in:
1 parent
60d67bbb7b
commit
c0970bdbf6
10 files changed
+466
-34
No files matched your search
+43
-14
@@ -4,11 +4,13 @@ use hayro_svg::{
|
||||
};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
sync::{Arc, Mutex, OnceLock},
|
||||
sync::{Arc, Mutex, OnceLock, atomic::{AtomicBool, Ordering}},
|
||||
};
|
||||
use texrra_tex_core::render::DisplayList;
|
||||
|
||||
mod device_fonts;
|
||||
mod pdf_dependencies;
|
||||
use device_fonts::PreviewFonts;
|
||||
use pdf_dependencies::{Fingerprint, PdfDependencies};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
|
||||
@@ -32,7 +34,7 @@ pub struct PreviewUpdate {
|
||||
struct CachedPage {
|
||||
svg: Arc<str>,
|
||||
pdf_page: Option<Fingerprint>,
|
||||
reused_pdf_page: bool,
|
||||
same_as_previous: bool,
|
||||
}
|
||||
|
||||
type PageSvg = OnceLock<Result<CachedPage, String>>;
|
||||
@@ -40,6 +42,7 @@ type PriorPdfPage = (Fingerprint, Arc<str>);
|
||||
|
||||
struct PdfPreview<'a> {
|
||||
bytes: Option<&'a Arc<[u8]>>,
|
||||
fonts: &'a PreviewFonts,
|
||||
document: OnceLock<Result<Pdf, String>>,
|
||||
dependencies: PdfDependencies,
|
||||
}
|
||||
@@ -57,8 +60,12 @@ impl PdfPreview<'_> {
|
||||
let bytes = self
|
||||
.bytes
|
||||
.ok_or("embedded PDF preview has no published PDF")?;
|
||||
Pdf::new(Arc::new(bytes.clone()))
|
||||
.map_err(|error| format!("could not read the published preview PDF: {error:?}"))
|
||||
let document = if let Some(data) = self.fonts.attach(bytes)? {
|
||||
Pdf::new(Arc::new(data))
|
||||
} else {
|
||||
Pdf::new(Arc::new(bytes.clone()))
|
||||
};
|
||||
document.map_err(|error| format!("could not read the published preview PDF: {error:?}"))
|
||||
})
|
||||
.as_ref()
|
||||
.map_err(Clone::clone)?;
|
||||
@@ -67,22 +74,35 @@ impl PdfPreview<'_> {
|
||||
.get(index)
|
||||
.ok_or("preview PDF page is missing")?;
|
||||
let pdf_page = self.dependencies.page(document, page, unit);
|
||||
if let Some((prior_page, svg)) = previous
|
||||
&& pdf_page == Some(prior_page)
|
||||
if let Some((prior_page, svg)) = &previous
|
||||
&& pdf_page.as_ref() == Some(prior_page)
|
||||
{
|
||||
return Ok(CachedPage {
|
||||
svg,
|
||||
svg: svg.clone(),
|
||||
pdf_page,
|
||||
reused_pdf_page: true,
|
||||
same_as_previous: true,
|
||||
});
|
||||
}
|
||||
|
||||
let mut settings = InterpreterSettings::default();
|
||||
let missing_font = self.fonts.includes_device_fonts().then(|| Arc::new(AtomicBool::new(false)));
|
||||
if let Some(flag) = &missing_font {
|
||||
let flag = flag.clone();
|
||||
settings.warning_sink = Arc::new(move |warning| {
|
||||
if matches!(warning, hayro_svg::hayro_interpret::InterpreterWarning::UnsupportedFont) {
|
||||
flag.store(true, Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
}
|
||||
let svg = hayro_svg::convert(
|
||||
page,
|
||||
&RenderCache::new(),
|
||||
&InterpreterSettings::default(),
|
||||
&settings,
|
||||
&SvgRenderSettings::default(),
|
||||
);
|
||||
if missing_font.is_some_and(|flag| flag.load(Ordering::Relaxed)) {
|
||||
return Err("native PDF preview needs an actual device font used by this page".into());
|
||||
}
|
||||
let svg = if unit == 1.0 {
|
||||
Arc::from(svg)
|
||||
} else {
|
||||
@@ -92,10 +112,13 @@ impl PdfPreview<'_> {
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{width}pt\" height=\"{height}pt\" viewBox=\"0 0 {width} {height}\"><g transform=\"scale({unit})\">{svg}</g></svg>"
|
||||
))
|
||||
};
|
||||
// A shared PDF object can change without affecting this page's paint.
|
||||
let same = previous.filter(|(_, old)| *old == svg);
|
||||
let same_as_previous = same.is_some();
|
||||
Ok(CachedPage {
|
||||
svg,
|
||||
svg: same.map_or(svg, |(_, old_svg)| old_svg),
|
||||
pdf_page,
|
||||
reused_pdf_page: false,
|
||||
same_as_previous,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -105,6 +128,7 @@ pub(crate) struct PreviewState {
|
||||
changed: Vec<usize>,
|
||||
slots: Vec<Arc<PageSvg>>,
|
||||
prior_pdf: BTreeMap<usize, Mutex<Option<PriorPdfPage>>>,
|
||||
fonts: PreviewFonts,
|
||||
}
|
||||
|
||||
impl PreviewState {
|
||||
@@ -116,10 +140,13 @@ impl PreviewState {
|
||||
let mut changed = Vec::new();
|
||||
let mut slots = Vec::with_capacity(pages.len());
|
||||
let mut prior_pdf = BTreeMap::new();
|
||||
let fonts = PreviewFonts::collect(pages);
|
||||
let pdf_inputs_unchanged = pdf_unchanged
|
||||
&& previous.is_some_and(|(_, _, old)| old.fonts == fonts);
|
||||
for (index, page) in pages.iter().enumerate() {
|
||||
let uses_pdf = page.has_embedded_pdf();
|
||||
if let Some((_, old_pages, old)) = previous
|
||||
&& (pdf_unchanged || !uses_pdf)
|
||||
&& (pdf_inputs_unchanged || !uses_pdf)
|
||||
&& old_pages
|
||||
.get(index)
|
||||
.is_some_and(|old_page| old_page.same_svg_paint(page))
|
||||
@@ -142,6 +169,7 @@ impl PreviewState {
|
||||
changed,
|
||||
slots,
|
||||
prior_pdf,
|
||||
fonts,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,6 +183,7 @@ impl PreviewState {
|
||||
) -> Result<PreviewUpdate, String> {
|
||||
let mut pdf = PdfPreview {
|
||||
bytes: pdf,
|
||||
fonts: &self.fonts,
|
||||
document: OnceLock::new(),
|
||||
dependencies: PdfDependencies::default(),
|
||||
};
|
||||
@@ -165,7 +194,7 @@ impl PreviewState {
|
||||
for &index in &self.changed {
|
||||
check()?;
|
||||
let cached = self.render_page(index, &pages[index], &mut pdf)?;
|
||||
if !cached.reused_pdf_page {
|
||||
if !cached.same_as_previous {
|
||||
rendered.push(PreviewPage {
|
||||
index,
|
||||
svg: cached.svg.clone(),
|
||||
@@ -213,7 +242,7 @@ impl PreviewState {
|
||||
page.try_to_svg().map(|svg| CachedPage {
|
||||
svg: Arc::from(svg),
|
||||
pdf_page: None,
|
||||
reused_pdf_page: false,
|
||||
same_as_previous: false,
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
use lopdf::{Dictionary, Document, Stream};
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
use texrra_tex_core::{
|
||||
native_font::NativeFontProgram,
|
||||
render::{DisplayItem, DisplayList},
|
||||
type1::Type1Font,
|
||||
};
|
||||
|
||||
#[derive(Default, PartialEq, Eq)]
|
||||
pub(super) struct PreviewFonts {
|
||||
programs: BTreeMap<String, Arc<Type1Font>>,
|
||||
missing: bool,
|
||||
conflict: Option<String>,
|
||||
}
|
||||
|
||||
impl PreviewFonts {
|
||||
pub(super) fn collect(pages: &[DisplayList]) -> Self {
|
||||
let mut fonts = Self::default();
|
||||
if pages.iter().any(DisplayList::has_embedded_pdf) {
|
||||
for page in pages {
|
||||
fonts.collect_from(page);
|
||||
}
|
||||
}
|
||||
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());
|
||||
}
|
||||
} else {
|
||||
self.programs.insert(device.name.clone(), program.clone());
|
||||
}
|
||||
} else {
|
||||
self.missing = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
for form in &page.forms {
|
||||
self.collect_from(&form.list);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn includes_device_fonts(&self) -> bool {
|
||||
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.
|
||||
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.is_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 descriptors: Vec<_> = 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)?))
|
||||
})
|
||||
.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 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);
|
||||
}
|
||||
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))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user