Share XeTeX PDF font resources across compatible instances

This commit is contained in:
gloamxun committed 2026-11-28 10:39:52 +08:00
1 parent a864c6c5ca
commit 4ae4275cf3
5 files changed
+179 -18

No files matched your search

+5 -1
View File
@@ -492,8 +492,12 @@ impl OpenTypeFont {
]
}
pub(crate) fn device_embolden(&self) -> i64 {
self.request.embolden_sp(self.size)
}
pub(crate) fn paint_embolden(&self) -> f64 {
let width = self.request.embolden_sp(self.size).max(0) as f64 / 65536.;
let width = self.device_embolden().max(0) as f64 / 65536.;
// The XDV PDF device writes the line width to six decimal places.
(width * 1_000_000.).round() / 1_000_000.
}
+8 -5
View File
@@ -6,7 +6,7 @@
use std::collections::BTreeSet;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::io::Write as _;
use std::sync::OnceLock;
use std::sync::{Arc, OnceLock};
use flate2::Compression;
use flate2::write::ZlibEncoder;
@@ -732,7 +732,7 @@ fn page_content(
cm_codes: &[Option<&BTreeMap<char, u8>>],
fallback_ids: &[usize; FACE_COUNT],
origin: PageOrigin,
opentype: &BTreeMap<crate::execution::FontId, opentype_fonts::EmbeddedFont>,
opentype: &BTreeMap<crate::execution::FontId, Arc<opentype_fonts::EmbeddedFont>>,
font_opacities: &BTreeMap<u8, String>,
) -> Vec<u8> {
let digits = list.pdf.as_ref().map_or(3, |p| p.file.decimal_digits);
@@ -2883,11 +2883,14 @@ fn write_pdf(
}
if !opentype.is_empty() {
let open_fonts: BTreeSet<_> = list.items.iter().filter_map(|item| match item {
DisplayItem::OpenTypeGlyph { font, .. } => Some(font.id),
DisplayItem::OpenTypeGlyph { font, .. } => {
let resource = &opentype[&font.id];
Some((resource.resource, resource.object))
}
_ => None,
}).collect();
for id in open_fonts {
fonts.push_str(&format!(" /U{} {} 0 R", id.index(), opentype[&id].object));
for (id, object) in open_fonts {
fonts.push_str(&format!(" /U{} {object} 0 R", id.index()));
}
}
fonts
+50 -12
View File
@@ -12,11 +12,16 @@ use read_fonts::{
};
use rustybuzz::ttf_parser::{Face, GlyphId, RawFace, Tag};
use sha2::{Digest, Sha256};
use std::{collections::BTreeMap, fmt::Write};
use std::{
collections::{BTreeMap, HashMap},
fmt::Write,
sync::Arc,
};
use subsetter::GlyphRemapper;
pub(super) struct EmbeddedFont {
pub object: usize,
pub resource: FontId,
glyphs: BTreeMap<u16, EmbeddedGlyph>,
units: u16,
}
@@ -64,12 +69,13 @@ impl TextRun {
&mut self,
output: &mut PageContent,
font: FontId,
resource: FontId,
size: i64,
bp_per_unit: f64,
embolden: f64,
) {
let size_bp = size as f64 * bp_per_unit;
output.push_str(&format!("/U{} {size_bp:.4} Tf ", font.index()));
output.push_str(&format!("/U{} {size_bp:.4} Tf ", resource.index()));
if embolden > 0. {
output.push_str(&format!("2 Tr {embolden:.6} w "));
} else if self.emboldened {
@@ -126,6 +132,12 @@ fn place_absolute(
#[derive(Default)]
pub(super) struct UsedFonts<'a>(BTreeMap<FontId, (&'a OpenTypeFont, BTreeMap<u16, &'a str>)>);
struct FontUse<'a> {
font: &'a OpenTypeFont,
glyphs: BTreeMap<u16, &'a str>,
instances: Vec<FontId>,
}
impl<'a> UsedFonts<'a> {
pub(super) fn observe(
&mut self,
@@ -152,13 +164,38 @@ impl<'a> UsedFonts<'a> {
objects: &mut Vec<Vec<u8>>,
compression: u8,
options: Option<crate::pdf_unicode::PdfFinalOptions<'_>>,
) -> Result<BTreeMap<FontId, EmbeddedFont>, String> {
self.0
.into_iter()
.map(|(id, (font, glyphs))| {
write_font(objects, font, glyphs, compression, options).map(|face| (id, face))
})
.collect()
) -> Result<BTreeMap<FontId, Arc<EmbeddedFont>>, String> {
let xdv = options.is_some_and(|options| options.xdv_font_unicode);
let mut groups: Vec<FontUse<'a>> = Vec::new();
let mut resources = HashMap::new();
for (id, (font, glyphs)) in self.0 {
if xdv {
let raw = RawFace::parse(&font.resource.data, font.face_index())
.map_err(|error| format!("invalid OpenType font {}: {error}", font.name))?;
// The XDV TrueType font-map key includes device transforms.
// CFF aliases of the same physical face can share the Type0 font.
let transforms = raw.table(Tag::from_bytes(b"CFF ")).is_none().then(|| (
font.device_transform().map(f64::to_bits),
font.device_embolden(),
));
let key = (&font.resource.version, font.face_index(), font.is_vertical(), transforms);
let index = *resources.entry(key).or_insert(groups.len());
if let Some(group) = groups.get_mut(index) {
// XDV's ToUnicode comes from the physical glyph, so this
// union is independent of shaping features or cluster text.
group.glyphs.extend(glyphs);
group.instances.push(id);
continue;
}
}
groups.push(FontUse { font, glyphs, instances: vec![id] });
}
let mut embedded = BTreeMap::new();
for group in groups {
let output = Arc::new(write_font(objects, group.font, group.glyphs, compression, options)?);
embedded.extend(group.instances.into_iter().map(|id| (id, output.clone())));
}
Ok(embedded)
}
}
@@ -458,7 +495,7 @@ fn write_font(
|| "/Registry (Adobe) /Ordering (Identity) /Supplement 0".to_owned(),
CidCff::system_info,
);
let type0_name = if cid_cff.is_some() || (vertical && cff.is_some()) {
let type0_name = if cff.is_some() && (xdv.is_some() || vertical) {
format!("{name}-{encoding}")
} else {
name.clone()
@@ -476,6 +513,7 @@ fn write_font(
}
Ok(EmbeddedFont {
object,
resource: font.id,
glyphs: embedded,
units: face.units_per_em(),
})
@@ -619,7 +657,7 @@ impl EmbeddedFont {
// Selecting a font ends the string but retains the text
// line matrix. Recompute Tm only when its shape changes.
output.push_str(">] TJ ");
run.select_font(output, font.id, size, bp_per_unit, embolden);
run.select_font(output, font.id, self.resource, size, bp_per_unit, embolden);
if relative && state.matrix == (device, vertical) {
run.place_line(output, [x, y], device, vertical, bp_per_unit);
} else {
@@ -661,7 +699,7 @@ impl EmbeddedFont {
offset: 0,
emboldened: false,
};
run.select_font(output, font.id, size, bp_per_unit, embolden);
run.select_font(output, font.id, self.resource, size, bp_per_unit, embolden);
if start_relative {
// At a new text object the XDV device reuses the font
// matrix at the page origin, then positions the first line.