This repository has been archived by the owner on Apr 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathmake_bw_font.py
483 lines (416 loc) · 16.5 KB
/
make_bw_font.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
# Copyright © 2019 Adobe, Inc.
# Author: Miguel Sousa
"""
Creates a sans-color emoji OT-CFF font from b&w SVG files.
"""
import argparse
from ast import literal_eval
from collections import deque
import glob
import io
import logging
import os
import re
import sys
from fontTools.feaLib.builder import addOpenTypeFeatures
from fontTools.fontBuilder import FontBuilder
from fontTools.misc.psCharStrings import T2CharString
from fontTools.pens.t2CharStringPen import T2CharStringPen
from fontTools.svgLib.path import SVGPath
COPYRIGHT = 'Copyright 2013 Google Inc.'
TRADEMARK = 'Noto is a trademark of Google Inc.'
FAMILY_NAME = 'Noto Emoji'
STYLE_NAME = 'Regular'
FULL_NAME = FAMILY_NAME
PS_NAME = 'NotoEmoji'
MANUFACTURER = 'Google Inc. & Adobe Inc.'
DESIGNER = 'Google Inc.'
VENDOR = 'GOOG'
VENDOR_URL = 'http://www.google.com/get/noto/'
DESIGNER_URL = VENDOR_URL
LICENSE = ('This Font Software is licensed under the SIL Open Font License, '
'Version 1.1. This Font Software is distributed on an "AS IS" '
'BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either '
'express or implied. See the SIL Open Font License for the '
'specific language, permissions and limitations governing your '
'use of this Font Software.')
LICENSE_URL = 'http://scripts.sil.org/OFL'
FSTYPE = 0 # Installable embedding
UPM = 2048
EMOJI_H_ADV = 2550
EMOJI_V_ADV = 2500
EMOJI_SIZE = 2400 # ASCENT + abs(DESCENT)
ABOVE_BASELINE = 0.7451 # ASCENT / EMOJI_H_ADV
ASCENT = 1900
DESCENT = -500
UNDERLINE_POSITION = -1244
UNDERLINE_THICKNESS = 131
SPACE_CHARSTRING = T2CharString(program=[EMOJI_H_ADV, 'endchar'])
RE_UNICODE = re.compile(r'^u[0-9a-f]{4,5}$', re.IGNORECASE)
RE_REVISION = re.compile(r'^[0-9]{1,3}\.[0-9]{3}$')
# The value of the viewBox attribute is a list of four numbers
# min-x, min-y, width and height, separated by whitespace and/or a comma
RE_VIEWBOX = re.compile(
r"(<svg.+?)(\s*viewBox=[\"|\']([-\d,. ]+)[\"|\'])(.+?>)", re.DOTALL)
VALID_1STCHARS = tuple('_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')
VALID_CHARS = VALID_1STCHARS + tuple('.0123456789')
TAG_LAT_LETTR = ('e0061 e0062 e0063 e0064 e0065 e0066 e0067 e0068 e0069 e006a '
'e006b e006c e006d e006e e006f e0070 e0071 e0072 e0073 e0074 '
'e0075 e0076 e0077 e0078 e0079 e007a e007f').split()
log = logging.getLogger('make_bw_font')
def parse_viewbox_values(vb_str):
"""
Input: viewbox's values string
Return: list of integers or floats of viewbox's values
"""
list_str = re.split(r'[\s,]', vb_str)
assert len(list_str) == 4, 'viewBox must have 4 values'
return [literal_eval(val) for val in list_str]
def get_svg_size(svg_file_path):
"""
Takes a path to an SVG file and reads it.
Checks for the existence of a 'viewBox' property in the 'svg' element.
Confirms that the viewBox is square.
Returns the viewBox dimension as an integer.
The regex match will contain 4 groups:
1. String from '<svg' up to the space before 'viewBox'
2. The whole 'viewBox' property (e.g. ' viewBox="0 100 128 128"')
3. The 'viewBox' values
4. Remainder of the '<svg>' element
"""
with io.open(svg_file_path, encoding='utf-8') as fp:
svg_str = fp.read()
vb = RE_VIEWBOX.search(svg_str)
if not vb:
log.error(f"'viewBox' property not found in {svg_file_path}")
return
min_x, min_y, width, height = parse_viewbox_values(vb.group(3))
if not (min_x == min_y == 0):
log.error("The origin of the 'viewBox' is not zero. "
f"min-x: {min_x}; min-y: {min_y}; {svg_file_path}")
return
if width != height:
log.error("The 'viewBox' is not square. "
f"width: {width}; height: {height}; {svg_file_path}")
return
return width
def draw_notdef(pen):
em_10th = EMOJI_H_ADV / 10
v_shift = EMOJI_H_ADV * (ABOVE_BASELINE - 1)
pen.moveTo((em_10th * 2, em_10th * 1 + v_shift))
pen.lineTo((em_10th * 8, em_10th * 1 + v_shift))
pen.lineTo((em_10th * 8, em_10th * 9 + v_shift))
pen.lineTo((em_10th * 2, em_10th * 9 + v_shift))
pen.closePath()
pen.moveTo((em_10th * 3, em_10th * 2 + v_shift))
pen.lineTo((em_10th * 3, em_10th * 8 + v_shift))
pen.lineTo((em_10th * 7, em_10th * 8 + v_shift))
pen.lineTo((em_10th * 7, em_10th * 2 + v_shift))
pen.closePath()
def glyph_name_is_valid(gname, fpath):
"""
Validates a string meant to be used as a glyph name, following the rules
defined at https://adobe-type-tools.github.io/afdko/...
OpenTypeFeatureFileSpecification.html#2.f.i
Returns True if the glyph name is valid and False otherwise.
"""
if not gname:
log.warning("Unable to get a glyph name from file '{}'.".format(fpath))
return False
elif gname[0] not in VALID_1STCHARS:
log.warning("Glyph name made from file '{}' starts with an invalid "
"character '{}'.".format(fpath, gname[0]))
return False
elif not all([char in VALID_CHARS for char in tuple(gname)]):
log.warning("Glyph name made from file '{}' contains one or more "
"invalid characters.".format(fpath))
return False
return True
def get_trimmed_glyph_name(gname, num):
"""
Glyph names cannot have more than 31 characters.
See https://docs.microsoft.com/en-us/typography/opentype/spec/...
recom#39post39-table
Trims an input string and appends a number to it.
"""
suffix = '_{}'.format(num)
return gname[:31 - len(suffix)] + suffix
def make_font(file_paths, out_dir, revision, gsub_path, gpos_path, uvs_lst):
cmap, gorder, validated_fpaths = {}, deque(), []
# build glyph order
for fpath in file_paths:
# derive glyph name from file name
gname = os.path.splitext(os.path.basename(fpath))[0] # trim extension
# validate glyph name
if not glyph_name_is_valid(gname, fpath):
continue
# skip any duplicates and 'space'
if gname in gorder or gname == 'space':
log.warning("Skipped file '{}'. The glyph name derived from it "
"is either a duplicate or 'space'.".format(fpath))
continue
# limit the length of glyph name to 31 chars
if len(gname) > 31:
num = 0
trimmed_gname = get_trimmed_glyph_name(gname, num)
while trimmed_gname in gorder:
num += 1
trimmed_gname = get_trimmed_glyph_name(trimmed_gname, num)
gorder.append(trimmed_gname)
log.warning("Glyph name '{}' was trimmed to 31 characters: "
"'{}'".format(gname, trimmed_gname))
else:
gorder.append(gname)
validated_fpaths.append(fpath)
# add to cmap
if RE_UNICODE.match(gname):
uni_int = int(gname[1:], 16) # trim leading 'u'
cmap[uni_int] = gname
fb = FontBuilder(UPM, isTTF=False)
fb.font['head'].fontRevision = float(revision)
fb.font['head'].lowestRecPPEM = 12
cs_dict = {}
cs_cache = {}
for i, svg_file_path in enumerate(validated_fpaths):
svg_file_realpath = os.path.realpath(svg_file_path)
if svg_file_realpath not in cs_cache:
svg_size = get_svg_size(svg_file_realpath)
if svg_size is None:
cs_dict[gorder[i]] = SPACE_CHARSTRING
continue
pen = T2CharStringPen(EMOJI_H_ADV, None)
svg = SVGPath(svg_file_realpath,
transform=(EMOJI_SIZE / svg_size, 0, 0,
-EMOJI_SIZE / svg_size,
(EMOJI_H_ADV * .5) - (EMOJI_SIZE * .5),
EMOJI_H_ADV * ABOVE_BASELINE))
svg.draw(pen)
cs = pen.getCharString()
cs_cache[svg_file_realpath] = cs
else:
cs = cs_cache.get(svg_file_realpath)
cs_dict[gorder[i]] = cs
# add '.notdef', 'space' and zero-width joiner
pen = T2CharStringPen(EMOJI_H_ADV, None)
draw_notdef(pen)
gorder.extendleft(reversed(['.notdef', 'space', 'ZWJ']))
cs_dict.update({'.notdef': pen.getCharString(),
'space': SPACE_CHARSTRING,
'ZWJ': SPACE_CHARSTRING,
})
cmap.update({32: 'space', # U+0020
160: 'space', # U+00A0
8205: 'ZWJ', # U+200D
})
# add TAG LATIN LETTER glyphs and mappings
for cdpt in TAG_LAT_LETTR:
tag_gname = f'u{cdpt}'
gorder.append(tag_gname)
cs_dict[tag_gname] = SPACE_CHARSTRING
cmap[int(cdpt, 16)] = tag_gname
fb.setupGlyphOrder(list(gorder)) # parts of FontTools require a list
fb.setupCharacterMap(cmap, uvs=uvs_lst)
fb.setupCFF(PS_NAME, {'version': revision,
'Notice': TRADEMARK,
'Copyright': COPYRIGHT,
'FullName': FULL_NAME,
'FamilyName': FAMILY_NAME,
'Weight': STYLE_NAME}, cs_dict, {})
glyphs_bearings = {}
for gname, cs in cs_dict.items():
gbbox = cs.calcBounds(None)
if gbbox:
xmin, ymin, _, ymax = gbbox
if ymax > ASCENT:
log.warning("Top of glyph '{}' may get clipped. "
"Glyph's ymax={}; Font's ascent={}".format(
gname, ymax, ASCENT))
if ymin < DESCENT:
log.warning("Bottom of glyph '{}' may get clipped. "
"Glyph's ymin={}; Font's descent={}".format(
gname, ymin, DESCENT))
lsb = xmin
tsb = EMOJI_V_ADV - ymax - EMOJI_H_ADV * (1 - ABOVE_BASELINE)
glyphs_bearings[gname] = (lsb, tsb)
else:
glyphs_bearings[gname] = (0, 0)
h_metrics = {}
v_metrics = {}
for gname in gorder:
h_metrics[gname] = (EMOJI_H_ADV, glyphs_bearings[gname][0])
v_metrics[gname] = (EMOJI_V_ADV, glyphs_bearings[gname][1])
fb.setupHorizontalMetrics(h_metrics)
fb.setupVerticalMetrics(v_metrics)
fb.setupHorizontalHeader(ascent=ASCENT, descent=DESCENT)
v_ascent = EMOJI_H_ADV // 2
v_descent = EMOJI_H_ADV - v_ascent
fb.setupVerticalHeader(
ascent=v_ascent, descent=-v_descent, caretSlopeRun=1)
VERSION_STRING = 'Version {};{}'.format(revision, VENDOR)
UNIQUE_ID = '{};{};{}'.format(revision, VENDOR, PS_NAME)
name_strings = dict(
copyright=COPYRIGHT, # ID 0
familyName=FAMILY_NAME, # ID 1
styleName=STYLE_NAME, # ID 2
uniqueFontIdentifier=UNIQUE_ID, # ID 3
fullName=FULL_NAME, # ID 4
version=VERSION_STRING, # ID 5
psName=PS_NAME, # ID 6
trademark=TRADEMARK, # ID 7
manufacturer=MANUFACTURER, # ID 8
designer=DESIGNER, # ID 9
vendorURL=VENDOR_URL, # ID 11
designerURL=DESIGNER_URL, # ID 12
licenseDescription=LICENSE, # ID 13
licenseInfoURL=LICENSE_URL, # ID 14
)
fb.setupNameTable(name_strings, mac=False)
fb.setupOS2(fsType=FSTYPE, achVendID=VENDOR, fsSelection=0x0040, # REGULAR
usWinAscent=ASCENT, usWinDescent=-DESCENT,
sTypoAscender=ASCENT, sTypoDescender=DESCENT,
sCapHeight=ASCENT, ulCodePageRange1=(1 << 1)) # set 1st CP bit
if gsub_path:
addOpenTypeFeatures(fb.font, gsub_path, tables=['GSUB'])
if gpos_path:
addOpenTypeFeatures(fb.font, gpos_path, tables=['GPOS'])
fb.setupPost(isFixedPitch=1,
underlinePosition=UNDERLINE_POSITION,
underlineThickness=UNDERLINE_THICKNESS)
fb.setupDummyDSIG()
fb.save(os.path.join(out_dir, '{}.otf'.format(PS_NAME)))
def parse_uvs_file(file_path):
"""
Parses an Unicode Variation Sequences text file.
Returns a list of tuples in the form
(unicodeValue, variationSelector, glyphName).
'unicodeValue' and 'variationSelector' are integer code points.
'glyphName' may be None, to indicate this is the default variation.
"""
with io.open(file_path, encoding='utf-8') as fp:
lines = fp.read().splitlines()
uvs_list = []
for i, line in enumerate(lines, 1):
line = line.strip()
if not line or line.startswith('#'):
continue
uni_str, gname = line.split(';')
uni_lst = uni_str.strip().split()
if not isinstance(uni_lst, list) and len(uni_lst) != 2:
log.error('Line #{} is not correctly formatted.'.format(i))
continue
try:
uni_int = [int(cdpt, 16) for cdpt in uni_lst]
except ValueError:
log.error('Line #{} has an invalid code point.'.format(i))
continue
gname = gname.strip()
if gname == 'None':
gname = None
uni_int.append(gname)
uvs_item = tuple(uni_int)
if uvs_item in uvs_list:
log.warning('Line #{} is a duplicate UVS.'.format(i))
continue
uvs_list.append(uvs_item)
if not uvs_list:
log.warning('No Unicode Variation Sequences were found.')
return None
return uvs_list
def validate_dir_path(path_str):
valid_path = os.path.abspath(os.path.realpath(path_str))
if not os.path.isdir(valid_path):
raise argparse.ArgumentTypeError(
"{} is not a valid directory path.".format(path_str))
return normalize_path(path_str)
def validate_file_path(path_str):
valid_path = os.path.abspath(os.path.realpath(path_str))
if not os.path.isfile(valid_path):
raise argparse.ArgumentTypeError(
"{} is not a valid file path.".format(path_str))
return normalize_path(path_str)
def normalize_path(path_str):
return os.path.normpath(path_str)
def validate_revision_number(rev_str):
if not RE_REVISION.match(rev_str):
raise argparse.ArgumentTypeError(
"The revision number must follow this format: 123.456")
return rev_str
def main(args=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'-v',
'--verbose',
help='verbose mode. Use -vv for debug mode',
action='count',
default=0
)
parser.add_argument(
'in_dirs',
help='one or more input directories containing SVG files',
metavar='DIR',
nargs='+',
type=validate_dir_path,
)
parser.add_argument(
'-o',
'--out-dir',
help='directory to save the font in. Defaults to 1st input directory.',
metavar='DIR',
type=normalize_path,
)
parser.add_argument(
'-r',
'--revision',
help="the font's revision number. Defaults to %(default)s",
type=validate_revision_number,
default='0.001',
)
parser.add_argument(
'--gsub',
help='path to GSUB features file',
type=validate_file_path,
)
parser.add_argument(
'--gpos',
help='path to GPOS features file',
type=validate_file_path,
)
parser.add_argument(
'--uvs',
help='path to Unicode Variation Sequences file',
type=validate_file_path,
)
opts = parser.parse_args(args)
if not opts.verbose:
level = "WARNING"
elif opts.verbose == 1:
level = "INFO"
else:
level = "DEBUG"
logging.basicConfig(level=level)
file_paths = []
for in_dir in opts.in_dirs:
fpaths = sorted(glob.iglob(os.path.join(in_dir, '*.[sS][vV][gG]')))
file_paths.extend(fpaths)
log.info(f"Found {len(fpaths)} SVG files in '{in_dir}'.")
if not len(file_paths):
log.error('Failed to match any SVG files.')
return 1
uvs = None
if opts.uvs:
uvs = parse_uvs_file(opts.uvs)
if opts.out_dir:
out_path = os.path.abspath(os.path.realpath(opts.out_dir))
# create directory if it doesn't exist
if not os.path.exists(out_path):
os.makedirs(out_path)
# the path exists but it's NOT a directory
elif not os.path.isdir(out_path):
log.error("'{}' is not a directory.".format(opts.out_dir))
return 1
out_dir = opts.out_dir
else:
out_dir = opts.in_dirs[0]
make_font(file_paths, out_dir, opts.revision, opts.gsub, opts.gpos, uvs)
if __name__ == "__main__":
sys.exit(main())