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
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
use fnv::FnvHashMap;
use owned_ttf_parser::{
    AsFaceRef,
    Face as TtfFont,
    GlyphId,
    OwnedFace,
};

use crate::{
    ErrorKind,
    Path,
};

pub struct GlyphMetrics {
    pub width: f32,
    pub height: f32,
    pub bearing_x: f32,
    pub bearing_y: f32,
}

pub struct Glyph {
    pub path: Option<Path>, // None means render as image
    pub metrics: GlyphMetrics,
}

pub(crate) enum GlyphRendering<'a> {
    RenderAsPath(&'a mut Path),
    #[cfg(feature = "image-loading")]
    RenderAsImage(image::DynamicImage),
}

/// Information about a font.
// TODO: underline, strikeout, subscript, superscript metrics
#[derive(Copy, Clone, Default, Debug)]
pub struct FontMetrics {
    ascender: f32,
    descender: f32,
    height: f32,
    regular: bool,
    italic: bool,
    bold: bool,
    oblique: bool,
    variable: bool,
    weight: u16,
    width: u16,
}

impl FontMetrics {
    fn scale(&mut self, scale: f32) {
        self.ascender *= scale;
        self.descender *= scale;
        self.height *= scale;
    }

    /// The distance from the baseline to the top of the highest glyph
    pub fn ascender(&self) -> f32 {
        self.ascender
    }

    /// The distance from the baseline to the bottom of the lowest descenders on the glyphs
    pub fn descender(&self) -> f32 {
        self.descender
    }

    pub fn height(&self) -> f32 {
        self.height.round()
    }

    pub fn regular(&self) -> bool {
        self.regular
    }

    pub fn italic(&self) -> bool {
        self.italic
    }

    pub fn bold(&self) -> bool {
        self.bold
    }

    pub fn oblique(&self) -> bool {
        self.oblique
    }

    pub fn variable(&self) -> bool {
        self.variable
    }

    pub fn weight(&self) -> u16 {
        self.weight
    }

    pub fn width(&self) -> u16 {
        self.width
    }
}

pub(crate) struct Font {
    data: Vec<u8>,
    owned_ttf_font: OwnedFace,
    units_per_em: u16,
    metrics: FontMetrics,
    glyphs: FnvHashMap<u16, Glyph>,
}

impl Font {
    pub fn new(data: &[u8]) -> Result<Self, ErrorKind> {
        let owned_ttf_font = OwnedFace::from_vec(data.to_owned(), 0).map_err(|_| ErrorKind::FontParseError)?;

        let units_per_em = owned_ttf_font
            .as_face_ref()
            .units_per_em()
            .ok_or(ErrorKind::FontInfoExtracionError)?;

        let ttf_font = owned_ttf_font.as_face_ref();

        let metrics = FontMetrics {
            ascender: ttf_font.ascender() as f32,
            descender: ttf_font.descender() as f32,
            height: ttf_font.height() as f32,
            regular: ttf_font.is_regular(),
            italic: ttf_font.is_italic(),
            bold: ttf_font.is_bold(),
            oblique: ttf_font.is_oblique(),
            variable: ttf_font.is_variable(),
            weight: ttf_font.width().to_number(),
            width: ttf_font.weight().to_number(),
        };

        Ok(Self {
            data: data.to_owned(),
            owned_ttf_font,
            units_per_em,
            metrics,
            glyphs: Default::default(),
        })
    }

    pub fn data(&self) -> &[u8] {
        self.data.as_ref()
    }

    fn font_ref(&self) -> &TtfFont<'_> {
        self.owned_ttf_font.as_face_ref()
    }

    pub fn metrics(&self, size: f32) -> FontMetrics {
        let mut metrics = self.metrics;

        metrics.scale(self.scale(size));

        metrics
    }

    pub fn scale(&self, size: f32) -> f32 {
        size / self.units_per_em as f32
    }

    pub fn glyph(&mut self, codepoint: u16) -> Option<&mut Glyph> {
        if !self.glyphs.contains_key(&codepoint) {
            let mut path = Path::new();

            let id = GlyphId(codepoint);

            let maybe_glyph = if let Some(image) = self
                .font_ref()
                .glyph_raster_image(id, std::u16::MAX)
                .filter(|img| img.format == owned_ttf_parser::RasterImageFormat::PNG)
            {
                let scale = if image.pixels_per_em != 0 {
                    self.units_per_em as f32 / image.pixels_per_em as f32
                } else {
                    1.0
                };
                Some(Glyph {
                    path: None,
                    metrics: GlyphMetrics {
                        width: image.width as f32 * scale,
                        height: image.height as f32 * scale,
                        bearing_x: image.x as f32 * scale,
                        bearing_y: (image.y as f32 + image.height as f32) * scale,
                    },
                })
            } else if let Some(bbox) = self.font_ref().outline_glyph(id, &mut path) {
                Some(Glyph {
                    path: Some(path),
                    metrics: GlyphMetrics {
                        width: bbox.width() as f32,
                        height: bbox.height() as f32,
                        bearing_x: bbox.x_min as f32,
                        bearing_y: bbox.y_max as f32,
                    },
                })
            } else {
                None
            };

            if let Some(glyph) = maybe_glyph {
                self.glyphs.insert(codepoint, glyph);
            }
        }

        self.glyphs.get_mut(&codepoint)
    }

    pub fn glyph_rendering_representation(&mut self, codepoint: u16, _pixels_per_em: u16) -> Option<GlyphRendering> {
        #[cfg(feature = "image-loading")]
        if let Some(image) = self
            .font_ref()
            .glyph_raster_image(GlyphId(codepoint), _pixels_per_em)
            .and_then(|raster_glyph_image| {
                image::load_from_memory_with_format(raster_glyph_image.data, image::ImageFormat::Png).ok()
            })
        {
            return Some(GlyphRendering::RenderAsImage(image));
        };

        self.glyph(codepoint)
            .and_then(|glyph| glyph.path.as_mut().map(|path| GlyphRendering::RenderAsPath(path)))
    }
}