Skip to main content

tectonic_bridge_freetype2/
lib.rs

1// Copyright 2020 the Tectonic Project
2// Licensed under the MIT License.
3
4//! This crate exists to export the `FreeType2` *C* API into the Cargo framework, as well as provide
5//! bindings to other tectonic crates.
6
7#![deny(clippy::undocumented_unsafe_blocks)]
8#![allow(clippy::unnecessary_cast)]
9
10use std::ffi::CStr;
11use std::marker::PhantomData;
12use std::num::NonZeroU32;
13use std::ops::BitOr;
14use std::ptr::NonNull;
15use std::sync::{Mutex, OnceLock};
16use std::{ptr, slice};
17
18mod sys;
19
20/// Import things from our bridge crates to ensure that we actually link with
21/// them.
22mod linkage {
23    #[allow(unused_imports)]
24    use tectonic_bridge_flate as clippyrenamehack1;
25    #[allow(unused_imports)]
26    use tectonic_bridge_png as clippyrenamehack2;
27}
28
29pub use sys::FT_BBox as BBox;
30pub use sys::FT_Fixed as Fixed;
31pub use sys::FT_Glyph_BBox_Mode as BBoxMode;
32pub use sys::FT_Glyph_Format as GlyphFormat;
33pub use sys::FT_Glyph_Metrics as GlyphMetrics;
34pub use sys::FT_Kerning_Mode as KerningMode;
35pub use sys::FT_Outline as Outline;
36pub use sys::FT_Sfnt_Tag as SfntTag;
37pub use sys::FT_Vector as Vector;
38
39/// Recognized tables that can be safely loaded by Rust code
40pub mod tables {
41    pub use crate::sys::TT_Header as Header;
42    pub use crate::sys::TT_Postscript as Postscript;
43    pub use crate::sys::TT_OS2 as Os2;
44}
45
46pub(crate) struct SyncPtr<T>(*mut T);
47
48// SAFETY: It is on the user of `SyncPtr` to only use the pointer in a Send-safe way
49unsafe impl<T> Send for SyncPtr<T> {}
50// SAFETY: It is on the user of `SyncPtr` to only use the pointer in a Sync-safe way
51unsafe impl<T> Sync for SyncPtr<T> {}
52
53// FT_Library can be used from many threads as long as a Mutex protects FT_New_Face and FT_Done_Face
54// - https://sourceforge.net/projects/freetype/files/freetype2/2.6/
55static FREE_TYPE_LIBRARY: OnceLock<SyncPtr<sys::FT_LibraryRec>> = OnceLock::new();
56static FACE_MUTEX: Mutex<()> = Mutex::new(());
57
58fn ft_lib() -> sys::FT_Library {
59    FREE_TYPE_LIBRARY
60        .get_or_init(|| {
61            let mut lib = ptr::null_mut();
62            // SAFETY: FreeType initialization is always sound
63            let error = unsafe { sys::FT_Init_FreeType(&mut lib) };
64            if error != 0 {
65                panic!("FreeType initialization failed, error {error}");
66            }
67            SyncPtr(lib)
68        })
69        .0
70}
71
72/// Initialize FreeType. This function will panic if initialization fails.
73pub fn init() {
74    ft_lib();
75}
76
77/// A tag representing a specific table to load.
78#[derive(Copy, Clone, Debug)]
79pub enum TableTag {
80    /// A well-known table type
81    Sfnt(SfntTag),
82    /// A custom table type not natively recognized by freetype
83    Other(u32),
84}
85
86impl TableTag {
87    fn as_u32(self) -> u32 {
88        match self {
89            TableTag::Sfnt(tag) => tag as u32,
90            TableTag::Other(other) => other,
91        }
92    }
93}
94
95/// Glyph loading flags, to control whether some steps are performed, or change loading modes
96/// (such as horizontal or vertical text).
97#[derive(Copy, Clone, Debug)]
98pub struct LoadFlags(i32);
99
100impl LoadFlags {
101    /// Default loading behavior.
102    pub const DEFAULT: LoadFlags = LoadFlags(0);
103    /// Don't scale the loaded glyph, keep it in font units.
104    pub const NO_SCALE: LoadFlags = LoadFlags(sys::FT_LOAD_NO_SCALE);
105    /// Load the glyph for a vertical text layout.
106    pub const VERTICAL_LAYOUT: LoadFlags = LoadFlags(sys::FT_LOAD_VERTICAL_LAYOUT);
107
108    fn as_i32(self) -> i32 {
109        self.0
110    }
111}
112
113impl BitOr for LoadFlags {
114    type Output = LoadFlags;
115
116    fn bitor(self, rhs: Self) -> Self::Output {
117        LoadFlags(self.0 | rhs.0)
118    }
119}
120
121/// A TrueType platform ID
122#[derive(Copy, Clone, Debug, PartialEq)]
123pub struct PlatformId(u16);
124
125impl PlatformId {
126    /// Apple unicode character map
127    pub const APPLE_UNICODE: PlatformId = PlatformId(sys::TT_PLATFORM_APPLE_UNICODE as u16);
128    /// Apple MacOS-specific character map
129    pub const MACINTOSH: PlatformId = PlatformId(sys::TT_PLATFORM_MACINTOSH as u16);
130    /// Windows-specific character map
131    pub const MICROSOFT: PlatformId = PlatformId(sys::TT_PLATFORM_MICROSOFT as u16);
132}
133
134/// A TrueType encoding ID
135#[derive(Copy, Clone, Debug, PartialEq)]
136pub struct EncodingId(u16);
137
138impl EncodingId {
139    /// MacOS-specific roman encoding.
140    pub const MAC_ROMAN: EncodingId = EncodingId(sys::TT_MAC_ID_ROMAN as u16);
141    /// Windows-specific unicode encoding.
142    pub const WIN_UNICODE: EncodingId = EncodingId(sys::TT_MS_ID_UNICODE_CS as u16);
143}
144
145/// A TrueType language ID
146#[derive(Copy, Clone, Debug, PartialEq)]
147pub struct LanguageId(u16);
148
149impl LanguageId {
150    /// MacOS-specific english language
151    pub const MAC_ENGLISH: LanguageId = LanguageId(sys::TT_MAC_LANGID_ENGLISH as u16);
152
153    /// Windows-specific US english language
154    pub const WIN_ENGLISH_US: LanguageId =
155        LanguageId(sys::TT_MS_LANGID_ENGLISH_UNITED_STATES as u16);
156}
157
158/// An error code returned by freetype.
159#[derive(Debug)]
160pub struct Error(sys::FT_Error);
161
162impl Error {
163    fn or_else<T>(err: sys::FT_Error, f: impl FnOnce() -> T) -> Result<T, Error> {
164        if err == 0 {
165            Ok(f())
166        } else {
167            Err(Error(err))
168        }
169    }
170
171    /// Convert this error into a descriptive message, if available.
172    ///
173    /// Error strings may not be available if freetype was compiled without certain options. In
174    /// such a situation, this method will always return `None`.
175    pub fn message(&self) -> Option<&'static str> {
176        // SAFETY: This is always safe to call
177        let str = unsafe { sys::FT_Error_String(self.0) };
178        if str.is_null() {
179            None
180        } else {
181            // SAFETY: If non-null, the pointer returned by FT_Error_String is a valid C-string
182            let str = unsafe { CStr::from_ptr(str) };
183            str::from_utf8(str.to_bytes()).ok()
184        }
185    }
186
187    /// The numeric code of this error.
188    ///
189    /// **Warning:** These codes can, and do, change between freetype versions.
190    pub fn code(&self) -> sys::FT_Error {
191        self.0
192    }
193}
194
195/// A font name table value
196#[derive(Debug)]
197#[non_exhaustive]
198pub struct SfntName<'a> {
199    /// The platform for this font
200    pub platform_id: PlatformId,
201    /// The encoding for this font
202    pub encoding_id: EncodingId,
203    /// The language for this font
204    pub language_id: LanguageId,
205    /// The type of name this is
206    pub name_id: u16,
207    /// The name string. May be UTF-16 BE, or any string of bytes
208    pub string: &'a [u8],
209}
210
211impl From<sys::FT_SfntName> for SfntName<'_> {
212    fn from(value: sys::FT_SfntName) -> Self {
213        SfntName {
214            platform_id: PlatformId(value.platform_id as u16),
215            encoding_id: EncodingId(value.encoding_id as u16),
216            language_id: LanguageId(value.language_id as u16),
217            name_id: value.name_id as u16,
218            string: if !value.string.is_null() {
219                // SAFETY: If non-null, the value in `string` is guaranteed to be allocated and
220                //         initialized to a length of `string_len`.
221                unsafe { slice::from_raw_parts(value.string, value.string_len as usize) }
222            } else {
223                &[]
224            },
225        }
226    }
227}
228
229/// A generic glyph image.
230pub struct Glyph(NonNull<sys::FT_GlyphRec>);
231
232impl Glyph {
233    /// Get a glyph's 'control box'. This is faster to calculate than a proper bounding box,
234    /// but may over-estimate in some cases.
235    pub fn get_cbox(&self, mode: BBoxMode) -> BBox {
236        let mut ft_bbox = BBox::default();
237        // SAFETY: Our internal pointer is guaranteed valid
238        unsafe { sys::FT_Glyph_Get_CBox(self.0.as_ptr(), mode, &mut ft_bbox) };
239        ft_bbox
240    }
241}
242
243impl Drop for Glyph {
244    fn drop(&mut self) {
245        // SAFETY: Our internal pointer is guaranteed valid, we own the pointer
246        unsafe { sys::FT_Done_Glyph(self.0.as_ptr()) }
247    }
248}
249
250/// A glyph loaded into a faces glyph slot.
251pub struct GlyphSlot<'a>(
252    NonNull<sys::FT_GlyphSlotRec>,
253    PhantomData<&'a sys::FT_GlyphSlotRec>,
254);
255
256impl GlyphSlot<'_> {
257    fn as_ref(&self) -> &sys::FT_GlyphSlotRec {
258        // SAFETY: Internal pointer is guaranteed valid
259        //         GlyphSlot is !Send+!Sync, so no C code can violate this reference.
260        unsafe { self.0.as_ref() }
261    }
262
263    /// Create a glyph image from this slot.
264    pub fn get_glyph(&self) -> Result<Glyph, Error> {
265        let mut ptr = ptr::null_mut();
266        // SAFETY: Internal pointer is guaranteed valid.
267        let err = unsafe { sys::FT_Get_Glyph(self.0.as_ptr(), &mut ptr) };
268        Error::or_else(err, || Glyph(NonNull::new(ptr).unwrap()))
269    }
270
271    /// Metrics of the currently loaded glyph.
272    pub fn metrics(&self) -> &GlyphMetrics {
273        &self.as_ref().metrics
274    }
275
276    /// The format of the currently loaded glyph.
277    pub fn format(&self) -> GlyphFormat {
278        self.as_ref().format
279    }
280
281    /// If the current format is an outline, the outline descriptor for it.
282    pub fn outline(&self) -> Option<&Outline> {
283        if self.format() == GlyphFormat::Outline {
284            Some(&self.as_ref().outline)
285        } else {
286            None
287        }
288    }
289}
290
291/// Trait for types that represent different sfnt tables you can read from a [`Face`].
292///
293/// # Safety
294///
295/// Code may assume that the [`SfntTag`] returned by `tag` is valid to read as an instance of `Self`.
296pub unsafe trait Table {
297    /// The [`SfntTag`] that matches this table
298    fn tag() -> SfntTag;
299}
300
301// SAFETY: SfntTag::Os2 == tables::OS2
302unsafe impl Table for tables::Os2 {
303    fn tag() -> SfntTag {
304        SfntTag::Os2
305    }
306}
307
308// SAFETY: SfntTag::Head == tables::Header
309unsafe impl Table for tables::Header {
310    fn tag() -> SfntTag {
311        SfntTag::Head
312    }
313}
314
315// SAFETY: SfntTag::Post == tables::Postscript
316unsafe impl Table for tables::Postscript {
317    fn tag() -> SfntTag {
318        SfntTag::Post
319    }
320}
321
322/// A typographic face - the combination of a general typeface and a style.
323pub struct Face(NonNull<sys::FT_FaceRec>, Vec<Vec<u8>>);
324
325impl Face {
326    /// Create a new [`Face`] object from the font file at a given path, plus the index of the
327    /// face within the file (as single files may contain the data for multiple styles).
328    pub fn new(path: &CStr, index: usize) -> Result<Face, Error> {
329        let _l = FACE_MUTEX.lock();
330        let mut raw_face = ptr::null_mut();
331        // SAFETY: We hold the FACE_MUTEX lock, so calls to FT_New_Face are guaranteed safe
332        //         with our global library instance.
333        let err = unsafe {
334            sys::FT_New_Face(
335                ft_lib(),
336                path.as_ptr(),
337                index as libc::c_long,
338                &mut raw_face,
339            )
340        };
341        drop(_l);
342        Error::or_else(err, || Face(NonNull::new(raw_face).unwrap(), Vec::new()))
343    }
344
345    /// Create a new [`Face`] object from an in-memory buffer containing font file data. The index
346    /// selects which face to load for data with multiple faces.
347    pub fn new_memory(mut data: Vec<u8>, index: usize) -> Result<Face, Error> {
348        let _l = FACE_MUTEX.lock();
349        let mut raw_face = ptr::null_mut();
350        // SAFETY: We hold the FACE_MUTEX lock, so calls to FT_New_Memory_Face are guaranteed safe
351        //         with our global library instance.
352        let err = unsafe {
353            sys::FT_New_Memory_Face(
354                ft_lib(),
355                data.as_mut_ptr().cast(),
356                data.len() as libc::c_long,
357                index as libc::c_long,
358                &mut raw_face,
359            )
360        };
361        drop(_l);
362        Error::or_else(err, || Face(NonNull::new(raw_face).unwrap(), vec![data]))
363    }
364
365    fn inner(&self) -> &sys::FT_FaceRec {
366        // SAFETY: Internal pointer is guaranteed valid
367        //         Faces are !Send+!Sync - as such, we know no C code will violate this reference
368        unsafe { self.0.as_ref() }
369    }
370
371    /// Check whether this face is scalable
372    pub fn is_scalable(&self) -> bool {
373        self.inner().face_flags & sys::FT_FACE_FLAG_SCALABLE != 0
374    }
375
376    /// Check whether this face is using the SFNT storage scheme
377    pub fn is_sfnt(&self) -> bool {
378        self.inner().face_flags & sys::FT_FACE_FLAG_SFNT != 0
379    }
380
381    /// Check whether this face has glyph names
382    pub fn has_glyph_names(&self) -> bool {
383        self.inner().face_flags & sys::FT_FACE_FLAG_GLYPH_NAMES != 0
384    }
385
386    /// The the units per EM square for this face. Only relevant for scalable fonts.
387    pub fn units_per_em(&self) -> u16 {
388        self.inner().units_per_EM as u16
389    }
390
391    /// The typographic ascender for this face. Only relevant for scalable fonts.
392    pub fn ascender(&self) -> i16 {
393        self.inner().ascender as i16
394    }
395
396    /// The typographic descender for this face. Only relevant for scalable fonts.
397    pub fn descender(&self) -> i16 {
398        self.inner().descender as i16
399    }
400
401    /// The number of glyphs in this face
402    pub fn num_glyphs(&self) -> usize {
403        self.inner().num_glyphs as usize
404    }
405
406    /// The number of faces in the backing font file
407    pub fn num_faces(&self) -> usize {
408        self.inner().num_faces as usize
409    }
410
411    fn glyph(&self) -> GlyphSlot<'_> {
412        GlyphSlot(NonNull::new(self.inner().glyph).unwrap(), PhantomData)
413    }
414
415    /// Get the advance for the given glyph in this font. If [`LoadFlags::VERTICAL_LAYOUT`] is set,
416    /// then the return value is the vertical advance, otherwise it is the horizontal advance.
417    pub fn get_advance(&self, index: u32, flags: LoadFlags) -> Result<i64, Error> {
418        let mut advance = 0;
419        // SAFETY: Out internal pointer is guaranteed valid
420        let err = unsafe {
421            sys::FT_Get_Advance(
422                self.0.as_ptr(),
423                index as libc::c_uint,
424                flags.as_i32(),
425                &mut advance,
426            )
427        };
428        Error::or_else(err, || advance as i64)
429    }
430
431    /// Returns the first character code in the charmap of this face, along with its glyph index.
432    pub fn get_first_char(&self) -> (u32, u32) {
433        let mut index = 0;
434        // SAFETY: Our internal pointer is guaranteed valid
435        let code = unsafe { sys::FT_Get_First_Char(self.0.as_ptr(), &mut index) };
436        (code as u32, index as u32)
437    }
438
439    /// Given a character code, return the next character code and glyph index in this face's
440    /// charmap.
441    pub fn get_next_char(&self, char: u32) -> (u32, u32) {
442        let mut index = 0;
443        // SAFETY: Our internal pointer is guaranteed valid
444        let code =
445            unsafe { sys::FT_Get_Next_Char(self.0.as_ptr(), char as libc::c_ulong, &mut index) };
446        (code as u32, index as u32)
447    }
448
449    /// Given a character code, get the glyph index for it, if present.
450    pub fn get_char_index(&self, char: u32) -> Option<NonZeroU32> {
451        // SAFETY: Our internal pointer is guaranteed valid
452        NonZeroU32::new(unsafe { sys::FT_Get_Char_Index(self.0.as_ptr(), char as libc::c_ulong) })
453    }
454
455    /// Given a character code and a Unicode variant selector, get the glyph index for it, if
456    /// present.
457    pub fn get_char_variant_index(&self, char: u32, variant: u32) -> Option<NonZeroU32> {
458        // SAFETY: Our internal pointer is guaranteed valid
459        NonZeroU32::new(unsafe {
460            sys::FT_Face_GetCharVariantIndex(
461                self.0.as_ptr(),
462                char as libc::c_ulong,
463                variant as libc::c_ulong,
464            )
465        })
466    }
467
468    /// For a given glyph index, get the kerning vector between them. This only works for 'simple'
469    /// kerning, for things such as vertical layouts or complicated GPOS layouts, something
470    /// such as Harfbuzz is needed.
471    pub fn get_kerning(&self, left: u32, right: u32, mode: KerningMode) -> Result<Vector, Error> {
472        let mut vector = Vector::default();
473        // SAFETY: Our internal pointer is guaranteed valid
474        let err = unsafe { sys::FT_Get_Kerning(self.0.as_ptr(), left, right, mode, &mut vector) };
475        Error::or_else(err, || vector)
476    }
477
478    /// If this font supports glyph names, get the name for the given glyph index.
479    ///
480    /// This is the inverse of [`Self::get_name_index`].
481    pub fn get_glyph_name<'a>(&self, index: u32, buf: &'a mut [u8]) -> Result<&'a CStr, Error> {
482        // SAFETY: Our internal pointer is guaranteed valid
483        let err = unsafe {
484            sys::FT_Get_Glyph_Name(
485                self.0.as_ptr(),
486                index as libc::c_uint,
487                buf.as_mut_ptr().cast(),
488                buf.len() as libc::c_uint,
489            )
490        };
491        Error::or_else(err, move || CStr::from_bytes_until_nul(buf).unwrap())
492    }
493
494    /// If this font supports glyph names, get the index of a given glyph name.
495    ///
496    /// This is the inverse of [`Self::get_glyph_name`].
497    pub fn get_name_index(&self, name: &CStr) -> Option<NonZeroU32> {
498        // SAFETY: Our internal pointer is guaranteed valid, name is valid for the length of this
499        //         method call and not retained.
500        NonZeroU32::new(unsafe { sys::FT_Get_Name_Index(self.0.as_ptr(), name.as_ptr()) as u32 })
501    }
502
503    /// Get the postscript name for this font, if one is available
504    pub fn get_postscript_name(&self) -> Option<&CStr> {
505        // SAFETY: Our internal pointer is guaranteed valid
506        let ptr = unsafe { sys::FT_Get_Postscript_Name(self.0.as_ptr()) };
507        if ptr.is_null() {
508            None
509        } else {
510            // SAFETY: If a non-null pointer was returned, it is guaranteed to contain a
511            //         nul-terminated C-string
512            Some(unsafe { CStr::from_ptr(ptr) })
513        }
514    }
515
516    /// Get the number of items in the name table for this face
517    pub fn get_sfnt_name_count(&self) -> u32 {
518        // SAFETY: Our internal pointer is guaranteed valid
519        unsafe { sys::FT_Get_Sfnt_Name_Count(self.0.as_ptr()) as u32 }
520    }
521
522    /// Get the item in the name table at the given index for this face
523    pub fn get_sfnt_name(&self, idx: u32) -> Result<SfntName<'_>, Error> {
524        let mut name = sys::FT_SfntName::default();
525        // SAFETY: Our internal pointer is guaranteed valid. The returned name is valid until self
526        //         is dropped.
527        let err = unsafe { sys::FT_Get_Sfnt_Name(self.0.as_ptr(), idx as libc::c_uint, &mut name) };
528        Error::or_else(err, || SfntName::from(name))
529    }
530
531    /// Load and return a reference to a glyph in this font. See [`LoadFlags`] for details on how
532    /// different flags affect the loaded glyph.
533    pub fn load_glyph(&mut self, index: u32, flags: LoadFlags) -> Result<GlyphSlot<'_>, Error> {
534        // SAFETY: Our internal pointer is guaranteed valid
535        let err =
536            unsafe { sys::FT_Load_Glyph(self.0.as_ptr(), index as libc::c_uint, flags.as_i32()) };
537        match Error::or_else(err, || ()) {
538            Ok(_) => Ok(self.glyph()),
539            Err(e) => Err(e),
540        }
541    }
542
543    /// Get a pointer to the table represented by [`SfntTag`]. This pointer is only valid for the
544    /// lifetime of this Face, and may be mutated by mutable calls to self.
545    pub fn get_sfnt_table_dyn(&self, tag: SfntTag) -> Option<NonNull<()>> {
546        // SAFETY: Our internal pointer is guaranteed valid
547        NonNull::new(unsafe { sys::FT_Get_Sfnt_Table(self.0.as_ptr(), tag) })
548    }
549
550    /// Get a reference to a loaded TrueType table. This may return `None` if the table doesn't
551    /// exist in the loaded font, or wasn't loaded.
552    pub fn get_sfnt_table<T: Table>(&self) -> Option<&T> {
553        // SAFETY: Our internal pointer is guaranteed valid
554        let ptr = unsafe { sys::FT_Get_Sfnt_Table(self.0.as_ptr(), T::tag()) };
555        // SAFETY: Per the guarantees of `Table`, the pointer returned by FT_Get_Sfnt_Table is a
556        //         valid `T` if non-null.
557        unsafe { ptr.cast::<T>().as_ref() }
558    }
559
560    /// Load a font table into an owned buffer.
561    ///
562    /// [`SfntTag::Head`] will, instead of loading the header, actually return the entire font file.
563    pub fn load_sfnt_table(&self, tag: TableTag) -> Result<Vec<u8>, Error> {
564        let mut len = 0;
565        // SAFETY: Our internal pointer is guaranteed valid
566        let err = unsafe {
567            sys::FT_Load_Sfnt_Table(
568                self.0.as_ptr(),
569                tag.as_u32() as libc::c_ulong,
570                0,
571                ptr::null_mut(),
572                &mut len,
573            )
574        };
575        Error::or_else(err, || ())?;
576
577        let mut buf = vec![0u8; len as usize];
578
579        // SAFETY: Our internal pointer is guaranteed valid. We know from previously calling the
580        //         method with the same tag that buffer is of sufficient length to hold the returned
581        //         table.
582        let err = unsafe {
583            sys::FT_Load_Sfnt_Table(
584                self.0.as_ptr(),
585                tag.as_u32() as libc::c_ulong,
586                0,
587                buf.as_mut_ptr().cast(),
588                &mut len,
589            )
590        };
591
592        Error::or_else(err, || buf)
593    }
594
595    /// Attach a custom byte stream to this face as extra data. This stream will be freed when this
596    /// face is dropped.
597    pub fn attach_stream_mem(&mut self, mut stream: Vec<u8>) -> Result<(), Error> {
598        let mut oa = sys::FT_Open_Args::default();
599        oa.flags |= sys::FT_OPEN_MEMORY;
600        oa.memory_base = stream.as_mut_ptr().cast();
601        oa.memory_size = stream.len() as libc::c_long;
602        self.1.push(stream);
603        // SAFETY: Our internal pointer is guaranteed valid
604        //         We ensure above that the attached stream will not be dropped until after
605        //         FT_Done_Face is called.
606        let err = unsafe { sys::FT_Attach_Stream(self.0.as_ptr(), &mut oa) };
607        Error::or_else(err, || ())
608    }
609}
610
611impl Drop for Face {
612    fn drop(&mut self) {
613        let _l = FACE_MUTEX.lock();
614        // SAFETY: We hold the FACE_MUTEX lock, so calls to FT_Done_Face are guaranteed safe
615        //         with our global library instance.
616        //         Our pointer is owned and guaranteed valid.
617        unsafe { sys::FT_Done_Face(self.0.as_ptr()) };
618        drop(_l);
619    }
620}
621
622// SAFETY: Functions that are not safe to share across threads (such as FT_Done_Face) are protected
623//         by mutex to ensure they are only called once per thread.
624unsafe impl Send for Face {}
625// SAFETY: Functions that are not safe to share across threads (such as FT_Done_Face) are protected
626//         by mutex to ensure they are only called once per thread.
627unsafe impl Sync for Face {}
628
629#[cfg(test)]
630mod tests {
631    use super::*;
632    use std::ffi::CString;
633    use std::fs;
634    use std::path::{Path, PathBuf};
635
636    fn assets_dir() -> PathBuf {
637        Path::new(env!("CARGO_MANIFEST_DIR"))
638            .join("../../tests/assets")
639            .canonicalize()
640            .unwrap()
641    }
642
643    fn get_face_data() -> Vec<u8> {
644        let roman = assets_dir().join("lmroman12-regular.otf");
645        fs::read(roman).unwrap()
646    }
647
648    fn get_face_file() -> Face {
649        let roman = assets_dir().join("lmroman12-regular.otf");
650        let roman_path = CString::new(roman.to_str().unwrap()).unwrap();
651
652        Face::new(&roman_path, 0).unwrap()
653    }
654
655    fn get_face_mem() -> Face {
656        let roman_data = get_face_data();
657
658        Face::new_memory(roman_data, 0).unwrap()
659    }
660
661    fn test_faces() -> Vec<Face> {
662        vec![get_face_file(), get_face_mem()]
663    }
664
665    #[test]
666    fn test_invalid_face() {
667        assert!(Face::new(c"/bad/path", 0).is_err());
668        assert!(Face::new_memory(vec![], 0).is_err());
669    }
670
671    #[test]
672    fn test_properties() {
673        for face in test_faces() {
674            assert!(face.is_scalable());
675            assert!(face.is_sfnt());
676            assert!(face.has_glyph_names());
677            assert_eq!(face.units_per_em(), 1000);
678            assert_eq!(face.ascender(), 1127);
679            assert_eq!(face.descender(), -280);
680            assert_eq!(face.num_glyphs(), 821);
681            assert_eq!(face.num_faces(), 1);
682        }
683    }
684
685    #[test]
686    fn test_roman_name() {
687        for face in test_faces() {
688            assert_eq!(face.get_sfnt_name_count(), 21);
689
690            let mac_name = face.get_sfnt_name(1).unwrap();
691
692            let name_16 = "Latin Modern Roman"
693                .encode_utf16()
694                .flat_map(|val| val.to_be_bytes())
695                .collect::<Vec<u8>>();
696
697            assert_eq!(mac_name.platform_id, PlatformId::MACINTOSH);
698            assert_eq!(mac_name.encoding_id, EncodingId::MAC_ROMAN);
699            assert_eq!(mac_name.language_id, LanguageId::MAC_ENGLISH);
700            assert_eq!(mac_name.string, b"Latin Modern Roman");
701
702            let win_name = face.get_sfnt_name(18).unwrap();
703            assert_eq!(win_name.platform_id, PlatformId::MICROSOFT);
704            assert_eq!(win_name.encoding_id, EncodingId::WIN_UNICODE);
705            assert_eq!(win_name.language_id, LanguageId::WIN_ENGLISH_US);
706            assert_eq!(win_name.string, &name_16);
707        }
708    }
709
710    #[test]
711    fn test_postscript_name() {
712        for face in test_faces() {
713            let name = face.get_postscript_name().unwrap();
714            assert_eq!(name.to_bytes(), b"LMRoman12-Regular");
715        }
716    }
717
718    #[test]
719    fn test_get_tables() {
720        for face in test_faces() {
721            let dyn_table = face.get_sfnt_table_dyn(SfntTag::Head).unwrap();
722            let table = face.get_sfnt_table::<tables::Header>().unwrap();
723
724            assert!(ptr::eq(table, dyn_table.as_ptr().cast_const().cast()));
725            assert_eq!(table.Units_Per_Em, face.units_per_em());
726
727            let dyn_table = face.get_sfnt_table_dyn(SfntTag::Os2).unwrap();
728            let table = face.get_sfnt_table::<tables::Os2>().unwrap();
729            assert!(ptr::eq(table, dyn_table.as_ptr().cast_const().cast()));
730
731            let dyn_table = face.get_sfnt_table_dyn(SfntTag::Post).unwrap();
732            let table = face.get_sfnt_table::<tables::Postscript>().unwrap();
733            assert!(ptr::eq(table, dyn_table.as_ptr().cast_const().cast()));
734        }
735    }
736
737    #[test]
738    fn test_load_tables() {
739        let data = get_face_data();
740        for face in test_faces() {
741            assert_eq!(
742                data,
743                face.load_sfnt_table(TableTag::Sfnt(SfntTag::Head)).unwrap()
744            );
745            face.load_sfnt_table(TableTag::Other(u32::MAX)).unwrap_err();
746        }
747    }
748
749    #[test]
750    fn test_get_char_index() {
751        for face in test_faces() {
752            face.get_char_index('!' as u32).unwrap();
753            assert!(face.get_char_index('∀' as u32).is_none());
754        }
755    }
756
757    #[test]
758    fn test_attach_stream() {
759        for mut face in test_faces() {
760            face.attach_stream_mem(b"Hello World!".to_vec())
761                .unwrap_err();
762        }
763    }
764
765    #[test]
766    fn test_bad_glyph() {
767        const BAD_IDX: u32 = 10000;
768        for mut face in test_faces() {
769            assert!(face.get_name_index(c"bad_name").is_none());
770            face.get_advance(BAD_IDX, LoadFlags::DEFAULT).unwrap_err();
771            face.get_glyph_name(BAD_IDX, &mut []).unwrap_err();
772            assert!(face.load_glyph(BAD_IDX, LoadFlags::DEFAULT).is_err());
773        }
774    }
775
776    #[test]
777    fn test_first_glyph() {
778        let mut buf = vec![0; 32];
779
780        for face in test_faces() {
781            let (c, idx) = face.get_first_char();
782            assert_eq!(c, ' ' as u32);
783
784            let advance = face.get_advance(idx, LoadFlags::NO_SCALE).unwrap();
785            assert_eq!(advance, 326);
786            assert_eq!(face.get_glyph_name(idx, &mut buf).unwrap(), c"space");
787            assert_eq!(face.get_char_index(' ' as u32).unwrap().get(), idx);
788            assert_eq!(face.get_name_index(c"space").unwrap().get(), idx);
789
790            let (c2, _) = face.get_next_char(c);
791            assert_eq!(c2, '!' as u32);
792
793            // No variant selectors in this font
794            assert_eq!(face.get_char_variant_index(c, 0xFE00), None);
795        }
796    }
797
798    #[test]
799    fn test_kerning() {
800        for face in test_faces() {
801            let exc_idx = face.get_char_index('!' as u32).unwrap().get();
802            let at_idx = face.get_char_index('@' as u32).unwrap().get();
803
804            let kern = face
805                .get_kerning(exc_idx, at_idx, KerningMode::Default)
806                .unwrap();
807            // TODO: Find pair of characters with non-zero kerning
808            assert_eq!(kern, Vector { x: 0, y: 0 });
809        }
810    }
811
812    #[test]
813    fn test_glyph_load() {
814        for mut face in test_faces() {
815            let idx = face.get_char_index(b'@' as u32).unwrap().get();
816
817            let slot = face.load_glyph(idx, LoadFlags::NO_SCALE).unwrap();
818
819            assert_eq!(slot.format(), GlyphFormat::Outline);
820            assert_eq!(slot.metrics().height, 714);
821            assert_eq!(slot.metrics().width, 653);
822
823            let outline = slot.outline().unwrap();
824            assert_eq!(outline.points().len(), 82);
825            assert_eq!(outline.contours().len(), 2);
826
827            let glyph = slot.get_glyph().unwrap();
828
829            assert_eq!(
830                glyph.get_cbox(BBoxMode::Unscaled),
831                BBox {
832                    x_min: 54,
833                    x_max: 707,
834                    y_min: -10,
835                    y_max: 704
836                }
837            );
838        }
839    }
840}