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 crate::interop;
use crate::interop::DynamicMemoryWStream;
use crate::prelude::*;
use crate::{FontStyle, Typeface, Unichar};
use skia_bindings as sb;
use skia_bindings::{SkFontMgr, SkFontStyleSet, SkRefCntBase};
use std::ffi::CString;
use std::mem;
use std::os::raw::c_char;

pub type FontStyleSet = RCHandle<SkFontStyleSet>;

impl NativeRefCountedBase for SkFontStyleSet {
    type Base = SkRefCntBase;

    fn ref_counted_base(&self) -> &Self::Base {
        &self._base._base
    }
}

impl Default for RCHandle<SkFontStyleSet> {
    fn default() -> Self {
        FontStyleSet::new_empty()
    }
}

impl RCHandle<SkFontStyleSet> {
    pub fn count(&mut self) -> usize {
        unsafe {
            sb::C_SkFontStyleSet_count(self.native_mut())
                .try_into()
                .unwrap()
        }
    }

    pub fn style(&mut self, index: usize) -> (FontStyle, Option<String>) {
        assert!(index < self.count());

        let mut font_style = FontStyle::default();
        let mut style = interop::String::default();
        unsafe {
            sb::C_SkFontStyleSet_getStyle(
                self.native_mut(),
                index.try_into().unwrap(),
                font_style.native_mut(),
                style.native_mut(),
            )
        }

        // Note: Android's FontMgr returns empty style names.
        let name = style
            .as_str()
            .is_empty()
            .if_false_then_some(|| style.as_str().into());

        (font_style, name)
    }

    pub fn new_typeface(&mut self, index: usize) -> Option<Typeface> {
        assert!(index < self.count());

        Typeface::from_ptr(unsafe {
            sb::C_SkFontStyleSet_createTypeface(self.native_mut(), index.try_into().unwrap())
        })
    }

    pub fn match_style(&mut self, index: usize, pattern: FontStyle) -> Option<Typeface> {
        assert!(index < self.count());
        Typeface::from_ptr(unsafe {
            sb::C_SkFontStyleSet_matchStyle(self.native_mut(), pattern.native())
        })
    }

    pub fn new_empty() -> Self {
        FontStyleSet::from_ptr(unsafe { SkFontStyleSet::CreateEmpty() }).unwrap()
    }
}

pub type FontMgr = RCHandle<SkFontMgr>;

impl NativeRefCountedBase for SkFontMgr {
    type Base = SkRefCntBase;

    fn ref_counted_base(&self) -> &Self::Base {
        &self._base._base
    }
}

impl Default for RCHandle<SkFontMgr> {
    fn default() -> Self {
        Self::new()
    }
}

impl RCHandle<SkFontMgr> {
    pub fn new() -> Self {
        FontMgr::from_ptr(unsafe { sb::C_SkFontMgr_RefDefault() }).unwrap()
    }

    pub fn count_families(&self) -> usize {
        unsafe { self.native().countFamilies().try_into().unwrap() }
    }

    pub fn family_name(&self, index: usize) -> String {
        assert!(index < self.count_families());
        let mut family_name = interop::String::default();
        unsafe {
            self.native()
                .getFamilyName(index.try_into().unwrap(), family_name.native_mut())
        }
        family_name.as_str().into()
    }

    pub fn new_styleset(&self, index: usize) -> FontStyleSet {
        assert!(index < self.count_families());
        FontStyleSet::from_ptr(unsafe { self.native().createStyleSet(index.try_into().unwrap()) })
            .unwrap()
    }

    pub fn match_family(&self, family_name: impl AsRef<str>) -> FontStyleSet {
        let family_name = CString::new(family_name.as_ref()).unwrap();
        FontStyleSet::from_ptr(unsafe { self.native().matchFamily(family_name.as_ptr()) }).unwrap()
    }

    pub fn match_family_style(
        &self,
        family_name: impl AsRef<str>,
        style: FontStyle,
    ) -> Option<Typeface> {
        let family_name = CString::new(family_name.as_ref()).unwrap();
        Typeface::from_ptr(unsafe {
            self.native()
                .matchFamilyStyle(family_name.as_ptr(), style.native())
        })
    }

    // TODO: support IntoIterator / AsRef<str> for bcp_47?
    pub fn match_family_style_character(
        &self,
        family_name: impl AsRef<str>,
        style: FontStyle,
        bcp_47: &[&str],
        character: Unichar,
    ) -> Option<Typeface> {
        let family_name = CString::new(family_name.as_ref()).unwrap();
        // create backing store for the pointer array.
        let bcp_47: Vec<CString> = bcp_47.iter().map(|s| CString::new(*s).unwrap()).collect();
        // note: mutability needed to comply to the C type "const char* bcp47[]".
        let mut bcp_47: Vec<*const c_char> = bcp_47.iter().map(|cs| cs.as_ptr()).collect();

        Typeface::from_ptr(unsafe {
            self.native().matchFamilyStyleCharacter(
                family_name.as_ptr(),
                style.native(),
                bcp_47.as_mut_ptr(),
                bcp_47.len().try_into().unwrap(),
                character,
            )
        })
    }

    pub fn match_face_style(
        &self,
        typeface: impl AsRef<Typeface>,
        style: FontStyle,
    ) -> Option<Typeface> {
        Typeface::from_ptr(unsafe {
            self.native()
                .matchFaceStyle(typeface.as_ref().native(), style.native())
        })
    }

    #[deprecated(since = "0.12.0", note = "use new_from_data()")]
    pub fn new_from_bytes(&self, bytes: &[u8], ttc_index: Option<usize>) -> Option<Typeface> {
        self.new_from_data(bytes, ttc_index)
    }

    pub fn new_from_data(
        &self,
        bytes: &[u8],
        ttc_index: impl Into<Option<usize>>,
    ) -> Option<Typeface> {
        let mut stream = DynamicMemoryWStream::from_bytes(bytes);
        let mut stream = stream.detach_as_stream();
        Typeface::from_ptr(unsafe {
            let stream_ptr = stream.native_mut() as *mut _;
            // makeFromStream takes ownership of the stream, so don't call drop on it.
            mem::forget(stream);
            sb::C_SkFontMgr_makeFromStream(
                self.native(),
                stream_ptr,
                ttc_index.into().unwrap_or_default().try_into().unwrap(),
            )
        })
    }

    // TODO: makeFromStream(.., ttcIndex).
}

#[test]
fn create_all_typefaces() {
    let font_mgr = FontMgr::default();
    let families = font_mgr.count_families();
    println!("FontMgr families: {}", families);
    // test requires that the font manager returns at least one family for now.
    assert!(families > 0);
    // print all family names and styles
    for i in 0..families {
        let name = font_mgr.family_name(i);
        println!("font_family: {}", name);
        let mut style_set = font_mgr.new_styleset(i);
        for style_index in 0..style_set.count() {
            let (_, style_name) = style_set.style(style_index);
            if let Some(style_name) = style_name {
                println!("  style: {}", style_name);
            }
            let face = style_set.new_typeface(style_index);
            drop(face);
        }
    }
}