Match XDV PDF text cursor and Type 1 descriptor metrics

This commit is contained in:
gloamxun committed 2026-11-26 13:49:41 +08:00
1 parent eb0afccc03
commit bd840df538
7 files changed
+144 -19

No files matched your search

+17 -6
View File
@@ -6,11 +6,11 @@ use crate::{
resources::{LoadedResource, ResourceVersion},
tfm::TfmMetrics,
type1::{Type1Font, Type1Transform},
type1_outline::Type1Outlines,
type1_outline::{Type1Outlines, XdvDescriptor},
};
use std::{
collections::{BTreeMap, VecDeque},
sync::{Arc, Mutex},
sync::{Arc, Mutex, OnceLock},
};
mod map;
mod virtual_paint;
@@ -25,6 +25,8 @@ pub struct NativeFontPaint {
pub glyph_paths: BTreeMap<u8, String>,
pub bbox: [i32; 4],
pub stem_v: i32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) xdv_descriptor: Option<XdvDescriptor>,
pub resources: Vec<crate::resources::ResourceVersion>,
#[serde(default, skip_serializing_if = "Option::is_none")]
program_index: Option<usize>,
@@ -200,6 +202,7 @@ struct DecodedType1 {
outlines: Type1Outlines,
bbox: [i32; 4],
stem_v: i32,
xdv_descriptor: OnceLock<Result<XdvDescriptor, String>>,
}
impl DecodedType1 {
@@ -223,6 +226,7 @@ impl DecodedType1 {
outlines,
bbox,
stem_v,
xdv_descriptor: OnceLock::new(),
})
}
}
@@ -363,10 +367,9 @@ fn resolve_physical_fonts(
.or_else(|| default_map.as_ref().map(|map| &map.version));
let mut resolved = BTreeMap::new();
let mut pk_resolved = BTreeMap::new();
let device = pages
.iter()
.find_map(|p| p.pdf.as_ref())
.map(|p| p.file.clone());
let device = pages.iter().find_map(|page| page.pdf.as_ref());
let xdv = device.is_some_and(|pdf| pdf.driver == crate::pdf_device::PdfDriver::Xdv);
let device = device.map(|pdf| pdf.file.clone());
let mut cache: BTreeMap<_, (NativeFontPaint, Arc<DecodedType1>)> = BTreeMap::new();
for (id, (font, slots, expanded)) in used {
let entry = if font.pdf_space_font && font.name == "pdftexspace" {
@@ -437,6 +440,7 @@ fn resolve_physical_fonts(
glyph_paths,
bbox: bbox.unwrap(),
stem_v: 0,
xdv_descriptor: None,
resources: entry.as_ref().and_then(|entry| entry.version.as_ref())
.or(default_version).cloned().into_iter()
.chain(std::iter::once(resource.version)).collect(),
@@ -486,6 +490,13 @@ fn resolve_physical_fonts(
glyph_paths: BTreeMap::new(),
bbox: decoded.bbox,
stem_v: decoded.stem_v,
xdv_descriptor: if xdv {
Some(decoded.xdv_descriptor.get_or_init(|| {
decoded.outlines.xdv_descriptor(program.bbox)
}).clone()?)
} else {
None
},
resources,
program_index,
},
+15 -3
View File
@@ -743,6 +743,7 @@ fn page_content(
let mut opentype_text = opentype_fonts::TextState::default();
let bp_per_unit = list.units.bp(1);
let one_inch = (72_000. / (bp_per_unit * f64::from(list.magnification))).round() as i64;
let xdv = list.pdf.as_ref().is_some_and(|pdf| pdf.driver == PdfDriver::Xdv);
for (index, item) in list.items.iter().enumerate() {
if !matches!(item, DisplayItem::OpenTypeGlyph { .. }) {
opentype_text.finish(&mut content);
@@ -822,6 +823,7 @@ fn page_content(
paint.as_ref().unwrap(),
*slot,
height,
xdv.then_some(one_inch),
digits,
list.pdf_space_plan.as_ref().and_then(|plan| plan.before_glyph.get(&index)).copied(),
list.pdf_space_plan.as_ref().and_then(|plan| plan.dedicated.as_ref()),
@@ -879,7 +881,7 @@ fn page_content(
opentype[&font.id].paint(
&mut opentype_text, &mut content, font, *glyph, text,
*size, *x - h, height - *y - v, bp_per_unit,
[one_inch - h, height - one_inch - v], !font_opacities.is_empty(),
[one_inch - h, height - one_inch - v], xdv, !font_opacities.is_empty(),
);
}
DisplayItem::NativeGlyph {
@@ -1678,8 +1680,18 @@ fn write_native_type1_descriptor(
} else {
font.italic_angle.parse::<f64>().unwrap_or(0.).round().to_string()
};
let stem_v = paint.stem_v;
objects.push(format!("<< /Type /FontDescriptor /FontName /{name} /Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /XHeight {x_height} /StemV {stem_v} /FontFile {program} 0 R >>").into_bytes());
let descriptor_bytes = if let Some(xdv) = paint.xdv_descriptor {
let [left, bottom, right, top] = font.bbox;
let [ascent, descent, cap, stem_v] = xdv.metrics();
let flags = flags | (i32::from(!font.name.contains("Sans")) << 1)
| (i32::from(font.name.contains("Caps")) << 17)
| (i32::from(xdv.force_bold) << 18);
format!("<< /Type /FontDescriptor /FontName /{name} /Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /StemV {stem_v} /FontFile {program} 0 R >>")
} else {
let stem_v = paint.stem_v;
format!("<< /Type /FontDescriptor /FontName /{name} /Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /XHeight {x_height} /StemV {stem_v} /FontFile {program} 0 R >>")
};
objects.push(descriptor_bytes.into_bytes());
objects.push(objects::stream(
&format!(
"/Length1 {} /Length2 {} /Length3 {}",
+15 -8
View File
@@ -337,6 +337,7 @@ impl EmbeddedFont {
y: i64,
bp_per_unit: f64,
page_origin: [i64; 2],
xdv: bool,
font_colors: bool,
) {
let glyph = &self.glyphs[&glyph];
@@ -344,7 +345,7 @@ impl EmbeddedFont {
let device = font.device_transform();
let embolden = font.paint_embolden();
let emboldened = embolden > 0.;
let relative = (device[1] != 0. || emboldened || font_colors) && device[0] != 0.;
let relative = (xdv || device[1] != 0. || emboldened || font_colors) && device[0] != 0.;
let horizontal_em = size as f64 * if relative { device[0] } else { horizontal_scale };
let override_text = glyph
.cluster_text
@@ -375,7 +376,7 @@ impl EmbeddedFont {
begin_actual_text(output, text, false);
}
let first = state.run.is_none();
let start_relative = first && (emboldened || font_colors) && relative && state.matrix == device;
let start_relative = first && (xdv || emboldened || font_colors) && relative && state.matrix == device;
state.matrix = device;
let run = state.run.get_or_insert_with(|| {
let size_bp = size as f64 * bp_per_unit;
@@ -400,14 +401,20 @@ impl EmbeddedFont {
run.start = page_origin;
run.place_line(output, [x, y], device, bp_per_unit);
} else {
let coordinates = [x, y].map(|coordinate| rounded_coordinate(coordinate, bp_per_unit));
let origin = if xdv { page_origin } else { [0, 0] };
let [tx, ty] = std::array::from_fn(|axis| {
let value = [x, y][axis];
let (delta, error) = rounded_coordinate(value - origin[axis], bp_per_unit);
(rounded_coordinate(origin[axis], bp_per_unit).0 + delta, error)
});
output.push_str(&format!(
"{horizontal_scale} 0 {slant} 1 {:.3} {:.3} Tm [<",
coordinates[0].0, coordinates[1].0,
"{horizontal_scale} 0 {slant} 1 {:.3} {:.3} Tm [<", tx.0, ty.0,
));
if !relative {
run.start = [x - coordinates[0].1, y - coordinates[1].1];
run.offset = coordinates[0].1;
if xdv || !relative {
run.start = [x - tx.1, y - ty.1];
}
if !xdv && !relative {
run.offset = tx.1;
}
}
run
+12 -2
View File
@@ -31,6 +31,7 @@ impl NativeText {
paint: &crate::native_font::NativeFontPaint,
slot: u8,
height: i64,
xdv_origin: Option<i64>,
digits: u8,
space: Option<SpaceUse>,
dedicated: Option<&ResolvedSpaceFont>,
@@ -38,12 +39,19 @@ impl NativeText {
let first = text.is_none();
let state = text.get_or_insert_with(|| {
out.push_str("BT\n");
if let Some(origin) = xdv_origin {
out.push_str(&format!(
"1 0 0 1 {} {} Tm\n",
print_sp(origin, digits),
print_sp(height - origin, digits),
));
}
Self {
font: None,
effective_size: 0,
expansion: 0,
v: height,
start_h: 0,
v: xdv_origin.unwrap_or(height),
start_h: xdv_origin.unwrap_or(0),
delta_h: 0,
opened: false,
}
@@ -187,6 +195,7 @@ impl NativeText {
&dedicated.paint,
b' ',
height,
None,
digits,
None,
None,
@@ -375,6 +384,7 @@ pub(crate) fn plan_spaces(
paint,
*slot,
page.height,
None,
digits,
space,
plan.dedicated.as_ref(),
@@ -125,12 +125,25 @@ impl<'a> Tokens<'a> {
Ok(bytes)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(crate) struct XdvDescriptor {
metrics: [u64; 4],
pub(crate) force_bold: bool,
}
impl XdvDescriptor {
pub(crate) fn metrics(self) -> [f64; 4] {
self.metrics.map(f64::from_bits)
}
}
#[derive(Clone, Debug)]
pub struct Type1Outlines {
subrs: Vec<Option<Vec<u8>>>,
glyphs: BTreeMap<String, Vec<u8>>,
matrix: [f64; 6],
std_vw: Option<f64>,
force_bold: bool,
}
impl Type1Outlines {
pub fn parse(font: &Type1Font) -> Result<Self, String> {
@@ -152,6 +165,7 @@ impl Type1Outlines {
let (mut len_iv, mut subrs, mut glyphs, mut in_subrs) =
(4i32, Vec::new(), BTreeMap::new(), false);
let mut std_vw = None;
let mut force_bold = false;
while let Some(token) = tokens.next()? {
match token.as_str() {
"/lenIV" => {
@@ -176,6 +190,7 @@ impl Type1Outlines {
}
std_vw = Some(width);
}
"/ForceBold" => force_bold = tokens.required()? == "true",
"/Subrs" => {
let count = tokens.number()?;
if count > 65536 {
@@ -245,6 +260,7 @@ impl Type1Outlines {
glyphs,
matrix,
std_vw,
force_bold,
})
}
/// PDF uses a 1000-unit glyph space. Zero denotes an unknown stem width.
@@ -284,6 +300,39 @@ impl Type1Outlines {
result[3].ceil() as i32,
]
}
pub(crate) fn xdv_descriptor(&self, bbox: [i32; 4]) -> Result<XdvDescriptor, String> {
let height = |names: &[&str], top: bool, fallback: i32| -> Result<f64, String> {
let Some(name) = names.iter().find(|name| self.has_glyph(name)) else {
return Ok(f64::from(fallback));
};
let mut budget = 1_000_000;
let mut bound: Option<f64> = None;
let mut include = |y: f64| {
bound = Some(bound.map_or(y, |old| if top { old.max(y) } else { old.min(y) }));
};
for command in self.commands(name, 0, &mut budget)? {
match command {
Command::Move(_, y) | Command::Line(_, y) => include(y),
Command::Curve(_, a, _, b, _, c) => {
include(a);
include(b);
include(c);
}
Command::Close => {}
}
}
Ok(bound.unwrap_or(0.))
};
let cap = height(&["H", "P", "Pi", "Rho"], true, bbox[3])?;
let ascent = height(&["b", "h", "lambda"], true, bbox[3])?;
let descent = height(&["p", "q", "mu", "eta"], false, bbox[1])?;
let stem = self.std_vw.unwrap_or(88.);
Ok(XdvDescriptor {
metrics: [ascent, descent, cap, stem].map(f64::to_bits),
force_bold: self.force_bold,
})
}
pub fn has_glyph(&self, name: &str) -> bool {
self.glyphs.contains_key(name)
}
+27
View File
@@ -2175,6 +2175,33 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。
全量编译一致。incremental-receipt.json 的 SHA-256 为
bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。
### XDV 的 PDF 文字游标与 Type 1 字体度量
XDV 的 OpenType 字距累计保留起点坐标取整后的余量。真实文字游标继续
参与后续的相对移动和字距计算,有无字体变换都走相同路径。XDV 的
传统 Type 1 文字也按页面原点和相对文字游标写出;字体描述符从原始
PFB 字形轮廓读取高度、下降深度和垂直笔画宽度。度量随已解码字体
复用。保留原始 PFB 嵌入,参考设备会转换为 CFF。
[参考文字游标与字距](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/dvipdfm-x/pdfdev.c#L944-L1006)
[参考 Type 1 描述符](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/dvipdfm-x/type1.c#L123-L256)
用冻结 schema71 和已收敛的辅助文件复编原样 ACL XeLaTeX 样稿。
589 个原始字形的身份与坐标、119 个提取词及顺序、命名目标均与
参考一致,词框最大差约 0.000001 bp。144 DPI 灰度像素差从 98
降为 0,aux、out、bbl 与上一轮相同。原始差异和首次复制辅助文件
触发所有权保护的日志均保留。
独立的三页 OpenType 与 Type 1 样例在修改前已有相同原始字形坐标,
PDF 灰度像素差为 169、290、198。三页现均为 0,19 个词框完全一致。
另复验阿拉伯标记、斜切和 Graphite 从右向左的共四页,灰度像素差均为
0。一个 pdfTeX Type 1 对照的前后 PDF 字节相同。
三次跨文件缩进编辑各复用 66 步,仅替换第二页。字形来源命中、PDF、
SVG、来源映射与实际 aux 通过相同生成初态的独立全量对照。
定向回执为 `target/p3-acl-pdf-device-differential/candidate-receipt.json`,
SHA-256 为 `5c40f13a10e19a4eb4c1d0636bf8c7ab97a5df7f99196b9dc0a0f8c241e4e78f`。
统一出版矩阵和端到端实时验收继续按既定门槛执行。
### XeTeX Graphite 字体造型与特性
文件和系统名的 `/GR` 选择器进入实际字体实例。HarfBuzz 的 Graphite2
+9
View File
@@ -758,6 +758,15 @@ XDV 链接注释接入后,沿原样 ACL 的第二轮辅助文件和 BibTeX
`target/p3-xdv-annotation/receipt.json`。
[链接注释阶段记录](P2_M1_PROGRESS.md#xdv-链接注释与实际矩形)
#### XDV PDF 设备差异复验
使用同一份未修改的 ACL XeLaTeX 样稿、冻结 schema71 与已收敛的辅助
文件复编。589 个原始字形身份及坐标、119 个词的提取顺序及命名目标
与冻结参考一致。词框最大差约 0.000001 bp,144 DPI 灰度图从 98 个
差异像素降至逐像素一致。aux、out、bbl 与上一轮逐字节相同。保留
冻结参考、原版差异回执和实际源、字体及映射指纹。
[设备阶段记录](P2_M1_PROGRESS.md#xdv-的-pdf-文字游标与-type-1-字体度量)
#### XeTeX Graphite 字体复编
真实 xelatex.ini 生成 schema78 后加载未修改的 fontspec,使用实际