Skip to main content

basemapper_core/vector/
fonts.rs

1//! Fonts for editable SVG text: MapLibre font names resolved to font files
2//! (user folders, a local cache, then Google Fonts for open fonts), the
3//! characters each font draws, and `@font-face` rules embedding them
4//! (subset to those characters, or whole).
5//!
6//! MapLibre styles name fonts ("Open Sans Bold") but serve only SDF glyph
7//! bitmaps, so true outlines need the font files themselves. Fonts that
8//! cannot be found stay referenced by name: the text remains editable and
9//! uses whatever the viewer has installed.
10
11use std::collections::{BTreeSet, HashMap};
12use std::path::{Path, PathBuf};
13use std::sync::{Arc, Mutex};
14
15use once_cell::sync::Lazy;
16
17/// How SVG output writes label text.
18#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
19pub enum SvgText {
20    /// `<text>` elements (editable, selectable), fonts embedded per
21    /// [`FontEmbed`]; glyph positions are MapLibre's layout.
22    #[default]
23    Editable,
24    /// Every label drawn from the style's SDF glyph bitmaps (embedded images
25    /// thresholded by SVG filters as MapLibre's shader does): MapLibre's
26    /// glyphs and edges at any zoom, not editable. Editable mode falls back
27    /// to this for labels whose font file is not available.
28    Bitmap,
29    /// Glyph outlines traced from the style's SDF glyphs: not editable,
30    /// plain paths (no filters).
31    Paths,
32}
33
34/// How fonts are embedded in editable SVG text.
35#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
36pub enum FontEmbed {
37    /// Only the glyphs the map uses (small files).
38    #[default]
39    Subset,
40    /// Whole font files (new text typed later keeps the font).
41    Full,
42    /// Reference fonts by name only.
43    None,
44}
45
46/// SVG output options.
47#[derive(Clone, Debug)]
48pub struct SvgOptions {
49    pub text: SvgText,
50    pub embed_fonts: FontEmbed,
51    /// Folders searched for font files (.ttf / .otf) before downloading;
52    /// default: `BASEMAPPER_FONT_DIRS` (path-separated).
53    pub font_dirs: Vec<PathBuf>,
54    /// Download open fonts from Google Fonts (cached on disk).
55    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
67/// A MapLibre font name split into family, CSS weight and italic, e.g.
68/// "Montserrat SemiBold Italic" -> ("Montserrat", 600, true).
69pub 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    // Trailing style words, possibly combined ("Bold Italic", "Extra Bold").
74    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
117/// The Google Fonts family for a style's font family (a few common names
118/// differ), or None for fonts that are not there.
119fn 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
135/// One font of the document: what CSS calls it and, when found, its file.
136pub struct FontFace {
137    pub family: String,
138    pub weight: u16,
139    pub italic: bool,
140    pub data: Option<Arc<Vec<u8>>>,
141}
142
143/// The fonts of an SVG document: faces, the faces of each font stack, and
144/// the characters each face draws.
145#[derive(Default)]
146pub struct SvgFonts {
147    pub faces: Vec<FontFace>,
148    stacks: HashMap<String, Vec<usize>>,
149    used: Mutex<Vec<BTreeSet<char>>>,
150    /// Text drawn per stack, routed to faces by [`SvgFonts::finish`].
151    texts: Mutex<Vec<(String, String)>>,
152    /// Faces whose file has not been looked up yet (fallbacks are fetched
153    /// only when a character needs them).
154    pending: Mutex<Vec<bool>>,
155    /// embed_fonts = None: text references fonts by name, never falls back.
156    by_name: bool,
157}
158
159impl SvgFonts {
160    /// `font-family`, `font-weight`, `font-style` attributes for a font stack
161    /// ("Open Sans Bold,Arial Unicode MS Bold").
162    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    /// Whether `text` can be written as `<text>` with an exact font: the
181    /// stack's first font was found and has every (non-space) character
182    /// (always, when fonts are referenced by name only).
183    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    /// Vertical shift (24 px glyph units, y down) from MapLibre's glyph line
194    /// position to the font baseline. The SDF glyph `top` is measured from a
195    /// generator-specific line (fontnik: the ascender), so it is measured per
196    /// font: the median over glyphs of (ink top from the real outline - SDF
197    /// top). `tops` gives (codepoint, SDF top) for the glyphs available.
198    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    /// Record text drawn with `stack` (characters are assigned to fonts by
219    /// [`SvgFonts::finish`]).
220    pub fn note_text(&self, stack: &str, text: &str) {
221        self.texts.lock().unwrap().push((stack.to_owned(), text.to_owned()));
222    }
223
224    /// Assign every recorded character to the first font of its stack that
225    /// has it, looking up fallback fonts (e.g. CJK) only when a character
226    /// needs them. Call before [`SvgFonts::font_face_css`].
227    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                    // Spaces go to the first embedded font (layout uses explicit positions).
243                    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    /// `@font-face` rules for the faces that draw something.
257    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
285/// `data` reduced to the glyphs of `chars` (plus .notdef), with a Unicode
286/// cmap so browsers accept it. None if the font cannot be subset.
287fn 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
311/// A subset of `data` with the characters of `chars` (test fixtures).
312pub fn subset_for_fixture(data: &[u8], chars: &str) -> Vec<u8> {
313    subset_font(data, &chars.chars().collect()).expect("subset")
314}
315
316/// Fonts found per (family, weight, italic) in this process (None: not found).
317static FOUND: Lazy<Mutex<HashMap<(String, u16, bool), Option<Arc<Vec<u8>>>>>> = Lazy::new(Default::default);
318
319/// Resolve the fonts of the given font stacks.
320pub 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        // The first font of each stack now: its metrics place the baseline.
341        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
375/// A font file in `dirs` whose name table matches (typographic or legacy
376/// family, OS/2 weight, italic flag), or whose full name is the font name.
377fn 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
434/// The TrueType file for a family/weight/style from Google Fonts (cached).
435async 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}