Render imported PDF TrueType device fonts from exact SFNT faces

This commit is contained in:
gloamxun committed 2026-11-28 04:21:30 +08:00
1 parent b640b26eff
commit 84d6f3ae51
14 files changed
+504 -76

No files matched your search

+10
View File
@@ -156,6 +156,16 @@ impl SourceProvider for RecordingHost<'_> {
})).map_err(Clone::clone)
})
}
fn pdf_truetype(
&mut self, name: &str, from: &str,
) -> Result<Option<texrra_tex_core::resources::NamedFont>, String> {
let (name, from) = (name.to_owned(), from.to_owned());
call!(self, pdf_truetype(&name, &from); |result| {
result.as_ref().map(|result| result.as_ref().map(|font| {
(font.resource.version.clone(), font.index, font.full_name.clone())
})).map_err(Clone::clone)
})
}
fn optional_font_file(&mut self, kind: ResourceKind, name: &str, from: &str) -> Result<Option<LoadedResource>, String> {
let (name, from) = (name.to_owned(), from.to_owned());
call!(self, optional_font_file(kind, &name, &from); |result| {
+9
View File
@@ -1676,6 +1676,15 @@ impl SourceProvider for Files {
}
Ok(selected)
}
fn pdf_truetype(
&mut self, name: &str, from: &str,
) -> Result<Option<texrra_tex_core::resources::NamedFont>, String> {
let selected = self.world.read_pdf_truetype(name, Path::new(from))?;
if let Some(font) = &selected {
self.observe_resource(ResourceKind::TrueType, &font.resource);
}
Ok(selected)
}
fn optional_font_file(&mut self, kind: ResourceKind, name: &str, from: &str) -> Result<Option<LoadedResource>, String> {
let resource = self.world.read_optional(kind, name, Path::new(from))?;
if let Some(resource) = &resource {
+96 -37
View File
@@ -15,7 +15,8 @@ mod overlay;
#[derive(Default, PartialEq, Eq)]
pub(crate) struct PreviewFonts {
programs: BTreeMap<String, Arc<Type1Font>>,
type1: BTreeMap<String, Arc<Type1Font>>,
truetype: BTreeMap<String, Arc<[u8]>>,
missing: bool,
conflict: Option<String>,
}
@@ -37,7 +38,8 @@ impl PreviewFonts {
.collect();
let mut pending: Vec<_> = pages.iter().collect();
let mut visited = BTreeSet::new();
let mut required: BTreeSet<(&Path, &str)> = BTreeSet::new();
let mut required_type1: BTreeSet<(&Path, &str)> = BTreeSet::new();
let mut required_truetype = BTreeSet::new();
while let Some(list) = pending.pop() {
for item in &list.items {
match item {
@@ -45,17 +47,29 @@ impl PreviewFonts {
paint: Some(paint), ..
} => {
if let NativeFontProgram::DeviceType1(device) = &paint.program {
fonts.record(&device.name, device.preview_program.as_ref());
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.extend(
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())),
);
}
DisplayItem::PdfForm { form, .. } => {
if visited.insert(form.number)
@@ -68,29 +82,32 @@ impl PreviewFonts {
}
}
}
for (from, name) in required {
for (from, name) in required_type1 {
let program = cache.pdf_device_type1(files, name, &from.to_string_lossy())?;
fonts.record(name, program.as_ref());
record(
&mut fonts.type1,
&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(),
);
}
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());
}
}
pub(super) fn includes_device_fonts(&self) -> bool {
self.missing || !self.programs.is_empty()
self.missing || !self.type1.is_empty() || !self.truetype.is_empty()
}
/// Attach the captured programs to a private copy for PDF-backed previews.
@@ -100,7 +117,7 @@ impl PreviewFonts {
"conflicting actual fonts for PDF preview device name {name}"
));
}
if self.programs.is_empty() {
if self.type1.is_empty() && self.truetype.is_empty() {
return Ok(None);
}
let mut document = Document::load_mem(pdf)
@@ -123,8 +140,8 @@ impl PreviewFonts {
})
.collect();
let prior_max_id = document.max_id;
let programs = self
.programs
let type1 = self
.type1
.iter()
.map(|(name, program)| {
let mut dictionary = Dictionary::new();
@@ -135,10 +152,21 @@ impl PreviewFonts {
(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 attachment = Attachment {
names,
descriptors,
programs,
type1,
truetype,
};
let mut attached = false;
let changes: Vec<_> = document
@@ -162,10 +190,31 @@ impl PreviewFonts {
}
}
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>,
programs: BTreeMap<&'a [u8], (&'a Arc<Type1Font>, ObjectId)>,
type1: BTreeMap<&'a [u8], (&'a Arc<Type1Font>, ObjectId)>,
truetype: BTreeMap<&'a [u8], ObjectId>,
}
impl Attachment<'_> {
@@ -197,13 +246,24 @@ impl Attachment<'_> {
_ => 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 {
let Some(base) = name(b"BaseFont") else {
return false;
};
let (file_key, stream, bbox) = match name(b"Subtype") {
Some(b"Type1") => {
let Some((program, stream)) = self.type1.get(base) else {
return false;
};
("FontFile", stream, Some(program.bbox))
}
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)) => {
@@ -215,11 +275,10 @@ impl Attachment<'_> {
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.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,
@@ -230,7 +289,7 @@ impl Attachment<'_> {
{
return false;
}
descriptor.set("FontFile", *stream);
descriptor.set(file_key, *stream);
font.set("FontDescriptor", descriptor);
true
}