Resolve named XeTeX fonts from configured directories

This commit is contained in:
gloamxun committed 2026-11-28 06:53:16 +08:00
1 parent aae23d837e
commit 2846f7f1e7
3 files changed
+310 -78

No files matched your search

@@ -25,6 +25,8 @@ pub(super) struct NamedFace {
bold: bool,
italic: bool,
regular: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
version: Option<ResourceVersion>,
}
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<u8> {
@@ -85,6 +93,61 @@ impl NamedFace {
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub(super) struct FontDirectory {
pub(super) scope: SearchPath,
faces: Result<Vec<NamedFace>, 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<PathBuf>,
) -> Option<NamedFace> {
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<Vec<NamedFace>, 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::<Vec<_>>()
{
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<PathBuf>,
) -> Result<Option<NamedFont>, 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<Vec<NamedFace>, 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<Vec<PathBuf>, 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<NamedFace>) -> Result<Option<NamedFont>, 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(
&regular_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(&regular_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);
}
}