1use std::collections::{BTreeSet, HashMap};
12use std::path::{Path, PathBuf};
13use std::sync::{Arc, Mutex};
14
15use once_cell::sync::Lazy;
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
19pub enum SvgText {
20 #[default]
23 Editable,
24 Bitmap,
29 Paths,
32}
33
34#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
36pub enum FontEmbed {
37 #[default]
39 Subset,
40 Full,
42 None,
44}
45
46#[derive(Clone, Debug)]
48pub struct SvgOptions {
49 pub text: SvgText,
50 pub embed_fonts: FontEmbed,
51 pub font_dirs: Vec<PathBuf>,
54 pub download_fonts: bool,
56}
57
58impl Default for SvgOptions {
59 fn default() -> Self {
60 let font_dirs = std::env::var_os("BASEMAPPER_FONT_DIRS")
61 .map(|v| std::env::split_paths(&v).collect())
62 .unwrap_or_default();
63 SvgOptions { text: SvgText::Editable, embed_fonts: FontEmbed::Subset, font_dirs, download_fonts: true }
64 }
65}
66
67pub fn parse_font_name(name: &str) -> (String, u16, bool) {
70 let mut words: Vec<&str> = name.split_whitespace().collect();
71 let mut italic = false;
72 let mut weight = 400;
73 loop {
75 let Some(last) = words.last().map(|w| w.to_ascii_lowercase()) else { break };
76 let prev = if words.len() >= 2 { words[words.len() - 2].to_ascii_lowercase() } else { String::new() };
77 let two = format!("{prev}{last}");
78 let w2 = match two.as_str() {
79 "extralight" | "ultralight" => Some(200),
80 "semibold" | "demibold" => Some(600),
81 "extrabold" | "ultrabold" => Some(800),
82 _ => None,
83 };
84 if let Some(w) = w2 {
85 weight = w;
86 words.truncate(words.len() - 2);
87 continue;
88 }
89 let w1 = match last.as_str() {
90 "thin" | "hairline" => Some(100),
91 "extralight" | "ultralight" => Some(200),
92 "light" => Some(300),
93 "regular" | "book" | "normal" | "roman" => Some(400),
94 "medium" => Some(500),
95 "semibold" | "demibold" => Some(600),
96 "bold" => Some(700),
97 "extrabold" | "ultrabold" | "heavy" => Some(800),
98 "black" => Some(900),
99 _ => None,
100 };
101 if let Some(w) = w1 {
102 weight = w;
103 words.pop();
104 continue;
105 }
106 if last == "italic" || last == "oblique" {
107 italic = true;
108 words.pop();
109 continue;
110 }
111 break;
112 }
113 let family = if words.is_empty() { name.to_owned() } else { words.join(" ") };
114 (family, weight, italic)
115}
116
117fn google_family(family: &str) -> Option<String> {
120 let f = family.trim_start_matches("Klokantech ").trim();
121 let mapped = match f {
122 "Noto Sans CJK JP" | "Noto Sans CJK" => "Noto Sans JP",
123 "Noto Sans CJK KR" => "Noto Sans KR",
124 "Noto Sans CJK SC" => "Noto Sans SC",
125 "Noto Sans CJK TC" => "Noto Sans TC",
126 other => other,
127 };
128 let proprietary = ["Arial", "Arial Unicode MS", "Helvetica", "Helvetica Neue", "Avenir", "Avenir Next", "Tahoma", "Verdana", "Times New Roman", "Segoe UI", "Calibri", "Frutiger"];
129 if proprietary.iter().any(|p| p.eq_ignore_ascii_case(mapped)) {
130 return None;
131 }
132 Some(mapped.to_owned())
133}
134
135pub struct FontFace {
137 pub family: String,
138 pub weight: u16,
139 pub italic: bool,
140 pub data: Option<Arc<Vec<u8>>>,
141}
142
143#[derive(Default)]
146pub struct SvgFonts {
147 pub faces: Vec<FontFace>,
148 stacks: HashMap<String, Vec<usize>>,
149 used: Mutex<Vec<BTreeSet<char>>>,
150 texts: Mutex<Vec<(String, String)>>,
152 pending: Mutex<Vec<bool>>,
155 by_name: bool,
157}
158
159impl SvgFonts {
160 pub fn text_attrs(&self, stack: &str) -> String {
163 let idx = self.stacks.get(stack).cloned().unwrap_or_default();
164 let mut fams: Vec<String> = Vec::new();
165 for &i in &idx {
166 let q = format!("'{}'", self.faces[i].family.replace('\'', ""));
167 if !fams.contains(&q) {
168 fams.push(q);
169 }
170 }
171 fams.push("sans-serif".into());
172 let (w, it) = idx.first().map(|&i| (self.faces[i].weight, self.faces[i].italic)).unwrap_or((400, false));
173 format!(
174 r#"font-family="{}" font-weight="{w}"{}"#,
175 super::svg::xml_escape(&fams.join(", ")),
176 if it { r#" font-style="italic""# } else { "" }
177 )
178 }
179
180 pub fn covers(&self, stack: &str, text: &str) -> bool {
184 if self.by_name {
185 return true;
186 }
187 let Some(&first) = self.stacks.get(stack).and_then(|idx| idx.first()) else { return false };
188 let Some(data) = &self.faces[first].data else { return false };
189 let Ok(face) = ttf_parser::Face::parse(data, 0) else { return false };
190 text.chars().all(|c| c.is_whitespace() || face.glyph_index(c).is_some())
191 }
192
193 pub fn baseline_shift(&self, stack: &str, tops: &[(u32, f64)]) -> f64 {
199 let face = self.stacks.get(stack).and_then(|idx| idx.iter().find_map(|&i| self.faces[i].data.clone()));
200 let Some(data) = face else { return 22.0 };
201 let Ok(f) = ttf_parser::Face::parse(&data, 0) else { return 22.0 };
202 let scale = 24.0 / f.units_per_em() as f64;
203 let mut d: Vec<f64> = tops
204 .iter()
205 .filter_map(|&(cp, top)| {
206 let g = f.glyph_index(char::from_u32(cp)?)?;
207 let bb = f.glyph_bounding_box(g)?;
208 Some(bb.y_max as f64 * scale - top)
209 })
210 .collect();
211 if d.is_empty() {
212 return f.ascender() as f64 * scale;
213 }
214 d.sort_by(|a, b| a.partial_cmp(b).unwrap());
215 d[d.len() / 2]
216 }
217
218 pub fn note_text(&self, stack: &str, text: &str) {
221 self.texts.lock().unwrap().push((stack.to_owned(), text.to_owned()));
222 }
223
224 pub async fn finish(&mut self, client: &reqwest::Client, opts: &SvgOptions) {
228 let texts = std::mem::take(&mut *self.texts.lock().unwrap());
229 let mut used = vec![BTreeSet::new(); self.faces.len()];
230 for (stack, text) in texts {
231 let Some(idx) = self.stacks.get(&stack).cloned() else { continue };
232 for ch in text.chars() {
233 let mut chosen = None;
234 for &i in &idx {
235 if std::mem::take(&mut self.pending.lock().unwrap()[i]) && opts.embed_fonts != FontEmbed::None {
236 let f = &self.faces[i];
237 let (family, weight, italic) = (f.family.clone(), f.weight, f.italic);
238 self.faces[i].data = find_font(client, &family, weight, italic, opts).await;
239 }
240 let Some(data) = &self.faces[i].data else { continue };
241 let Ok(face) = ttf_parser::Face::parse(data, 0) else { continue };
242 if ch.is_whitespace() || face.glyph_index(ch).is_some() {
244 chosen = Some(i);
245 break;
246 }
247 }
248 if let Some(i) = chosen {
249 used[i].insert(ch);
250 }
251 }
252 }
253 *self.used.lock().unwrap() = used;
254 }
255
256 pub fn font_face_css(&self, embed: FontEmbed) -> String {
258 if embed == FontEmbed::None {
259 return String::new();
260 }
261 let used = self.used.lock().unwrap();
262 let mut css = String::new();
263 for (i, face) in self.faces.iter().enumerate() {
264 let Some(data) = &face.data else { continue };
265 if used[i].is_empty() {
266 continue;
267 }
268 let bytes = match embed {
269 FontEmbed::Full => Some(data.as_ref().clone()),
270 _ => subset_font(data, &used[i]),
271 };
272 let Some(bytes) = bytes else { continue };
273 css.push_str(&format!(
274 "@font-face{{font-family:'{}';font-weight:{};font-style:{};src:url(data:font/ttf;base64,{}) format('truetype');}}",
275 face.family.replace('\'', ""),
276 face.weight,
277 if face.italic { "italic" } else { "normal" },
278 super::svg::base64(&bytes)
279 ));
280 }
281 css
282 }
283}
284
285fn subset_font(data: &[u8], chars: &BTreeSet<char>) -> Option<Vec<u8>> {
288 use allsorts::binary::read::ReadScope;
289 use allsorts::font_data::FontData;
290 use allsorts::subset::{subset, CmapTarget, SubsetProfile};
291 let face = ttf_parser::Face::parse(data, 0).ok()?;
292 let mut gids: Vec<u16> = vec![0];
293 for &c in chars {
294 if let Some(g) = face.glyph_index(c) {
295 if !gids.contains(&g.0) {
296 gids.push(g.0);
297 }
298 }
299 }
300 let font = ReadScope::new(data).read::<FontData<'_>>().ok()?;
301 let provider = font.table_provider(0).ok()?;
302 match subset(&provider, &gids, &SubsetProfile::Minimal, CmapTarget::Unicode) {
303 Ok(b) => Some(b),
304 Err(e) => {
305 log::warn!("font subsetting failed ({e:?}); embedding the whole font");
306 Some(data.to_vec())
307 }
308 }
309}
310
311pub fn subset_for_fixture(data: &[u8], chars: &str) -> Vec<u8> {
313 subset_font(data, &chars.chars().collect()).expect("subset")
314}
315
316static FOUND: Lazy<Mutex<HashMap<(String, u16, bool), Option<Arc<Vec<u8>>>>>> = Lazy::new(Default::default);
318
319pub async fn resolve(client: &reqwest::Client, stacks: &[String], opts: &SvgOptions) -> SvgFonts {
321 let mut fonts = SvgFonts { by_name: opts.embed_fonts == FontEmbed::None, ..Default::default() };
322 let mut key_index: HashMap<(String, u16, bool), usize> = HashMap::new();
323 let mut pending: Vec<bool> = Vec::new();
324 for stack in stacks {
325 let mut idx = Vec::new();
326 for name in stack.split(',').map(str::trim).filter(|s| !s.is_empty()) {
327 let (family, weight, italic) = parse_font_name(name);
328 let key = (family.clone(), weight, italic);
329 let i = match key_index.get(&key) {
330 Some(&i) => i,
331 None => {
332 fonts.faces.push(FontFace { family: family.clone(), weight, italic, data: None });
333 pending.push(true);
334 key_index.insert(key, fonts.faces.len() - 1);
335 fonts.faces.len() - 1
336 }
337 };
338 idx.push(i);
339 }
340 if let Some(&first) = idx.first() {
342 if std::mem::take(&mut pending[first]) && opts.embed_fonts != FontEmbed::None {
343 let f = &fonts.faces[first];
344 let (family, weight, italic) = (f.family.clone(), f.weight, f.italic);
345 fonts.faces[first].data = find_font(client, &family, weight, italic, opts).await;
346 }
347 }
348 fonts.stacks.insert(stack.clone(), idx);
349 }
350 *fonts.used.lock().unwrap() = vec![BTreeSet::new(); fonts.faces.len()];
351 *fonts.pending.lock().unwrap() = pending;
352 fonts
353}
354
355async fn find_font(client: &reqwest::Client, family: &str, weight: u16, italic: bool, opts: &SvgOptions) -> Option<Arc<Vec<u8>>> {
356 let key = (family.to_owned(), weight, italic);
357 if let Some(hit) = FOUND.lock().unwrap().get(&key) {
358 return hit.clone();
359 }
360 let found = from_dirs(&opts.font_dirs, family, weight, italic)
361 .or_else(|| cache_path(family, weight, italic).and_then(|p| std::fs::read(p).ok()))
362 .map(Arc::new);
363 let found = match found {
364 Some(f) => Some(f),
365 None if opts.download_fonts => download(client, family, weight, italic).await.map(Arc::new),
366 None => None,
367 };
368 if found.is_none() {
369 log::info!("font {family} {weight}{}: no file found; SVG text references it by name", if italic { " italic" } else { "" });
370 }
371 FOUND.lock().unwrap().insert(key, found.clone());
372 found
373}
374
375fn from_dirs(dirs: &[PathBuf], family: &str, weight: u16, italic: bool) -> Option<Vec<u8>> {
378 let mut files = Vec::new();
379 for d in dirs {
380 collect_font_files(d, &mut files, 3);
381 }
382 let mut best: Option<(u32, Vec<u8>)> = None;
383 for path in files {
384 let Ok(data) = std::fs::read(&path) else { continue };
385 let Ok(face) = ttf_parser::Face::parse(&data, 0) else { continue };
386 let names: Vec<String> = face
387 .names()
388 .into_iter()
389 .filter(|n| matches!(n.name_id, 1 | 4 | 16))
390 .filter_map(|n| n.to_string())
391 .collect();
392 if !names.iter().any(|n| n.eq_ignore_ascii_case(family) || n.to_ascii_lowercase().starts_with(&family.to_ascii_lowercase())) {
393 continue;
394 }
395 let w = face.weight().to_number();
396 let score = (w as i32 - weight as i32).unsigned_abs() + if face.is_italic() == italic { 0 } else { 1000 };
397 if best.as_ref().map_or(true, |b| score < b.0) {
398 best = Some((score, data));
399 }
400 }
401 best.filter(|b| b.0 < 1000).map(|b| b.1)
402}
403
404fn collect_font_files(dir: &Path, out: &mut Vec<PathBuf>, depth: u32) {
405 let Ok(rd) = std::fs::read_dir(dir) else { return };
406 for e in rd.flatten() {
407 let p = e.path();
408 if p.is_dir() {
409 if depth > 0 {
410 collect_font_files(&p, out, depth - 1);
411 }
412 } else if p.extension().and_then(|x| x.to_str()).is_some_and(|x| x.eq_ignore_ascii_case("ttf") || x.eq_ignore_ascii_case("otf")) {
413 out.push(p);
414 }
415 }
416}
417
418fn cache_dir() -> Option<PathBuf> {
419 if let Some(d) = std::env::var_os("BASEMAPPER_FONT_CACHE") {
420 return Some(PathBuf::from(d));
421 }
422 let base = std::env::var_os("LOCALAPPDATA")
423 .or_else(|| std::env::var_os("XDG_CACHE_HOME"))
424 .map(PathBuf::from)
425 .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache")))?;
426 Some(base.join("basemapper").join("fonts"))
427}
428
429fn cache_path(family: &str, weight: u16, italic: bool) -> Option<PathBuf> {
430 let safe: String = family.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect();
431 Some(cache_dir()?.join(format!("{safe}-{weight}{}.ttf", if italic { "i" } else { "" })))
432}
433
434async fn download(client: &reqwest::Client, family: &str, weight: u16, italic: bool) -> Option<Vec<u8>> {
436 let g = google_family(family)?;
437 let fam = g.replace(' ', "+");
438 let urls = [
439 format!("https://fonts.googleapis.com/css2?family={fam}:ital,wght@{},{weight}", if italic { 1 } else { 0 }),
440 format!("https://fonts.googleapis.com/css2?family={fam}"),
441 ];
442 for css_url in urls {
443 let Ok(resp) = client.get(&css_url).header("User-Agent", "basemapper").send().await else { continue };
444 if !resp.status().is_success() {
445 continue;
446 }
447 let Ok(css) = resp.text().await else { continue };
448 let Some(start) = css.find("url(") else { continue };
449 let rest = &css[start + 4..];
450 let Some(end) = rest.find(')') else { continue };
451 let font_url = rest[..end].trim_matches(|c| c == '\'' || c == '"');
452 let Ok(r) = client.get(font_url).send().await else { continue };
453 if !r.status().is_success() {
454 continue;
455 }
456 let Ok(bytes) = r.bytes().await else { continue };
457 let bytes = bytes.to_vec();
458 if ttf_parser::Face::parse(&bytes, 0).is_err() {
459 continue;
460 }
461 if let Some(p) = cache_path(family, weight, italic) {
462 if let Some(dir) = p.parent() {
463 let _ = std::fs::create_dir_all(dir);
464 }
465 let _ = std::fs::write(&p, &bytes);
466 }
467 return Some(bytes);
468 }
469 None
470}
471
472#[cfg(test)]
473mod tests {
474 use super::*;
475
476 #[test]
477 fn font_names_split_into_family_weight_style() {
478 assert_eq!(parse_font_name("Open Sans Bold"), ("Open Sans".into(), 700, false));
479 assert_eq!(parse_font_name("Montserrat SemiBold Italic"), ("Montserrat".into(), 600, true));
480 assert_eq!(parse_font_name("Open Sans Semibold"), ("Open Sans".into(), 600, false));
481 assert_eq!(parse_font_name("Noto Sans CJK JP Regular"), ("Noto Sans CJK JP".into(), 400, false));
482 assert_eq!(parse_font_name("Roboto Extra Bold"), ("Roboto".into(), 800, false));
483 assert_eq!(parse_font_name("Arial Unicode MS Regular"), ("Arial Unicode MS".into(), 400, false));
484 assert_eq!(google_family("Noto Sans CJK JP").as_deref(), Some("Noto Sans JP"));
485 assert_eq!(google_family("Arial"), None);
486 }
487
488 #[test]
489 fn fonts_from_a_folder_are_subset_and_embedded() {
490 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/fonts");
491 let opts = SvgOptions { text: SvgText::Editable, embed_fonts: FontEmbed::Subset, font_dirs: vec![dir], download_fonts: false };
492 let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
493 let client = reqwest::Client::new();
494 let stack = "Open Sans Bold,Arial Unicode MS Bold".to_owned();
495 let mut fonts = rt.block_on(resolve(&client, &[stack.clone()], &opts));
496 assert!(fonts.faces[0].data.is_some(), "Open Sans Bold found in the fixture folder");
497 assert!(fonts.faces[1].data.is_none(), "Arial Unicode MS is referenced by name only");
498 let attrs = fonts.text_attrs(&stack);
499 assert!(attrs.contains("'Open Sans', 'Arial Unicode MS', sans-serif") && attrs.contains(r#"font-weight="700""#), "{attrs}");
500 fonts.note_text(&stack, "Salt Lake");
501 rt.block_on(fonts.finish(&client, &opts));
502 let css = fonts.font_face_css(FontEmbed::Subset);
503 assert!(css.starts_with("@font-face{font-family:'Open Sans';font-weight:700;font-style:normal;"), "{}", &css[..80]);
504 let b64 = css.split("base64,").nth(1).unwrap().split(')').next().unwrap();
505 let bytes = decode_b64(b64);
506 let face = ttf_parser::Face::parse(&bytes, 0).expect("embedded subset parses");
507 for c in "SaltLake".chars() {
508 assert!(face.glyph_index(c).is_some(), "{c} kept");
509 }
510 assert!(face.glyph_index('Q').is_none(), "unused glyphs dropped");
511 assert!(fonts.font_face_css(FontEmbed::None).is_empty());
512 }
513
514 fn decode_b64(s: &str) -> Vec<u8> {
515 const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
516 let val = |c: u8| T.iter().position(|&t| t == c).unwrap() as u32;
517 let bytes: Vec<u8> = s.bytes().filter(|&c| c != b'=').collect();
518 let mut out = Vec::new();
519 for chunk in bytes.chunks(4) {
520 let n = chunk.iter().enumerate().fold(0u32, |acc, (i, &c)| acc | (val(c) << (18 - 6 * i)));
521 out.push((n >> 16) as u8);
522 if chunk.len() > 2 {
523 out.push((n >> 8) as u8);
524 }
525 if chunk.len() > 3 {
526 out.push(n as u8);
527 }
528 }
529 out
530 }
531}