use crate::word::fmt::model::{EmbeddedFont, FontKind};
use rustybuzz::ttf_parser;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
static ADDED: RwLock<Vec<Arc<Vec<u8>>>> = RwLock::new(Vec::new());
pub fn add_font(data: Vec<u8>) -> anyhow::Result<usize> {
let faces = (0..face_count(&data))
.filter(|&index| ttf_parser::Face::parse(&data, index).is_ok_and(|face| !describe(&face).0.is_empty()))
.count();
if faces == 0 {
anyhow::bail!("not a TrueType or OpenType font with a readable family name");
}
ADDED
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(Arc::new(data));
Ok(faces)
}
pub(crate) fn added_fonts() -> Vec<Arc<Vec<u8>>> {
ADDED.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
}
fn face_count(data: &[u8]) -> u32 {
let room = u32::try_from(data.len().saturating_sub(12) / 4).unwrap_or(u32::MAX);
ttf_parser::fonts_in_collection(data).map_or(1, |count| count.min(room))
}
const NO_FONT: &str = "no font is installed: laying out pages needs at least one TrueType or OpenType font \
(install one, name its folder in KAKEMONO_FONT_DIRS, or give it with add_font)";
fn is_font_file(path: &Path) -> bool {
let ext = path
.extension()
.and_then(std::ffi::OsStr::to_str)
.unwrap_or_default()
.to_ascii_lowercase();
matches!(ext.as_str(), "ttf" | "otf" | "ttc" | "otc")
}
pub struct Face {
pub data: Arc<Vec<u8>>,
pub index: u32,
pub metrics: Metrics,
pub family: String,
}
#[derive(Debug, Clone, Copy)]
pub struct Metrics {
pub upem: f32,
pub ascent: f32,
pub descent: f32,
pub leading: f32,
pub underline_pos: f32,
pub underline_thickness: f32,
pub strike_pos: f32,
pub x_height: f32,
pub cap_height: f32,
}
pub type FaceId = usize;
type StyleKey = (String, bool, bool);
type ChosenFace = (FaceId, bool, bool);
#[derive(Debug, Clone, Copy)]
pub struct Style {
pub face: FaceId,
pub fake_bold: bool,
pub fake_italic: bool,
pub missing: bool,
pub metric: Option<&'static super::metrics::MetricFace>,
}
#[derive(Debug, Clone)]
struct Candidate {
source: Source,
index: u32,
bold: bool,
italic: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Source {
File(PathBuf),
Embedded(usize),
Added(usize),
}
pub struct FontBook {
faces: Vec<Face>,
by_family: HashMap<String, Vec<Candidate>>,
loaded: HashMap<(Source, u32), FaceId>,
embedded: Vec<Arc<Vec<u8>>>,
added: Vec<Arc<Vec<u8>>>,
resolved: HashMap<StyleKey, Option<ChosenFace>>,
styles: HashMap<String, [Option<Style>; 4]>,
fallback_faces: Option<Vec<FaceId>>,
kinds: HashMap<String, FontKind>,
}
const ALIASES: &[(&str, &[&str])] = &[
("calibri", &["carlito"]),
("cambria", &["caladea"]),
("times new roman", &["liberation serif", "tinos"]),
("times", &["liberation serif", "tinos"]),
("arial", &["liberation sans", "arimo"]),
("helvetica", &["liberation sans", "arimo"]),
("arial narrow", &["liberation sans narrow"]),
("courier new", &["liberation mono", "cousine"]),
("courier", &["liberation mono", "cousine"]),
("georgia", &["gelasio"]),
("segoe ui", &["selawik"]),
("ms 明朝", &["ipamincho"]),
("ms mincho", &["ipamincho"]),
("ms p明朝", &["ipapmincho"]),
("ms pmincho", &["ipapmincho"]),
("ms ゴシック", &["ipagothic"]),
("ms gothic", &["ipagothic"]),
("ms pゴシック", &["ipapgothic"]),
("ms pgothic", &["ipapgothic"]),
];
const LOOKALIKES: &[(&str, &[&str])] = &[
("calibri light", &["carlito"]),
("century gothic", &["urw gothic", "tex gyre adventor"]),
("verdana", &["dejavu sans"]),
("tahoma", &["dejavu sans"]),
("segoe ui", &["open sans", "noto sans", "dejavu sans"]),
("trebuchet ms", &["dejavu sans"]),
("symbol", &["dejavu sans", "freeserif"]),
("wingdings", &["dejavu sans", "freeserif"]),
("cambria math", &["dejavu serif", "freeserif"]),
("times new roman", &["freeserif"]),
("arial", &["freesans"]),
("courier new", &["freemono"]),
("明朝", &["ipaexmincho", "noto serif cjk jp"]),
("ms 明朝", &["noto serif cjk jp"]),
("ms mincho", &["noto serif cjk jp"]),
("ms p明朝", &["ipaexmincho", "noto serif cjk jp"]),
("ms pmincho", &["ipaexmincho", "noto serif cjk jp"]),
("游明朝", &["ipaexmincho", "noto serif cjk jp"]),
("yu mincho", &["ipaexmincho", "noto serif cjk jp"]),
("ms ゴシック", &["noto sans cjk jp"]),
("ms gothic", &["noto sans cjk jp"]),
("ms pゴシック", &["ipaexgothic", "noto sans cjk jp"]),
("ms pgothic", &["ipaexgothic", "noto sans cjk jp"]),
("游ゴシック", &["ipaexgothic", "noto sans cjk jp"]),
("yu gothic", &["ipaexgothic", "noto sans cjk jp"]),
("メイリオ", &["ipaexgothic", "noto sans cjk jp"]),
("meiryo", &["ipaexgothic", "noto sans cjk jp"]),
];
const FALLBACKS: &[&str] = &[
"liberation sans",
"dejavu sans",
"noto sans",
"freeserif",
"noto sans cjk sc",
"wenquanyi zen hei",
"noto sans symbols",
"noto sans symbols2",
"dejavu serif",
];
const LAST_RESORT: &[&str] = &["liberation serif", "dejavu serif", "dejavu sans", "freeserif"];
impl FontBook {
pub fn new(embedded: &[EmbeddedFont], kinds: &HashMap<String, FontKind>) -> Self {
let mut book = FontBook {
faces: Vec::new(),
by_family: HashMap::new(),
loaded: HashMap::new(),
embedded: Vec::new(),
added: added_fonts(),
resolved: HashMap::new(),
styles: HashMap::new(),
fallback_faces: None,
kinds: kinds.clone(),
};
for dir in font_dirs() {
book.scan(&dir, 0);
}
for at in 0..book.added.len() {
let data = Arc::clone(&book.added[at]);
book.add_faces(&data, &Source::Added(at));
}
for (at, font) in embedded.iter().enumerate() {
book.embedded.push(Arc::new(font.data.clone()));
book.by_family.entry(font.family.to_lowercase()).or_default().insert(
0,
Candidate {
source: Source::Embedded(at),
index: 0,
bold: font.bold,
italic: font.italic,
},
);
}
book
}
fn scan(&mut self, dir: &Path, depth: usize) {
const MAX_DEPTH: usize = 6;
let Ok(entries) = std::fs::read_dir(dir) else { return };
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
if depth < MAX_DEPTH {
self.scan(&path, depth + 1);
}
continue;
}
if !is_font_file(&path) {
continue;
}
let Ok(data) = std::fs::read(&path) else { continue };
self.add_faces(&data, &Source::File(path));
}
}
fn add_faces(&mut self, data: &[u8], source: &Source) {
for index in 0..face_count(data) {
let Ok(face) = ttf_parser::Face::parse(data, index) else {
continue;
};
let (families, bold, italic) = describe(&face);
for family in families {
self.by_family.entry(family).or_default().push(Candidate {
source: source.clone(),
index,
bold,
italic,
});
}
}
}
pub fn style(&mut self, family: &str, bold: bool, italic: bool) -> Style {
let at = usize::from(bold) * 2 + usize::from(italic);
if let Some(style) = self.styles.get(family).and_then(|styles| styles[at]) {
return style;
}
let (face, fake_bold, fake_italic) = self.face(family, bold, italic);
let style = Style {
face,
fake_bold,
fake_italic,
missing: !self.has_family(family),
metric: super::metrics::lookup(family, bold, italic),
};
self.styles.entry(family.to_string()).or_default()[at] = Some(style);
style
}
pub fn face(&mut self, family: &str, bold: bool, italic: bool) -> (FaceId, bool, bool) {
let key = (family.to_lowercase(), bold, italic);
if let Some(found) = self.resolved.get(&key) {
return found.unwrap_or_else(|| self.last_resort(bold, italic));
}
let mut names = vec![key.0.clone()];
let plain = table_name(&key.0);
for table in [ALIASES, LOOKALIKES] {
for (_, aliases) in table.iter().filter(|(name, _)| *name == plain) {
names.extend(aliases.iter().map(|alias| (*alias).to_string()));
}
}
let mut found = None;
for name in &names {
if let Some(face) = self.load_family(name, bold, italic) {
found = Some(face);
break;
}
}
if found.is_none() {
let lower = key.0.as_str();
let kind = self.kinds.get(lower).copied().unwrap_or_else(|| guess_kind(lower));
let stand_ins: &[&str] = match kind {
FontKind::Serif => &["liberation serif", "dejavu serif", "freeserif"],
FontKind::Mono => &["liberation mono", "dejavu sans mono", "freemono"],
FontKind::Sans | FontKind::Symbol => &["liberation sans", "dejavu sans", "freesans"],
};
for name in stand_ins {
if let Some(face) = self.load_family(name, bold, italic) {
found = Some(face);
break;
}
}
}
self.resolved.insert(key, found);
found.unwrap_or_else(|| self.last_resort(bold, italic))
}
pub fn has_family(&self, family: &str) -> bool {
let name = family.to_lowercase();
let plain = table_name(&name);
self.by_family.contains_key(&name)
|| ALIASES
.iter()
.find(|(alias, _)| *alias == plain)
.is_some_and(|(_, aliases)| aliases.iter().any(|alias| self.by_family.contains_key(*alias)))
}
pub fn latin_stand_in(&self, family: &str) -> Option<&'static str> {
let lower = family.to_lowercase();
let plain = table_name(&lower);
let east_asian = !plain.is_ascii()
|| LOOKALIKES
.iter()
.any(|(name, aliases)| *name == plain && aliases.iter().any(|alias| alias.contains("cjk")));
if !east_asian || self.by_family.contains_key(&lower) {
return None;
}
Some(match guess_kind(&plain) {
FontKind::Serif => "Times New Roman",
FontKind::Mono => "Courier New",
FontKind::Sans | FontKind::Symbol => "Arial",
})
}
pub fn require_font(&mut self) -> anyhow::Result<()> {
match self.try_last_resort(false, false) {
Some(_) => Ok(()),
None => anyhow::bail!(NO_FONT),
}
}
fn last_resort(&mut self, bold: bool, italic: bool) -> (FaceId, bool, bool) {
self.try_last_resort(bold, italic).expect(NO_FONT)
}
fn try_last_resort(&mut self, bold: bool, italic: bool) -> Option<(FaceId, bool, bool)> {
for name in LAST_RESORT {
if let Some(face) = self.load_family(name, bold, italic) {
return Some(face);
}
}
let mut names: Vec<String> = self.by_family.keys().cloned().collect();
names.sort_unstable();
names.into_iter().find_map(|name| self.load_family(&name, bold, italic))
}
fn load_family(&mut self, name: &str, bold: bool, italic: bool) -> Option<(FaceId, bool, bool)> {
let candidates = self.by_family.get(name)?.clone();
let score = |cand: &Candidate| u8::from(cand.bold != bold) * 2 + u8::from(cand.italic != italic);
let best = candidates.iter().min_by_key(|cand| score(cand))?;
let id = self.load(best.source.clone(), best.index, name)?;
Some((id, bold && !best.bold, italic && !best.italic))
}
fn load(&mut self, source: Source, index: u32, family: &str) -> Option<FaceId> {
if let Some(&id) = self.loaded.get(&(source.clone(), index)) {
return Some(id);
}
let data = match &source {
Source::File(path) => Arc::new(std::fs::read(path).ok()?),
Source::Embedded(at) => self.embedded.get(*at)?.clone(),
Source::Added(at) => self.added.get(*at)?.clone(),
};
let face = ttf_parser::Face::parse(&data, index).ok()?;
let metrics = metrics(&face);
self.faces.push(Face {
data: data.clone(),
index,
metrics,
family: family.to_string(),
});
let id = self.faces.len() - 1;
self.loaded.insert((source, index), id);
Some(id)
}
pub fn get(&self, id: FaceId) -> &Face {
&self.faces[id]
}
pub fn faces(&self) -> &[Face] {
&self.faces
}
pub fn fallbacks(&mut self) -> Vec<FaceId> {
if let Some(faces) = &self.fallback_faces {
return faces.clone();
}
let mut faces = Vec::new();
for name in FALLBACKS {
if let Some((id, _, _)) = self.load_family(name, false, false) {
faces.push(id);
}
}
self.fallback_faces = Some(faces.clone());
faces
}
pub fn covers(&self, id: FaceId, ch: char) -> bool {
let face = &self.faces[id];
ttf_parser::Face::parse(&face.data, face.index)
.ok()
.and_then(|parsed| parsed.glyph_index(ch))
.is_some()
}
}
pub(crate) fn table_name(name: &str) -> String {
const FULL_WIDTH_OFFSET: u32 = 0xFEE0;
name.chars()
.map(|ch| match ch {
'\u{3000}' => ' ',
'\u{FF01}'..='\u{FF5E}' => char::from_u32(u32::from(ch) - FULL_WIDTH_OFFSET).unwrap_or(ch),
_ => ch,
})
.collect::<String>()
.to_lowercase()
}
fn guess_kind(name: &str) -> FontKind {
const SERIF_WORDS: &[&str] = &[
"times",
"roman",
"serif",
"garamond",
"georgia",
"book",
"mincho",
"明朝",
"明體",
"宋体",
"mingliu",
"simsun",
"batang",
"myeongjo",
"cambria",
"palatino",
"baskerville",
"minion",
"caslon",
"bodoni",
"century",
];
const MONO_WORDS: &[&str] = &["mono", "courier", "consolas", "code", "typewriter"];
let name = name.strip_suffix("-roman").unwrap_or(name);
if name.contains("sans") || name.contains("gothic") || name.contains("ゴシック") {
FontKind::Sans
} else if MONO_WORDS.iter().any(|word| name.contains(word)) {
FontKind::Mono
} else if SERIF_WORDS.iter().any(|word| name.contains(word)) {
FontKind::Serif
} else {
FontKind::Sans
}
}
fn describe(face: &ttf_parser::Face<'_>) -> (Vec<String>, bool, bool) {
let mut families = Vec::new();
for name in face.names() {
let id = name.name_id;
if id != ttf_parser::name_id::FAMILY && id != ttf_parser::name_id::TYPOGRAPHIC_FAMILY {
continue;
}
if let Some(text) = name.to_string() {
let text = text.to_lowercase();
if !families.contains(&text) {
families.push(text);
}
}
}
let bold = face.is_bold() || face.weight().to_number() >= 600;
(families, bold, face.is_italic() || face.is_oblique())
}
fn metrics(face: &ttf_parser::Face<'_>) -> Metrics {
let upem = f32::from(face.units_per_em());
let tables = face.tables();
let (win_ascent, win_descent) = tables
.os2
.map(|os2| {
(
f32::from(os2.windows_ascender()),
f32::from(os2.windows_descender()).abs(),
)
})
.filter(|(ascent, descent)| ascent + descent > 0.0)
.unwrap_or_else(|| (f32::from(face.ascender()), f32::from(face.descender()).abs()));
let hhea_height = f32::from(face.ascender()) - f32::from(face.descender());
let leading = (f32::from(face.line_gap()) - ((win_ascent + win_descent) - hhea_height)).max(0.0);
let underline = face.underline_metrics();
let strike = face.strikeout_metrics();
Metrics {
upem,
ascent: win_ascent / upem,
descent: win_descent / upem,
leading: leading / upem,
underline_pos: underline.map_or(0.1, |line| -f32::from(line.position) / upem),
underline_thickness: underline.map_or(0.05, |line| f32::from(line.thickness).max(1.0) / upem),
strike_pos: strike.map_or(0.25, |line| f32::from(line.position) / upem),
x_height: face.x_height().map_or(0.45, |height| f32::from(height) / upem),
cap_height: face.capital_height().map_or(0.65, |height| f32::from(height) / upem),
}
}
fn font_dirs() -> Vec<PathBuf> {
let mut dirs = Vec::new();
if let Some(extra) = std::env::var_os("KAKEMONO_FONT_DIRS") {
dirs.extend(std::env::split_paths(&extra));
}
let home = std::env::var_os("HOME").map(PathBuf::from);
if cfg!(target_os = "windows") {
let windir = std::env::var_os("WINDIR").map_or_else(|| PathBuf::from("C:\\Windows"), PathBuf::from);
dirs.push(windir.join("Fonts"));
if let Some(local) = std::env::var_os("LOCALAPPDATA") {
dirs.push(PathBuf::from(local).join("Microsoft\\Windows\\Fonts"));
}
} else if cfg!(target_os = "macos") {
dirs.push("/System/Library/Fonts".into());
dirs.push("/Library/Fonts".into());
if let Some(home) = &home {
dirs.push(home.join("Library/Fonts"));
}
} else {
dirs.push("/usr/share/fonts".into());
dirs.push("/usr/local/share/fonts".into());
if let Some(home) = &home {
dirs.push(home.join(".local/share/fonts"));
dirs.push(home.join(".fonts"));
}
}
dirs
}
#[cfg(test)]
mod tests {
use super::{FontKind, guess_kind};
#[test]
fn a_roman_style_is_not_a_serif() {
assert_eq!(guess_kind("times new roman"), FontKind::Serif);
assert_eq!(guess_kind("metanormallf-roman"), FontKind::Sans);
assert_eq!(guess_kind("century gothic"), FontKind::Sans);
assert_eq!(guess_kind("ms p明朝"), FontKind::Serif);
}
}