use super::mathabx::MathAbx;
use super::symbols::SymbolFont;
use hayro_font::{Font, FontCache, FontGlyph, GlyphId};
use hayro_interpret::InterpreterSettings;
use hayro_syntax::object::{Array, Dict, Name, Number, Stream};
use hayro_syntax::page::{Page, Resources};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
pub const UNKNOWN_FONT: u16 = 0;
const SUBSET_PREFIX_LEN: usize = 6;
const FLAG_FIXED_PITCH: u32 = 1;
const FLAG_SERIF: u32 = 2;
const FLAG_ITALIC: u32 = 1 << 6;
const FLAG_SMALL_CAP: u32 = 1 << 17;
const FLAG_FORCE_BOLD: u32 = 1 << 18;
const BOLD_MIN_WEIGHT: f32 = 600.0;
const ITALIC_MIN_ANGLE_DEG: f32 = 0.5;
const MAX_FORM_DEPTH: u32 = 6;
const MATH_PATTERNS: &[&str] = &[
"cmmi", "cmsy", "cmex", "cmbsy", "msam", "msbm", "eufm", "eufb", "eusm", "eurm", "rsfs", "math", "mtmi", "mtsy",
"mtex", "txsy", "txmi", "txex", "pxsy", "pxmi", "pxex", "ntxmi", "ntxsy", "ntxex", "stmary", "wasy", "esint",
"bbm", "bbold", "dsrom", "dsss", "mnsymbol", "lasy", "cmbrmi", "lmmi", "lmsy", "lmex", "fplmbi", "zplm", "zptm",
"zeur", "zeus", "symbol", "mdbch", "md-",
];
const MATH_PREFIXES: &[&str] = &["line", "lcircle"];
const TEX_BOLD_PATTERNS: &[&str] = &[
"cmbx", "cmssbx", "cmssdc", "sfbx", "sfsx", "ecbx", "ecsx", "cmbsy", "cmmib", "sfxc", "ectb", "cmtb",
];
const TEX_BOLD_SIZE_PREFIX: &str = "cmb";
const NAMED_BOLD_PATTERNS: &[&str] = &["bold", "black", "heavy", "demi", "-bd", "extrab", "ultra"];
const MEDIUM_BOLD_ABBREVIATION: &str = "medi";
const MEDIUM_WORD: &str = "medium";
const BOLD_SUFFIXES: &[&str] = &["-b", ".b"];
const TEX_ITALIC_PATTERNS: &[&str] = &[
"cmti", "cmsl", "cmbxti", "cmbxsl", "cmssi", "cmitt", "sfti", "sfsl", "sfbi", "ecti", "ecsl", "ecbi", "cmu",
"sfsi", "sfso",
];
const NAMED_ITALIC_PATTERNS: &[&str] = &["ital", "obli", "slant", "-it", "kursiv", "inclined"];
const ITALIC_SUFFIXES: &[&str] = &["-i", "-ri", "-bi", ".i"];
const MATH_ITALIC_PATTERNS: &[&str] = &["cmmi", "cmmib", "ntxmi", "txmi", "pxmi", "mtmi", "lmmi"];
const MONO_PATTERNS: &[&str] = &[
"mono",
"courier",
"cmtt",
"cmitt",
"typewriter",
"consol",
"inconsolata",
"sftt",
"ectt",
"txtt",
"menlo",
"sourcecode",
"nimbusmon",
"lmtt",
"cmvtt",
"dejavusansm",
"zi4",
"fira",
"cascadia",
];
const MATH_PI_PREFIX: &str = "advp4c4e74";
const RADICAL_PI_PREFIX: &str = "advp4c4e46";
const MATH_PI_PATTERNS: &[&str] = &["mathematicalpi-one", "mathpi-one"];
const SMALL_CAPS_PATTERNS: &[&str] = &["cmcsc", "eccc", "romancaps", "smallcaps"];
const SMALL_CAPS_SUFFIXES: &[&str] = &["sc", "-sc", "smcp"];
const SANS_PATTERNS: &[&str] = &[
"helvet",
"arial",
"sans",
"cmss",
"nimbussan",
"verdana",
"calibri",
"roboto",
"lato",
"lmss",
"tahoma",
"futura",
"avenir",
"gotham",
"inter-",
"segoe",
"frutiger",
"univers",
"phv",
"sfss",
"myriad",
"avantgarde",
"gillsans",
"din-",
"gothic",
"shingo",
"kakugo",
"marugo",
"meiryo",
"heiti",
"simhei",
"yahei",
"dotum",
"gulim",
];
const LIBERTINE_PATTERNS: &[&str] = &["linlibertine", "linbiolinum"];
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct FontInfo {
pub name: String,
pub bold: bool,
pub italic: bool,
pub mono: bool,
pub math: bool,
pub serif: bool,
pub math_pi: bool,
pub radical_pi: bool,
pub mathabx: Option<MathAbx>,
pub sans: bool,
#[serde(default)]
pub small_caps: bool,
#[serde(default)]
pub libertine: bool,
#[serde(default)]
pub symbols: Option<SymbolFont>,
}
impl FontInfo {
pub fn from_name(raw: &str, flags: u32, italic_angle: f32, weight: f32) -> Self {
let name = match raw.split_once('+') {
Some((prefix, rest)) if prefix.len() == SUBSET_PREFIX_LEN => rest.to_string(),
_ => raw.to_string(),
};
let lower = name.to_ascii_lowercase();
let math = is_math_name(&lower);
let bold = is_bold(&lower, flags, weight);
let italic = is_italic(&lower, flags, italic_angle);
let mono = flags & FLAG_FIXED_PITCH != 0 || contains_any(&lower, MONO_PATTERNS);
let serif = flags & FLAG_SERIF != 0;
let math_italic = contains_any(&lower, MATH_ITALIC_PATTERNS);
let italic = if math { math_italic } else { italic };
let math_pi = lower.starts_with(MATH_PI_PREFIX) || contains_any(&lower, MATH_PI_PATTERNS);
let sans = !math && !mono && contains_any(&lower, SANS_PATTERNS);
let small_caps = !math
&& (flags & FLAG_SMALL_CAP != 0
|| contains_any(&lower, SMALL_CAPS_PATTERNS)
|| SMALL_CAPS_SUFFIXES.iter().any(|suffix| lower.ends_with(suffix)));
let libertine = contains_any(&lower, LIBERTINE_PATTERNS);
Self {
symbols: SymbolFont::from_name(&lower),
sans,
small_caps,
libertine,
name,
bold: bold && !math_pi,
italic: italic && !math_pi,
mono,
math: math || math_pi,
serif,
math_pi,
radical_pi: lower.starts_with(RADICAL_PI_PREFIX),
mathabx: MathAbx::from_name(&lower),
}
}
}
struct Candidate<'a> {
font: Font<'a>,
idx: u16,
key: u128,
}
pub struct FontRegistry<'a> {
cache: FontCache<'a>,
settings: InterpreterSettings,
pub infos: Vec<FontInfo>,
by_info: HashMap<FontInfo, u16>,
loaded: HashMap<u128, Option<(u16, Font<'a>)>>,
glyph_cache: HashMap<u128, u16>,
outline_cache: HashMap<u128, Option<kurbo::Rect>>,
candidates: Vec<Candidate<'a>>,
}
impl<'a> FontRegistry<'a> {
pub fn new() -> Self {
Self {
cache: FontCache::new(),
settings: InterpreterSettings::default(),
infos: vec![FontInfo {
name: "unknown".into(),
..Default::default()
}],
by_info: HashMap::new(),
loaded: HashMap::new(),
glyph_cache: HashMap::new(),
outline_cache: HashMap::new(),
candidates: Vec::new(),
}
}
pub fn begin_page(&mut self, page: &Page<'a>) {
self.candidates.clear();
self.glyph_cache.clear();
let mut seen_forms = HashSet::new();
let resources = page.resources().clone();
self.collect_fonts(&resources, &mut seen_forms, 0);
}
pub fn outline_bbox(&mut self, glyph: &hayro_font::OutlineGlyph) -> Option<kurbo::Rect> {
use kurbo::Shape;
let key = glyph.identifier().cache_key();
*self.outline_cache.entry(key).or_insert_with(|| {
let outline = glyph.outline();
if outline.elements().is_empty() {
return None;
}
let bounds = outline.bounding_box();
(bounds.width() > 0.0 && bounds.height() > 0.0 && bounds.width().is_finite() && bounds.height().is_finite())
.then_some(bounds)
})
}
pub fn identify(&mut self, glyph: &hayro_font::OutlineGlyph) -> u16 {
let key = glyph.identifier().cache_key();
if let Some(&idx) = self.glyph_cache.get(&key) {
return idx;
}
let gid: GlyphId = glyph.glyph_id();
let code = glyph.char_code();
let found = self.candidates.iter().find(|candidate| {
matches!(candidate.font.glyph(gid, code), FontGlyph::Outline(outline) if outline.identifier().cache_key() == key)
});
let idx = found.map_or(UNKNOWN_FONT, |candidate| candidate.idx);
self.glyph_cache.insert(key, idx);
idx
}
fn intern(&mut self, info: FontInfo) -> u16 {
if let Some(&idx) = self.by_info.get(&info) {
return idx;
}
let idx = self.infos.len() as u16;
self.by_info.insert(info.clone(), idx);
self.infos.push(info);
idx
}
fn collect_fonts(&mut self, resources: &Resources<'a>, seen: &mut HashSet<(u32, i32)>, depth: u32) {
let keys: Vec<Name<'a>> = resources.fonts.keys().collect();
for key in keys {
if let Some(dict) = resources.fonts.get::<Dict<'a>>(&key) {
self.add_font(&dict);
}
}
if depth >= MAX_FORM_DEPTH {
return;
}
let keys: Vec<Name<'a>> = resources.x_objects.keys().collect();
for key in keys {
let Some(stream) = resources.x_objects.get::<Stream<'a>>(&key) else {
continue;
};
let id = stream.obj_id();
if !seen.insert((id.obj_number, id.gen_number)) {
continue;
}
let dict = stream.dict();
let is_form = dict
.get::<Name<'_>>("Subtype")
.is_some_and(|subtype| subtype.as_str() == "Form");
if !is_form {
continue;
}
if let Some(res) = dict.get::<Dict<'a>>("Resources") {
let res = Resources::new(res);
self.collect_fonts(&res, seen, depth + 1);
}
}
}
fn add_font(&mut self, dict: &Dict<'a>) {
use hayro_interpret::CacheKey;
let key = dict.cache_key();
if let Some(entry) = self.loaded.get(&key) {
if let Some((idx, font)) = entry
&& !self.candidates.iter().any(|candidate| candidate.key == key)
{
self.candidates.push(Candidate {
font: font.clone(),
idx: *idx,
key,
});
}
return;
}
let info = describe(dict);
let font = self
.cache
.font(dict, &self.settings.font_resolver, &self.settings.cmap_resolver);
let entry = font.map(|font| {
let idx = self.intern(info);
(idx, font)
});
if let Some((idx, font)) = &entry {
self.candidates.push(Candidate {
font: font.clone(),
idx: *idx,
key,
});
}
self.loaded.insert(key, entry);
}
}
impl Default for FontRegistry<'_> {
fn default() -> Self {
Self::new()
}
}
fn describe(dict: &Dict<'_>) -> FontInfo {
let mut name = dict
.get::<Name<'_>>("BaseFont")
.map(|base_font| base_font.as_str().to_string())
.unwrap_or_default();
let mut descriptor = dict.get::<Dict<'_>>("FontDescriptor");
if descriptor.is_none()
&& let Some(descendants) = dict.get::<Array<'_>>("DescendantFonts")
&& let Some(descendant) = descendants.iter::<Dict<'_>>().next()
{
descriptor = descendant.get::<Dict<'_>>("FontDescriptor");
if name.is_empty() {
name = descendant
.get::<Name<'_>>("BaseFont")
.map(|base_font| base_font.as_str().to_string())
.unwrap_or_default();
}
}
let num = |entries: &Dict<'_>, key: &str| -> Option<f32> {
entries.get::<Number>(key).map(|number| number.as_f64() as f32)
};
let (mut flags, mut angle, mut weight) = (0u32, 0.0f32, 0.0f32);
if let Some(desc) = &descriptor {
flags = num(desc, "Flags").unwrap_or(0.0) as u32;
angle = num(desc, "ItalicAngle").unwrap_or(0.0);
weight = num(desc, "FontWeight").unwrap_or(0.0);
if name.is_empty() {
name = desc
.get::<Name<'_>>("FontName")
.map(|font_name| font_name.as_str().to_string())
.unwrap_or_default();
}
}
if name.is_empty() {
name = dict
.get::<Name<'_>>("Subtype")
.map(|subtype| subtype.as_str().to_string())
.unwrap_or_else(|| "unnamed".into());
}
FontInfo::from_name(&name, flags, angle, weight)
}
fn contains_any(lower: &str, patterns: &[&str]) -> bool {
patterns.iter().any(|pattern| lower.contains(pattern))
}
fn is_math_name(lower: &str) -> bool {
contains_any(lower, MATH_PATTERNS) || MATH_PREFIXES.iter().any(|prefix| lower.starts_with(prefix))
}
fn is_bold(lower: &str, flags: u32, weight: f32) -> bool {
let tex_bold = contains_any(lower, TEX_BOLD_PATTERNS)
|| (lower.starts_with(TEX_BOLD_SIZE_PREFIX)
&& lower[TEX_BOLD_SIZE_PREFIX.len()..]
.chars()
.next()
.is_some_and(|ch| ch.is_ascii_digit()));
let named_bold = contains_any(lower, NAMED_BOLD_PATTERNS)
|| (lower.contains(MEDIUM_BOLD_ABBREVIATION) && !lower.contains(MEDIUM_WORD))
|| BOLD_SUFFIXES.iter().any(|suffix| lower.ends_with(suffix));
tex_bold || named_bold || weight >= BOLD_MIN_WEIGHT || flags & FLAG_FORCE_BOLD != 0
}
fn is_italic(lower: &str, flags: u32, italic_angle: f32) -> bool {
let tex_italic = contains_any(lower, TEX_ITALIC_PATTERNS);
let named_italic =
contains_any(lower, NAMED_ITALIC_PATTERNS) || ITALIC_SUFFIXES.iter().any(|suffix| lower.ends_with(suffix));
tex_italic
|| named_italic
|| italic_angle.abs() > ITALIC_MIN_ANGLE_DEG
|| flags & FLAG_ITALIC != 0
|| contains_any(lower, MATH_ITALIC_PATTERNS)
}
#[cfg(test)]
mod tests {
use super::FontInfo;
#[test]
fn font_names() {
let font = FontInfo::from_name("ABCDEF+CMBX10", 0, 0.0, 0.0);
assert_eq!(font.name, "CMBX10");
assert!(font.bold && !font.italic && !font.math);
let font = FontInfo::from_name("NimbusRomNo9L-ReguItal", 0, 0.0, 0.0);
assert!(font.italic && !font.bold);
let font = FontInfo::from_name("NimbusRomNo9L-Medi", 0, 0.0, 0.0);
assert!(font.bold);
assert!(FontInfo::from_name("CMMI10", 0, -14.0, 0.0).italic);
let sy = FontInfo::from_name("CMSY10", 0, -14.0, 0.0);
assert!(sy.math && !sy.italic);
assert!(FontInfo::from_name("SFTT1000", 0, 0.0, 0.0).mono);
assert!(!FontInfo::from_name("Helvetica", 0, 0.0, 0.0).bold);
}
#[test]
fn small_caps_fonts() {
assert!(FontInfo::from_name("ABCDEF+CMCSC10", 0, 0.0, 0.0).small_caps);
assert!(FontInfo::from_name("LMRomanCaps10-Regular", 0, 0.0, 0.0).small_caps);
assert!(FontInfo::from_name("MinionPro-RegularSC", 0, 0.0, 0.0).small_caps);
assert!(!FontInfo::from_name("EXCSCL+Helvetica", 0, 0.0, 0.0).small_caps);
assert!(!FontInfo::from_name("CMR10", 0, 0.0, 0.0).small_caps);
assert!(FontInfo::from_name("CMEULC+LASY10", 0, 0.0, 0.0).symbols.is_some());
}
}