Resolve named XeTeX fonts through captured resource catalogues
This commit is contained in:
1 parent
a31de14eb2
commit
767c8ffced
10 files changed
+513
-12
No files matched your search
@@ -0,0 +1,329 @@
|
||||
//! Named OpenType faces from the host catalogue or an atomic project.
|
||||
use super::*;
|
||||
use rustybuzz::ttf_parser::{self, name_id};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct FontStyle {
|
||||
pub bold: bool,
|
||||
pub italic: bool,
|
||||
}
|
||||
|
||||
pub struct NamedFont {
|
||||
pub resource: LoadedResource,
|
||||
pub index: u32,
|
||||
pub full_name: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub(super) struct NamedFace {
|
||||
path: PathBuf,
|
||||
index: u32,
|
||||
full_name: String,
|
||||
family: String,
|
||||
style: String,
|
||||
postscript: String,
|
||||
bold: bool,
|
||||
italic: bool,
|
||||
regular: bool,
|
||||
}
|
||||
|
||||
impl NamedFace {
|
||||
fn at(path: &Path, data: &[u8], index: u32) -> Option<Self> {
|
||||
let face = ttf_parser::Face::parse(data, index).ok()?;
|
||||
let name = |id| {
|
||||
face.names()
|
||||
.into_iter()
|
||||
.filter(|name| name.name_id == id)
|
||||
.find_map(|name| name.to_string())
|
||||
};
|
||||
let postscript = name(name_id::POST_SCRIPT_NAME)?;
|
||||
Some(Self {
|
||||
path: path.to_path_buf(),
|
||||
index,
|
||||
full_name: name(name_id::FULL_NAME).unwrap_or_else(|| postscript.clone()),
|
||||
family: name(name_id::TYPOGRAPHIC_FAMILY)
|
||||
.or_else(|| name(name_id::FAMILY))
|
||||
.unwrap_or_default(),
|
||||
style: name(name_id::TYPOGRAPHIC_SUBFAMILY)
|
||||
.or_else(|| name(name_id::SUBFAMILY))
|
||||
.unwrap_or_default(),
|
||||
postscript,
|
||||
bold: face.is_bold(),
|
||||
italic: face.is_italic() || face.is_oblique(),
|
||||
regular: face.is_regular(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn valid_capture(&self) -> bool {
|
||||
self.path.is_absolute() && is_outline(&self.path) && self.index <= u32::from(u16::MAX)
|
||||
}
|
||||
|
||||
fn name_priority(&self, name: &str) -> Option<u8> {
|
||||
if self.full_name == name {
|
||||
Some(0)
|
||||
} else if name.split_once('-') == Some((&self.family, &self.style)) {
|
||||
Some(1)
|
||||
} else if self.postscript == name {
|
||||
Some(2)
|
||||
} else if self.family == name {
|
||||
Some(3)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn regular_priority(&self) -> u8 {
|
||||
match self.style.as_str() {
|
||||
"Regular" => 0,
|
||||
"Plain" => 1,
|
||||
"Normal" => 2,
|
||||
"Roman" => 3,
|
||||
_ if self.regular => 4,
|
||||
_ if !self.bold && !self.italic => 5,
|
||||
_ => 6,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_outline(path: &Path) -> bool {
|
||||
path.extension()
|
||||
.and_then(|ext| ext.to_str())
|
||||
.is_some_and(|ext| {
|
||||
["otf", "ttf", "otc", "ttc"]
|
||||
.iter()
|
||||
.any(|kind| ext.eq_ignore_ascii_case(kind))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn system_faces(limit: usize) -> Result<Vec<NamedFace>, String> {
|
||||
let output = match std::process::Command::new("fc-list").args([
|
||||
"--format", "%{file}\\t%{index}\\t%{fullname[0]}\\t%{family[0]}\\t%{style[0]}\\t%{postscriptname[0]}\\t%{weight[0]}\\t%{slant[0]}\\n",
|
||||
]).output() {
|
||||
Ok(output) => output,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||
Err(error) => return Err(format!("Fontconfig font catalogue: {error}")),
|
||||
};
|
||||
if !output.status.success() {
|
||||
return Err(format!(
|
||||
"Fontconfig font catalogue exited with {}",
|
||||
output.status
|
||||
));
|
||||
}
|
||||
let mut faces = Vec::new();
|
||||
let text =
|
||||
String::from_utf8(output.stdout).map_err(|_| "Fontconfig font catalogue is not UTF-8")?;
|
||||
for line in text.lines() {
|
||||
let mut fields = line.split('\t');
|
||||
let (
|
||||
Some(path),
|
||||
Some(index),
|
||||
Some(full),
|
||||
Some(family),
|
||||
Some(style),
|
||||
Some(postscript),
|
||||
Some(weight),
|
||||
Some(slant),
|
||||
) = (
|
||||
fields.next(),
|
||||
fields.next(),
|
||||
fields.next(),
|
||||
fields.next(),
|
||||
fields.next(),
|
||||
fields.next(),
|
||||
fields.next(),
|
||||
fields.next(),
|
||||
)
|
||||
else {
|
||||
return Err("invalid Fontconfig font catalogue record".into());
|
||||
};
|
||||
let path = PathBuf::from(path);
|
||||
if !path.is_absolute() || !is_outline(&path) {
|
||||
continue;
|
||||
}
|
||||
let index: u32 = index.parse().map_err(|_| "invalid Fontconfig face index")?;
|
||||
// Fontconfig encodes variable named instances in the high bits. The
|
||||
// OpenType loader currently takes a face index, not axis coordinates.
|
||||
if index > u32::from(u16::MAX) {
|
||||
continue;
|
||||
}
|
||||
let weight = weight.parse::<i32>().unwrap_or(80);
|
||||
let italic = slant != "0" && !slant.is_empty();
|
||||
if faces.len() >= limit {
|
||||
return Err("Fontconfig font catalogue capacity exceeded".into());
|
||||
}
|
||||
faces.push(NamedFace {
|
||||
path,
|
||||
index,
|
||||
full_name: if full.is_empty() { postscript } else { full }.into(),
|
||||
family: family.into(),
|
||||
style: style.into(),
|
||||
postscript: postscript.into(),
|
||||
bold: weight >= 180,
|
||||
italic,
|
||||
regular: weight == 80 && !italic,
|
||||
});
|
||||
}
|
||||
Ok(faces)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn system_faces(_limit: usize) -> Result<Vec<NamedFace>, String> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
impl FileWorld {
|
||||
pub fn read_named_font(
|
||||
&mut self,
|
||||
name: &str,
|
||||
style: FontStyle,
|
||||
from: &Path,
|
||||
) -> Result<Option<NamedFont>, String> {
|
||||
let mut candidates = Vec::new();
|
||||
let result = self.select_named_face(name, style, from, &mut candidates);
|
||||
self.trace.lookups.push(ResourceLookup {
|
||||
kind: ResourceKind::OpenType,
|
||||
name: name.into(),
|
||||
from: from.into(),
|
||||
candidates,
|
||||
resolved: result
|
||||
.as_ref()
|
||||
.ok()
|
||||
.and_then(|result| result.as_ref())
|
||||
.map(|font| font.resource.version.path.clone()),
|
||||
error: result.as_ref().err().cloned(),
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
fn select_named_face(
|
||||
&mut self,
|
||||
name: &str,
|
||||
style: FontStyle,
|
||||
from: &Path,
|
||||
candidates: &mut Vec<PathBuf>,
|
||||
) -> Result<Option<NamedFont>, String> {
|
||||
let scoped = if let Some(project) = &self.project {
|
||||
if self.project_named_fonts.is_none() {
|
||||
let paths: Vec<_> = self
|
||||
.paths(ResourceKind::OpenType, from)
|
||||
.into_iter()
|
||||
.chain(self.paths(ResourceKind::TrueType, from))
|
||||
.collect();
|
||||
let mut all = Vec::new();
|
||||
let mut remaining = self.config.max_index_entries;
|
||||
for (path, file) in project.files() {
|
||||
if !is_outline(path)
|
||||
|| !paths.iter().any(|scope| self.font_path_in(scope, path))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let count = if let Some(count) = ttf_parser::fonts_in_collection(&file.data) {
|
||||
if count as usize > file.data.len().saturating_sub(12) / 4 {
|
||||
continue; // The collection's face directory is truncated.
|
||||
}
|
||||
count
|
||||
} else {
|
||||
1
|
||||
};
|
||||
remaining = remaining
|
||||
.checked_sub(count as usize)
|
||||
.ok_or("project font catalogue capacity exceeded")?;
|
||||
all.extend(
|
||||
(0..count).filter_map(|index| NamedFace::at(path, &file.data, index)),
|
||||
);
|
||||
}
|
||||
self.project_named_fonts = Some(all);
|
||||
}
|
||||
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.
|
||||
}
|
||||
};
|
||||
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 Some(path) = self.probe(&face.path)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let resource = self.read_path(path)?;
|
||||
let actual =
|
||||
NamedFace::at(&resource.version.path, &resource.data, face.index).ok_or_else(|| {
|
||||
format!(
|
||||
"named font has no valid face {} in {}",
|
||||
face.index,
|
||||
resource.version.path.display()
|
||||
)
|
||||
})?;
|
||||
if !face.postscript.is_empty() && face.postscript != actual.postscript {
|
||||
return Err(format!(
|
||||
"named font catalogue changed for {}",
|
||||
resource.version.path.display()
|
||||
));
|
||||
}
|
||||
Ok(Some(NamedFont {
|
||||
resource,
|
||||
index: face.index,
|
||||
full_name: actual.full_name,
|
||||
}))
|
||||
}
|
||||
|
||||
fn font_path_in(&self, scope: &SearchPath, candidate: &Path) -> bool {
|
||||
let SearchPath::Directory {
|
||||
path,
|
||||
recursive,
|
||||
suffix,
|
||||
} = scope
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let root = self.config.cwd.join(path);
|
||||
let Some(parent) = candidate.parent() else {
|
||||
return false;
|
||||
};
|
||||
if *recursive {
|
||||
parent
|
||||
.strip_prefix(root)
|
||||
.is_ok_and(|relative| relative.ends_with(suffix))
|
||||
} else {
|
||||
parent == root.join(suffix)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user