use std::{cell::RefCell, collections::HashMap, path::PathBuf};
use ab_glyph::{Font, FontVec, GlyphId, PxScale, ScaleFont};
use crate::Error;
use crate::layout::TextMetrics;
const CANDIDATES: &[&str] = &[
"segoeui.ttf",
"arial.ttf",
"tahoma.ttf",
"verdana.ttf",
"DejaVuSans.ttf",
"LiberationSans-Regular.ttf",
];
const EMOJI_CANDIDATES: &[&str] = &[
"seguiemj.ttf",
"segoeuiemoji.ttf",
"segoeuisl.ttf",
"NotoColorEmoji.ttf",
"Symbola.ttf",
"AppleColorEmoji.ttc",
];
fn font_dirs() -> Vec<PathBuf> {
let mut dirs = Vec::new();
if let Ok(windir) = std::env::var("WINDIR") {
dirs.push(PathBuf::from(windir).join("Fonts"));
}
dirs.push(PathBuf::from("/usr/share/fonts/truetype/dejavu"));
dirs.push(PathBuf::from("/usr/share/fonts/truetype/liberation"));
dirs.push(PathBuf::from("/usr/share/fonts/TTF"));
dirs.push(PathBuf::from("/usr/share/fonts"));
dirs
}
fn macos_font_dir() -> Option<PathBuf> {
PathBuf::from("/System/Library/Fonts")
.exists()
.then_some(PathBuf::from("/System/Library/Fonts"))
.or_else(|| {
PathBuf::from("/Library/Fonts")
.exists()
.then_some(PathBuf::from("/Library/Fonts"))
})
}
fn find_file(names: &[&str], extra_dirs: &mut [PathBuf]) -> Option<PathBuf> {
for name in names {
for dir in font_dirs() {
let path = dir.join(name);
if path.exists() {
return Some(path);
}
}
if let Some(dir) = macos_font_dir() {
let path = dir.join(name);
if path.exists() {
return Some(path);
}
}
for dir in extra_dirs.iter() {
let path = dir.join(name);
if path.exists() {
return Some(path);
}
}
}
None
}
pub fn load_system_font() -> Result<FontVec, Error> {
let mut extra_dirs: Vec<PathBuf> = Vec::new();
if let Some(path) = find_file(CANDIDATES, &mut extra_dirs) {
let data = std::fs::read(&path)
.map_err(|e| Error::Font(format!("не удалось прочитать {}: {e}", path.display())))?;
return FontVec::try_from_vec(data)
.map_err(|_| Error::Font(format!("файл шрифта повреждён: {}", path.display())));
}
Err(Error::Font(format!(
"системный шрифт не найден (проверенные файлы: {})",
CANDIDATES.join(", ")
)))
}
pub fn load_fallback_fonts() -> Vec<FontVec> {
let mut result = Vec::new();
for name in EMOJI_CANDIDATES {
for dir in font_dirs() {
let path = dir.join(name);
if path.exists() {
if let Ok(data) = std::fs::read(&path) {
if let Ok(font) = FontVec::try_from_vec(data) {
eprintln!(
"light: loaded fallback font {:?} ({})",
path.display(),
name
);
result.push(font);
} else {
eprintln!(
"light: failed to parse fallback font {:?}: invalid font data",
path.display()
);
}
}
break; }
}
if let Some(dir) = macos_font_dir() {
let path = dir.join(name);
if path.exists() {
if let Ok(data) = std::fs::read(&path)
&& let Ok(font) = FontVec::try_from_vec(data)
{
eprintln!(
"light: loaded fallback font {:?} ({})",
path.display(),
name
);
result.push(font);
}
break;
}
}
}
result
}
pub struct FontMetrics {
fonts: Vec<FontVec>,
texts: RefCell<HashMap<(u32, String), (f32, f32)>>,
advances: RefCell<HashMap<(u32, char, usize), f32>>,
heights: RefCell<HashMap<u32, f32>>,
}
const TEXT_CACHE_LIMIT: usize = 4096;
impl FontMetrics {
pub fn load() -> Result<Self, Error> {
let primary = load_system_font()?;
let fallbacks = load_fallback_fonts();
let mut fonts = vec![primary];
fonts.extend(fallbacks);
Ok(Self {
fonts,
texts: RefCell::new(HashMap::new()),
advances: RefCell::new(HashMap::new()),
heights: RefCell::new(HashMap::new()),
})
}
pub fn font(&self) -> &FontVec {
&self.fonts[0]
}
pub fn all_fonts(&self) -> &[FontVec] {
&self.fonts
}
pub fn glyph_for(&self, ch: char) -> Option<(usize, GlyphId)> {
let id = self.fonts[0].glyph_id(ch);
if id.0 != 0 {
let cp = ch as u32;
let is_basic = matches!(
cp,
0x00..=0x7E | 0xA0..=0x2FF | 0x400..=0x4FF | 0x2000..=0x206F
);
if is_basic || self.fonts[0].outline(id).is_some() {
return Some((0, id));
}
}
let cp = ch as u32;
let is_basic = matches!(
cp,
0x00..=0x7E | 0xA0..=0x2FF | 0x400..=0x4FF | 0x2000..=0x206F
);
if is_basic {
let box_id = self.fonts[0].glyph_id('\u{25A1}');
return (box_id.0 != 0).then_some((0, box_id));
}
for (idx, font) in self.fonts.iter().enumerate().skip(1) {
let id = font.glyph_id(ch);
if id.0 != 0 && font.outline(id).is_some() {
return Some((idx, id));
}
}
None
}
pub fn advance_for(&self, ch: char, font_size: f32) -> f32 {
match self.glyph_for(ch) {
Some((idx, id)) => {
let scaled = self.fonts[idx].as_scaled(PxScale::from(font_size));
scaled.h_advance(id)
}
None => {
let scaled = self.fonts[0].as_scaled(PxScale::from(font_size));
scaled.h_advance(self.fonts[0].glyph_id('\u{25A1}'))
}
}
}
}
impl TextMetrics for FontMetrics {
fn measure(&self, text: &str, font_size: f32) -> (f32, f32) {
let size = font_size.to_bits();
let key = (size, text.to_owned());
if let Some(size) = self.texts.borrow().get(&key) {
return *size;
}
let width: f32 = text
.chars()
.map(|ch| {
let cache_key = (size, ch, 0);
if let Some(advance) = self.advances.borrow().get(&cache_key) {
return *advance;
}
let advance = self.advance_for(ch, font_size);
self.advances.borrow_mut().insert(cache_key, advance);
advance
})
.sum();
let height = if let Some(height) = self.heights.borrow().get(&size) {
*height
} else {
let scaled = self.fonts[0].as_scaled(PxScale::from(font_size));
let height = scaled.ascent() - scaled.descent();
self.heights.borrow_mut().insert(size, height);
height
};
let measured = (width, height);
let mut texts = self.texts.borrow_mut();
if texts.len() >= TEXT_CACHE_LIMIT {
texts.clear();
}
texts.insert(key, measured);
measured
}
}
pub fn measure(font: &FontVec, text: &str, font_size: f32) -> (f32, f32) {
let scaled = font.as_scaled(PxScale::from(font_size));
let width: f32 = text
.chars()
.map(|ch| scaled.h_advance(font.glyph_id(ch)))
.sum();
(width, scaled.ascent() - scaled.descent())
}
pub fn advance(font: &FontVec, ch: char, font_size: f32) -> f32 {
let scaled = font.as_scaled(PxScale::from(font_size));
scaled.h_advance(font.glyph_id(ch))
}
pub fn line_height(font: &FontVec, font_size: f32) -> f32 {
font.as_scaled(PxScale::from(font_size)).height()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn measure_excludes_line_gap() {
let Ok(metrics) = FontMetrics::load() else {
return;
};
let size = 20.0;
let scaled = metrics.font().as_scaled(PxScale::from(size));
let (_, height) = metrics.measure("Ag", size);
assert!((height - (scaled.ascent() - scaled.descent())).abs() < 0.01);
assert!((scaled.height() - height - scaled.line_gap()).abs() < 0.01);
}
#[test]
fn emoji_glyph_for_fire() {
let Ok(metrics) = FontMetrics::load() else {
eprintln!("skip: system font not available");
return;
};
let result = metrics.glyph_for('\u{1F525}');
match result {
Some((idx, id)) => {
eprintln!("🔥 resolved via font[{idx}] glyph_id={id:?}")
}
None => {
eprintln!(
"🔥 not resolved: no emoji font found among {} candidates",
EMOJI_CANDIDATES.len()
);
}
}
}
#[test]
fn whitespace_uses_primary_font() {
let Ok(m) = FontMetrics::load() else {
return;
};
for ch in [' ', '\t', '\u{00A0}'] {
let (idx, _) = m.glyph_for(ch).unwrap();
assert_eq!(idx, 0, "whitespace {:?} must be in primary", ch);
}
}
}