File size: 9,763 Bytes
d82cf6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Wrapper around the Linux FontConfig library. Used to find available fonts.
"""

from collections import OrderedDict
from ctypes import *

import pyglet.lib
from pyglet.util import asbytes, asstr
from pyglet.font.base import FontException


# fontconfig library definitions

(FcResultMatch,
 FcResultNoMatch,
 FcResultTypeMismatch,
 FcResultNoId,
 FcResultOutOfMemory) = range(5)
FcResult = c_int

FC_FAMILY = asbytes('family')
FC_SIZE = asbytes('size')
FC_SLANT = asbytes('slant')
FC_WEIGHT = asbytes('weight')
FC_FT_FACE = asbytes('ftface')
FC_FILE = asbytes('file')

FC_WEIGHT_REGULAR = 80
FC_WEIGHT_BOLD = 200

FC_SLANT_ROMAN = 0
FC_SLANT_ITALIC = 100

(FcTypeVoid,
 FcTypeInteger,
 FcTypeDouble,
 FcTypeString,
 FcTypeBool,
 FcTypeMatrix,
 FcTypeCharSet,
 FcTypeFTFace,
 FcTypeLangSet) = range(9)
FcType = c_int

(FcMatchPattern,
 FcMatchFont) = range(2)
FcMatchKind = c_int


class _FcValueUnion(Union):
    _fields_ = [
        ('s', c_char_p),
        ('i', c_int),
        ('b', c_int),
        ('d', c_double),
        ('m', c_void_p),
        ('c', c_void_p),
        ('f', c_void_p),
        ('p', c_void_p),
        ('l', c_void_p),
    ]


class FcValue(Structure):
    _fields_ = [
        ('type', FcType),
        ('u', _FcValueUnion)
    ]

# End of library definitions


class FontConfig:
    def __init__(self):
        self._fontconfig = self._load_fontconfig_library()
        self._search_cache = OrderedDict()
        self._cache_size = 20

    def dispose(self):
        while len(self._search_cache) > 0:
            self._search_cache.popitem().dispose()

        self._fontconfig.FcFini()
        self._fontconfig = None

    def create_search_pattern(self):
        return FontConfigSearchPattern(self._fontconfig)

    def find_font(self, name, size=12, bold=False, italic=False):
        result = self._get_from_search_cache(name, size, bold, italic)
        if result:
            return result

        search_pattern = self.create_search_pattern()
        search_pattern.name = name
        search_pattern.size = size
        search_pattern.bold = bold
        search_pattern.italic = italic

        result = search_pattern.match()
        self._add_to_search_cache(search_pattern, result)
        search_pattern.dispose()
        return result

    def have_font(self, name):
        result = self.find_font(name)
        if result:
            # Check the name matches, fontconfig can return a default
            if name and result.name and result.name.lower() != name.lower():
                return False
            return True
        else:
            return False

    def char_index(self, ft_face, character):
        return self._fontconfig.FcFreeTypeCharIndex(ft_face, ord(character))

    def _add_to_search_cache(self, search_pattern, result_pattern):
        self._search_cache[(search_pattern.name,
                            search_pattern.size,
                            search_pattern.bold,
                            search_pattern.italic)] = result_pattern
        if len(self._search_cache) > self._cache_size:
            self._search_cache.popitem(last=False)[1].dispose()

    def _get_from_search_cache(self,  name, size, bold, italic):
        result = self._search_cache.get((name, size, bold, italic), None)

        if result and result.is_valid:
            return result
        else:
            return None

    @staticmethod
    def _load_fontconfig_library():
        fontconfig = pyglet.lib.load_library('fontconfig')
        fontconfig.FcInit()

        fontconfig.FcPatternBuild.restype = c_void_p
        fontconfig.FcPatternCreate.restype = c_void_p
        fontconfig.FcFontMatch.restype = c_void_p
        fontconfig.FcFreeTypeCharIndex.restype = c_uint

        fontconfig.FcPatternAddDouble.argtypes = [c_void_p, c_char_p, c_double]
        fontconfig.FcPatternAddInteger.argtypes = [c_void_p, c_char_p, c_int]
        fontconfig.FcPatternAddString.argtypes = [c_void_p, c_char_p, c_char_p]
        fontconfig.FcConfigSubstitute.argtypes = [c_void_p, c_void_p, c_int]
        fontconfig.FcDefaultSubstitute.argtypes = [c_void_p]
        fontconfig.FcFontMatch.argtypes = [c_void_p, c_void_p, c_void_p]
        fontconfig.FcPatternDestroy.argtypes = [c_void_p]

        fontconfig.FcPatternGetFTFace.argtypes = [c_void_p, c_char_p, c_int, c_void_p]
        fontconfig.FcPatternGet.argtypes = [c_void_p, c_char_p, c_int, c_void_p]

        return fontconfig


class FontConfigPattern:
    def __init__(self, fontconfig, pattern=None):
        self._fontconfig = fontconfig
        self._pattern = pattern

    @property
    def is_valid(self):
        return self._fontconfig and self._pattern

    def _create(self):
        assert not self._pattern
        assert self._fontconfig
        self._pattern = self._fontconfig.FcPatternCreate()

    def _destroy(self):
        assert self._pattern
        assert self._fontconfig
        self._fontconfig.FcPatternDestroy(self._pattern)
        self._pattern = None

    @staticmethod
    def _bold_to_weight(bold):
        return FC_WEIGHT_BOLD if bold else FC_WEIGHT_REGULAR

    @staticmethod
    def _italic_to_slant(italic):
        return FC_SLANT_ITALIC if italic else FC_SLANT_ROMAN

    def _set_string(self, name, value):
        assert self._pattern
        assert name
        assert self._fontconfig

        if not value:
            return

        value = value.encode('utf8')

        self._fontconfig.FcPatternAddString(self._pattern, name, asbytes(value))

    def _set_double(self, name, value):
        assert self._pattern
        assert name
        assert self._fontconfig

        if not value:
            return

        self._fontconfig.FcPatternAddDouble(self._pattern, name, c_double(value))

    def _set_integer(self, name, value):
        assert self._pattern
        assert name
        assert self._fontconfig

        if not value:
            return

        self._fontconfig.FcPatternAddInteger(self._pattern, name, c_int(value))

    def _get_value(self, name):
        assert self._pattern
        assert name
        assert self._fontconfig

        value = FcValue()
        result = self._fontconfig.FcPatternGet(self._pattern, name, 0, byref(value))
        if _handle_fcresult(result):
            return value
        else:
            return None

    def _get_string(self, name):
        value = self._get_value(name)

        if value and value.type == FcTypeString:
            return asstr(value.u.s)
        else:
            return None

    def _get_face(self, name):
        value = self._get_value(name)

        if value and value.type == FcTypeFTFace:
            return value.u.f
        else:
            return None

    def _get_integer(self, name):
        value = self._get_value(name)

        if value and value.type == FcTypeInteger:
            return value.u.i
        else:
            return None

    def _get_double(self, name):
        value = self._get_value(name)

        if value and value.type == FcTypeDouble:
            return value.u.d
        else:
            return None


class FontConfigSearchPattern(FontConfigPattern):
    def __init__(self, fontconfig):
        super(FontConfigSearchPattern, self).__init__(fontconfig)

        self.name = None
        self.bold = False
        self.italic = False
        self.size = None

    def match(self):
        self._prepare_search_pattern()
        result_pattern = self._get_match()

        if result_pattern:
            return FontConfigSearchResult(self._fontconfig, result_pattern)
        else:
            return None

    def _prepare_search_pattern(self):
        self._create()
        self._set_string(FC_FAMILY, self.name)
        self._set_double(FC_SIZE, self.size)
        self._set_integer(FC_WEIGHT, self._bold_to_weight(self.bold))
        self._set_integer(FC_SLANT, self._italic_to_slant(self.italic))

        self._substitute_defaults()

    def _substitute_defaults(self):
        assert self._pattern
        assert self._fontconfig

        self._fontconfig.FcConfigSubstitute(None, self._pattern, FcMatchPattern)
        self._fontconfig.FcDefaultSubstitute(self._pattern)

    def _get_match(self):
        assert self._pattern
        assert self._fontconfig

        match_result = FcResult()
        match_pattern = self._fontconfig.FcFontMatch(0, self._pattern, byref(match_result))

        if _handle_fcresult(match_result.value):
            return match_pattern
        else:
            return None

    def dispose(self):
        self._destroy()


class FontConfigSearchResult(FontConfigPattern):
    def __init__(self, fontconfig, result_pattern):
        super(FontConfigSearchResult, self).__init__(fontconfig, result_pattern)

    @property
    def name(self):
        return self._get_string(FC_FAMILY)

    @property
    def size(self):
        return self._get_double(FC_SIZE)

    @property
    def bold(self):
        return self._get_integer(FC_WEIGHT) == FC_WEIGHT_BOLD

    @property
    def italic(self):
        return self._get_integer(FC_SLANT) == FC_SLANT_ITALIC

    @property
    def face(self):
        return self._get_face(FC_FT_FACE)

    @property
    def file(self):
        return self._get_string(FC_FILE)

    def dispose(self):
        self._destroy()


def _handle_fcresult(result):
    if result == FcResultMatch:
        return True
    elif result in (FcResultNoMatch, FcResultTypeMismatch, FcResultNoId):
        return False
    elif result == FcResultOutOfMemory:
        raise FontException('FontConfig ran out of memory.')


_fontconfig_instance = None


def get_fontconfig():
    global _fontconfig_instance
    if not _fontconfig_instance:
        _fontconfig_instance = FontConfig()
    return _fontconfig_instance