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
use std::ptr::null;

use core_foundation::{
    array::{CFArray, CFArrayRef},
    base::{CFType, CFTypeID, TCFType},
    data::{CFData, CFDataRef},
    dictionary::{CFDictionary, CFDictionaryRef},
    number::CFNumber,
    string::{CFString, CFStringRef},
};
use libc::{c_int, c_ushort, c_void, size_t};

use crate::{
    base::CGFloat,
    data_provider::{CGDataProvider, CGDataProviderRef},
    geometry::CGRect,
};

#[repr(C)]
pub struct __CGFont(c_void);

pub type CGFontRef = *mut __CGFont;

pub type CGFontIndex = c_ushort;

pub type CGGlyph = CGFontIndex;

#[repr(i32)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CGFontPostScriptFormat {
    #[doc(alias = "kCGFontPostScriptFormatType1")]
    Type1  = 1,
    #[doc(alias = "kCGFontPostScriptFormatType3")]
    Type3  = 3,
    #[doc(alias = "kCGFontPostScriptFormatType42")]
    Type42 = 42,
}

pub const kCGFontIndexMax: CGFontIndex = u16::MAX - 1;
pub const kCGFontIndexInvalid: CGFontIndex = u16::MAX;
pub const kCGGlyphMax: CGFontIndex = kCGFontIndexMax;

extern "C" {
    pub fn CGFontGetTypeID() -> CFTypeID;
    pub fn CGFontCreateWithPlatformFont(platformFontReference: *mut c_void) -> CGFontRef;
    pub fn CGFontCreateWithDataProvider(provider: CGDataProviderRef) -> CGFontRef;
    pub fn CGFontCreateWithFontName(name: CFStringRef) -> CGFontRef;
    pub fn CGFontCreateCopyWithVariations(font: CGFontRef, variations: CFDictionaryRef) -> CGFontRef;
    pub fn CGFontRetain(font: CGFontRef) -> CGFontRef;
    pub fn CGFontRelease(font: CGFontRef);
    pub fn CGFontGetNumberOfGlyphs(font: CGFontRef) -> size_t;
    pub fn CGFontGetUnitsPerEm(font: CGFontRef) -> c_int;
    pub fn CGFontCopyPostScriptName(font: CGFontRef) -> CFStringRef;
    pub fn CGFontCopyFullName(font: CGFontRef) -> CFStringRef;
    pub fn CGFontGetAscent(font: CGFontRef) -> c_int;
    pub fn CGFontGetDescent(font: CGFontRef) -> c_int;
    pub fn CGFontGetLeading(font: CGFontRef) -> c_int;
    pub fn CGFontGetCapHeight(font: CGFontRef) -> c_int;
    pub fn CGFontGetXHeight(font: CGFontRef) -> c_int;
    pub fn CGFontGetFontBBox(font: CGFontRef) -> CGRect;
    pub fn CGFontGetItalicAngle(font: CGFontRef) -> CGFloat;
    pub fn CGFontGetStemV(font: CGFontRef) -> CGFloat;
    pub fn CGFontCopyVariationAxes(font: CGFontRef) -> CFArrayRef;
    pub fn CGFontCopyVariations(font: CGFontRef) -> CFDictionaryRef;
    pub fn CGFontGetGlyphAdvances(font: CGFontRef, glyphs: *const CGGlyph, count: size_t, advances: *mut c_int) -> bool;
    pub fn CGFontGetGlyphBBoxes(font: CGFontRef, glyphs: *const CGGlyph, count: size_t, bboxes: *mut CGRect) -> bool;
    pub fn CGFontGetGlyphWithGlyphName(font: CGFontRef, name: CFStringRef) -> CGGlyph;
    pub fn CGFontCopyGlyphNameForGlyph(font: CGFontRef, glyph: CGGlyph) -> CFStringRef;
    pub fn CGFontCanCreatePostScriptSubset(font: CGFontRef, format: CGFontPostScriptFormat) -> bool;
    pub fn CGFontCreatePostScriptSubset(
        font: CGFontRef,
        subsetName: CFStringRef,
        format: CGFontPostScriptFormat,
        glyphs: *const CGGlyph,
        count: size_t,
        encoding: *const CGGlyph,
    ) -> CFDataRef;
    pub fn CGFontCreatePostScriptEncoding(font: CGFontRef, encoding: *const CGGlyph) -> CFDataRef;
    pub fn CGFontCopyTableTags(font: CGFontRef) -> CFArrayRef;
    pub fn CGFontCopyTableForTag(font: CGFontRef, tag: u32) -> CFDataRef;

    pub static kCGFontVariationAxisName: CFStringRef;
    pub static kCGFontVariationAxisMinValue: CFStringRef;
    pub static kCGFontVariationAxisMaxValue: CFStringRef;
    pub static kCGFontVariationAxisDefaultValue: CFStringRef;
}

pub struct CGFont(CGFontRef);

impl Drop for CGFont {
    fn drop(&mut self) {
        unsafe { CGFontRelease(self.0) }
    }
}

impl_TCFType!(CGFont, CGFontRef, CGFontGetTypeID);
impl_CFTypeDescription!(CGFont);

impl CGFont {
    pub fn from_data_provider(provider: &CGDataProvider) -> Option<Self> {
        unsafe {
            let font = CGFontCreateWithDataProvider(provider.as_concrete_TypeRef());
            if font.is_null() {
                None
            } else {
                Some(TCFType::wrap_under_create_rule(font))
            }
        }
    }

    pub fn from_name(name: &CFString) -> Option<Self> {
        unsafe {
            let font = CGFontCreateWithFontName(name.as_concrete_TypeRef());
            if font.is_null() {
                None
            } else {
                Some(TCFType::wrap_under_create_rule(font))
            }
        }
    }

    pub fn new_copy_from_variations(&self, variations: Option<&CFDictionary<CFString, CFNumber>>) -> Option<CGFont> {
        unsafe {
            let font = CGFontCreateCopyWithVariations(self.as_concrete_TypeRef(), variations.as_ref().map_or(null(), |v| v.as_concrete_TypeRef()));
            if font.is_null() {
                None
            } else {
                Some(TCFType::wrap_under_create_rule(font))
            }
        }
    }

    pub fn number_of_glyphs(&self) -> usize {
        unsafe { CGFontGetNumberOfGlyphs(self.as_concrete_TypeRef()) }
    }

    pub fn units_per_em(&self) -> i32 {
        unsafe { CGFontGetUnitsPerEm(self.as_concrete_TypeRef()) as i32 }
    }

    pub fn copy_post_script_name(&self) -> CFString {
        unsafe {
            let name = CGFontCopyPostScriptName(self.as_concrete_TypeRef());
            TCFType::wrap_under_create_rule(name)
        }
    }

    pub fn copy_full_name(&self) -> CFString {
        unsafe {
            let name = CGFontCopyFullName(self.as_concrete_TypeRef());
            TCFType::wrap_under_create_rule(name)
        }
    }

    pub fn ascent(&self) -> i32 {
        unsafe { CGFontGetAscent(self.as_concrete_TypeRef()) as i32 }
    }

    pub fn descent(&self) -> i32 {
        unsafe { CGFontGetDescent(self.as_concrete_TypeRef()) as i32 }
    }

    pub fn leading(&self) -> i32 {
        unsafe { CGFontGetLeading(self.as_concrete_TypeRef()) as i32 }
    }

    pub fn cap_height(&self) -> i32 {
        unsafe { CGFontGetCapHeight(self.as_concrete_TypeRef()) as i32 }
    }

    pub fn x_height(&self) -> i32 {
        unsafe { CGFontGetXHeight(self.as_concrete_TypeRef()) as i32 }
    }

    pub fn font_b_box(&self) -> CGRect {
        unsafe { CGFontGetFontBBox(self.as_concrete_TypeRef()) }
    }

    pub fn italic_angle(&self) -> CGFloat {
        unsafe { CGFontGetItalicAngle(self.as_concrete_TypeRef()) }
    }

    pub fn stem_v(&self) -> CGFloat {
        unsafe { CGFontGetStemV(self.as_concrete_TypeRef()) }
    }

    pub fn copy_variation_axes(&self) -> Option<CFArray<CFDictionary<CFString, CFType>>> {
        unsafe {
            let axes = CGFontCopyVariationAxes(self.as_concrete_TypeRef());
            if axes.is_null() {
                None
            } else {
                Some(TCFType::wrap_under_create_rule(axes))
            }
        }
    }

    pub fn copy_variations(&self) -> Option<CFDictionary<CFString, CFNumber>> {
        let variations = unsafe { CGFontCopyVariations(self.as_concrete_TypeRef()) };
        if !variations.is_null() {
            Some(unsafe { TCFType::wrap_under_create_rule(variations) })
        } else {
            None
        }
    }

    pub fn glyph_advances(&self, glyphs: &[CGGlyph], advances: &mut [c_int]) -> bool {
        if glyphs.len() > advances.len() {
            return false;
        }

        unsafe { CGFontGetGlyphAdvances(self.as_concrete_TypeRef(), glyphs.as_ptr(), glyphs.len(), advances.as_mut_ptr()) }
    }

    pub fn glyph_b_boxes(&self, glyphs: &[CGGlyph], bboxes: &mut [CGRect]) -> bool {
        if glyphs.len() > bboxes.len() {
            return false;
        }

        unsafe { CGFontGetGlyphBBoxes(self.as_concrete_TypeRef(), glyphs.as_ptr(), glyphs.len(), bboxes.as_mut_ptr()) }
    }

    pub fn glyph_with_glyph_name(&self, name: &CFString) -> CGGlyph {
        unsafe { CGFontGetGlyphWithGlyphName(self.as_concrete_TypeRef(), name.as_concrete_TypeRef()) }
    }

    pub fn copy_glyph_name_for_glyph(&self, glyph: CGGlyph) -> CFString {
        unsafe {
            let name = CGFontCopyGlyphNameForGlyph(self.as_concrete_TypeRef(), glyph);
            TCFType::wrap_under_create_rule(name)
        }
    }

    pub fn copy_table_tags(&self) -> CFArray<u32> {
        unsafe { TCFType::wrap_under_create_rule(CGFontCopyTableTags(self.as_concrete_TypeRef())) }
    }

    pub fn copy_table_for_tag(&self, tag: u32) -> Option<CFData> {
        let data = unsafe { CGFontCopyTableForTag(self.as_concrete_TypeRef(), tag) };
        if data.is_null() {
            None
        } else {
            Some(unsafe { TCFType::wrap_under_create_rule(data) })
        }
    }
}

pub enum CGFontVariationAxis {
    Name,
    MinValue,
    MaxValue,
    DefaultValue,
}

impl From<CGFontVariationAxis> for CFStringRef {
    fn from(axis: CGFontVariationAxis) -> Self {
        unsafe {
            match axis {
                CGFontVariationAxis::Name => kCGFontVariationAxisName,
                CGFontVariationAxis::MinValue => kCGFontVariationAxisMinValue,
                CGFontVariationAxis::MaxValue => kCGFontVariationAxisMaxValue,
                CGFontVariationAxis::DefaultValue => kCGFontVariationAxisDefaultValue,
            }
        }
    }
}

impl From<CGFontVariationAxis> for CFString {
    fn from(axis: CGFontVariationAxis) -> Self {
        unsafe { CFString::wrap_under_get_rule(CFStringRef::from(axis)) }
    }
}