Rebind native format TFM resources after project relocation

This commit is contained in:
gloamxun committed 2026-11-28 01:46:37 +08:00
1 parent 1ad9c4db82
commit 65204a7dae
9 files changed
+304 -35

No files matched your search

@@ -5,7 +5,7 @@ mod interword;
mod tail;
pub(super) use tail::TailNodeRef;
mod leaders;
mod legacy_fonts;
mod format_fonts;
mod native_words;
pub use leaders::{LeaderGlue, LeaderMode, LeaderPattern};
@@ -1,64 +1,66 @@
//! Format schema 53 stored device faces in boxes. Rebind them to the original
//! logical font slots before a restored job changes any active expansion links.
//! Visit the font instances retained by packed glyphs in a format.
use super::*;
use crate::{math_engine_tex::MathItem, native_font::NativeFont};
use std::{collections::BTreeMap, sync::Arc};
type Replacements = BTreeMap<(FontId, i32), Arc<NativeFont>>;
use std::sync::Arc;
impl NativeBox {
pub(in crate::execution) fn rebind_legacy_expansion_fonts(&mut self, fonts: &Replacements) {
pub(in crate::execution) fn visit_format_fonts_mut(
&mut self,
visit: &mut impl FnMut(&mut Arc<NativeFont>),
) {
match &mut self.content {
BoxContent::Horizontal(nodes) => rebind_horizontal(nodes, fonts),
BoxContent::Vertical(nodes) => rebind_vertical(nodes, fonts),
BoxContent::Horizontal(nodes) => rebind_horizontal(nodes, visit),
BoxContent::Vertical(nodes) => rebind_vertical(nodes, visit),
}
}
}
fn rebind_horizontal(nodes: &mut [TextNode], fonts: &Replacements) {
fn rebind_horizontal(nodes: &mut [TextNode], visit: &mut impl FnMut(&mut Arc<NativeFont>)) {
for node in nodes {
match node {
TextNode::Glyph { glyph, .. } | TextNode::Box(glyph) | TextNode::MathChar(glyph) => {
if let Some(b) = &mut glyph.native_box {
b.rebind_legacy_expansion_fonts(fonts);
b.visit_format_fonts_mut(visit);
}
if let Some(geometry) = &mut glyph.math_geometry {
for item in &mut geometry.items {
if let MathItem::NativeGlyph { font, .. } = &mut item.item
&& let Some(logical) = fonts.get(&(font.id, font.expansion))
{
*font = logical.clone();
if let MathItem::NativeGlyph { font, .. } = &mut item.item {
visit(font);
}
}
}
}
TextNode::Discretionary { pre_break, post_break, .. } => {
rebind_horizontal(pre_break, fonts);
rebind_horizontal(post_break, fonts);
TextNode::Discretionary {
pre_break,
post_break,
..
} => {
rebind_horizontal(pre_break, visit);
rebind_horizontal(post_break, visit);
}
TextNode::Adjustment(value) => rebind_vertical(&mut value.nodes, fonts),
TextNode::Insertion(value) => rebind_vertical(&mut value.nodes, fonts),
TextNode::Leaders(leader) => rebind_leader(leader, fonts),
TextNode::Adjustment(value) => rebind_vertical(&mut value.nodes, visit),
TextNode::Insertion(value) => rebind_vertical(&mut value.nodes, visit),
TextNode::Leaders(leader) => rebind_leader(leader, visit),
_ => {}
}
}
}
fn rebind_vertical(nodes: &mut [NativeVerticalNode], fonts: &Replacements) {
fn rebind_vertical(nodes: &mut [NativeVerticalNode], visit: &mut impl FnMut(&mut Arc<NativeFont>)) {
for node in nodes {
match node {
NativeVerticalNode::Box(b) | NativeVerticalNode::Line(b) => {
b.rebind_legacy_expansion_fonts(fonts);
b.visit_format_fonts_mut(visit);
}
NativeVerticalNode::Insertion(value) => rebind_vertical(&mut value.nodes, fonts),
NativeVerticalNode::Leaders(leader) => rebind_leader(leader, fonts),
NativeVerticalNode::Insertion(value) => rebind_vertical(&mut value.nodes, visit),
NativeVerticalNode::Leaders(leader) => rebind_leader(leader, visit),
_ => {}
}
}
}
fn rebind_leader(leader: &mut LeaderGlue, fonts: &Replacements) {
fn rebind_leader(leader: &mut LeaderGlue, visit: &mut impl FnMut(&mut Arc<NativeFont>)) {
if let LeaderPattern::Box(b) = &mut leader.pattern {
b.rebind_legacy_expansion_fonts(fonts);
b.visit_format_fonts_mut(visit);
}
}
@@ -1025,6 +1025,27 @@ impl FontCatalog {
.collect()
}
pub(super) fn rebind_format_resources(
&mut self,
bindings: &BTreeMap<std::path::PathBuf, std::path::PathBuf>,
) -> bool {
let mut relocated = false;
for resource in &mut self.resources {
if let Some(path) = bindings.get(&resource.version.path) {
resource.version.path.clone_from(path);
relocated = true;
}
}
if relocated {
for instance in &mut self.fonts {
if let Some(font) = &mut instance.glyph_font {
NativeFont::rebind_resource_path(font, bindings);
}
}
}
relocated
}
pub(super) fn reset_format_font_state(&mut self) {
for font in &mut self.fonts {
font.expansion_origin = None;
@@ -16,9 +16,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 93;
const COMPATIBLE_SCHEMAS: [u32; 59] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, SCHEMA,
const SCHEMA: u32 = 94;
const COMPATIBLE_SCHEMAS: [u32; 60] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 93, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
@@ -44,8 +44,10 @@ impl FormatImage {
}
match &lookup.lookup_path {
Some(spelling)
if matches!(lookup.kind, ResourceKind::Tex | ResourceKind::PdfImage)
&& relative_tree_path(spelling)
if matches!(
lookup.kind,
ResourceKind::Tex | ResourceKind::PdfImage | ResourceKind::Tfm
) && relative_tree_path(spelling)
&& !spelling.as_os_str().is_empty() =>
{
inputs
@@ -167,6 +169,7 @@ impl FormatImage {
.clone_from(path);
}
}
self.state.rebind_format_font_resources(bindings);
self.input_checks.take();
}
}
+30 -3
View File
@@ -1716,12 +1716,39 @@ impl State {
})
}
fn visit_format_fonts_mut(
&mut self,
mut visit: impl FnMut(&mut std::sync::Arc<crate::native_font::NativeFont>),
) {
for b in self.boxes.values_mut() {
b.visit_format_fonts_mut(&mut visit);
}
for form in self.pdf_forms.values_mut() {
if let crate::pdf_device::forms::FormContents::Pending(body) = &mut form.contents {
std::sync::Arc::make_mut(body).box_node.visit_format_fonts_mut(&mut visit);
}
}
}
pub(super) fn rebind_format_font_resources(
&mut self,
bindings: &BTreeMap<std::path::PathBuf, std::path::PathBuf>,
) {
if self.fonts.rebind_format_resources(bindings) {
self.visit_format_fonts_mut(|font| {
crate::native_font::NativeFont::rebind_resource_path(font, bindings);
});
}
}
pub(super) fn restore_legacy_format_fonts(&mut self) -> Result<(), String> {
let replacements = self.fonts.restore_legacy_synthesized_fonts()?;
if !replacements.is_empty() {
for b in self.boxes.values_mut() {
b.rebind_legacy_expansion_fonts(&replacements);
}
self.visit_format_fonts_mut(|font| {
if let Some(logical) = replacements.get(&(font.id, font.expansion)) {
*font = logical.clone();
}
});
}
self.fonts.reset_format_font_state();
Ok(())
+22
View File
@@ -114,6 +114,28 @@ pub(crate) fn unexpanded(amount: &i32) -> bool {
}
impl NativeFont {
pub(crate) fn rebind_resource_path(
font: &mut Arc<Self>,
bindings: &BTreeMap<std::path::PathBuf, std::path::PathBuf>,
) -> bool {
let path = bindings.get(&font.resource.version.path);
let base = font.letter_spacing.as_ref().and_then(|spacing| {
let mut base = spacing.base.clone();
Self::rebind_resource_path(&mut base, bindings).then_some(base)
});
if path.is_none() && base.is_none() {
return false;
}
let font = Arc::make_mut(font);
if let Some(path) = path {
font.resource.version.path.clone_from(path);
}
if let Some(base) = base {
font.letter_spacing.as_mut().expect("relocated letterspace base").base = base;
}
true
}
pub fn metrics(&self) -> &TfmMetrics {
&self.metrics
}
+38
View File
@@ -781,6 +781,44 @@ pdftex-eager.log 为 cf0693d6382cab49b219018676dad1e21ac6e296ef7816ec59fb217e0e1
next-local-tfm,逐步接通格式字体本身、已装盒字形及后续设备读取
使用的资源版本。
### 格式中的项目本地 TFM 迁移
schema94 把项目内相对查找获得的 TFM 纳入原有的输入迁移和字节
校验。在目录移动后,字体目录、已装盒字形、待写出的 Form 以及
字距字体引用的基础字体使用当前度量文件身份。原有字号、字形槽位、
盒尺寸及字体编号沿用转储值。设备通过实际宿主读取绘制所需的
映射、轮廓或虚拟字体,读取版本进入作业追踪。旧格式可继续加载,
绝对查找仍保留原绑定规则。
[XeTeX 格式的字体表读写](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/xetexdir/xetex.web#L26812-L26852)
以同一真实 cmr10.tfm、CMR10 字体程序和映射转储并移动项目。
已装盒字形和重载后新排的字形共用字体编号与新路径上的资源版本。
XeTeX 一页及 pdfTeX 两页在 144 DPI 下与原版逐像素一致,
盒宽同为 21.8056 pt。pdfTeX 含一个待写出的 Form。实际 schema93
仍可重载并绘制原有页面。
七项格式相关回归通过。迁移后的项目修改第二页正文时恢复检查点,
只刷新该页。页面、PDF、完整 SVG 和来源映射与独立全量逐项一致。
在同一项目快照中改动 TFM 内容会报告新路径版本失配,原已发布
结果可继续使用。
证据在 target/p3-format-tfm-relocation。device-xetex-moved.log 为
78a0470dcb26c1dd61978d50c1309b13f70deca06fd7ec18815095b62696019b,
device-pdftex-regular-moved.log 为
48ac988d6032f38d515fbc610c512b3acedb1d51b0638c9205b1d5ad3072e97c,
release-tests.log 为 4b7a1b29888735a0bf3c38c3ed6f83d937f7adbcee46818e511ddf80a983eb68。
字距字体对照中,使用同一真实映射和 PFB 的转储前作业两页逐像素
一致。原版格式重载后,首字轮廓相对于前版移动约半个字距,页差
为 187 和 259 像素。原生在重载前后沿用相同绘制位置,迁移本身的
两页输出也与迁移前的原生基线逐像素一致。保留缺少派生字体映射
时的原版失败,以及配置派生字体映射后的原输出。回执见
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 纸张指令进入实际发页
XeTeX 每页隐式纸张设置与文档内的 `pdf:pagesize` 按发页顺序生效。
+156
View File
@@ -1732,6 +1732,162 @@ fn relocated_format_checks_current_sources_and_consumed_stream_ranges() {
fs::remove_dir_all(root).unwrap();
}
#[test]
fn relocated_format_binds_packed_and_new_glyphs_to_the_current_tfm() {
use texrra_tex_core::render::DisplayItem;
let root = directory("format-tfm-relocation").canonicalize().unwrap();
let origin = root.join("origin");
let project = root.join("project");
let world = |cwd: &Path| {
let mut configuration = WorldConfig::new(cwd);
for (kind, directory) in [
(ResourceKind::Tfm, "metrics"),
(ResourceKind::Map, "fonts"),
(ResourceKind::Type1, "fonts"),
] {
configuration
.paths
.insert(kind, vec![SearchPath::directory(directory, false)]);
}
configuration
};
let mut build = request(&origin);
build.world = world(&origin);
build.input = "seed.tex".into();
build.output = "seed.tfx".into();
let seed = br"\catcode123=1 \catcode125=2
\pdfoutput=1 \font\moving=cmr10
\setbox0=\vbox{\hbox{\moving ABC}}
\dump
";
let tfm_bytes = include_bytes!("../crates/texrra-tex-core/assets/cmr10.tfm");
let type1_bytes = include_bytes!("../assets/fonts/cmr10.pfb");
let map = b"cmr10 CMR10 <cmr10.pfb\n";
fs::create_dir_all(origin.join("metrics")).unwrap();
fs::create_dir_all(origin.join("fonts")).unwrap();
fs::write(origin.join("seed.tex"), seed).unwrap();
fs::write(origin.join("metrics/cmr10.tfm"), tfm_bytes).unwrap();
fs::write(origin.join("fonts/pdftex.map"), map).unwrap();
fs::write(origin.join("fonts/cmr10.pfb"), type1_bytes).unwrap();
dump_format(build, Cancellation::default()).unwrap();
fs::rename(&origin, &project).unwrap();
let format = project.join("seed.tfx");
let entry = project.join("entry.tex");
let metric = project.join("metrics/cmr10.tfm");
let outline = project.join("fonts/cmr10.pfb");
let prefix = "\\shipout\\hbox{\\copy0 \\moving DEF}\n";
let padding = format!("{}\n", "\\relax ".repeat(30)).repeat(42);
let source = |word| format!("{prefix}{padding}\\shipout\\hbox{{\\moving {word}}}\\end\n");
let configuration = world(&project);
let snapshot = ProjectSnapshot::new(ProjectDefinition {
configuration: configuration.clone(),
revision: 1,
roots: [project.clone()].into(),
files: [
(project.join("seed.tex"), Arc::from(seed.as_slice())),
(format.clone(), fs::read(&format).unwrap().into()),
(entry.clone(), source("OLD").into_bytes().into()),
(metric.clone(), Arc::from(tfm_bytes.as_slice())),
(outline.clone(), Arc::from(type1_bytes.as_slice())),
(project.join("fonts/pdftex.map"), Arc::from(map.as_slice())),
]
.into(),
directories: Default::default(),
aliases: Default::default(),
generated_roots: [project.clone()].into(),
generated: Default::default(),
})
.unwrap();
let mut job = request(&project);
job.world = configuration;
job.input = entry.clone();
job.entry = Entry::Format(format);
let compiler = NativeCompiler::default().with_entry_checkpoints(prefix.len() + 48);
let first = compiler
.compile(job.clone().with_project(snapshot.clone()))
.unwrap();
let version = file_version(&metric).unwrap().unwrap();
assert_eq!(
first.resources.trace.format_input_bindings[&origin.join("metrics/cmr10.tfm")],
metric
);
assert!(first.resources.trace.reads.contains(&version));
assert!(
first
.resources
.trace
.reads
.contains(&file_version(&outline).unwrap().unwrap())
);
let glyphs: Vec<_> = first.pages[0]
.items
.iter()
.filter_map(|item| match item {
DisplayItem::NativeGlyph { font, slot, .. } => {
assert_eq!(font.resource.version, version);
Some((font.id, *slot))
}
_ => None,
})
.collect();
assert_eq!(
glyphs.iter().map(|(_, slot)| *slot).collect::<Vec<_>>(),
b"ABCDEF"
);
assert!(glyphs.iter().all(|(id, _)| *id == glyphs[0].0));
let changed = snapshot
.with_file_edits(2, [(entry, source("NEW").into_bytes().into())].into())
.unwrap();
let revised = job.clone().with_project(changed.clone());
let next = compiler.compile(revised.clone()).unwrap();
assert!(
next.entry_checkpoint_work.reused_steps > 0,
"{:?}",
next.entry_checkpoint_work
);
let delta = next.preview_since(Some(first.revision())).unwrap();
assert_eq!(
delta
.pages
.iter()
.map(|page| page.index)
.collect::<Vec<_>>(),
[1]
);
let full = NativeCompiler::default().compile(revised).unwrap();
assert_eq!(next.pdf, full.pdf);
assert_eq!(next.pages, full.pages);
assert_eq!(next.source_map.pages, full.source_map.pages);
assert_eq!(next.source_map.sources, full.source_map.sources);
assert_eq!(
next.preview_since(None).unwrap().pages,
full.preview_since(None).unwrap().pages
);
let mut altered = tfm_bytes.to_vec();
altered[24] ^= 1;
let changed = changed
.with_file_edits(3, [(metric.clone(), altered.into())].into())
.unwrap();
let error = compiler
.compile_detailed(job.with_project(changed))
.err()
.unwrap()
.error
.to_string();
assert!(
error.contains("native format resource changed")
&& error.contains(metric.to_str().unwrap()),
"{error}"
);
assert!(Arc::ptr_eq(&next, &compiler.latest().unwrap()));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn shared_format_build_load_and_cancelled_build_preserve_real_output_policy() {
let p = directory("format");