mod symbols;
use std::cell::RefCell;
use std::collections::{BTreeSet, HashMap};
use std::sync::{Arc, LazyLock};
use compatifont::{Description, Group, Item, Level};
use f_office_fonts::environment::{FontEnvironment, OwnFace, WordLine};
use f_office_fonts::{
FaceInfo, FamilyName, FileNotRead, FontDb, FontId, KerningSource, Ligature, MathBars,
MathLimits, MathRadical, Os2Metrics, OutlineError, PathCommand, ScriptLevel, ShapeFailure,
ShapeRequest, ShapedGlyph, version_number,
};
use f_office_units::scale::THOUSANDTHS;
use sha2::{Digest, Sha256};
use crate::params::{STRIKEOUT_WITHOUT_OS2, UNDERLINE_WITHOUT_POST};
use crate::profile::Profile;
use crate::text::StandInLines;
use crate::{ChosenFace, FaceMetrics, Fonts, KerningTable, OutlineCommand, SubstituteLayout};
use f_office_warnings::Name;
use symbols::SymbolDrawing;
pub(crate) use symbols::SymbolFonts;
fn apply_line(line: &WordLine, own: FaceMetrics) -> FaceMetrics {
let em = i64::from(own.units_per_em.max(1));
let units = |thousandths: i16| {
let value = i64::from(thousandths) * em;
i16::try_from((value + value.signum() * (THOUSANDTHS / 2)) / THOUSANDTHS).unwrap_or(0)
};
let ascent = u16::try_from(units(line.ascent)).unwrap_or(0);
FaceMetrics {
hhea_ascender: units(line.ascent),
hhea_descender: -units(line.descent),
hhea_line_gap: 0,
descent: u16::try_from(units(line.descent)).unwrap_or(0),
line_top: ascent,
script_top: ascent,
..own
}
}
pub(crate) const HELVETICA: &str = "Helvetica";
const DRAWN_WITH: &[(&str, &str)] = &[
(HELVETICA, "Arial"),
("Times", "Times New Roman"),
("Courier", "Courier New"),
];
static KNOWN: LazyLock<Vec<Description>> =
LazyLock::new(|| compatifont::known().unwrap_or_default());
pub struct FontChoice<'a> {
db: &'a FontDb,
environment: Arc<FontEnvironment>,
added_families: Vec<FamilyName>,
uses: Vec<(FamilyName, String)>,
descriptions: Vec<Description>,
stand_in_lines: StandInLines,
symbols: Arc<SymbolFonts>,
symbol_drawing: Option<SymbolDrawing>,
chosen: RefCell<HashMap<FamilyName, Answers>>,
kerning_sources: RefCell<HashMap<FontId, KerningSource>>,
described: RefCell<HashMap<FontId, Option<Described>>>,
not_read: RefCell<BTreeSet<FileNotRead>>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum Described {
Exact { at: usize, family: String },
Metrics { family: String },
OtherVersion {
family: String,
made_for: String,
target: String,
},
}
type Answers = Vec<(Request, Option<ChosenFace>)>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Request {
bold: bool,
italic: bool,
named: bool,
}
impl Fonts for FontChoice<'_> {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<ChosenFace> {
self.choose(family, bold, italic, true)
}
fn substitute(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<ChosenFace> {
self.choose(family, bold, italic, false)
}
fn family_substitute(
&self,
family: &FamilyName,
bold: bool,
italic: bool,
) -> Option<ChosenFace> {
let substitute = self.environment.family_substitute(family.as_str())?;
self.choose(&FamilyName::new(substitute), bold, italic, false)
}
fn metafile_face(
&self,
family: &FamilyName,
charset: u8,
pitch_and_family: u8,
) -> Option<FamilyName> {
self.environment
.metafile_face(family.as_str(), charset, pitch_and_family)
.map(FamilyName::new)
}
fn glyph(&self, font: FontId, ch: char) -> Option<u32> {
match self.symbol_face(font) {
Some(face) => face.widths.code(ch),
None => self.db.glyph_id(font, ch),
}
}
fn advance(&self, font: FontId, glyph: u32) -> Option<u16> {
match self.symbol_face(font) {
Some(face) => face.widths.advance(glyph),
None => self.db.advance(font, glyph),
}
}
fn kerning(&self, font: FontId, left: u32, right: u32, table: KerningTable) -> i32 {
match table {
KerningTable::FaceSource => self.db.kerning(font, left, right),
KerningTable::KernTable => {
self.db
.kerning_from(font, left, right, KerningSource::KernTable)
}
}
}
fn kerning_source(&self, font: FontId) -> KerningSource {
*self
.kerning_sources
.borrow_mut()
.entry(font)
.or_insert_with(|| {
self.db
.info(font)
.and_then(|info| {
self.environment
.recorded_kerning(
&info.family,
&info.subfamily,
info.version.as_deref()?,
)
.or_else(|| self.exact_own_face(font)?.kerning)
})
.unwrap_or_else(|| self.db.kerning_source(font))
})
}
fn ligatures(&self, font: FontId, glyphs: &[u32]) -> Vec<Ligature> {
self.db.ligatures(font, glyphs)
}
fn shape(
&self,
font: FontId,
request: &ShapeRequest<'_>,
) -> Result<Vec<ShapedGlyph>, ShapeFailure> {
match self.symbol_face(font) {
Some(face) => Ok(Self::symbol_shape(&face, request)),
None => self.db.shape(font, request),
}
}
fn files_not_read(&self) -> Vec<FileNotRead> {
self.not_read.borrow().iter().cloned().collect()
}
fn family_name(&self, font: FontId) -> Option<String> {
if let Some(face) = self.symbol_face(font) {
return self.symbol_drawing_names(&face).map(|(family, _)| family);
}
self.db.info(font).map(|info| info.family.clone())
}
fn layout_family(&self, font: FontId) -> Option<String> {
if let Some(face) = self.symbol_face(font) {
return Some(Self::symbol_family(&face));
}
let info = self.db.info(font)?;
let target = match self.described(font) {
Some(Described::Exact { family, .. }) => Some(family),
_ => None,
};
Some(target.unwrap_or_else(|| info.family.clone()))
}
fn face_version(&self, font: FontId) -> Option<String> {
if let Some(face) = self.symbol_face(font) {
return self.symbol_drawing_names(&face)?.1;
}
let version = self.db.info(font)?.version.as_deref()?;
Some(version_number(version).to_owned())
}
fn substitute_layout(&self, asked: &FamilyName, font: FontId) -> SubstituteLayout {
if let Some(face) = self.symbol_face(font) {
return if asked.is(&Self::symbol_family(&face)) {
SubstituteLayout::Exact
} else {
SubstituteLayout::Fallback
};
}
match self.described(font) {
Some(Described::Exact { family, .. }) if asked.is(&family) => SubstituteLayout::Exact,
Some(Described::Metrics { family }) if asked.is(&family) => SubstituteLayout::Metrics,
Some(Described::OtherVersion {
family,
made_for,
target,
}) if asked.is(&family) => SubstituteLayout::OtherVersion {
family: Name::new(&family),
made_for: Name::new(&made_for),
target: Name::new(&target),
},
_ if self.is_stand_in_for(asked, font) => SubstituteLayout::Widths,
_ => SubstituteLayout::Fallback,
}
}
fn classification(&self, font: FontId) -> Option<f_office_fonts::FaceClassification> {
if let Some(face) = self.symbol_face(font) {
return Some(face.widths.classification);
}
self.db.info(font).map(|info| info.classification)
}
fn target_face(&self, font: FontId) -> Option<(String, String)> {
if let Some(face) = self.symbol_face(font) {
return self.symbol_target_face(&face);
}
let info = self.db.info(font)?;
let (name, version) = (info.postscript_name.as_ref()?, info.version.as_ref()?);
(self
.environment
.is_target_file(&info.family, &info.subfamily, version)
|| self.exact_own_face(font).is_some())
.then(|| (name.clone(), version.clone()))
}
fn bi_level_advance(&self, font: FontId, glyph: u32, ppem: u16) -> Option<i32> {
match self.symbol_face(font) {
Some(face) => Self::symbol_bi_level_advance(&face, glyph, ppem),
None => self.db.bi_level_advance(font, glyph, ppem),
}
}
fn device_width(&self, font: FontId, glyph: u32, ppem: u16) -> Option<i32> {
match self.symbol_face(font) {
Some(face) => face.widths.device_width(glyph, ppem),
None => self.db.device_width(font, glyph, ppem),
}
}
fn device_heights(&self, font: FontId, pels: u16) -> Option<(i16, i16)> {
match self.symbol_face(font) {
Some(face) => face.widths.heights(pels),
None => self.db.device_heights(font, pels),
}
}
fn ink(&self, font: FontId, glyph: u32) -> Result<Option<(i32, i32)>, OutlineError> {
if let Some(face) = self.symbol_face(font) {
return self.symbol_ink(&face, glyph);
}
let outline = self.db.outline(font, glyph)?;
let heights = outline.iter().flat_map(|command| {
let heights = match *command {
PathCommand::MoveTo(p) | PathCommand::LineTo(p) => [Some(p.y), None, None],
PathCommand::QuadTo(c, p) => [Some(c.y), Some(p.y), None],
PathCommand::CubicTo(c, d, p) => [Some(c.y), Some(d.y), Some(p.y)],
PathCommand::Close => [None, None, None],
};
heights.into_iter().flatten()
});
let range = heights.fold(None, |range: Option<(f32, f32)>, y| {
Some(range.map_or((y, y), |(low, high)| (low.min(y), high.max(y))))
});
Ok(range.map(|(low, high)| (font_units(low.floor()), font_units(high.ceil()))))
}
fn outline(&self, font: FontId, glyph: u32) -> Result<Vec<OutlineCommand>, OutlineError> {
if let Some(face) = self.symbol_face(font) {
return self.symbol_outline(&face, glyph);
}
let at = |p: f_office_fonts::Point| [font_units(p.x.round()), font_units(p.y.round())];
let outline = self.db.outline(font, glyph)?;
Ok(outline
.into_iter()
.map(|command| match command {
PathCommand::MoveTo(p) => OutlineCommand::MoveTo(at(p)),
PathCommand::LineTo(p) => OutlineCommand::LineTo(at(p)),
PathCommand::QuadTo(c, p) => OutlineCommand::QuadTo(at(c), at(p)),
PathCommand::CubicTo(c, d, p) => OutlineCommand::CubicTo(at(c), at(d), at(p)),
PathCommand::Close => OutlineCommand::Close,
})
.collect())
}
fn math_limits(&self, font: FontId) -> Option<MathLimits> {
self.db.math_limits(font)
}
fn math_radical(&self, font: FontId) -> Option<MathRadical> {
self.db.math_radical(font)
}
fn math_bars(&self, font: FontId) -> Option<MathBars> {
self.db.math_bars(font)
}
fn math_skewed_fraction(&self, font: FontId) -> Option<f_office_fonts::MathSkewedFraction> {
self.db.math_skewed_fraction(font)
}
fn math_limit_gaps(&self, font: FontId) -> Option<f_office_fonts::MathLimitGaps> {
self.db.math_limit_gaps(font)
}
fn display_variant(&self, font: FontId, glyph: u32) -> Option<u32> {
self.db.display_variant(font, glyph)
}
fn vertical_variant(&self, font: FontId, glyph: u32, least: i32) -> Option<(u32, bool)> {
self.db.vertical_variant(font, glyph, least)
}
fn math_accent(&self, font: FontId) -> Option<f_office_fonts::MathAccent> {
self.db.math_accent(font)
}
fn math_stretch_stack(&self, font: FontId) -> Option<f_office_fonts::MathStretchStack> {
self.db.math_stretch_stack(font)
}
fn top_accent_attachment(&self, font: FontId, glyph: u32) -> Option<i32> {
self.db.top_accent_attachment(font, glyph)
}
fn horizontal_construction(
&self,
font: FontId,
glyph: u32,
) -> Option<f_office_fonts::HorizontalConstruction> {
self.db.horizontal_construction(font, glyph)
}
fn flattened_accent(&self, font: FontId, glyph: u32) -> Option<u32> {
self.db.flattened_accent(font, glyph)
}
fn dotless_form(&self, font: FontId, glyph: u32) -> Option<u32> {
self.db.dotless_form(font, glyph)
}
fn italic_correction(&self, font: FontId, glyph: u32) -> Option<i32> {
self.db.italic_correction(font, glyph)
}
fn space_after_script(&self, font: FontId) -> Option<i32> {
self.db.space_after_script(font)
}
fn math_kern(
&self,
font: FontId,
glyph: u32,
corner: f_office_fonts::MathCorner,
height: i32,
) -> Option<i32> {
self.db.math_kern(font, glyph, corner, height)
}
fn script_glyph(&self, font: FontId, glyph: u32, level: ScriptLevel) -> Option<u32> {
self.db.script_glyph(font, glyph, level)
}
}
#[expect(
clippy::cast_possible_truncation,
reason = "a glyph's coordinates are font units, far inside i32"
)]
fn font_units(value: f32) -> i32 {
value as i32
}
impl<'a> FontChoice<'a> {
pub(crate) fn of(db: &'a FontDb, profile: &Profile) -> Self {
Self::with_environment(db, profile.shared_font_environment(), profile)
}
#[cfg(test)]
pub(crate) fn new(db: &'a FontDb, environment: &FontEnvironment, profile: &Profile) -> Self {
Self::with_environment(db, Arc::new(environment.clone()), profile)
}
fn with_environment(
db: &'a FontDb,
environment: Arc<FontEnvironment>,
profile: &Profile,
) -> Self {
let descriptions = (db.descriptions().iter())
.chain(KNOWN.iter())
.cloned()
.collect();
Self {
db,
environment,
added_families: profile.added_families().map(FamilyName::new).collect(),
uses: (profile.used_families())
.map(|(family, uses)| (FamilyName::new(family), uses.to_owned()))
.collect(),
descriptions,
stand_in_lines: profile.stand_in_lines(),
symbols: profile.symbol_fonts(),
symbol_drawing: SymbolDrawing::of(db),
chosen: RefCell::default(),
kerning_sources: RefCell::default(),
described: RefCell::default(),
not_read: RefCell::default(),
}
}
fn choose(
&self,
family: &FamilyName,
bold: bool,
italic: bool,
named: bool,
) -> Option<ChosenFace> {
let request = Request {
bold,
italic,
named,
};
let known = self.chosen.borrow().get(family).and_then(|answers| {
answers
.iter()
.find(|(asked, _)| *asked == request)
.map(|(_, face)| *face)
});
if let Some(face) = known {
return face;
}
let mut not_loaded = Vec::new();
let face = loop {
let Some(chosen) = self.choose_anew(family, bold, italic, named, ¬_loaded) else {
break None;
};
if self.loads(chosen.font) {
break Some(chosen);
}
not_loaded.push(chosen.font);
};
self.chosen
.borrow_mut()
.entry(family.clone())
.or_default()
.push((request, face));
face
}
fn loads(&self, font: FontId) -> bool {
let Err(not_read) = self.db.load(font) else {
return true;
};
self.not_read.borrow_mut().insert(not_read);
false
}
fn choose_anew(
&self,
name: &FamilyName,
bold: bool,
italic: bool,
named: bool,
not_loaded: &[FontId],
) -> Option<ChosenFace> {
let family = name.as_str();
let drawn_with = self.drawn_with(family);
if !self.environment.permits(family)
&& drawn_with.is_empty()
&& self.environment.face_name(family).is_none()
{
return None;
}
let older = family
.strip_suffix("MT")
.or_else(|| family.strip_suffix(" MS"))
.filter(|name| !name.is_empty());
let accept = |id, info: &FaceInfo| !not_loaded.contains(&id) && self.permits_face(info);
let found = self.db.query_with(name, bold, italic, accept).or_else(|| {
older.and_then(|older| {
self.db
.query_with(&FamilyName::new(older), bold, italic, accept)
})
});
if let Some(font) = found {
return self.chosen_own(font, family, (bold, italic), named);
}
self.draw_stand_in(family, &drawn_with, (bold, italic), not_loaded)
.or_else(|| self.symbol_stand_in(family, (bold, italic), named))
.or_else(|| self.draw_face_name(family, (bold, italic), not_loaded))
.or_else(|| {
let font = self.db.query_typographic_with(name, bold, italic, accept)?;
self.chosen_own(font, family, (bold, italic), named)
})
}
fn chosen_own(
&self,
font: FontId,
family: &str,
(bold, italic): (bool, bool),
named: bool,
) -> Option<ChosenFace> {
let info = self.db.info(font)?;
if self.environment.lacks(&info.family)
&& !self.added(&info.family)
&& !self.reference_stand_in(info)
{
return None;
}
let synthetic_bold = bold && info.light();
let synthetic_italic = italic && !info.italic;
let own = self.metrics(font)?;
let line = (self.line(family)).filter(|line| named && line.over_own_file);
Some(ChosenFace {
font,
metrics: line.map_or(own, |line| apply_line(line, own)),
synthetic_bold,
synthetic_italic,
stands_in: false,
})
}
fn exact_own_face(&self, font: FontId) -> Option<&OwnFace> {
match self.described(font)? {
Described::Exact { at, .. } => self.environment.faces().get(at),
Described::Metrics { .. } | Described::OtherVersion { .. } => None,
}
}
fn described(&self, font: FontId) -> Option<Described> {
if let Some(known) = self.described.borrow().get(&font) {
return known.clone();
}
let answer = self.describe(font);
self.described.borrow_mut().insert(font, answer.clone());
answer
}
fn describe(&self, font: FontId) -> Option<Described> {
let info = self.db.info(font)?;
let version = version_number(info.version.as_deref()?);
let description = self.descriptions.iter().find(|description| {
FamilyName::new(description.family_name.as_str()).is(&info.family)
&& description.version == version
})?;
let file = description.font(&info.subfamily)?;
let (bytes, _) = self.db.data(font)?;
if sha256(bytes) != file.sha256.as_str() {
return None;
}
let mut metrics = None;
let mut other = None;
for entry in &description.compatible_with {
match self.describe_entry(entry, &info.subfamily) {
Some(exact @ Described::Exact { .. }) => return Some(exact),
Some(found @ Described::Metrics { .. }) => {
metrics.get_or_insert(found);
}
Some(found @ Described::OtherVersion { .. }) => {
other.get_or_insert(found);
}
None => {}
}
}
metrics.or(other)
}
fn describe_entry(
&self,
entry: &compatifont::CompatibleWith,
subfamily: &str,
) -> Option<Described> {
if entry.basis != compatifont::Basis::Check {
return None;
}
let level = entry.level()?;
let exact_layout = level == Level::Layout;
let exact_metrics = level == Level::Widths && line_metrics_equal(&entry.items);
if !exact_layout && !exact_metrics {
return None;
}
let style = entry
.subfamilies
.get(subfamily)
.map_or(subfamily, String::as_str);
let mut own = (self.environment.faces().iter().enumerate())
.filter(|(_, own)| own_matches_entry(own, &entry.family_name, style));
let made_for = entry.version.as_deref();
if let Some((at, _)) = own
.clone()
.find(|(_, own)| Some(version_number(&own.version)) == made_for)
{
return Some(if exact_layout {
Described::Exact {
at,
family: entry.family_name.clone(),
}
} else {
Described::Metrics {
family: entry.family_name.clone(),
}
});
}
let (_, own) = own.next()?;
Some(Described::OtherVersion {
family: entry.family_name.clone(),
made_for: made_for?.to_owned(),
target: version_number(&own.version).to_owned(),
})
}
fn drawn_with(&self, family: &str) -> Vec<String> {
let mut drawn_with: Vec<String> = Vec::new();
let mut last = family.to_owned();
while let Some(next) = self.next_family(&last) {
let again = |name: &String| FamilyName::new(name.as_str()).is(next);
if FamilyName::new(family).is(next) || drawn_with.iter().any(again) {
break;
}
drawn_with.push(next.to_owned());
last = next.to_owned();
}
let version = self.target_version(&last);
for candidate in compatifont::choose(&self.descriptions, &last, version) {
let name = &candidate.description.family_name;
if !(drawn_with.iter()).any(|other| FamilyName::new(other.as_str()).is(name)) {
drawn_with.push(name.clone());
}
}
drawn_with
}
fn is_stand_in_for(&self, asked: &FamilyName, font: FontId) -> bool {
let Some(info) = self.db.info(font) else {
return false;
};
let used = FamilyName::new(&info.family);
self.drawn_with(asked.as_str())
.iter()
.any(|candidate| used.is(candidate))
}
fn next_family(&self, family: &str) -> Option<&str> {
(self.uses.iter())
.find(|(of, _)| of.is(family))
.map(|(_, uses)| uses.as_str())
.or_else(|| {
(DRAWN_WITH.iter())
.find(|(of, _)| FamilyName::from_static(of).is(family))
.map(|(_, uses)| *uses)
})
}
fn target_own_face(&self, family: &str) -> Option<&OwnFace> {
let faces =
|| (self.environment.faces().iter()).filter(|face| own_matches_family(face, family));
faces()
.find(|face| own_matches_entry(face, family, "Regular"))
.or_else(|| faces().next())
}
fn target_version(&self, family: &str) -> Option<&str> {
self.target_own_face(family)
.map(|face| version_number(&face.version))
}
fn target_units_per_em(&self, family: &str) -> Option<u16> {
self.target_own_face(family)
.and_then(|face| face.units_per_em)
}
fn line(&self, family: &str) -> Option<&WordLine> {
(self.environment.line(family)).filter(|_| self.stand_in_lines.of_family(family))
}
fn permits_face(&self, info: &FaceInfo) -> bool {
info.postscript_name
.as_deref()
.is_none_or(|name| self.environment.permits(name))
|| self.added(&info.family)
|| self.reference_stand_in(info)
}
fn added(&self, family: &str) -> bool {
self.added_families.iter().any(|added| added.is(family))
}
fn reference_stand_in(&self, info: &FaceInfo) -> bool {
!self.environment.available().is_empty()
&& info.version.as_deref().is_some_and(|version| {
self.environment
.is_target_file(&info.family, &info.subfamily, version)
})
&& !self.drawn_with(&info.family).is_empty()
}
fn draw_stand_in(
&self,
family: &str,
drawn_with: &[String],
(bold, italic): (bool, bool),
not_loaded: &[FontId],
) -> Option<ChosenFace> {
let accept = |id, _: &FaceInfo| !not_loaded.contains(&id);
let font = drawn_with.iter().find_map(|other| {
let other = FamilyName::new(other.as_str());
self.db
.query_with(&other, bold, italic, accept)
.or_else(|| self.db.query_with(&other, false, false, accept))
})?;
let info = self.db.info(font)?;
let own = self.metrics(font)?;
let mut metrics = self.line(family).map_or(own, |line| apply_line(line, own));
if let Some(target_em) = self.target_units_per_em(family)
&& target_em != metrics.units_per_em
{
metrics.target_units_per_em = Some(target_em);
}
Some(ChosenFace {
font,
metrics,
synthetic_bold: bold && info.light(),
synthetic_italic: italic && !info.italic,
stands_in: true,
})
}
fn draw_face_name(
&self,
name: &str,
(bold, italic): (bool, bool),
not_loaded: &[FontId],
) -> Option<ChosenFace> {
let face = self.environment.face_name(name)?;
let style = face.style.as_deref().map_or((bold, italic), |style| {
(style.contains("Bold"), style.contains("Italic"))
});
let drawn_with = self.drawn_with(&face.family);
let chosen = self.draw_stand_in(&face.family, &drawn_with, style, not_loaded)?;
let info = self.db.info(chosen.font)?;
Some(ChosenFace {
synthetic_bold: bold && info.light(),
synthetic_italic: italic && !info.italic,
..chosen
})
}
fn metrics(&self, font: FontId) -> Option<FaceMetrics> {
self.db.metrics(font).map(metrics_of)
}
}
fn own_matches_family(own: &OwnFace, family: &str) -> bool {
if own.family == family {
return true;
}
let Some(suffix) = family
.strip_prefix(&own.family)
.and_then(|rest| rest.strip_prefix(' '))
else {
return false;
};
own.style == suffix
|| own
.style
.strip_prefix(suffix)
.is_some_and(|rest| rest.starts_with(' '))
}
fn own_matches_entry(own: &OwnFace, family: &str, style: &str) -> bool {
if own.family == family {
return own.style == style;
}
let Some(suffix) = family
.strip_prefix(&own.family)
.and_then(|rest| rest.strip_prefix(' '))
else {
return false;
};
if style == "Regular" {
own.style == suffix
} else {
own.style
.strip_prefix(suffix)
.and_then(|rest| rest.strip_prefix(' '))
== Some(style)
}
}
fn line_metrics_equal(items: &std::collections::BTreeMap<Item, compatifont::ItemResult>) -> bool {
Item::all()
.filter(|item| item.group() == Group::Line)
.all(|item| items.get(&item).is_some_and(|result| result.is_same()))
}
fn metrics_of(m: &f_office_fonts::FontMetrics) -> FaceMetrics {
let hhea_descent = u16::try_from(i32::from(m.hhea.descender).abs()).unwrap_or(0);
let hhea_ascent = u16::try_from(m.hhea.ascender.max(0)).unwrap_or(0);
let hhea_line =
i32::from(m.hhea.ascender) - i32::from(m.hhea.descender) + i32::from(m.hhea.line_gap);
let hhea_top = u16::try_from((hhea_line - i32::from(hhea_descent)).max(0)).unwrap_or(0);
let (line_top, script_top) = m
.os2
.as_ref()
.map_or((hhea_top, hhea_ascent), |os2| script_tops(os2, hhea_line));
let em = i16::try_from(m.units_per_em).unwrap_or(i16::MAX);
let part = |parts: i16| em / parts;
let (underline_position, underline_thickness) = UNDERLINE_WITHOUT_POST;
let (strikeout_position, strikeout_thickness) = STRIKEOUT_WITHOUT_OS2;
FaceMetrics {
units_per_em: m.units_per_em,
hhea_ascender: m.hhea.ascender,
hhea_descender: m.hhea.descender,
hhea_line_gap: m.hhea.line_gap,
descent: m.os2.as_ref().map_or(hhea_descent, line_descent),
underline_position: m
.underline
.as_ref()
.map_or(-part(underline_position), |u| u.position),
underline_thickness: m
.underline
.as_ref()
.map_or(part(underline_thickness), |u| u.thickness),
strikeout_position: m
.os2
.as_ref()
.map_or(part(strikeout_position), |os2| os2.strikeout.position),
strikeout_thickness: m
.os2
.as_ref()
.map_or(part(strikeout_thickness), |os2| os2.strikeout.thickness),
superscript_offset: m.os2.as_ref().map_or(0, |os2| os2.superscript.y_offset),
subscript_offset: m.os2.as_ref().map_or(0, |os2| os2.subscript.y_offset),
superscript_size: m.os2.as_ref().map_or(0, |os2| os2.superscript.y_size),
subscript_size: m.os2.as_ref().map_or(0, |os2| os2.subscript.y_size),
line_top,
script_top,
east_asian: m.os2.as_ref().is_some_and(|os2| os2.east_asian),
average_width: m.os2.as_ref().map_or(0, |os2| os2.average_width),
target_units_per_em: None,
}
}
fn script_tops(os2: &Os2Metrics, hhea_line: i32) -> (u16, u16) {
let clamp = |value: i32| u16::try_from(value.max(0)).unwrap_or(u16::MAX);
if os2.use_typo_metrics {
let top = clamp(i32::from(os2.typo.ascender) + i32::from(os2.typo.line_gap));
return (top, top);
}
let (ascent, descent) = (i32::from(os2.win_ascent), i32::from(os2.win_descent));
(
clamp(hhea_line.max(ascent + descent) - descent),
clamp(ascent),
)
}
fn line_descent(os2: &Os2Metrics) -> u16 {
let typo = os2.typo.descender.unsigned_abs();
if os2.use_typo_metrics {
typo
} else {
os2.win_descent
}
}
fn sha256(bytes: &[u8]) -> String {
use std::fmt::Write as _;
let digest = Sha256::digest(bytes);
digest
.iter()
.fold(String::with_capacity(digest.len() * 2), |mut hex, byte| {
let _ = write!(hex, "{byte:02x}");
hex
})
}
#[cfg(test)]
mod tests;