Share size-independent XDV Type 1 font dictionaries

This commit is contained in:
gloamxun committed 2026-11-28 11:19:57 +08:00
1 parent 01c6f1d4bd
commit e72104eab3
4 files changed
+147 -11

No files matched your search

+41 -7
View File
@@ -732,6 +732,7 @@ fn page_content(
cm_codes: &[Option<&BTreeMap<char, u8>>],
fallback_ids: &[usize; FACE_COUNT],
origin: PageOrigin,
xdv_font_aliases: &BTreeMap<crate::execution::FontId, crate::execution::FontId>,
opentype: &BTreeMap<crate::execution::FontId, Arc<opentype_fonts::EmbeddedFont>>,
font_opacities: &BTreeMap<u8, String>,
) -> Vec<u8> {
@@ -870,6 +871,7 @@ fn page_content(
*x,
*y,
font,
xdv_font_aliases.get(&font.id).copied().unwrap_or(font.id),
paint.as_ref().unwrap(),
*slot,
height,
@@ -2440,10 +2442,20 @@ fn write_pdf(
}
}
let xdv_font_aliases: BTreeMap<_, _> = {
let mut owners = HashMap::new();
native_used.iter().filter_map(|(&id, (_, paint, _))| {
paint.xdv_descriptor?;
let key = (paint.type1_program_key()?, paint.encoding_version());
let owner = *owners.entry(key).or_insert(id);
(owner != id).then_some((id, owner))
}).collect()
};
let mut aliases = BTreeMap::new();
let mut grouped_fonts = BTreeMap::new();
for (id, (face, paint, used)) in native_used {
let owner = pdf_font_owner(registry, id);
let owner = xdv_font_aliases.get(&id).copied()
.unwrap_or_else(|| pdf_font_owner(registry, id));
aliases.insert(id, owner);
let entry = grouped_fonts.entry(owner).or_insert_with(|| {
let face = if owner == id {
@@ -2454,10 +2466,29 @@ fn write_pdf(
};
(face, paint.clone(), BTreeMap::new())
});
if entry.1.encoding != paint.encoding
|| entry.1.type1_program_key() != paint.type1_program_key()
{
return Err("shared PDF font has inconsistent output encoding or program".into());
if !Arc::ptr_eq(&entry.1, &paint) {
if entry.1.encoding != paint.encoding
|| entry.1.type1_program_key() != paint.type1_program_key()
{
return Err("shared PDF font has inconsistent output encoding or program".into());
}
if xdv_font_aliases.contains_key(&id) {
// Separate map entries can resolve to the same physical
// program with disjoint sets of measured glyph widths.
for slot in used.keys() {
let width = *paint.xdv_widths.get(slot)
.ok_or("shared XDV Type 1 font is missing a glyph width")?;
match entry.1.xdv_widths.get(slot) {
Some(old) if *old != width => {
return Err("shared XDV Type 1 font has inconsistent glyph widths".into());
}
Some(_) => {}
None => {
Arc::make_mut(&mut entry.1).xdv_widths.insert(*slot, width);
}
}
}
}
}
entry.2.extend(used);
}
@@ -2893,7 +2924,9 @@ fn write_pdf(
fonts.push_str(&format!(" /M{} {id} 0 R", face.0));
}
let native_fonts: BTreeSet<_> = list.items.iter().filter_map(|item| match item {
DisplayItem::NativeGlyph { font, .. } => Some(font.id),
DisplayItem::NativeGlyph { font, .. } => {
Some(xdv_font_aliases.get(&font.id).copied().unwrap_or(font.id))
}
_ => None,
}).chain(list.pdf_space_plan.iter().filter_map(|plan| {
plan.dedicated.as_ref().map(|font| font.font.id)
@@ -2950,7 +2983,7 @@ fn write_pdf(
let font_opacities = remapped.as_ref().map_or(&no_font_opacity, |r| &r.font_opacities[slot]);
let content = page_content(
list, list.height, &names, faces, &cm_views,
&fallback_font_ids, PageOrigin::default(), &opentype, font_opacities,
&fallback_font_ids, PageOrigin::default(), &xdv_font_aliases, &opentype, font_opacities,
);
objects[device_objects[&form.form.number] as usize - 1] = objects::stream_bytes(
&entries, &content, list.pdf.as_ref().map_or(0, |pdf| pdf.stream_compression),
@@ -3128,6 +3161,7 @@ fn write_pdf(
&cm_views,
&fallback_font_ids,
origin,
&xdv_font_aliases,
&opentype,
font_opacities,
);
+7 -4
View File
@@ -29,6 +29,7 @@ impl NativeText {
x: i64,
y: i64,
font: &NativeFont,
resource: FontId,
paint: &crate::native_font::NativeFontPaint,
slot: u8,
height: i64,
@@ -66,10 +67,10 @@ impl NativeText {
}
if space == Some(SpaceUse::Dedicated) {
let dedicated = dedicated.expect("resolved PDF space font");
state.select_font(out, &dedicated.font);
state.select_font(out, &dedicated.font, dedicated.font.id);
out.push_str("( ) Tj\n");
}
state.select_font(out, font);
state.select_font(out, font, resource);
let expansion_changed = state.expansion != font.expansion;
if state.xdv && expansion_changed {
state.close_string(out);
@@ -139,7 +140,7 @@ impl NativeText {
state.delta_h += state.char_advance(font, paint, slot, state.effective_size);
}
fn select_font(&mut self, out: &mut PageContent, font: &NativeFont) {
fn select_font(&mut self, out: &mut PageContent, font: &NativeFont, resource: FontId) {
if self.font != Some(font.id) {
self.close_string(out);
let (number, size) = divide_scaled(font.size_sp(), 6_578_176, 6);
@@ -148,7 +149,7 @@ impl NativeText {
if !out.measuring {
out.push_str(&format!(
"/N{} {} Tf\n",
font.id.index(),
resource.index(),
print_decimal(number, 4)
));
}
@@ -239,6 +240,7 @@ impl NativeText {
x,
y,
&dedicated.font,
dedicated.font.id,
&dedicated.paint,
b' ',
height,
@@ -425,6 +427,7 @@ pub(crate) fn plan_spaces(
*x,
*y,
font,
font.id,
paint,
*slot,
page.height,
+30
View File
@@ -819,6 +819,36 @@ letterspace-fresh.log 和 device-pdftex-spaced-moved.log。
[原版字距虚拟字体构造](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L16400-L16492)
[原版格式所写字体字段](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L30627-L30696)
### XeTeX 传统字体跨字号共享
XDV 的传统 Type 1 字体按物理程序及实际编码共享 PDF 字典与子集。
原生使用程序资源版本、字体变换和编码资源版本合并,合计各实例实际
绘制的槽位,再生成完整的共用字幅、编码与 ToUnicode。每个 TeX
字体编号仍驱动自己的字号和排版度量。页面及 Form 上的文字命令与
资源字典使用相同的归并后名称。
[参考驱动的普通字体查找与别名](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/dvipdfm-x/pdffont.c#L959-L994)
两页 CMR10 用例将两个字号的嵌入资源从两份合为一份,与参考
一致。PDF 从 3,536 字节降为 2,795 字节。另一两页用例显式
重编码部分字符,两端均生成内建编码和自定义编码各一份资源。
两组共四页的词框和 144 DPI 光栅均一致。
原样 xeCJK-example-boundary-register.tex 的一页、380 个词框、
8 份字体资源、40 条出页警告、灰度光栅及 aux 均与参考一致。
12 项定向测试通过。新测试实际检查跨页资源引用同一字典、不同
字号的选字体命令、合并后的字幅及独立重编码字典。
三页项目用两个字号共用一个子集。只改第 2 页字符的修订复用
1,048 步、重放四次宿主调用,仅更新第 2 页。下一修订用同一
路径交付另一份实际字体程序,复用 1,546 步的 TeX 执行,并在
字体解析与出页阶段读取新版本、刷新三个用字页。PDF、页面度量、
SVG、来源映射及 aux 与同版本独立全量一致。三份 PDF 各有
一份 Type 1C。独立光栅对照核验了应变化和应复用的页面。
证据在 target/p3-xdv-simple-font-sharing。receipt.json 的
SHA-256 为 a4e481755e4e44f071a53cf1052b5b1d5fb1d9dc2aa5ac36e42e7dae98f4d3da,
revision.log 为 fc312b20c14484b95fbdbc55383511f2dd01c34af09d4fb4a11686dcebdcdc13。
### XeTeX 的传统 Type 1 字体子集
按 XDV 参考驱动从实际 Type 1 字形选择构建 Type 1C 字体。复用
+69
View File
@@ -793,6 +793,75 @@ fn xetex_type1_widths_follow_the_encoded_glyph_program() {
fs::remove_dir_all(root).unwrap();
}
#[test]
fn xetex_type1_shares_the_font_dictionary_across_sizes_and_pages() {
use lopdf::{Document, content::Content};
use texrra_tex_core::execution::InputProfile;
let root = directory("xetex-type1-shared-face");
let mut job = request(&root);
job.input_profile = InputProfile::XeTeX;
for kind in [ResourceKind::Encoding, ResourceKind::Map, ResourceKind::Tfm] {
job.world.paths.entry(kind).or_default().insert(
0, SearchPath::directory(root.clone(), false),
);
}
fs::write(
root.join("recoded.tfm"),
include_bytes!("../crates/texrra-tex-core/assets/cmr10.tfm"),
)
.unwrap();
let mut glyphs = [".notdef"; 256];
glyphs[b'A' as usize] = "V";
let encoding = format!("/ProbeVector [{}] def\n", glyphs.map(|glyph| format!("/{glyph}")).join(" "));
fs::write(root.join("probe.enc"), encoding).unwrap();
fs::write(
root.join("pdftex.map"),
"cmr10 CMR10 <cmr10.pfb\nrecoded CMR10 \"ProbeVector ReEncodeFont\" <probe.enc <cmr10.pfb\n",
)
.unwrap();
fs::write(
root.join("main.tex"),
br"\catcode123=1 \catcode125=2
\font\small=cmr10 at 10pt
\font\large=cmr10 at 14pt
\font\recoded=recoded
\shipout\hbox{\small A\kern5pt\large W}
\shipout\hbox{\large M\kern5pt\recoded A}
\end",
)
.unwrap();
let result = NativeCompiler::default().compile(job).unwrap();
let pdf = Document::load_mem(result.pdf.as_deref().unwrap()).unwrap();
let pages = pdf.get_pages();
let content = Content::decode(&pdf.get_page_content(pages[&1]).unwrap()).unwrap();
let selections: Vec<_> = content
.operations
.iter()
.filter(|op| op.operator == "Tf")
.map(|op| (op.operands[0].as_name().unwrap(), op.operands[1].as_f64().unwrap()))
.collect();
assert_eq!(selections.len(), 2);
assert_eq!(selections[0].0, selections[1].0);
assert_ne!(selections[0].1, selections[1].1);
let first = pdf.get_page_fonts(pages[&1]);
let second = pdf.get_page_fonts(pages[&2]);
assert_eq!(first.len(), 1);
assert_eq!(second.len(), 2);
let shared = first[selections[0].0];
assert!(std::ptr::eq(shared, second[selections[0].0]));
assert!(shared.get(b"Encoding").is_err());
assert!(second.values().any(|font| font.get(b"Encoding").is_ok()));
let first = shared.get(b"FirstChar").unwrap().as_i64().unwrap();
let widths = shared.get(b"Widths").unwrap().as_array().unwrap();
for slot in [b'A', b'M', b'W'] {
assert!(widths[(i64::from(slot) - first) as usize].as_f64().unwrap() > 0.);
}
fs::remove_dir_all(root).unwrap();
}
#[test]
fn xetex_opentype_font_switch_uses_the_current_text_line_origin() {
use lopdf::{Document, content::Content};