use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use crate::{
FontDb, FontId, KerningSource, MathCorner, PathCommand, ScriptLevel, ShapeRequest, ShapedScript,
};
mod compare;
pub use compare::{Comparison, Difference, KindComparison};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum ValueKind {
Characters,
Advance,
Box,
Kerning,
KernTable,
LineValues,
Selection,
PixelHeights,
BiLevelAdvance,
DeviceWidth,
Ligatures,
Forms,
Math,
Shaping,
}
impl ValueKind {
pub const ALL: [Self; 14] = [
Self::Characters,
Self::Advance,
Self::Box,
Self::Kerning,
Self::KernTable,
Self::LineValues,
Self::Selection,
Self::PixelHeights,
Self::BiLevelAdvance,
Self::DeviceWidth,
Self::Ligatures,
Self::Forms,
Self::Math,
Self::Shaping,
];
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Characters => "characters",
Self::Advance => "advance",
Self::Box => "box",
Self::Kerning => "kerning",
Self::KernTable => "kern-table",
Self::LineValues => "line-values",
Self::Selection => "selection",
Self::PixelHeights => "pixel-heights",
Self::BiLevelAdvance => "bi-level",
Self::DeviceWidth => "device-width",
Self::Ligatures => "ligatures",
Self::Forms => "forms",
Self::Math => "math",
Self::Shaping => "shaping",
}
}
#[must_use]
pub fn named(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|kind| kind.name() == name)
}
#[must_use]
pub const fn in_pixels(self) -> bool {
matches!(
self,
Self::PixelHeights | Self::BiLevelAdvance | Self::DeviceWidth
)
}
const fn unlisted(self) -> Option<&'static [i64]> {
match self {
Self::Kerning | Self::KernTable => Some(&[0]),
_ => None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Place {
Face(&'static str),
Character(char),
Pair(char, char),
Size(u16),
CharacterAt(char, u16),
Sequence(Vec<char>),
CharacterValue(char, &'static str),
}
impl Place {
#[must_use]
pub fn characters(&self) -> Vec<char> {
match self {
Self::Face(_) | Self::Size(_) => Vec::new(),
Self::Character(c) | Self::CharacterAt(c, _) | Self::CharacterValue(c, _) => {
vec![*c]
}
Self::Pair(a, b) => vec![*a, *b],
Self::Sequence(characters) => characters.clone(),
}
}
}
impl Place {
#[must_use]
pub const fn size(&self) -> Option<u16> {
match self {
Self::Size(size) | Self::CharacterAt(_, size) => Some(*size),
_ => None,
}
}
}
impl fmt::Display for Place {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let code = |c: &char| format!("U+{:04X}", u32::from(*c));
match self {
Self::Face(name) => f.write_str(name),
Self::Character(c) => f.write_str(&code(c)),
Self::Pair(a, b) => write!(f, "{} {}", code(a), code(b)),
Self::Size(size) => write!(f, "{size} px"),
Self::CharacterAt(c, size) => write!(f, "{} at {size} px", code(c)),
Self::Sequence(characters) => {
let codes: Vec<String> = characters.iter().map(code).collect();
f.write_str(&codes.join(" "))
}
Self::CharacterValue(c, name) => write!(f, "{} {name}", code(c)),
}
}
}
pub type Values = Vec<i64>;
#[derive(Clone, Debug, Default, PartialEq)]
pub struct LayoutValues {
units_per_em: u16,
sizes: Vec<u16>,
values: BTreeMap<ValueKind, BTreeMap<Place, Values>>,
}
impl LayoutValues {
#[must_use]
pub const fn units_per_em(&self) -> u16 {
self.units_per_em
}
#[must_use]
pub fn sizes(&self) -> &[u16] {
&self.sizes
}
#[must_use]
pub fn of(&self, kind: ValueKind) -> Option<&BTreeMap<Place, Values>> {
self.values.get(&kind)
}
pub fn characters(&self) -> impl Iterator<Item = char> + '_ {
self.values
.get(&ValueKind::Characters)
.into_iter()
.flat_map(BTreeMap::keys)
.flat_map(Place::characters)
}
pub fn keep_characters(&mut self, range: std::ops::RangeInclusive<char>) {
for places in self.values.values_mut() {
places.retain(|place, _| place.characters().iter().all(|c| range.contains(c)));
}
}
}
impl FontDb {
#[must_use]
pub fn layout_values(&self, id: FontId, sizes: &[u16]) -> Option<LayoutValues> {
let metrics = self.metrics(id)?;
let mut reader = Reader {
db: self,
id,
glyphs: mapped_characters(self, id),
values: BTreeMap::new(),
};
reader.characters();
reader.kerning();
reader.line_values();
reader.selection();
reader.pixels(sizes);
reader.ligatures();
reader.forms();
reader.math(metrics.units_per_em);
reader.shaping();
Some(LayoutValues {
units_per_em: metrics.units_per_em,
sizes: sizes.to_vec(),
values: reader.values,
})
}
}
fn mapped_characters(db: &FontDb, id: FontId) -> BTreeMap<char, u32> {
let listed: Vec<u32> = db
.face(id)
.and_then(crate::face::Face::font)
.map_or_else(Vec::new, |font| {
font.charmap().unicodes().map(|(code, _)| code).collect()
});
listed
.into_iter()
.chain(0..=0xFF)
.filter_map(char::from_u32)
.filter_map(|c| Some((c, db.glyph_id(id, c)?)))
.collect()
}
struct Reader<'a> {
db: &'a FontDb,
id: FontId,
glyphs: BTreeMap<char, u32>,
values: BTreeMap<ValueKind, BTreeMap<Place, Values>>,
}
fn number(value: impl Into<i64>) -> i64 {
value.into()
}
fn flag(set: bool) -> i64 {
i64::from(set)
}
impl Reader<'_> {
fn put(&mut self, kind: ValueKind, place: Place, values: Values) {
self.values.entry(kind).or_default().insert(place, values);
}
fn characters_of(&self) -> BTreeMap<u32, Vec<char>> {
let mut by_glyph: BTreeMap<u32, Vec<char>> = BTreeMap::new();
for (&c, &glyph) in &self.glyphs {
by_glyph.entry(glyph).or_default().push(c);
}
by_glyph
}
fn glyph_values(&self, glyph: u32) -> Values {
let mut values: Values = self
.db
.advance(self.id, glyph)
.map(number)
.into_iter()
.collect();
values.extend(glyph_box(self.db, self.id, glyph));
values
}
fn characters(&mut self) {
let glyphs: Vec<(char, u32)> = self.glyphs.iter().map(|(&c, &g)| (c, g)).collect();
for (c, glyph) in glyphs {
self.put(ValueKind::Characters, Place::Character(c), Vec::new());
if let Some(advance) = self.db.advance(self.id, glyph) {
self.put(
ValueKind::Advance,
Place::Character(c),
vec![number(advance)],
);
}
let shape = glyph_box(self.db, self.id, glyph);
self.put(ValueKind::Box, Place::Character(c), shape);
}
}
fn kerning(&mut self) {
let source = self.db.kerning_source(self.id);
let gpos = source == KerningSource::Gpos;
self.put(
ValueKind::Kerning,
Place::Face("source is GPOS"),
vec![flag(gpos)],
);
let table = self.db.has_kern_table(self.id);
self.put(
ValueKind::KernTable,
Place::Face("has a kern table"),
vec![flag(table)],
);
let glyphs: BTreeSet<u32> = self.glyphs.values().copied().collect();
let by_glyph = self.characters_of();
for (left, right) in self.db.listed_kerning_pairs(self.id, &glyphs) {
let values = [
(ValueKind::Kerning, self.db.kerning(self.id, left, right)),
(
ValueKind::KernTable,
self.db
.kerning_from(self.id, left, right, KerningSource::KernTable),
),
];
for (kind, value) in values {
if value != 0 {
self.put_pairs(kind, &by_glyph, (left, right), value);
}
}
}
}
fn put_pairs(
&mut self,
kind: ValueKind,
by_glyph: &BTreeMap<u32, Vec<char>>,
(left, right): (u32, u32),
value: i32,
) {
let lefts = by_glyph.get(&left).map_or(&[][..], Vec::as_slice);
let rights = by_glyph.get(&right).map_or(&[][..], Vec::as_slice);
for &a in lefts {
for &b in rights {
self.put(kind, Place::Pair(a, b), vec![number(value)]);
}
}
}
fn line_values(&mut self) {
let Some(metrics) = self.db.metrics(self.id) else {
return;
};
for (name, value) in metric_fields(metrics) {
self.put(ValueKind::LineValues, Place::Face(name), vec![value]);
}
}
fn selection(&mut self) {
let Some(info) = self.db.info(self.id) else {
return;
};
let classification = &info.classification;
let mut fields = vec![
("weight", number(info.weight)),
("italic", flag(info.italic)),
("PANOSE weight", number(info.panose_weight)),
("East Asian code pages", flag(classification.east_asian)),
];
let panose = PANOSE_NAMES.iter().zip(classification.panose);
fields.extend(panose.map(|(&name, value)| (name, number(value))));
for (name, value) in fields {
self.put(ValueKind::Selection, Place::Face(name), vec![value]);
}
}
fn pixels(&mut self, sizes: &[u16]) {
for &size in sizes {
if let Some((above, below)) = self.db.device_heights(self.id, size) {
let values = vec![number(above), number(below)];
self.put(ValueKind::PixelHeights, Place::Size(size), values);
}
}
for (glyph, characters) in self.characters_of() {
for &size in sizes {
let bi_level = self.db.bi_level_advance(self.id, glyph, size);
let device = self.db.device_width(self.id, glyph, size);
for &c in &characters {
let at = Place::CharacterAt(c, size);
if let Some(width) = bi_level {
self.put(ValueKind::BiLevelAdvance, at.clone(), vec![number(width)]);
}
if let Some(width) = device {
self.put(ValueKind::DeviceWidth, at, vec![number(width)]);
}
}
}
}
}
fn ligatures(&mut self) {
let by_glyph = self.characters_of();
for glyphs in self.db.ligature_sequences(self.id) {
let mut values = Vec::new();
for ligature in self.db.ligatures(self.id, &glyphs) {
values.push(count(ligature.start));
values.push(count(ligature.len));
values.extend(self.glyph_values(ligature.glyph));
}
for characters in sequences_of(&glyphs, &by_glyph) {
self.put(
ValueKind::Ligatures,
Place::Sequence(characters),
values.clone(),
);
}
}
}
fn forms(&mut self) {
let glyphs: Vec<(char, u32)> = self.glyphs.iter().map(|(&c, &g)| (c, g)).collect();
for (c, glyph) in glyphs {
let forms = [
(
"script glyph",
self.db.script_glyph(self.id, glyph, ScriptLevel::Script),
),
(
"script-of-script glyph",
self.db
.script_glyph(self.id, glyph, ScriptLevel::ScriptOfScript),
),
("flattened accent", self.db.flattened_accent(self.id, glyph)),
("dotless form", self.db.dotless_form(self.id, glyph)),
];
for (name, form) in forms {
if let Some(form) = form {
let values = self.glyph_values(form);
self.put(ValueKind::Forms, Place::CharacterValue(c, name), values);
}
}
}
}
fn math(&mut self, units_per_em: u16) {
for (name, value) in math_constants(self.db, self.id) {
self.put(ValueKind::Math, Place::Face(name), vec![value]);
}
let glyphs: Vec<(char, u32)> = self.glyphs.iter().map(|(&c, &g)| (c, g)).collect();
for (c, glyph) in glyphs {
for (name, values) in self.math_values(glyph, units_per_em) {
self.put(ValueKind::Math, Place::CharacterValue(c, name), values);
}
}
}
fn math_values(&self, glyph: u32, units_per_em: u16) -> Vec<(&'static str, Values)> {
let (db, id) = (self.db, self.id);
let mut found = Vec::new();
if let Some(value) = db.italic_correction(id, glyph) {
found.push(("italic correction", vec![number(value)]));
}
if let Some(value) = db.top_accent_attachment(id, glyph) {
found.push(("top accent attachment", vec![number(value)]));
}
if let Some(variant) = db.display_variant(id, glyph) {
found.push(("display variant", self.glyph_values(variant)));
}
let em = i32::from(units_per_em);
let heights = [0, em / 2, em, em * 3 / 2, em * 2, em * 3, i32::MAX];
let variants: Vec<Values> = heights
.iter()
.filter_map(|&least| db.vertical_variant(id, glyph, least))
.map(|(variant, reached)| {
let mut values = self.glyph_values(variant);
values.push(flag(reached));
values
})
.collect();
if !variants.is_empty() {
found.push(("vertical variants", variants.concat()));
}
if let Some(construction) = db.horizontal_construction(id, glyph) {
found.push(("horizontal construction", self.construction(&construction)));
}
found.extend(math_kerning(db, id, glyph, units_per_em));
found
}
fn shaping(&mut self) {
let shaped: Vec<(char, ShapedScript)> = self
.glyphs
.keys()
.filter_map(|&c| Some((c, ShapedScript::of(c)?)))
.collect();
for (c, script) in shaped {
for repeat in [1, 3] {
let text: String = std::iter::repeat_n(c, repeat).collect();
let request = ShapeRequest {
text: &text,
script,
direction: script.direction(),
language: None,
};
let Ok(glyphs) = self.db.shape(self.id, &request) else {
continue;
};
let mut values = Vec::new();
for glyph in glyphs {
values.push(count(glyph.cluster));
values.push(number(glyph.advance));
values.push(number(glyph.offset.0));
values.push(number(glyph.offset.1));
values.extend(self.glyph_values(glyph.glyph));
}
let place = Place::Sequence(vec![c; repeat]);
self.put(ValueKind::Shaping, place, values);
}
}
}
fn construction(&self, construction: &crate::HorizontalConstruction) -> Values {
let mut values = vec![count(construction.variants.len())];
for &(variant, measurement) in &construction.variants {
values.push(number(measurement));
values.extend(self.glyph_values(variant));
}
values.push(count(construction.assembly.len()));
for part in &construction.assembly {
values.push(number(part.full_advance));
values.push(flag(part.extender));
values.extend(self.glyph_values(part.glyph));
}
values
}
}
fn count(value: usize) -> i64 {
i64::try_from(value).unwrap_or(i64::MAX)
}
#[expect(
clippy::cast_possible_truncation,
reason = "a glyph's coordinates are font units, far inside i64, and are whole when this \
is called"
)]
fn font_units(value: f32) -> i64 {
value as i64
}
fn glyph_box(db: &FontDb, id: FontId, glyph: u32) -> Values {
let Ok(outline) = db.outline(id, glyph) else {
return Vec::new();
};
let points = outline.iter().flat_map(|command| match *command {
PathCommand::MoveTo(p) | PathCommand::LineTo(p) => vec![p],
PathCommand::QuadTo(c, p) => vec![c, p],
PathCommand::CubicTo(c, d, p) => vec![c, d, p],
PathCommand::Close => Vec::new(),
});
let mut bounds: Option<[f32; 4]> = None;
for p in points {
let [x0, y0, x1, y1] = bounds.unwrap_or([p.x, p.y, p.x, p.y]);
bounds = Some([x0.min(p.x), y0.min(p.y), x1.max(p.x), y1.max(p.y)]);
}
bounds.map_or_else(Vec::new, |[x0, y0, x1, y1]| {
vec![
font_units(x0.floor()),
font_units(y0.floor()),
font_units(x1.ceil()),
font_units(y1.ceil()),
]
})
}
fn sequences_of(glyphs: &[u32], by_glyph: &BTreeMap<u32, Vec<char>>) -> Vec<Vec<char>> {
let mut sequences: Vec<Vec<char>> = vec![Vec::new()];
for glyph in glyphs {
let characters = by_glyph.get(glyph).map_or(&[][..], Vec::as_slice);
sequences = sequences
.iter()
.flat_map(|start| {
characters.iter().map(move |&c| {
let mut next = start.clone();
next.push(c);
next
})
})
.collect();
}
sequences
}
const PANOSE_NAMES: [&str; 10] = [
"PANOSE family",
"PANOSE serif",
"PANOSE weight number",
"PANOSE proportion",
"PANOSE contrast",
"PANOSE stroke",
"PANOSE arm",
"PANOSE letterform",
"PANOSE midline",
"PANOSE x height",
];
fn metric_fields(metrics: &crate::FontMetrics) -> Vec<(&'static str, i64)> {
let hhea = metrics.hhea;
let mut fields = vec![
("units per em", number(metrics.units_per_em)),
("hhea ascender", number(hhea.ascender)),
("hhea descender", number(hhea.descender)),
("hhea line gap", number(hhea.line_gap)),
];
if let Some(underline) = metrics.underline {
fields.push(("post underline position", number(underline.position)));
fields.push(("post underline thickness", number(underline.thickness)));
}
if let Some(os2) = metrics.os2 {
fields.extend(os2_fields(&os2));
}
fields
}
fn os2_fields(os2: &crate::Os2Metrics) -> Vec<(&'static str, i64)> {
let mut fields = vec![
("OS/2 average width", number(os2.average_width)),
("OS/2 typo ascender", number(os2.typo.ascender)),
("OS/2 typo descender", number(os2.typo.descender)),
("OS/2 typo line gap", number(os2.typo.line_gap)),
("OS/2 win ascent", number(os2.win_ascent)),
("OS/2 win descent", number(os2.win_descent)),
("OS/2 use typo metrics", flag(os2.use_typo_metrics)),
("OS/2 strikeout position", number(os2.strikeout.position)),
("OS/2 strikeout size", number(os2.strikeout.thickness)),
("OS/2 subscript x size", number(os2.subscript.x_size)),
("OS/2 subscript y size", number(os2.subscript.y_size)),
("OS/2 subscript x offset", number(os2.subscript.x_offset)),
("OS/2 subscript y offset", number(os2.subscript.y_offset)),
("OS/2 superscript x size", number(os2.superscript.x_size)),
("OS/2 superscript y size", number(os2.superscript.y_size)),
(
"OS/2 superscript x offset",
number(os2.superscript.x_offset),
),
(
"OS/2 superscript y offset",
number(os2.superscript.y_offset),
),
("OS/2 East Asian code pages", flag(os2.east_asian)),
];
if let Some(value) = os2.x_height {
fields.push(("OS/2 x height", number(value)));
}
if let Some(value) = os2.cap_height {
fields.push(("OS/2 cap height", number(value)));
}
fields
}
fn math_constants(db: &FontDb, id: FontId) -> Vec<(&'static str, i64)> {
let mut fields = Vec::new();
if let Some(accent) = db.math_accent(id) {
fields.push(("accent base height", number(accent.accent_base_height)));
let flattened = accent.flattened_accent_base_height;
fields.push(("flattened accent base height", number(flattened)));
fields.push((
"min connector overlap",
number(accent.min_connector_overlap),
));
}
if let Some(radical) = db.math_radical(id) {
fields.extend([
("radical vertical gap", number(radical.vertical_gap)),
("radical rule thickness", number(radical.rule_thickness)),
("radical extra ascender", number(radical.extra_ascender)),
(
"radical kern before degree",
number(radical.kern_before_degree),
),
(
"radical kern after degree",
number(radical.kern_after_degree),
),
(
"radical degree bottom raise",
number(radical.degree_bottom_raise_percent),
),
(
"radical flattened accent base height",
number(radical.flattened_accent_base_height),
),
]);
}
if let Some(bars) = db.math_bars(id) {
fields.extend([
("overbar vertical gap", number(bars.overbar_vertical_gap)),
(
"overbar rule thickness",
number(bars.overbar_rule_thickness),
),
(
"overbar extra ascender",
number(bars.overbar_extra_ascender),
),
("underbar vertical gap", number(bars.underbar_vertical_gap)),
(
"underbar rule thickness",
number(bars.underbar_rule_thickness),
),
(
"underbar extra descender",
number(bars.underbar_extra_descender),
),
]);
}
if let Some(skewed) = db.math_skewed_fraction(id) {
fields.extend([
(
"skewed fraction horizontal gap",
number(skewed.horizontal_gap),
),
("skewed fraction vertical gap", number(skewed.vertical_gap)),
]);
}
if let Some(gaps) = db.math_limit_gaps(id) {
fields.extend([
("lower limit gap min", number(gaps.lower_limit_gap_min)),
("upper limit gap min", number(gaps.upper_limit_gap_min)),
]);
}
fields.extend(math_limit_fields(db, id));
if let Some(space) = db.space_after_script(id) {
fields.push(("space after script", number(space)));
}
fields
}
fn math_limit_fields(db: &FontDb, id: FontId) -> Vec<(&'static str, i64)> {
let mut fields = Vec::new();
if let Some(limits) = db.math_limits(id) {
fields.extend([
("math leading", number(limits.math_leading)),
(
"display operator min height",
number(limits.display_operator_min_height),
),
(
"upper limit baseline rise min",
number(limits.upper_limit_baseline_rise_min),
),
(
"lower limit baseline drop min",
number(limits.lower_limit_baseline_drop_min),
),
(
"superscript baseline drop max",
number(limits.superscript_baseline_drop_max),
),
(
"subscript baseline drop min",
number(limits.subscript_baseline_drop_min),
),
(
"delimited sub formula min height",
number(limits.delimited_sub_formula_min_height),
),
]);
}
if let Some(stack) = db.math_stretch_stack(id) {
fields.extend([
("stretch stack top shift up", number(stack.top_shift_up)),
(
"stretch stack bottom shift down",
number(stack.bottom_shift_down),
),
("stretch stack gap above min", number(stack.gap_above_min)),
("stretch stack gap below min", number(stack.gap_below_min)),
(
"stretch stack min connector overlap",
number(stack.min_connector_overlap),
),
]);
}
fields
}
fn math_kerning(
db: &FontDb,
id: FontId,
glyph: u32,
units_per_em: u16,
) -> Vec<(&'static str, Values)> {
let em = i32::from(units_per_em);
let corners = [
("math kerning top right", MathCorner::TopRight),
("math kerning top left", MathCorner::TopLeft),
("math kerning bottom right", MathCorner::BottomRight),
("math kerning bottom left", MathCorner::BottomLeft),
];
corners
.into_iter()
.filter_map(|(name, corner)| {
let values: Option<Values> = [0, em / 2, em]
.into_iter()
.map(|height| db.math_kern(id, glyph, corner, height).map(number))
.collect();
Some((name, values?))
})
.collect()
}
#[cfg(test)]
mod tests;