Files
texrra-engine/crates/texrra-tex-core/src/resources/named_fonts.rs
T

541 lines
18 KiB
Rust

//! 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,
}
}
}
#[derive(Clone, Copy)]
pub(crate) enum PdfSfntKind {
TrueType,
Cff { cid_keyed: bool },
}
impl PdfSfntKind {
fn resource_kind(self) -> ResourceKind {
match self {
Self::TrueType => ResourceKind::TrueType,
Self::Cff { .. } => ResourceKind::OpenType,
}
}
}
pub(crate) fn cff_program(data: &[u8], index: u32, cid_keyed: bool) -> Option<&[u8]> {
let face = ttf_parser::RawFace::parse(data, index).ok()?;
let bytes = face.table(ttf_parser::Tag::from_bytes(b"CFF "))?;
let cff = read_fonts::ps::cff::CffFontRef::new_cff(bytes, 0, None).ok()?;
(cff.is_cid() == cid_keyed).then_some(bytes)
}
pub(crate) fn exact_pdf_sfnt_name(
data: &[u8],
index: u32,
requested: &str,
kind: PdfSfntKind,
) -> Option<String> {
let face = ttf_parser::Face::parse(data, index).ok()?;
match kind {
PdfSfntKind::TrueType => {
face.tables().glyf.as_ref()?;
}
PdfSfntKind::Cff { cid_keyed } => {
cff_program(data, index, cid_keyed)?;
}
}
let mut names = face.names().into_iter();
names
.any(|name| {
name.name_id == name_id::POST_SCRIPT_NAME
&& name.to_string().is_some_and(|name| name == requested)
})
.then(|| {
face.names()
.into_iter()
.filter(|name| name.name_id == name_id::FULL_NAME)
.find_map(|name| name.to_string())
.unwrap_or_else(|| requested.to_owned())
})
}
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()),
lookup_path: None,
error: result.as_ref().err().cloned(),
});
result
}
/// PDF device name lookup requires the exact PostScript name and glyf outlines.
pub fn read_pdf_truetype(
&mut self,
name: &str,
from: &Path,
) -> Result<Option<NamedFont>, String> {
self.read_pdf_sfnt(name, from, PdfSfntKind::TrueType)
}
/// Resolve a versioned OpenType face with the requested CFF charset kind.
pub fn read_pdf_cff(
&mut self,
name: &str,
from: &Path,
cid_keyed: bool,
) -> Result<Option<NamedFont>, String> {
self.read_pdf_sfnt(name, from, PdfSfntKind::Cff { cid_keyed })
}
fn read_pdf_sfnt(
&mut self,
name: &str,
from: &Path,
kind: PdfSfntKind,
) -> Result<Option<NamedFont>, String> {
let mut candidates = Vec::new();
let result = self.select_pdf_sfnt(name, from, kind, &mut candidates);
self.trace.lookups.push(ResourceLookup {
kind: kind.resource_kind(),
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()),
lookup_path: None,
error: result.as_ref().err().cloned(),
});
result
}
fn select_pdf_sfnt(
&mut self,
name: &str,
from: &Path,
kind: PdfSfntKind,
candidates: &mut Vec<PathBuf>,
) -> Result<Option<NamedFont>, String> {
let search_order = match kind {
PdfSfntKind::TrueType => [ResourceKind::TrueType, ResourceKind::OpenType],
PdfSfntKind::Cff { .. } => [ResourceKind::OpenType, ResourceKind::TrueType],
};
let mut seen = BTreeSet::new();
for (entry, _) in search_order
.into_iter()
.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();
// 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);
paths.sort_by(|left, right| (priority(left), left).cmp(&(priority(right), right)));
for candidate in paths {
candidates.push(candidate.clone());
let Some(path) = self.probe(&candidate)? else {
continue;
};
if !seen.insert(path.clone()) {
continue;
}
let data = self.input_file(path.clone())?;
let count = ttf_parser::fonts_in_collection(&data.data).unwrap_or(1) as usize;
if count > self.config.max_index_entries
|| (count > 1 && count > data.data.len().saturating_sub(12) / 4)
{
continue;
}
for index in 0..count as u32 {
if let Some(full_name) = exact_pdf_sfnt_name(&data.data, index, name, kind) {
let resource = self.read_path(path)?;
return Ok(Some(NamedFont {
resource,
index,
full_name,
}));
}
}
}
}
if self.project.is_some() {
return Ok(None);
}
if self.system_fonts.is_none() && !self.replay {
self.system_fonts = Some(system_faces(self.config.max_index_entries));
}
let Some(faces) = &self.system_fonts else {
return Ok(None);
};
let mut matching: Vec<_> = faces
.as_ref()
.map_err(Clone::clone)?
.iter()
.filter(|face| face.postscript == name)
.map(|face| (face.path.clone(), face.index))
.collect();
matching.sort();
matching.dedup();
for (candidate, index) in matching {
candidates.push(candidate.clone());
let Some(path) = self.probe(&candidate)? else {
continue;
};
let data = self.input_file(path.clone())?;
if let Some(full_name) = exact_pdf_sfnt_name(&data.data, index, name, kind) {
let resource = self.read_path(path)?;
return Ok(Some(NamedFont {
resource,
index,
full_name,
}));
}
}
Ok(None)
}
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)
}
}
}