Write XeTeX PDF font descriptors from OS/2 and CFF data

This commit is contained in:
gloamxun committed 2026-11-25 22:15:06 +08:00
1 parent 2b82172bfb
commit fa27e0985f
5 files changed
+125 -16

No files matched your search

Generated
+1
View File
@@ -1536,6 +1536,7 @@ dependencies = [
"lopdf",
"md5",
"png 0.18.1",
"read-fonts",
"rusttype",
"rustybuzz",
"serde",
+1
View File
@@ -13,6 +13,7 @@ libloading = "=0.8.9"
md5 = "0.8"
png = "0.18.1"
rusttype = "0.8.3"
read-fonts = { version = "=0.46.0", default-features = false }
rustybuzz = "=0.20.1"
subsetter = { version = "=0.2.3", default-features = false }
unicode-bidi = "=0.3.18"
+83 -16
View File
@@ -1,7 +1,11 @@
//! Embedding for glyphs selected by the native OpenType shaper.
use super::{PageContent, native_pdf_name, objects, to_unicode_map};
use crate::{execution::FontId, opentype::OpenTypeFont};
use rustybuzz::ttf_parser::{GlyphId, RawFace, Tag};
use read_fonts::{
FontData, FontRead,
ps::cff::{dict, v1::Cff},
};
use rustybuzz::ttf_parser::{Face, GlyphId, RawFace, Tag};
use sha2::{Digest, Sha256};
use std::{collections::BTreeMap, fmt::Write};
use subsetter::GlyphRemapper;
@@ -149,21 +153,7 @@ fn write_font(
objects.push(format!(
"<< /Type /Font /Subtype /{subtype} /BaseFont /{name} /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor {descriptor} 0 R /W [{widths}]{mapping} >>"
).into_bytes());
let rect = face.global_bounding_box();
let [left, bottom, right, top] =
[rect.x_min, rect.y_min, rect.x_max, rect.y_max].map(|v| width(i64::from(v)));
let ascent = width(i64::from(face.tables().hhea.ascender));
let descent = width(i64::from(face.tables().hhea.descender));
let cap = face
.capital_height()
.map_or(ascent, |n| width(i64::from(n)));
let flags = 4 | i32::from(face.is_monospaced()) | if face.is_italic() { 64 } else { 0 };
let angle = face.italic_angle();
let stem = f64::from(face.weight().to_number()) / 65.;
let stem = (50. + stem * stem).round() as i32;
objects.push(format!(
"<< /Type /FontDescriptor /FontName /{name} /Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /StemV {stem} /{file_key} {font_file} 0 R >>"
).into_bytes());
objects.push(font_descriptor(&face, &name, file_key, font_file));
objects.push(objects::stream(&file_options, program, compression));
objects.push(objects::stream("", &to_unicode_map(&cmap, 4), compression));
Ok(EmbeddedFont {
@@ -173,6 +163,83 @@ fn write_font(
})
}
fn font_descriptor(face: &Face<'_>, name: &str, file_key: &str, font_file: usize) -> Vec<u8> {
// XDV uses the OS/2 typographic values for PDF metadata independently
// of the metrics selected by the layout engine.
let os2 = face
.raw_face()
.table(Tag::from_bytes(b"OS/2"))
.filter(|table| table.len() >= 68);
let field = |offset| {
let bytes = os2?.get(offset..offset + 2)?;
Some(u16::from_be_bytes([bytes[0], bytes[1]]))
};
let pdf_units = |value: i16| {
(1000. * f64::from(value) / f64::from(face.units_per_em()) + 0.5).floor() as i32
};
let rect = face.global_bounding_box();
let [left, bottom, right, top] =
[rect.x_min, rect.y_min, rect.x_max, rect.y_max].map(pdf_units);
let ascent = pdf_units(field(68).map_or(880, |number| number as i16));
let descent = pdf_units(field(70).map_or(-120, |number| number as i16));
let (cap, x_height) = if field(0) == Some(2) {
let cap = field(88).map_or(ascent, |number| pdf_units(number as i16));
let x_height = field(86).map(|number| pdf_units(number as i16));
(cap, x_height)
} else {
(ascent, None)
};
let average_width = field(2).unwrap_or(0) as i16;
let weight = f64::from(field(4).unwrap_or(400)) / 65.;
let stem = cff_stem_width(face).unwrap_or_else(|| (weight * weight + 50.).trunc());
let selection = field(62).unwrap_or(0);
let family = field(30).unwrap_or(0) >> 8;
let flags = 4
| i32::from(face.is_monospaced())
| (i32::from(family != 8) << 1)
| (i32::from(family == 10) << 3)
| (i32::from(selection & 1 != 0) << 6)
| (i32::from(selection & (1 << 5) != 0) << 18);
let angle = face.italic_angle();
let mut descriptor = format!(
"<< /Type /FontDescriptor /FontName /{name} /Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /StemV {stem}"
);
if let Some(height) = x_height {
write!(descriptor, " /XHeight {height}").unwrap();
}
if average_width != 0 {
write!(descriptor, " /AvgWidth {}", pdf_units(average_width)).unwrap();
}
descriptor.push_str(" /Style << /Panose <");
for byte in os2.map_or(&[0; 12][..], |table| &table[30..42]) {
write!(descriptor, "{byte:02X}").unwrap();
}
write!(descriptor, "> >> /{file_key} {font_file} 0 R >>").unwrap();
descriptor.into_bytes()
}
fn cff_stem_width(face: &Face<'_>) -> Option<f64> {
let data = face.raw_face().table(Tag::from_bytes(b"CFF "))?;
let cff = Cff::read(FontData::new(data)).ok()?;
let top_dict = cff.top_dicts().get(0)?;
let mut private_dict = None;
for entry in dict::entries(top_dict, None).flatten() {
match entry {
dict::Entry::Ros { .. } => return None,
dict::Entry::PrivateDictRange(range) => private_dict = Some(range),
_ => {}
}
}
let private_dict = data.get(private_dict?)?;
dict::entries(private_dict, None).flatten().find_map(|entry| {
if let dict::Entry::StdVw(width) = entry {
Some(width.to_f64())
} else {
None
}
})
}
fn utf16_hex(value: &str) -> String {
value
.encode_utf16()
+32
View File
@@ -2175,6 +2175,38 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。
全量编译一致。incremental-receipt.json 的 SHA-256 为
bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。
### XeTeX OpenType 的 PDF 字体描述符
原生 PDF 取实际 OS/2 排版度量生成描述符,并按 xdvipdfmx 的规则
应用千分单位舍入、版本 2 的 CapHeight/XHeight、平均字宽、Flags 和
PANOSE。缺 OS/2 时采用同样的默认值。普通 CFF 的 StemV 从实际
Private DICT 的 StdVW 读取,其他情况使用字体权重计算。这里的
度量保留 PDF 导出的语义,盒子和断行继续使用原有的排版度量。
[XDV 字体描述符规则](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/dvipdfm-x/tt_aux.c#L196-L270)
[CFF 私有字典的 StemV](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/dvipdfm-x/cidtype0.c#L1228-L1236)
七份同源用例的描述符字段、字形编号和原始坐标完全一致。覆盖实际
CFF 和 TrueType、等宽与斜体,以及同源字体的 OS/2 版本 2、缺表和
负数半值舍入。12 项已有 XeTeX 定向测试通过。三页项目两次替换
同名字体的描述符度量,PDF Ascent 976 → 1044 → 976。每次复用 66 步,
只重发含该字体的第二页,虽然 SVG 字节相同。PDF、SVG 与来源映射
均与独立全量一致。
回执 `target/p3-xetex-pdf-descriptors/receipt.json` 的 SHA-256 为
`9860a784868d1adfd00fbc9c418c8a6236c41528736b9342f0e0678edf873631`。
原样 ACL 的六种 OpenType 字体校对字段逐项一致,原始布局清单与前版
逐字节一致。首行 8 个词框的最大偏差从 4.633823 bp 降为 0。
119 个参考词中 106 个可顺序配对,前版为 101 个。`.aux`、`.out`
与 `.bbl` 仍与参考逐字节一致,整页版面仍有差异。
原始坐标的首处差异位于摘要正文的词间距。同一 TeXGyreTermesX 源和
字体的四页最小样例里,普通词、预容差轮及实际选中断点三页一致。
第二页进入容差轮,`pro-vides` 的断点存在但未被选中。原生少了
装箱时对原词的重塑形,`v` 及后续字形偏移 22938 sp。下一步按
参考装箱过程合并未使用断点两侧的原生词段,保留断行搜索的实测词段。
证据在 `target/p3-xetex-unbroken-word/selected-comparison.json`。
[XeTeX 装箱时合并词段](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/web2c/xetexdir/xetex.web#L30044-L30118)
### XeTeX OpenType 字体的垂直度量
OpenType 字体加载按同一字面数据选择 ascent 和 descent。置位
+8
View File
@@ -758,6 +758,14 @@ XDV 链接注释接入后,沿原样 ACL 的第二轮辅助文件和 BibTeX
`target/p3-xdv-annotation/receipt.json`。
[链接注释阶段记录](P2_M1_PROGRESS.md#xdv-链接注释与实际矩形)
#### PDF OpenType 字体描述符复编
同一 schema71 和原样 ACL 的一页 PDF 完成复编。六种 OpenType 字体
的描述符字段与参考逐项一致,首行八个词框最大偏差从 4.633823 bp
降为 0。原始布局清单、`.aux`、`.out` 与 `.bbl` 保持相同指纹。
正文仍有词间距与字形位置差异,整页版面门禁保持未通过。
回执 `target/p3-xetex-pdf-descriptors/receipt.json`。
#### OpenType 垂直度量复编
原样 ACL 的 schema71、十份源文件和 BibTeX 产物继续按原指纹复编。