1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use std::collections::HashMap;

use ttf_parser::Face;

/// Implementing this allows overriding of how glyphs are measured.
pub trait Measure: std::fmt::Debug {
    /// Measures the display width of `text`.
    fn str(&self, text: &str) -> u32;

    /// Measures the display width of `c`.
    fn char(&self, c: char) -> u16;
}

/// Implements measuring glyphs via `ttf_parser`
#[derive(Clone, Debug)]
pub struct TTFParserMeasure<'a> {
    face: &'a Face<'a>,
    cache: HashMap<char, u16>,
}

impl<'a> TTFParserMeasure<'a> {
    /// Creates a new TTFParserMeasure for the font `face`.
    pub fn new(face: &'a Face<'a>) -> Self {
        Self {
            face,
            cache: HashMap::new(),
        }
    }
}

impl<'a> Measure for TTFParserMeasure<'a> {
    fn str(&self, text: &str) -> u32 {
        text.chars().map(|c| u32::from(self.char(c))).sum()
    }

    #[inline]
    fn char(&self, c: char) -> u16 {
        self.face
            .glyph_index(c)
            .map(|glyph_id| self.face.glyph_hor_advance(glyph_id))
            .flatten()
            .unwrap_or_default()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_str() {
        let font_data = crate::tests::read_font();
        let font_face = Face::from_slice(&font_data, 0).expect("TTF should be valid");
        let dw = TTFParserMeasure::new(&font_face);

        let text = "aoeu";
        let width = dw.str(text);
        assert_eq!(width, 4496);
    }

    #[test]
    fn test_char() {
        let font_data = crate::tests::read_font();
        let font_face = Face::from_slice(&font_data, 0).expect("TTF should be valid");
        let dw = TTFParserMeasure::new(&font_face);

        let text = "a";
        let width = dw.char(text.chars().next().unwrap());
        assert_eq!(width, 1114);
    }

    #[test]
    fn caverns() {
        let font_data = crate::tests::read_font();
        let font_face = Face::from_slice(&font_data, 0).expect("TTF should be valid");
        let dw = TTFParserMeasure::new(&font_face);

        let text = "caverns are not for the";
        let width = dw.str(text);
        assert_eq!(width, 20483);
    }
}