Select named XeTeX faces by optical size

This commit is contained in:
gloamxun committed 2026-11-28 13:01:52 +08:00
1 parent 115e1f0fe0
commit d4e78bc29a
9 files changed
+290 -31

No files matched your search

@@ -1,5 +1,6 @@
//! Named OpenType faces from the host catalogue or an atomic project.
use super::*;
use crate::opentype::{OpticalSize, optical_size};
use rustybuzz::ttf_parser::{self, name_id};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -32,6 +33,10 @@ pub(super) struct NamedFace {
impl NamedFace {
fn at(path: &Path, data: &[u8], index: u32) -> Option<Self> {
let face = ttf_parser::Face::parse(data, index).ok()?;
Self::from_face(path, &face, index)
}
fn from_face(path: &Path, face: &ttf_parser::Face<'_>, index: u32) -> Option<Self> {
let name = |id| {
face.names()
.into_iter()
@@ -110,12 +115,35 @@ impl FontDirectory {
}
}
struct NamedSelection {
design_base: Option<NamedFace>,
preferred: NamedFace,
family: Vec<NamedFace>,
}
struct OpenedFace {
file: SnapshotFile,
index: u32,
full_name: String,
optical: Option<OpticalSize>,
}
impl OpenedFace {
fn into_font(self) -> NamedFont {
NamedFont {
resource: self.file.into_loaded(),
index: self.index,
full_name: self.full_name,
}
}
}
fn matching_face(
scoped: &[NamedFace],
name: &str,
style: FontStyle,
candidates: &mut Vec<PathBuf>,
) -> Option<NamedFace> {
) -> Option<NamedSelection> {
let mut matches: Vec<_> = scoped
.iter()
.filter_map(|face| {
@@ -130,7 +158,7 @@ fn matching_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 (priority, _, _, _, base) = matches.first()?;
let face = if style.bold || style.italic {
let bold = style.bold || base.bold;
let italic = style.italic || base.italic;
@@ -145,7 +173,22 @@ fn matching_face(
if !candidates.contains(&face.path) {
candidates.push(face.path.clone());
}
Some((*face).clone())
let mut family: Vec<_> = scoped
.iter()
.filter(|other| {
!face.family.is_empty()
&& other.family == face.family
&& (other.path != face.path || other.index != face.index)
})
.cloned()
.collect();
family.sort_by(|a, b| (&a.style, &a.path, a.index).cmp(&(&b.style, &b.path, b.index)));
Some(NamedSelection {
// A family-only match uses the manager's 10pt nominal size.
design_base: (*priority < 3).then(|| (*base).clone()),
preferred: (*face).clone(),
family,
})
}
#[derive(Clone, Copy)]
@@ -294,9 +337,20 @@ impl FileWorld {
name: &str,
style: FontStyle,
from: &Path,
) -> Result<Option<NamedFont>, String> {
self.read_named_font_with_size(name, style, None, from)
}
/// Resolve a named font after applying its optical family size ranges.
pub fn read_named_font_with_size(
&mut self,
name: &str,
style: FontStyle,
optical_points: Option<f64>,
from: &Path,
) -> Result<Option<NamedFont>, String> {
let mut candidates = Vec::new();
let result = self.select_named_face(name, style, from, &mut candidates);
let result = self.select_named_face(name, style, optical_points, from, &mut candidates);
self.trace.lookups.push(ResourceLookup {
kind: ResourceKind::OpenType,
name: name.into(),
@@ -445,6 +499,7 @@ impl FileWorld {
&mut self,
name: &str,
style: FontStyle,
optical_points: Option<f64>,
from: &Path,
candidates: &mut Vec<PathBuf>,
) -> Result<Option<NamedFont>, String> {
@@ -484,16 +539,17 @@ impl FileWorld {
}
self.project_named_fonts.as_deref().unwrap_or_default()
} else {
return self.select_host_or_directory_font(name, style, from, candidates);
return self.select_host_or_directory_font(name, style, optical_points, from, candidates);
};
let face = matching_face(scoped, name, style, candidates);
self.open_named_face(face)
self.open_named_selection(face, optical_points, candidates)
}
fn select_host_or_directory_font(
&mut self,
name: &str,
style: FontStyle,
optical_points: Option<f64>,
from: &Path,
candidates: &mut Vec<PathBuf>,
) -> Result<Option<NamedFont>, String> {
@@ -502,7 +558,7 @@ impl FileWorld {
}
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)? {
if let Some(font) = self.open_named_selection(face, optical_points, candidates)? {
return Ok(Some(font));
}
}
@@ -521,7 +577,7 @@ impl FileWorld {
continue;
}
let face = matching_face(self.directory_faces(&scope)?, name, style, candidates);
if let Some(font) = self.open_named_face(face)? {
if let Some(font) = self.open_named_selection(face, optical_points, candidates)? {
return Ok(Some(font));
}
searched.push(scope);
@@ -602,33 +658,78 @@ impl FileWorld {
.cloned().collect())
}
fn open_named_face(&mut self, face: Option<NamedFace>) -> Result<Option<NamedFont>, String> {
let Some(face) = face else { return Ok(None) };
fn open_named_selection(
&mut self,
selection: Option<NamedSelection>,
optical_points: Option<f64>,
candidates: &mut Vec<PathBuf>,
) -> Result<Option<NamedFont>, String> {
let Some(selection) = selection else { return Ok(None) };
let Some(mut best) = self.open_named_face(&selection.preferred)? else { return Ok(None) };
let Some(range) = best.optical.filter(|size| size.subfamily != 0) else {
return Ok(Some(best.into_font()));
};
let points = match (optical_points, selection.design_base) {
(Some(points), _) => points,
(None, Some(base)) if base.path == selection.preferred.path
&& base.index == selection.preferred.index => range.design_points(),
(None, Some(base)) => self.open_named_face(&base)?
.and_then(|face| face.optical).map_or(10.0, OpticalSize::design_points),
(None, None) => 10.0,
};
let mut mismatch = range.mismatch(points);
if points > 0.0 && mismatch > 0.0 {
for sibling in &selection.family {
if !candidates.contains(&sibling.path) {
candidates.push(sibling.path.clone());
}
let Some(candidate) = self.open_named_face(sibling)? else { continue };
let Some(other) = candidate.optical.filter(|size| size.subfamily == range.subfamily)
else { continue };
let distance = other.mismatch(points);
if distance < mismatch {
best = candidate;
mismatch = distance;
if mismatch <= 0.0 {
break;
}
}
}
}
Ok(Some(best.into_font()))
}
fn open_named_face(&mut self, face: &NamedFace) -> Result<Option<OpenedFace>, String> {
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 file = self.read_shared_path(path)?;
if face.version.as_ref().is_some_and(|version| version != &file.version) {
return Err(format!("named font directory changed for {}", file.version.path.display()));
}
let parsed = ttf_parser::Face::parse(&file.data, face.index).map_err(|error| {
format!("named font face {} in {}: {error}", face.index, file.version.path.display())
})?;
let actual =
NamedFace::at(&resource.version.path, &resource.data, face.index).ok_or_else(|| {
NamedFace::from_face(&file.version.path, &parsed, face.index).ok_or_else(|| {
format!(
"named font has no valid face {} in {}",
face.index,
resource.version.path.display()
file.version.path.display()
)
})?;
if !face.postscript.is_empty() && face.postscript != actual.postscript {
return Err(format!(
"named font catalogue changed for {}",
resource.version.path.display()
file.version.path.display()
));
}
Ok(Some(NamedFont {
resource,
let optical = optical_size(&parsed);
Ok(Some(OpenedFace {
file,
index: face.index,
full_name: actual.full_name,
optical,
}))
}