From 2846f7f1e7ea8dd7df6ae634527d58235840f9dc Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 28 Nov 2026 06:53:16 +0800 Subject: [PATCH] Resolve named XeTeX fonts from configured directories --- crates/texrra-tex-core/src/resources.rs | 34 +- .../src/resources/named_fonts.rs | 318 ++++++++++++++---- docs/P2_M1_PROGRESS.md | 36 ++ 3 files changed, 310 insertions(+), 78 deletions(-) diff --git a/crates/texrra-tex-core/src/resources.rs b/crates/texrra-tex-core/src/resources.rs index d080e13..0122ee7 100644 --- a/crates/texrra-tex-core/src/resources.rs +++ b/crates/texrra-tex-core/src/resources.rs @@ -383,6 +383,8 @@ pub struct InputSnapshot { tex_suffix_fallback: bool, #[serde(default, skip_serializing_if = "Option::is_none")] system_fonts: Option, String>>, + #[serde(default, skip_serializing_if = "Option::is_none")] + named_font_directories: Option>, } /// A failed enumeration is not a complete namespace. Retain the usable prefix /// only as evidence and replay its actual error, never as a successful index. @@ -462,6 +464,15 @@ impl InputSnapshot { { return Err("invalid captured font catalogue".into()); } + if let Some(directories) = &self.named_font_directories + && (self.project.is_some() && !directories.is_empty() + || directories.iter().enumerate().any(|(i, directory)| { + !directory.valid_capture(self.config.max_index_entries) + || directories[..i].iter().any(|prior| prior.scope == directory.scope) + })) + { + return Err("invalid captured named font directory".into()); + } if let Some(project) = &self.project { project.validate()?; if project.configuration() != self.config { @@ -570,6 +581,7 @@ pub struct FileWorld { project: Option>, system_fonts: Option, String>>, project_named_fonts: Option>, + named_font_directories: Option>, } impl FileWorld { pub fn default_pk_resolution(&self) -> i32 { @@ -709,6 +721,7 @@ impl FileWorld { project: None, system_fonts: None, project_named_fonts: None, + named_font_directories: Some(Vec::new()), }) } pub fn capture_inputs(&mut self) { @@ -758,6 +771,7 @@ impl FileWorld { project: Some(project), system_fonts: None, project_named_fonts: None, + named_font_directories: Some(Vec::new()), }) } pub fn project(&self) -> Option<&Arc> { @@ -847,6 +861,7 @@ impl FileWorld { project: snapshot.project.clone(), system_fonts: snapshot.system_fonts.clone(), project_named_fonts: None, + named_font_directories: snapshot.named_font_directories.clone(), }) } pub fn input_snapshot(&self) -> Arc { @@ -868,6 +883,7 @@ impl FileWorld { replay_gaps: gaps, project: self.project.clone(), system_fonts: self.system_fonts.clone(), + named_font_directories: self.named_font_directories.clone(), }) } /// Only the authorized host may mark its generated-file paths live. These @@ -1218,20 +1234,24 @@ impl FileWorld { )); } } - let value = fs::read(self.generated_storage(&path)) + let value = self.read_input_from_disk(&path); + if self.pinned && !live { + self.input_files.insert(path, value.clone()); + } + value + } + + fn read_input_from_disk(&self, path: &Path) -> Result { + fs::read(self.generated_storage(path)) .map(|data| SnapshotFile { version: ResourceVersion { - path: path.clone(), + path: path.to_owned(), sha256: format!("{:x}", Sha256::digest(&data)), bytes: data.len() as u64, }, data: Arc::from(data), }) - .map_err(|e| format!("resource {}: {e}", path.display())); - if self.pinned && !live { - self.input_files.insert(path, value.clone()); - } - value + .map_err(|e| format!("resource {}: {e}", path.display())) } /// Pins bytes for an external stream without claiming that its whole /// contents were delivered to TeX. Consumption remains in stream_reads. diff --git a/crates/texrra-tex-core/src/resources/named_fonts.rs b/crates/texrra-tex-core/src/resources/named_fonts.rs index 0430b7a..ee5d244 100644 --- a/crates/texrra-tex-core/src/resources/named_fonts.rs +++ b/crates/texrra-tex-core/src/resources/named_fonts.rs @@ -25,6 +25,8 @@ pub(super) struct NamedFace { bold: bool, italic: bool, regular: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + version: Option, } impl NamedFace { @@ -51,11 +53,17 @@ impl NamedFace { bold: face.is_bold(), italic: face.is_italic() || face.is_oblique(), regular: face.is_regular(), + version: None, }) } pub(super) fn valid_capture(&self) -> bool { - self.path.is_absolute() && is_outline(&self.path) && self.index <= u32::from(u16::MAX) + self.path.is_absolute() + && self.index <= u32::from(u16::MAX) + && self.version.as_ref().map_or_else( + || is_outline(&self.path), + |version| version.path == self.path, + ) } fn name_priority(&self, name: &str) -> Option { @@ -85,6 +93,61 @@ impl NamedFace { } } +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub(super) struct FontDirectory { + pub(super) scope: SearchPath, + faces: Result, String>, +} + +impl FontDirectory { + pub(super) fn valid_capture(&self, limit: usize) -> bool { + matches!(self.scope, SearchPath::Directory { .. }) + && self.faces.as_ref().map_or(true, |faces| { + faces.len() <= limit && faces.iter().all(|face| { + face.valid_capture() && face.version.is_some() + }) + }) + } +} + +fn matching_face( + scoped: &[NamedFace], + name: &str, + style: FontStyle, + candidates: &mut Vec, +) -> Option { + let mut matches: Vec<_> = scoped + .iter() + .filter_map(|face| { + Some(( + face.name_priority(name)?, + face.regular_priority(), + &face.path, + face.index, + face, + )) + }) + .collect(); + matches.sort_by(|a, b| (a.0, a.1, a.2, a.3).cmp(&(b.0, b.1, b.2, b.3))); + candidates.extend(matches.iter().map(|(_, _, path, _, _)| (*path).clone())); + let (_, _, _, _, base) = matches.first()?; + let face = if style.bold || style.italic { + let bold = style.bold || base.bold; + let italic = style.italic || base.italic; + scoped + .iter() + .filter(|face| face.family == base.family && face.bold == bold && face.italic == italic) + .min_by_key(|face| (&face.style, &face.path, face.index)) + .unwrap_or(base) + } else { + base + }; + if !candidates.contains(&face.path) { + candidates.push(face.path.clone()); + } + Some((*face).clone()) +} + #[derive(Clone, Copy)] pub(crate) enum PdfSfntKind { TrueType, @@ -214,6 +277,7 @@ fn system_faces(limit: usize) -> Result, String> { bold: weight >= 180, italic, regular: weight == 80 && !italic, + version: None, }); } Ok(faces) @@ -309,35 +373,7 @@ impl FileWorld { .flat_map(|kind| self.paths(kind, from)) .collect::>() { - let SearchPath::Directory { - path, - recursive, - suffix, - } = entry - else { - continue; - }; - let root = self.config.cwd.join(path); - let prefix = root.join(&suffix); - let index = self.index_at(if recursive { &root } else { &prefix }, recursive)?; - let mut paths: Vec<_> = index - .names - .values() - .flatten() - .filter(|candidate| is_outline(candidate)) - .filter(|candidate| { - candidate.parent().is_some_and(|parent| { - if recursive { - parent - .strip_prefix(&root) - .is_ok_and(|part| part.ends_with(&suffix)) - } else { - parent == prefix - } - }) - }) - .cloned() - .collect(); + let mut paths = self.outline_paths(&entry)?; // Try the matching basename first, then discover arbitrary filenames // by inspecting the versioned program's name table. let priority = |path: &Path| !path.file_stem().is_some_and(|stem| stem == name); @@ -448,53 +484,133 @@ impl FileWorld { } self.project_named_fonts.as_deref().unwrap_or_default() } else { - if self.system_fonts.is_none() && !self.replay { - self.system_fonts = Some(system_faces(self.config.max_index_entries)); - } - match &self.system_fonts { - Some(Ok(faces)) => faces, - Some(Err(error)) => return Err(error.clone()), - None => return Ok(None), // Older captures had no host named-font lookup. - } + return self.select_host_or_directory_font(name, style, from, candidates); }; - let mut matches: Vec<_> = scoped - .iter() - .filter_map(|face| { - Some(( - face.name_priority(name)?, - face.regular_priority(), - &face.path, - face.index, - face, - )) - }) - .collect(); - matches.sort_by(|a, b| (a.0, a.1, a.2, a.3).cmp(&(b.0, b.1, b.2, b.3))); - candidates.extend(matches.iter().map(|(_, _, path, _, _)| (*path).clone())); - let Some((_, _, _, _, base)) = matches.first() else { - return Ok(None); - }; - let face = if style.bold || style.italic { - let bold = style.bold || base.bold; - let italic = style.italic || base.italic; - scoped - .iter() - .filter(|face| { - face.family == base.family && face.bold == bold && face.italic == italic - }) - .min_by_key(|face| (&face.style, &face.path, face.index)) - .unwrap_or(base) - } else { - base - }; - let face = (*face).clone(); - if !candidates.contains(&face.path) { - candidates.push(face.path.clone()); + let face = matching_face(scoped, name, style, candidates); + self.open_named_face(face) + } + + fn select_host_or_directory_font( + &mut self, + name: &str, + style: FontStyle, + from: &Path, + candidates: &mut Vec, + ) -> Result, String> { + if self.system_fonts.is_none() && !self.replay { + self.system_fonts = Some(system_faces(self.config.max_index_entries)); } + if let Some(faces) = &self.system_fonts { + let face = matching_face(faces.as_ref().map_err(Clone::clone)?, name, style, candidates); + if let Some(font) = self.open_named_face(face)? { + return Ok(Some(font)); + } + } + + // Files delivered through explicitly scoped roots have a complete + // name table even when they are absent from the OS font catalogue. + // Earlier input images only observed the host catalogue. + if self.named_font_directories.is_none() { + return Ok(None); + } + let mut searched = Vec::new(); + for (scope, _) in self.paths(ResourceKind::OpenType, from) + .into_iter().chain(self.paths(ResourceKind::TrueType, from)) + { + if !matches!(scope, SearchPath::Directory { .. }) || searched.contains(&scope) { + continue; + } + let face = matching_face(self.directory_faces(&scope)?, name, style, candidates); + if let Some(font) = self.open_named_face(face)? { + return Ok(Some(font)); + } + searched.push(scope); + } + Ok(None) + } + + fn directory_faces(&mut self, scope: &SearchPath) -> Result<&[NamedFace], String> { + let cached = self.named_font_directories.as_ref().unwrap().iter().position(|d| &d.scope == scope); + let index = match cached.filter(|_| self.pinned) { + Some(index) => index, + None => { + if self.replay { + return Err("native input snapshot has no observation for this font directory".into()); + } + let faces = self.read_directory_faces(scope); + let directories = self.named_font_directories.as_mut().unwrap(); + let record = FontDirectory { scope: scope.clone(), faces }; + if let Some(index) = cached { + directories[index] = record; + index + } else { + directories.push(record); + directories.len() - 1 + } + } + }; + self.named_font_directories.as_ref().unwrap()[index].faces.as_deref().map_err(Clone::clone) + } + + fn read_directory_faces(&mut self, scope: &SearchPath) -> Result, String> { + let mut seen = BTreeSet::new(); + let mut remaining = self.config.max_index_entries; + let mut faces = Vec::new(); + for candidate in self.outline_paths(scope)? { + let Some(path) = self.probe(&candidate)? else { continue }; + if !seen.insert(path.clone()) { + continue; + } + // Retain the inspected names and identity. Pin full font bytes + // only when a query actually selects the physical program. + let file = match self.input_files.get(&path) { + Some(captured) => captured.clone()?, + None => self.read_input_from_disk(&path)?, + }; + let count = ttf_parser::fonts_in_collection(&file.data).unwrap_or(1); + if count > u32::from(u16::MAX) + 1 + || (count > 1 && count as usize > file.data.len().saturating_sub(12) / 4) + { + continue; + } + remaining = remaining.checked_sub(count as usize).ok_or("named font directory capacity exceeded")?; + faces.extend((0..count).filter_map(|index| { + let mut face = NamedFace::at(&path, &file.data, index)?; + face.version = Some(file.version.clone()); + Some(face) + })); + } + Ok(faces) + } + + fn outline_paths(&mut self, scope: &SearchPath) -> Result, String> { + let SearchPath::Directory { path, recursive, suffix } = scope else { + return Ok(Vec::new()); + }; + let root = self.config.cwd.join(path); + let prefix = root.join(suffix); + let index = self.index_at(if *recursive { &root } else { &prefix }, *recursive)?; + Ok(index.names.values().flatten() + .filter(|candidate| is_outline(candidate)) + .filter(|candidate| candidate.parent().is_some_and(|parent| { + if *recursive { + parent.strip_prefix(&root).is_ok_and(|part| part.ends_with(suffix)) + } else { + parent == prefix + } + })) + .cloned().collect()) + } + + fn open_named_face(&mut self, face: Option) -> Result, String> { + let Some(face) = face else { return Ok(None) }; let Some(path) = self.probe(&face.path)? else { return Ok(None); }; let resource = self.read_path(path)?; + if face.version.as_ref().is_some_and(|version| version != &resource.version) { + return Err(format!("named font directory changed for {}", resource.version.path.display())); + } let actual = NamedFace::at(&resource.version.path, &resource.data, face.index).ok_or_else(|| { format!( @@ -538,3 +654,63 @@ impl FileWorld { } } } + + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + + #[test] + fn scoped_named_fonts_capture_the_directory_without_pinning_unused_fonts() { + static NEXT: AtomicU64 = AtomicU64::new(0); + let dir = std::env::temp_dir().join(format!( + "texrra-scoped-names-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed), + )); + fs::create_dir_all(dir.join("fonts/truetype/project")).unwrap(); + let root = dir.canonicalize().unwrap(); + let regular_path = root.join("fonts/truetype/project/regular-resource.ttf"); + let bold_path = root.join("fonts/truetype/project/bold-resource.ttf"); + fs::write( + ®ular_path, + include_bytes!("../../../../assets/fonts-subset/LiberationSerif-Regular.ttf"), + ) + .unwrap(); + fs::write( + &bold_path, + include_bytes!("../../../../assets/fonts-subset/LiberationSerif-Bold.ttf"), + ) + .unwrap(); + let mut config = WorldConfig::new(&root); + config.texmf_roots.push(root.clone()); + let mut world = FileWorld::new(config).unwrap(); + world.system_fonts = Some(Ok(Vec::new())); + world.capture_inputs(); + let from = root.join("document.tex"); + let request = |world: &mut FileWorld| { + world.read_named_font( + "Liberation Serif", + FontStyle { bold: true, italic: false }, + &from, + ) + }; + let font = request(&mut world).unwrap().unwrap(); + assert_eq!(font.index, 0); + assert_eq!(font.resource.version.path, bold_path); + assert_eq!(world.trace().reads, [font.resource.version.clone()]); + let snapshot = world.input_snapshot(); + assert!(snapshot.file(®ular_path).is_none()); + assert!(snapshot.file(&bold_path).is_some()); + let frozen = serde_json::to_vec(snapshot.as_ref()).unwrap(); + let expected_lookups = world.trace().lookups.clone(); + + fs::remove_dir_all(dir).unwrap(); + let mut replay = FileWorld::from_snapshot(serde_json::from_slice(&frozen).unwrap()).unwrap(); + let reproduced = request(&mut replay).unwrap().unwrap(); + assert_eq!(reproduced.resource.version, font.resource.version); + assert_eq!(reproduced.full_name, font.full_name); + assert_eq!(replay.trace().lookups, expected_lookups); + } +} diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index ead402f..9a535e8 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -819,6 +819,42 @@ 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 从配置目录按实际字体名称选择字面 + +现有 Fontconfig 路径在两端加载同一配置时已能按名称接通真实 +SimSun 和 SimHei。新路径在宿主目录未命中时按已配置的 +OpenType、TrueType 搜索目录查找。它检查实际字体名称表的全名、 +家族加样式和 PostScript 名,并选择 TTC 内的实际索引。原子 +项目继续只使用该修订的文件集合。配置目录的目录观测、实际字 +面名称及文件指纹进入输入快照。只有实际选中的字体保留完整 +程序,并核对同一指纹后交给正常字体读取。回放使用已捕获目录 +和文件,旧快照沿用原来保存的宿主查找。 +[参考引擎的名称和样式选择](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/xetexdir/XeTeXFontMgr.cpp) + +参考通过 Fontconfig 选择实际 SimSun TTC 与 SimHei。原生仅 +通过配置目录选择相同文件。两组对照分别使用 SimSun、SimHei +及额外的 NSimSun 字面。三种字面身份、词框与 144 DPI 灰度图 +均一致。五项 XeTeX 管线回归和目录捕获回归通过。目录捕获 +以实际字体选择粗体,序列化后移除整个目录,再从快照复现 +查找和字体指纹。未选中的字体程序未进入快照。四页项目中 +按名称加载 NSimSun 后移动真实 TTC,旧检查点失效,只更新第 2 页。 +后来移动子文件正文时复用 93 步,也只更新第 2 页。删除字体 +时保留已发布预览和 aux,原处恢复后复用 93 步且无需发页。 +成功修订的 PDF、测量页面、SVG、来源映射及 aux 与独立全量 +一致。证据在 target/p3-xetex-font-directories,receipt.json +为 02b1ca7c749c0ca4271c56e85ae586bf689e1b6f694b15594080bb20acaf0fc6, +revision.log 为 01f917835f7e5878fea3a296b693bb7cd0c649790dbe5b2195be59f63407ae3e。 + +原样 xeCJK 下划线样稿使用同一实际字体配置进入原生作业。最早 +停止于 ctexart.cls 第 1219 行的宏参数扫描,参考成功生成 6 页。 +直接见证用 let 将控制序列绑定到 catcode 6 的字符,随后在字面 +井号变成普通字符时定义并调用宏。参考在定义参数和正文时消费 +该控制序列的命令含义,原生将其保留为不匹配的前缀。下一入口 +是按扫描时命令含义识别参数标记,同时保留实际 token 的字面 +身份、分组和增量依赖。参考、原生诊断和原样项目失败均保留在 +next-parameter-marker 与 target/p3-xetex-text-switch/next-fntef。 +[参考定义扫描](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/xetexdir/xetex.web) + ### XeTeX OpenType 字体切换的文本行定位 切换 OpenType 字体时,XDV 结束当前字形字符串,保留同一 PDF