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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
use std::ffi::{CStr, CString};
use std::fmt;
use std::num::NonZeroU32;
use std::rc::Rc;

use crate::charmap::CharMap;
use {ffi, FtResult, GlyphSlot, Matrix, Vector};

#[repr(u32)]
#[derive(Copy, Clone)]
pub enum KerningMode {
    KerningDefault = ffi::FT_KERNING_DEFAULT,
    KerningUnfitted = ffi::FT_KERNING_UNFITTED,
    KerningUnscaled = ffi::FT_KERNING_UNSCALED,
}

bitflags! {
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct LoadFlag: i32 {
        const DEFAULT                    = ::ffi::FT_LOAD_DEFAULT;
        const NO_SCALE                   = ::ffi::FT_LOAD_NO_SCALE;
        const NO_HINTING                 = ::ffi::FT_LOAD_NO_HINTING;
        const RENDER                     = ::ffi::FT_LOAD_RENDER;
        const NO_BITMAP                  = ::ffi::FT_LOAD_NO_BITMAP;
        const VERTICAL_LAYOUT            = ::ffi::FT_LOAD_VERTICAL_LAYOUT;
        const FORCE_AUTOHINT             = ::ffi::FT_LOAD_FORCE_AUTOHINT;
        const CROP_BITMAP                = ::ffi::FT_LOAD_CROP_BITMAP;
        const PEDANTIC                   = ::ffi::FT_LOAD_PEDANTIC;
        const IGNORE_GLOBAL_ADVANCE_WITH = ::ffi::FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
        const NO_RECURSE                 = ::ffi::FT_LOAD_NO_RECURSE;
        const IGNORE_TRANSFORM           = ::ffi::FT_LOAD_IGNORE_TRANSFORM;
        const MONOCHROME                 = ::ffi::FT_LOAD_MONOCHROME;
        const LINEAR_DESIGN              = ::ffi::FT_LOAD_LINEAR_DESIGN;
        const NO_AUTOHINT                = ::ffi::FT_LOAD_NO_AUTOHINT;
        const TARGET_NORMAL              = ::ffi::FT_LOAD_TARGET_NORMAL;
        const TARGET_LIGHT               = ::ffi::FT_LOAD_TARGET_LIGHT;
        const TARGET_MONO                = ::ffi::FT_LOAD_TARGET_MONO;
        const TARGET_LCD                 = ::ffi::FT_LOAD_TARGET_LCD;
        const TARGET_LCD_V               = ::ffi::FT_LOAD_TARGET_LCD_V;
        const COLOR                      = ::ffi::FT_LOAD_COLOR;
    }
}

bitflags! {
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct StyleFlag: ffi::FT_Long {
        const BOLD   = ::ffi::FT_STYLE_FLAG_BOLD;
        const ITALIC = ::ffi::FT_STYLE_FLAG_ITALIC;
    }
}

pub struct CharIterator<'a, BYTES> {
    started: bool,
    face: &'a Face<BYTES>,
    gindex: ffi::FT_UInt,
    charcode: ffi::FT_ULong,
}

impl<'a, BYTES> CharIterator<'a, BYTES> {
    fn new(face: &'a Face<BYTES>) -> Self {
        CharIterator {
            started: false,
            face,
            gindex: 0,
            charcode: 0,
        }
    }
}

impl<'a, BYTES> Iterator for CharIterator<'a, BYTES> {
    type Item = (usize, NonZeroU32);

    fn next(&mut self) -> Option<Self::Item> {
        // Implementing per https://freetype.org/freetype2/docs/reference/ft2-character_mapping.html#ft_get_first_char
        //  FT_UInt   gindex;
        //  FT_ULong charcode = FT_Get_First_Char( face, &gindex );
        //  while ( gindex != 0 ) {
        //    ... do something with (charcode,gindex) pair ...
        //    charcode = FT_Get_Next_Char( face, charcode, &gindex );
        //  }

        if self.started {
            self.charcode =
                unsafe { ffi::FT_Get_Next_Char(self.face.raw, self.charcode, &mut self.gindex) };
        } else {
            self.started = true;
            self.charcode = unsafe { ffi::FT_Get_First_Char(self.face.raw, &mut self.gindex) };
        }

        if self.gindex == 0 {
            None
        } else {
            NonZeroU32::new(self.gindex).map(|gindex| (self.charcode as usize, gindex))
        }
    }

    // TODO: implement size_hint
}

#[derive(Eq, PartialEq, Hash)]
pub struct Face<BYTES = Rc<Vec<u8>>> {
    library_raw: ffi::FT_Library,
    raw: ffi::FT_Face,
    glyph: GlyphSlot,
    bytes: Option<BYTES>,
}

impl<BYTES: Clone> Clone for Face<BYTES> {
    fn clone(&self) -> Self {
        let err = unsafe { ffi::FT_Reference_Library(self.library_raw) };
        if err != ffi::FT_Err_Ok {
            panic!("Failed to reference library");
        }
        let err = unsafe { ffi::FT_Reference_Face(self.raw) };
        if err != ffi::FT_Err_Ok {
            panic!("Failed to reference face");
        }
        Face {
            library_raw: self.library_raw,
            raw: self.raw,
            glyph: self.glyph,
            bytes: self.bytes.clone(),
        }
    }
}

impl<BYTES> Face<BYTES> {
    pub unsafe fn from_raw(
        library_raw: ffi::FT_Library,
        raw: ffi::FT_Face,
        bytes: Option<BYTES>,
    ) -> Self {
        ffi::FT_Reference_Library(library_raw);
        Face {
            library_raw,
            raw,
            glyph: GlyphSlot::from_raw(library_raw, (*raw).glyph),
            bytes,
        }
    }

    pub fn attach_file(&self, filepathname: &str) -> FtResult<()> {
        let err = unsafe { ffi::FT_Attach_File(self.raw, filepathname.as_ptr() as *const _) };
        if err == ffi::FT_Err_Ok {
            Ok(())
        } else {
            Err(err.into())
        }
    }

    pub fn reference(&self) -> FtResult<()> {
        let err = unsafe { ffi::FT_Reference_Face(self.raw) };
        if err == ffi::FT_Err_Ok {
            Ok(())
        } else {
            Err(err.into())
        }
    }

    pub fn set_char_size(
        &self,
        char_width: isize,
        char_height: isize,
        horz_resolution: u32,
        vert_resolution: u32,
    ) -> FtResult<()> {
        let err = unsafe {
            ffi::FT_Set_Char_Size(
                self.raw,
                char_width as ffi::FT_F26Dot6,
                char_height as ffi::FT_F26Dot6,
                horz_resolution,
                vert_resolution,
            )
        };
        if err == ffi::FT_Err_Ok {
            Ok(())
        } else {
            Err(err.into())
        }
    }

    pub fn set_pixel_sizes(&self, pixel_width: u32, pixel_height: u32) -> FtResult<()> {
        let err = unsafe { ffi::FT_Set_Pixel_Sizes(self.raw, pixel_width, pixel_height) };
        if err == ffi::FT_Err_Ok {
            Ok(())
        } else {
            Err(err.into())
        }
    }

    pub fn load_glyph(&self, glyph_index: u32, load_flags: LoadFlag) -> FtResult<()> {
        let err = unsafe { ffi::FT_Load_Glyph(self.raw, glyph_index, load_flags.bits()) };
        if err == ffi::FT_Err_Ok {
            Ok(())
        } else {
            Err(err.into())
        }
    }

    pub fn load_char(&self, char_code: usize, load_flags: LoadFlag) -> FtResult<()> {
        let err =
            unsafe { ffi::FT_Load_Char(self.raw, char_code as ffi::FT_ULong, load_flags.bits()) };
        if err == ffi::FT_Err_Ok {
            Ok(())
        } else {
            Err(err.into())
        }
    }

    pub fn set_transform(&self, matrix: &mut Matrix, delta: &mut Vector) {
        unsafe {
            ffi::FT_Set_Transform(self.raw, matrix, delta);
        }
    }

    pub fn get_char_index(&self, charcode: usize) -> Option<u32> {
        let res = unsafe { ffi::FT_Get_Char_Index(self.raw, charcode as ffi::FT_ULong) };
        if res == 0 {
            None
        } else {
            Some(res)
        }
    }

    pub fn get_name_index(&self, glyph_name: &str) -> Option<u32> {
        if !ffi::FT_HAS_GLYPH_NAMES(self.raw) {
            return None;
        }

        match CString::new(glyph_name) {
            Ok(name) => {
                Some(unsafe { ffi::FT_Get_Name_Index(self.raw, name.as_ptr() as *const _) })
            }
            Err(_) => None,
        }
    }

    pub fn chars(&self) -> CharIterator<'_, BYTES> {
        CharIterator::new(self)
    }

    pub fn get_kerning(
        &self,
        left_char_index: u32,
        right_char_index: u32,
        kern_mode: KerningMode,
    ) -> FtResult<Vector> {
        let mut vec = Vector { x: 0, y: 0 };

        let err = unsafe {
            ffi::FT_Get_Kerning(
                self.raw,
                left_char_index,
                right_char_index,
                kern_mode as u32,
                &mut vec,
            )
        };
        if err == ffi::FT_Err_Ok {
            Ok(vec)
        } else {
            Err(err.into())
        }
    }

    pub fn get_charmap(&self, charmap_index: isize) -> CharMap {
        let charmap = unsafe { *self.raw().charmaps.offset(charmap_index) };
        CharMap::new(charmap)
    }

    pub fn set_charmap(&self, charmap: &CharMap) -> FtResult<()> {
        let err = unsafe { ffi::FT_Set_Charmap(self.raw, charmap.raw()) };
        if err == ffi::FT_Err_Ok {
            Ok(())
        } else {
            Err(err.into())
        }
    }

    // According to FreeType doc, each time you load a new glyph image,
    // the previous one is erased from the glyph slot.
    #[inline(always)]
    pub fn glyph(&self) -> &GlyphSlot {
        &self.glyph
    }

    #[inline(always)]
    pub fn has_horizontal(&self) -> bool {
        ffi::FT_HAS_HORIZONTAL(self.raw)
    }

    #[inline(always)]
    pub fn has_vertical(&self) -> bool {
        ffi::FT_HAS_VERTICAL(self.raw)
    }

    #[inline(always)]
    pub fn has_kerning(&self) -> bool {
        ffi::FT_HAS_KERNING(self.raw)
    }

    #[inline(always)]
    pub fn is_scalable(&self) -> bool {
        ffi::FT_IS_SCALABLE(self.raw)
    }

    #[inline(always)]
    pub fn is_sfnt(&self) -> bool {
        ffi::FT_IS_SFNT(self.raw)
    }

    #[inline(always)]
    pub fn is_fixed_width(&self) -> bool {
        ffi::FT_IS_FIXED_WIDTH(self.raw)
    }

    #[inline(always)]
    pub fn has_fixed_sizes(&self) -> bool {
        ffi::FT_HAS_FIXED_SIZES(self.raw)
    }

    #[inline(always)]
    pub fn has_glyph_names(&self) -> bool {
        ffi::FT_HAS_GLYPH_NAMES(self.raw)
    }

    #[inline(always)]
    pub fn is_cid_keyed(&self) -> bool {
        ffi::FT_IS_CID_KEYED(self.raw)
    }

    #[inline(always)]
    pub fn is_tricky(&self) -> bool {
        ffi::FT_IS_TRICKY(self.raw)
    }

    #[inline(always)]
    pub fn has_color(&self) -> bool {
        ffi::FT_HAS_COLOR(self.raw)
    }

    #[inline(always)]
    pub fn raw(&self) -> &ffi::FT_FaceRec {
        unsafe { &*self.raw }
    }

    #[inline(always)]
    pub fn raw_mut(&mut self) -> &mut ffi::FT_FaceRec {
        unsafe { &mut *self.raw }
    }

    #[inline(always)]
    pub fn ascender(&self) -> ffi::FT_Short {
        unsafe { (*self.raw).ascender }
    }

    #[inline(always)]
    pub fn num_charmaps(&self) -> i32 {
        unsafe { (*self.raw).num_charmaps }
    }

    #[inline(always)]
    pub fn descender(&self) -> ffi::FT_Short {
        unsafe { (*self.raw).descender }
    }

    #[inline(always)]
    pub fn em_size(&self) -> ffi::FT_Short {
        unsafe { (*self.raw).units_per_EM as i16 }
    }

    #[inline(always)]
    pub fn height(&self) -> ffi::FT_Short {
        unsafe { (*self.raw).height }
    }

    #[inline(always)]
    pub fn max_advance_width(&self) -> ffi::FT_Short {
        unsafe { (*self.raw).max_advance_width }
    }

    #[inline(always)]
    pub fn max_advance_height(&self) -> ffi::FT_Short {
        unsafe { (*self.raw).max_advance_height }
    }

    #[inline(always)]
    pub fn underline_position(&self) -> ffi::FT_Short {
        unsafe { (*self.raw).underline_position }
    }

    #[inline(always)]
    pub fn underline_thickness(&self) -> ffi::FT_Short {
        unsafe { (*self.raw).underline_thickness }
    }

    #[inline(always)]
    pub fn num_faces(&self) -> ffi::FT_Short {
        unsafe { (*self.raw).num_faces as i16 }
    }

    #[inline(always)]
    pub fn num_glyphs(&self) -> ffi::FT_Long {
        unsafe { (*self.raw).num_glyphs }
    }

    pub fn family_name(&self) -> Option<String> {
        let family_name = unsafe { (*self.raw).family_name };

        if family_name.is_null() {
            None
        } else {
            let family_name =
                unsafe { CStr::from_ptr(family_name as *const _).to_bytes().to_vec() };
            String::from_utf8(family_name).ok()
        }
    }

    pub fn style_name(&self) -> Option<String> {
        let style_name = unsafe { (*self.raw).style_name };

        if style_name.is_null() {
            None
        } else {
            let style_name = unsafe { CStr::from_ptr(style_name as *const _).to_bytes().to_vec() };
            String::from_utf8(style_name).ok()
        }
    }

    pub fn style_flags(&self) -> StyleFlag {
        let style_flags = unsafe { (*self.raw).style_flags };
        StyleFlag::from_bits_truncate(style_flags)
    }

    pub fn size_metrics(&self) -> Option<ffi::FT_Size_Metrics> {
        if self.raw.is_null() {
            None
        } else {
            let size = unsafe { (*self.raw).size };
            if size.is_null() {
                None
            } else {
                Some(unsafe { (*size).metrics })
            }
        }
    }

    pub fn postscript_name(&self) -> Option<String> {
        let face_name = unsafe { ffi::FT_Get_Postscript_Name(self.raw) };
        if face_name.is_null() {
            None
        } else {
            let face_name = unsafe { CStr::from_ptr(face_name as *const _).to_bytes().to_vec() };
            String::from_utf8(face_name).ok()
        }
    }
}

impl<BYTES> fmt::Debug for Face<BYTES> {
    fn fmt(&self, form: &mut fmt::Formatter) -> fmt::Result {
        let name = self.style_name().unwrap_or("[unknown name]".to_owned());
        form.write_str("Font Face: ")?;
        form.write_str(&name[..])
    }
}

impl<BYTES> Drop for Face<BYTES> {
    fn drop(&mut self) {
        let err = unsafe { ffi::FT_Done_Face(self.raw) };
        if err != ffi::FT_Err_Ok {
            panic!("Failed to drop face");
        }
        let err = unsafe { ffi::FT_Done_Library(self.library_raw) };
        if err != ffi::FT_Err_Ok {
            panic!("Failed to drop library")
        }
        self.bytes = None;
    }
}