1use std::collections::HashMap;
22use std::path::{Path, PathBuf};
23use std::sync::{Arc, Mutex, OnceLock};
24
25#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
27pub enum Family {
28 Sans,
29 Serif,
30 Mono,
31 Symbol,
32 Dingbats,
33 Cjk,
35}
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
38pub struct Style {
39 pub family: Family,
40 pub bold: bool,
41 pub italic: bool,
42}
43
44pub struct FallbackFace {
46 pub font: skrifa::font::Font,
48 pub path: PathBuf,
49}
50
51struct Index {
52 files: HashMap<String, PathBuf>,
54}
55
56fn index() -> &'static Index {
57 static INDEX: OnceLock<Index> = OnceLock::new();
58 INDEX.get_or_init(|| {
59 let mut files = HashMap::new();
60 for dir in font_dirs() {
61 scan(&dir, 0, &mut files);
62 }
63 Index { files }
64 })
65}
66
67fn font_dirs() -> Vec<PathBuf> {
68 let system = docling_core::env::nonempty("DOCLING_RS_SYSTEM_FONTS").is_none()
71 || docling_core::env::flag("DOCLING_RS_SYSTEM_FONTS");
72 font_dirs_from(
73 PathBuf::from(crate::resolve_asset(".models/fonts")),
74 docling_core::env::nonempty("DOCLING_RS_FONT_DIRS").as_deref(),
75 system.then(|| HostDirs {
76 home: std::env::var_os("HOME").map(PathBuf::from),
77 windir: std::env::var_os("WINDIR").map(PathBuf::from),
78 }),
79 )
80}
81
82struct HostDirs {
84 home: Option<PathBuf>,
85 windir: Option<PathBuf>,
86}
87
88fn font_dirs_from(models: PathBuf, extra: Option<&str>, host: Option<HostDirs>) -> Vec<PathBuf> {
92 let mut dirs = vec![models];
93 if let Some(extra) = extra {
94 dirs.extend(std::env::split_paths(extra));
95 }
96 let Some(host) = host else {
97 return dirs;
98 };
99 if let Some(home) = host.home {
100 dirs.push(home.join(".fonts"));
101 dirs.push(home.join(".local/share/fonts"));
102 dirs.push(home.join("Library/Fonts"));
103 }
104 for d in [
105 "/usr/share/fonts",
106 "/usr/local/share/fonts",
107 "/usr/X11R6/lib/X11/fonts",
108 "/Library/Fonts",
109 "/System/Library/Fonts",
110 "/System/Library/Fonts/Supplemental",
111 "C:\\Windows\\Fonts",
112 ] {
113 dirs.push(PathBuf::from(d));
114 }
115 if let Some(windir) = host.windir {
116 dirs.push(windir.join("Fonts"));
117 }
118 dirs
119}
120
121fn scan(dir: &Path, depth: usize, files: &mut HashMap<String, PathBuf>) {
122 if depth > 4 {
123 return;
124 }
125 let Ok(rd) = std::fs::read_dir(dir) else {
126 return;
127 };
128 for entry in rd.flatten() {
129 let p = entry.path();
130 if p.is_dir() {
131 scan(&p, depth + 1, files);
132 continue;
133 }
134 let ext = p
135 .extension()
136 .and_then(|e| e.to_str())
137 .map(|e| e.to_ascii_lowercase())
138 .unwrap_or_default();
139 if !matches!(ext.as_str(), "ttf" | "otf" | "ttc") {
140 continue;
141 }
142 if let Some(stem) = p.file_stem().and_then(|s| s.to_str()) {
143 let key = stem.to_ascii_lowercase().replace([' ', '_'], "");
144 files.entry(key).or_insert(p);
145 }
146 }
147}
148
149fn candidates(style: Style) -> Vec<String> {
153 let (b, i) = (style.bold, style.italic);
154 let suffix_dash = |reg: &'static str,
155 bold: &'static str,
156 it: &'static str,
157 bi: &'static str|
158 -> &'static str {
159 match (b, i) {
160 (true, true) => bi,
161 (true, false) => bold,
162 (false, true) => it,
163 (false, false) => reg,
164 }
165 };
166 let mut out = Vec::new();
167 let mut push = |s: String| out.push(s.to_ascii_lowercase().replace([' ', '_'], ""));
168 match style.family {
169 Family::Sans => {
170 push(format!(
171 "LiberationSans-{}",
172 suffix_dash("Regular", "Bold", "Italic", "BoldItalic")
173 ));
174 push(format!("arial{}", suffix_dash("", "bd", "i", "bi")));
175 push(format!(
176 "Arial{}",
177 suffix_dash("", " Bold", " Italic", " Bold Italic")
178 ));
179 push(format!(
180 "NimbusSans-{}",
181 suffix_dash("Regular", "Bold", "Italic", "BoldItalic")
182 ));
183 push(format!(
184 "DejaVuSans{}",
185 suffix_dash("", "-Bold", "-Oblique", "-BoldOblique")
186 ));
187 push(format!(
188 "FreeSans{}",
189 suffix_dash("", "Bold", "Oblique", "BoldOblique")
190 ));
191 push(format!(
192 "NotoSans-{}",
193 suffix_dash("Regular", "Bold", "Italic", "BoldItalic")
194 ));
195 push("Helvetica".into());
196 push("DejaVuSans".into());
197 push("LiberationSans-Regular".into());
198 }
199 Family::Serif => {
200 push(format!(
201 "LiberationSerif-{}",
202 suffix_dash("Regular", "Bold", "Italic", "BoldItalic")
203 ));
204 push(format!("times{}", suffix_dash("", "bd", "i", "bi")));
205 push(format!(
206 "Times New Roman{}",
207 suffix_dash("", " Bold", " Italic", " Bold Italic")
208 ));
209 push(format!(
210 "NimbusRoman-{}",
211 suffix_dash("Regular", "Bold", "Italic", "BoldItalic")
212 ));
213 push(format!(
214 "DejaVuSerif{}",
215 suffix_dash("", "-Bold", "-Italic", "-BoldItalic")
216 ));
217 push(format!(
218 "FreeSerif{}",
219 suffix_dash("", "Bold", "Italic", "BoldItalic")
220 ));
221 push(format!(
222 "NotoSerif-{}",
223 suffix_dash("Regular", "Bold", "Italic", "BoldItalic")
224 ));
225 push("Times".into());
226 push("DejaVuSerif".into());
227 push("LiberationSerif-Regular".into());
228 }
229 Family::Mono => {
230 push(format!(
231 "LiberationMono-{}",
232 suffix_dash("Regular", "Bold", "Italic", "BoldItalic")
233 ));
234 push(format!("cour{}", suffix_dash("", "bd", "i", "bi")));
235 push(format!(
236 "Courier New{}",
237 suffix_dash("", " Bold", " Italic", " Bold Italic")
238 ));
239 push(format!(
240 "NimbusMonoPS-{}",
241 suffix_dash("Regular", "Bold", "Italic", "BoldItalic")
242 ));
243 push(format!(
244 "DejaVuSansMono{}",
245 suffix_dash("", "-Bold", "-Oblique", "-BoldOblique")
246 ));
247 push(format!(
248 "FreeMono{}",
249 suffix_dash("", "Bold", "Oblique", "BoldOblique")
250 ));
251 push("Courier".into());
252 push("DejaVuSansMono".into());
253 push("LiberationMono-Regular".into());
254 }
255 Family::Symbol => {
256 push("StandardSymbolsPS".into());
257 push("Symbol".into());
258 push("symbol".into());
259 push("DejaVuSans".into());
260 }
261 Family::Dingbats => {
262 push("D050000L".into());
263 push("Dingbats".into());
264 push("ZapfDingbats".into());
265 push("DejaVuSans".into());
266 }
267 Family::Cjk => {
268 push("NotoSansCJK-Regular".into());
269 push("NotoSansCJKjp-Regular".into());
270 push("NotoSansCJKsc-Regular".into());
271 push("DroidSansFallbackFull".into());
272 push("DroidSansFallback".into());
273 push("wqy-microhei".into());
274 push("wqy-zenhei".into());
275 push("fonts-japanese-gothic".into());
276 push("ipag".into());
277 push("msgothic".into());
278 push("simsun".into());
279 push("PingFang".into());
280 push("DejaVuSans".into());
281 }
282 }
283 out
284}
285
286pub fn face(style: Style) -> Option<Arc<FallbackFace>> {
288 static CACHE: OnceLock<Mutex<HashMap<Style, Option<Arc<FallbackFace>>>>> = OnceLock::new();
289 let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
290 if let Some(v) = cache.lock().ok().and_then(|c| c.get(&style).cloned()) {
291 return v;
292 }
293 let idx = index();
294 let mut found = None;
295 for cand in candidates(style) {
296 if let Some(p) = idx.files.get(&cand) {
297 if let Ok(data) = std::fs::read(p) {
298 if let Some(font) = skrifa::font::Font::new(data, 0) {
299 found = Some(Arc::new(FallbackFace {
300 font,
301 path: p.clone(),
302 }));
303 break;
304 }
305 }
306 }
307 }
308 if found.is_none() && (style.bold || style.italic) {
310 found = face(Style {
311 family: style.family,
312 bold: false,
313 italic: false,
314 });
315 } else {
316 docling_core::debug_log!(
319 "docling-pdf fallback font: {:?} bold={} italic={} → {}",
320 style.family,
321 style.bold,
322 style.italic,
323 found
324 .as_ref()
325 .map_or_else(|| "none".to_string(), |f| f.path.display().to_string())
326 );
327 }
328 if let Ok(mut c) = cache.lock() {
329 c.insert(style, found.clone());
330 }
331 found
332}
333
334pub fn style_for(base_font: &str, flags: Option<i64>, serif_hint: Option<bool>) -> Style {
338 let name = base_font.to_ascii_lowercase();
339 let style_part = name.split_once(['-', ',']).map(|(_, s)| s).unwrap_or("");
340 let bold = style_part.contains("bold")
341 || name.contains("bold")
342 || name.contains("black")
343 || name.contains("heavy")
344 || name.contains("semibold")
345 || flags.is_some_and(|f| f & (1 << 18) != 0);
346 let italic = name.contains("italic")
347 || name.contains("oblique")
348 || flags.is_some_and(|f| f & (1 << 6) != 0);
349 let family = if name.contains("symbol") {
350 Family::Symbol
351 } else if name.contains("dingbat") || name.contains("wingding") {
352 Family::Dingbats
353 } else if name.contains("courier")
354 || name.contains("mono")
355 || name.contains("consolas")
356 || name.contains("menlo")
357 || flags.is_some_and(|f| f & 1 != 0 && !name.contains("arial"))
358 {
359 Family::Mono
360 } else if name.contains("times")
361 || name.contains("georgia")
362 || name.contains("garamond")
363 || name.contains("book")
364 || name.contains("palatino")
365 || name.contains("century")
366 || name.contains("cambria")
367 || name.contains("minion")
368 || name.contains("nimbusrom")
369 || name.contains("roman")
370 || name.contains("serif") && !name.contains("sans")
371 || name.starts_with("cm")
372 && (name.starts_with("cmr") || name.starts_with("cmbx") || name.starts_with("cmti"))
373 {
374 Family::Serif
375 } else if name.contains("arial")
376 || name.contains("helvetica")
377 || name.contains("verdana")
378 || name.contains("calibri")
379 || name.contains("sans")
380 || name.contains("tahoma")
381 || name.contains("segoe")
382 {
383 Family::Sans
384 } else if serif_hint == Some(true) || flags.is_some_and(|f| f & 2 != 0) {
385 Family::Serif
386 } else {
387 Family::Sans
388 };
389 Style {
390 family,
391 bold,
392 italic,
393 }
394}
395
396#[cfg(test)]
397mod tests {
398 use super::*;
399
400 #[test]
405 fn system_fonts_off_keeps_only_the_deployment_directories() {
406 let extra = std::env::join_paths(["/srv/fonts", "/opt/fonts"]).unwrap();
407 let dirs = font_dirs_from(PathBuf::from(".models/fonts"), extra.to_str(), None);
408 assert_eq!(
409 dirs,
410 [".models/fonts", "/srv/fonts", "/opt/fonts"].map(PathBuf::from)
411 );
412 }
413
414 #[test]
417 fn host_directories_follow_the_deployment_ones() {
418 let dirs = font_dirs_from(
419 PathBuf::from(".models/fonts"),
420 Some("/srv/fonts"),
421 Some(HostDirs {
422 home: Some(PathBuf::from("/home/u")),
423 windir: Some(PathBuf::from("C:\\W")),
424 }),
425 );
426 assert_eq!(
427 dirs[..3],
428 [".models/fonts", "/srv/fonts", "/home/u/.fonts"].map(PathBuf::from)
429 );
430 assert!(dirs.contains(&PathBuf::from("/usr/share/fonts")));
431 assert_eq!(dirs.last(), Some(&PathBuf::from("C:\\W").join("Fonts")));
432 }
433}