forked from Kozea/WeasyPrint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fonts.py
421 lines (374 loc) · 16.8 KB
/
fonts.py
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
"""
weasyprint.fonts
----------------
Interface with external libraries managing fonts installed on the system.
:copyright: Copyright 2011-2016 Simon Sapin and contributors, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import os
import sys
import tempfile
import warnings
from .logger import LOGGER
from .text import (
cairo, dlopen, ffi, get_font_features, gobject, pango, pangocairo)
from .urls import fetch
# XXX No unicode_literals, cffi likes native strings
class FontConfiguration:
"""Font configuration"""
def __init__(self):
"""Create a font configuration before rendering a document."""
self.font_map = None
def add_font_face(self, rule_descriptors, url_fetcher):
"""Add a font into the application."""
fontconfig = None
pangoft2 = None
if pango.pango_version() < 13800:
warnings.warn('@font-face support needs Pango >= 1.38')
else:
try:
fontconfig = dlopen(ffi, 'fontconfig', 'libfontconfig',
'libfontconfig-1.dll',
'libfontconfig.so.1', 'libfontconfig-1.dylib')
pangoft2 = dlopen(ffi, 'pangoft2-1.0', 'libpangoft2-1.0-0',
'libpangoft2-1.0.so', 'libpangoft2-1.0.dylib')
except Exception as err:
# dont alter behavior on other platforms!
if not sys.platform.startswith('win'):
raise err
else:
warnings.warn("'@font-face not supported: {0}".format(err))
fontconfig = None
pangoft2 = None
# if both libraries are present: Use them
if fontconfig and pangoft2:
ffi.cdef('''
// FontConfig
typedef int FcBool;
typedef struct _FcConfig FcConfig;
typedef struct _FcPattern FcPattern;
typedef struct _FcStrList FcStrList;
typedef unsigned char FcChar8;
typedef enum {
FcResultMatch, FcResultNoMatch, FcResultTypeMismatch, FcResultNoId,
FcResultOutOfMemory
} FcResult;
typedef enum {
FcMatchPattern, FcMatchFont, FcMatchScan
} FcMatchKind;
typedef struct _FcFontSet {
int nfont;
int sfont;
FcPattern **fonts;
} FcFontSet;
typedef enum _FcSetName {
FcSetSystem = 0,
FcSetApplication = 1
} FcSetName;
FcConfig * FcInitLoadConfigAndFonts (void);
void FcConfigDestroy (FcConfig *config);
FcBool FcConfigAppFontAddFile (
FcConfig *config, const FcChar8 *file);
FcConfig * FcConfigGetCurrent (void);
FcBool FcConfigSetCurrent (FcConfig *config);
FcBool FcConfigParseAndLoad (
FcConfig *config, const FcChar8 *file, FcBool complain);
FcFontSet * FcConfigGetFonts(FcConfig *config, FcSetName set);
FcStrList * FcConfigGetConfigFiles(FcConfig *config);
FcChar8 * FcStrListNext(FcStrList *list);
void FcDefaultSubstitute (FcPattern *pattern);
FcBool FcConfigSubstitute (
FcConfig *config, FcPattern *p, FcMatchKind kind);
FcPattern * FcPatternCreate (void);
FcPattern * FcPatternDestroy (FcPattern *p);
FcBool FcPatternAddString (
FcPattern *p, const char *object, const FcChar8 *s);
FcResult FcPatternGetString (
FcPattern *p, const char *object, int n, FcChar8 **s);
FcPattern * FcFontMatch (
FcConfig *config, FcPattern *p, FcResult *result);
// PangoFT2
typedef ... PangoFcFontMap;
void pango_fc_font_map_set_config (
PangoFcFontMap *fcfontmap, FcConfig *fcconfig);
void pango_fc_font_map_shutdown (PangoFcFontMap *fcfontmap);
// PangoCairo
typedef ... PangoCairoFontMap;
void pango_cairo_font_map_set_default (PangoCairoFontMap *fontmap);
PangoFontMap * pango_cairo_font_map_new_for_font_type (
cairo_font_type_t fonttype);
''')
FONTCONFIG_WEIGHT_CONSTANTS = {
'normal': 'normal',
'bold': 'bold',
100: 'thin',
200: 'extralight',
300: 'light',
400: 'normal',
500: 'medium',
600: 'demibold',
700: 'bold',
800: 'extrabold',
900: 'black',
}
FONTCONFIG_STYLE_CONSTANTS = {
'normal': 'roman',
'italic': 'italic',
'oblique': 'oblique',
}
FONTCONFIG_STRETCH_CONSTANTS = {
'normal': 'normal',
'ultra-condensed': 'ultracondensed',
'extra-condensed': 'extracondensed',
'condensed': 'condensed',
'semi-condensed': 'semicondensed',
'semi-expanded': 'semiexpanded',
'expanded': 'expanded',
'extra-expanded': 'extraexpanded',
'ultra-expanded': 'ultraexpanded',
}
_warned_once = False
def _warn_once(msg):
"""don't annoy with warnings, one is enough"""
global _warned_once
if not _warned_once:
warnings.warn(msg)
_warned_once = True
def _checkfontconfiguration(font_config):
"""
Check whether the given font_config has fonts.
Maybe that never happens on Nix, but the GTK3 Runtime for Windows,
https://github.com/tschoonj/
GTK-for-Windows-Runtime-Environment-Installer
which is recommended at
http://weasyprint.readthedocs.io/en/latest/install.html#windows
comes without fonts.conf in etc/fonts, giving
"Fontconfig error: Cannot load default config file"
No default config == No fonts.
No fonts == expect ugly output.
If you happen to have an html without a valid @font-face all
letters turn into rectangles.
If you happen to have an html with at least one valid @font-face
all text is styled with that font.
"""
# Nobody ever complained about such a situation on Nix...
# Since I cannot test this on Linux, and dont know whta happens
# without FontConfig, I leave it as it was before an return True
if not sys.platform.startswith('win'):
return True
fonts = fontconfig.FcConfigGetFonts(
font_config, fontconfig.FcSetSystem)
if fonts.nfont > 0:
return True
# Is the reason a missing default config file?
configfiles = fontconfig.FcConfigGetConfigFiles(font_config)
file = fontconfig.FcStrListNext(configfiles)
if file == ffi.NULL:
_warn_once(
'@font-face not supported: Cannot load default config file')
else:
_warn_once('@font-face not supported: no fonts configured')
# fall back to defaul @font-face-less behaviour
return False
# on Windows we could try to add the system fonts like that:
# fontdir = os.path.join(os.environ['WINDIR'], 'Fonts')
# fontconfig.FcConfigAppFontAddDir(
# font_config,
# # not shure which encoding fontconfig expects
# fontdir.encode('mbcs'))
class FontConfiguration(FontConfiguration):
def __init__(self):
"""Create a FT2 font configuration.
See Behdad's blog:
https://mces.blogspot.fr/2015/05/
how-to-use-custom-application-fonts.html
"""
# load the master config file and the fonts
self._fontconfig_config = ffi.gc(
fontconfig.FcInitLoadConfigAndFonts(),
fontconfig.FcConfigDestroy)
# usable config?
if not _checkfontconfiguration(self._fontconfig_config):
self.font_map = None
else:
self.font_map = ffi.gc(
pangocairo.pango_cairo_font_map_new_for_font_type(
cairo.FONT_TYPE_FT),
gobject.g_object_unref)
pangoft2.pango_fc_font_map_set_config(
ffi.cast('PangoFcFontMap *', self.font_map),
self._fontconfig_config)
# pango_fc_font_map_set_config keeps a reference to config
fontconfig.FcConfigDestroy(self._fontconfig_config)
# On Windows the font tempfiles cannot be deleted
# putting them in a subfolder made my life easier.
self._tempdir = None
if sys.platform.startswith('win'):
self._tempdir = os.path.join(
tempfile.gettempdir(), 'weasyprint')
try:
os.mkdir(self._tempdir)
except FileExistsError:
pass
except Exception:
# back to default
self._tempdir = None
self._filenames = []
def add_font_face(self, rule_descriptors, url_fetcher):
if self.font_map is None:
return
for font_type, url in rule_descriptors['src']:
if url is None:
continue
if font_type in ('external', 'local'):
config = self._fontconfig_config
# default: use `url_fetcher` to fetch the font
fetch_as_url = True
if font_type == 'local':
font_name = url.encode('utf-8')
pattern = ffi.gc(
fontconfig.FcPatternCreate(),
fontconfig.FcPatternDestroy)
fontconfig.FcConfigSubstitute(
config, pattern, fontconfig.FcMatchFont)
fontconfig.FcDefaultSubstitute(pattern)
fontconfig.FcPatternAddString(
pattern, b'fullname', font_name)
fontconfig.FcPatternAddString(
pattern, b'postscriptname', font_name)
family = ffi.new('FcChar8 **')
postscript = ffi.new('FcChar8 **')
result = ffi.new('FcResult *')
matching_pattern = fontconfig.FcFontMatch(
config, pattern, result)
# TODO: do many fonts have multiple family values?
fontconfig.FcPatternGetString(
matching_pattern, b'fullname', 0, family)
fontconfig.FcPatternGetString(
matching_pattern, b'postscriptname', 0, postscript)
family = ffi.string(family[0])
postscript = ffi.string(postscript[0])
if font_name.lower() in (
family.lower(), postscript.lower()):
filename = ffi.new('FcChar8 **')
matching_pattern = fontconfig.FcFontMatch(
config, pattern, result)
fontconfig.FcPatternGetString(
matching_pattern, b'file', 0, filename)
# cant use urlopen('file://..') on Windows.
# Fails with
# URLError: <urlopen error file ot on local host>
if sys.platform.startswith('win'):
fetch_as_url = False
url = (
ffi.string(filename[0]).decode(
sys.getfilesystemencoding()))
else:
url = (
u'file://' +
ffi.string(filename[0]).decode('utf-8'))
else:
LOGGER.warning(
'Failed to load local font "%s"',
font_name.decode('utf-8'))
continue
try:
if fetch_as_url:
with fetch(url_fetcher, url) as result:
if 'string' in result:
font = result['string']
else:
font = result['file_obj'].read()
else:
with open(url, 'rb') as fd:
font = fd.read()
except Exception as exc:
LOGGER.error(
'Failed to load font at "%s" (%s)', url, exc)
continue
font_features = {
rules[0][0].replace('-', '_'): rules[0][1] for rules in
rule_descriptors.get('font_variant', [])}
if 'font_feature_settings' in rule_descriptors:
font_features['font_feature_settings'] = (
rule_descriptors['font_feature_settings'])
features_string = ''
for key, value in get_font_features(
**font_features).items():
features_string += '<string>%s %s</string>' % (
key, value)
fd, filename = tempfile.mkstemp(dir=self._tempdir)
os.write(fd, font)
os.close(fd)
self._filenames.append(filename)
xml = '''<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
<match target="scan">
<test name="file" compare="eq">
<string>%s</string>
</test>
<edit name="family" mode="assign_replace">
<string>%s</string>
</edit>
<edit name="slant" mode="assign_replace">
<const>%s</const>
</edit>
<edit name="weight" mode="assign_replace">
<const>%s</const>
</edit>
<edit name="width" mode="assign_replace">
<const>%s</const>
</edit>
</match>
<match target="font">
<test name="file" compare="eq">
<string>%s</string>
</test>
<edit name="fontfeatures"
mode="assign_replace">%s</edit>
</match>
</fontconfig>''' % (
filename,
rule_descriptors['font_family'],
FONTCONFIG_STYLE_CONSTANTS[
rule_descriptors.get('font_style', 'normal')],
FONTCONFIG_WEIGHT_CONSTANTS[
rule_descriptors.get('font_weight', 'normal')],
FONTCONFIG_STRETCH_CONSTANTS[
rule_descriptors.get('font_stretch', 'normal')],
filename, features_string)
fd, conf_filename = tempfile.mkstemp(dir=self._tempdir)
# TODO: is this encoding OK?
os.write(fd, xml.encode('utf-8'))
os.close(fd)
self._filenames.append(conf_filename)
fontconfig.FcConfigParseAndLoad(
config, conf_filename.encode('ascii'), True)
font_added = fontconfig.FcConfigAppFontAddFile(
config, filename.encode('ascii'))
if font_added:
# TODO: we should mask local fonts with the same name
# too as explained in Behdad's blog entry
# What about pango_fc_font_map_config_changed()
# as suggested in Behdad's blog entry?
# Though it seems to work without...
return filename
else:
LOGGER.error('Failed to load font at "%s"', url)
LOGGER.warning(
'Font-face "%s" cannot be loaded',
rule_descriptors['font_family'])
def __del__(self):
"""Clean a font configuration for a document."""
# Can't cleanup the temporary font files on Windows,
# library has still open file handles.
# On Unix `os.remove()` a file that is in use works fine,
# on Windows a PermissionError is raised.
# FcConfigAppFontClear() doesn't help
# pango_fc_font_map_shutdown() doesn't help
for filename in self._filenames:
try:
os.remove(filename)
except OSError:
continue