summaryrefslogtreecommitdiff
path: root/src/font.rs
blob: c37c913ee4a8a56dc91559ad4a0d05c0a6185b6f (plain) (blame)
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
//! Font handling.

use std::cell::RefCell;
use std::ops::Deref;
use std::rc::Rc;

use fontdock::{ContainsChar, FaceFromVec, FontLoader, FontProvider};
use ttf_parser::Face;

/// A referenced-count shared font loader backed by a dynamic provider.
pub type SharedFontLoader = Rc<RefCell<FontLoader<Box<DynProvider>>>>;

/// The dynamic font provider type backing the font loader.
pub type DynProvider = dyn FontProvider<Face = OwnedFace>;

/// An owned font face.
pub struct OwnedFace {
    data: Vec<u8>,
    face: Face<'static>,
}

impl OwnedFace {
    /// The raw face data.
    pub fn data(&self) -> &[u8] {
        &self.data
    }
}

impl FaceFromVec for OwnedFace {
    fn from_vec(vec: Vec<u8>, i: u32) -> Option<Self> {
        // The vec's location is stable in memory since we don't touch it and
        // it can't be touched from outside this type.
        let slice: &'static [u8] = unsafe {
            std::slice::from_raw_parts(vec.as_ptr(), vec.len())
        };

        Some(Self {
            data: vec,
            face: Face::from_slice(slice, i).ok()?,
        })
    }
}

impl ContainsChar for OwnedFace {
    fn contains_char(&self, c: char) -> bool {
        self.glyph_index(c).is_some()
    }
}

impl Deref for OwnedFace {
    type Target = Face<'static>;

    fn deref(&self) -> &Self::Target {
        &self.face
    }
}