Debian Codegraph @

third_party/color_emoji/emoji_builder.py

raw symbols SCIP
1 #!/usr/bin/env python
2 #
3 # Copyright 2013 Google, Inc. All Rights Reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17 # Google Author(s): Behdad Esfahbod, Stuart Gill, Roozbeh Pournader
18 #
19
20
21 from __future__ import print_function
22 import sys, struct
23 from png import PNG
24 import os
25 from os import path
26
27 from nototools import font_data
28
29
30 try:
31 unichr # py2
32 except NameError:
33 unichr = chr # py3
34
35 def get_glyph_name_from_gsub (string, font, cmap_dict):
36 ligatures = font['GSUB'].table.LookupList.Lookup[0].SubTable[0].ligatures
37 first_glyph = cmap_dict[ord (string[0])]
38 rest_of_glyphs = [cmap_dict[ord (ch)] for ch in string[1:]]
39 for ligature in ligatures[first_glyph]:
40 if ligature.Component == rest_of_glyphs:
41 return ligature.LigGlyph
42
43
44 def div (a, b):
45 return int (round (a / float (b)))
46
47 class FontMetrics:
48 def __init__ (self, upem, ascent, descent):
49 self.upem = upem
50 self.ascent = ascent
51 self.descent = descent
52
53 class StrikeMetrics:
54 def __init__ (self, font_metrics, advance, bitmap_width, bitmap_height):
55 self.width = bitmap_width # in pixels
56 self.height = bitmap_height # in pixels
57 self.advance = advance # in font units
58 self.x_ppem = self.y_ppem = div (bitmap_width * font_metrics.upem, advance)
59
60 class GlyphMap:
61 def __init__ (self, glyph, offset, image_format):
62 self.glyph = glyph
63 self.offset = offset
64 self.image_format = image_format
65
66
67 # Based on http://www.microsoft.com/typography/otspec/ebdt.htm
68 class CBDT:
69
70 def __init__ (self, font_metrics, options = (), stream = None):
71 self.stream = stream if stream != None else bytearray ()
72 self.options = options
73 self.font_metrics = font_metrics
74 self.base_offset = 0
75 self.base_offset = self.tell ()
76
77 def tell (self):
78 return len (self.stream) - self.base_offset
79 def write (self, data):
80 self.stream.extend (data)
81 def data (self):
82 return self.stream
83
84 def write_header (self):
85 self.write (struct.pack (">L", 0x00030000)) # FIXED version
86
87 def start_strike (self, strike_metrics):
88 self.strike_metrics = strike_metrics
89 self.glyph_maps = []
90
91 def write_glyphs (self, glyphs, glyph_filenames, image_format):
92
93 write_func = self.image_write_func (image_format)
94 for glyph in glyphs:
95 img_file = glyph_filenames[glyph]
96 # print 'writing data for glyph %s' % path.basename(img_file)
97 offset = self.tell ()
98 write_func (PNG (img_file))
99 self.glyph_maps.append (GlyphMap (glyph, offset, image_format))
100
101 def end_strike (self):
102
103 self.glyph_maps.append (GlyphMap (None, self.tell (), None))
104 glyph_maps = self.glyph_maps
105 del self.glyph_maps
106 del self.strike_metrics
107 return glyph_maps
108
109 def write_glyphMetrics (self, width, height, big_metrics):
110
111 ascent = self.font_metrics.ascent
112 descent = self.font_metrics.descent
113 upem = self.font_metrics.upem
114 y_ppem = self.strike_metrics.y_ppem
115
116 x_bearing = 0
117 # center vertically
118 line_height = (ascent + descent) * y_ppem / float (upem)
119 line_ascent = ascent * y_ppem / float (upem)
120 y_bearing = int (round (line_ascent - .5 * (line_height - height)))
121 # fudge y_bearing if calculations are a bit off
122 if y_bearing == 128:
123 y_bearing = 127
124 advance = width
125
126 vert_x_bearing = - width / 2
127 vert_y_bearing = 0
128 vert_advance = height
129
130 # print "big glyph metrics h: %d w: %d" % (height, width)
131 # smallGlyphMetrics
132 # Type Name
133 # BYTE height
134 # BYTE width
135 # CHAR horiBearingX
136 # CHAR horiBearingY
137 # BYTE horiAdvance
138 # add for bigGlyphMetrics:
139 # CHAR vertBearingX
140 # CHAR vertBearingY
141 # BYTE vertAdvance
142 try:
143 if big_metrics:
144 self.write (struct.pack ("BBbbBbbB",
145 height, width,
146 x_bearing, y_bearing,
147 advance,
148 vert_x_bearing, vert_y_bearing,
149 vert_advance))
150 else:
151 self.write (struct.pack ("BBbbB",
152 height, width,
153 x_bearing, y_bearing,
154 advance))
155 except Exception as e:
156 raise ValueError("%s, h: %d w: %d x: %d y: %d %d a:" % (
157 e, height, width, x_bearing, y_bearing, advance))
158
159 def write_format1 (self, png):
160
161 import cairo
162 img = cairo.ImageSurface.create_from_png (png.stream ())
163 if img.get_format () != cairo.FORMAT_ARGB32:
164 raise Exception ("Expected FORMAT_ARGB32, but image has format %d" % img.get_format ())
165
166 width = img.get_width ()
167 height = img.get_height ()
168 stride = img.get_stride ()
169 data = img.get_data ()
170
171 self.write_smallGlyphMetrics (width, height)
172
173 if sys.byteorder == "little" and stride == width * 4:
174 # Sweet. Data is in desired format, ship it!
175 self.write (data)
176 return
177
178 # Unexpected stride or endianness, do it the slow way
179 offset = 0
180 for y in range (height):
181 for x in range (width):
182 pixel = data[offset + 4 * x: offset + 4 * (x + 1)]
183 # Convert to little endian
184 pixel = struct.pack ("<I", struct.unpack ("@I", pixel)[0])
185 self.write (pixel)
186 offset += stride
187
188 png_allowed_chunks = [b"IHDR", b"PLTE", b"tRNS", b"sRGB", b"IDAT", b"IEND"]
189
190 def write_format17 (self, png):
191 self.write_format17or18(png, False)
192
193 def write_format18 (self, png):
194 self.write_format17or18(png, True)
195
196 def write_format17or18 (self, png, big_metrics):
197 width, height = png.get_size ()
198
199 if 'keep_chunks' not in self.options:
200 png = png.filter_chunks (self.png_allowed_chunks)
201
202 self.write_glyphMetrics (width, height, big_metrics)
203
204 png_data = png.data ()
205 # ULONG data length
206 self.write (struct.pack(">L", len (png_data)))
207 self.write (png_data)
208
209 def image_write_func (self, image_format):
210 if image_format == 1: return self.write_format1
211 if image_format == 17: return self.write_format17
212 if image_format == 18: return self.write_format18
213 return None
214
215
216 # Based on http://www.microsoft.com/typography/otspec/eblc.htm
217 class CBLC:
218
219 def __init__ (self, font_metrics, options = (), stream = None):
220 self.stream = stream if stream != None else bytearray ()
221 self.streams = []
222 self.options = options
223 self.font_metrics = font_metrics
224 self.base_offset = 0
225 self.base_offset = self.tell ()
226
227 def tell (self):
228 return len (self.stream) - self.base_offset
229 def write (self, data):
230 self.stream.extend (data)
231 def data (self):
232 return self.stream
233 def push_stream (self, stream):
234 self.streams.append (self.stream)
235 self.stream = stream
236 def pop_stream (self):
237 stream = self.stream
238 self.stream = self.streams.pop ()
239 return stream
240
241 def write_header (self):
242 self.write (struct.pack (">L", 0x00030000)) # FIXED version
243
244 def start_strikes (self, num_strikes):
245 self.num_strikes = num_strikes
246 self.write (struct.pack (">L", self.num_strikes)) # ULONG numSizes
247 self.bitmapSizeTables = bytearray ()
248 self.otherTables = bytearray ()
249
250 def write_strike (self, strike_metrics, glyph_maps):
251 self.strike_metrics = strike_metrics
252 self.write_bitmapSizeTable (glyph_maps)
253 del self.strike_metrics
254
255 def end_strikes (self):
256 self.write (self.bitmapSizeTables)
257 self.write (self.otherTables)
258 del self.bitmapSizeTables
259 del self.otherTables
260
261 def write_sbitLineMetrics_hori (self):
262
263 ascent = self.font_metrics.ascent
264 descent = self.font_metrics.descent
265 upem = self.font_metrics.upem
266 y_ppem = self.strike_metrics.y_ppem
267
268 # sbitLineMetrics
269 # Type Name
270 # CHAR ascender
271 # CHAR descender
272 # BYTE widthMax
273 # CHAR caretSlopeNumerator
274 # CHAR caretSlopeDenominator
275 # CHAR caretOffset
276 # CHAR minOriginSB
277 # CHAR minAdvanceSB
278 # CHAR maxBeforeBL
279 # CHAR minAfterBL
280 # CHAR pad1
281 # CHAR pad2
282 line_height = div ((ascent + descent) * y_ppem, upem)
283 ascent = div (ascent * y_ppem, upem)
284 descent = - (line_height - ascent)
285 self.write (struct.pack ("bbBbbbbbbbbb",
286 ascent, descent,
287 self.strike_metrics.width,
288 0, 0, 0,
289 0, 0, 0, 0, # TODO
290 0, 0))
291
292 def write_sbitLineMetrics_vert (self):
293 self.write_sbitLineMetrics_hori () # XXX
294
295 def write_indexSubTable1 (self, glyph_maps):
296
297 image_format = glyph_maps[0].image_format
298
299 self.write (struct.pack(">H", 1)) # USHORT indexFormat
300 self.write (struct.pack(">H", image_format)) # USHORT imageFormat
301 imageDataOffset = glyph_maps[0].offset
302 self.write (struct.pack(">L", imageDataOffset)) # ULONG imageDataOffset
303 for gmap in glyph_maps[:-1]:
304 self.write (struct.pack(">L", gmap.offset - imageDataOffset)) # ULONG offsetArray
305 assert gmap.image_format == image_format
306 self.write (struct.pack(">L", glyph_maps[-1].offset - imageDataOffset))
307
308 def write_bitmapSizeTable (self, glyph_maps):
309
310 # count number of ranges
311 count = 1
312 start = glyph_maps[0].glyph
313 last_glyph = start
314 last_image_format = glyph_maps[0].image_format
315 for gmap in glyph_maps[1:-1]:
316 if last_glyph + 1 != gmap.glyph or last_image_format != gmap.image_format:
317 count += 1
318 last_glyph = gmap.glyph
319 last_image_format = gmap.image_format
320 headersLen = count * 8
321
322 headers = bytearray ()
323 subtables = bytearray ()
324 start = glyph_maps[0].glyph
325 start_id = 0
326 last_glyph = start
327 last_image_format = glyph_maps[0].image_format
328 last_id = 0
329 for gmap in glyph_maps[1:-1]:
330 if last_glyph + 1 != gmap.glyph or last_image_format != gmap.image_format:
331 headers.extend (struct.pack(">HHL", start, last_glyph, headersLen + len (subtables)))
332 self.push_stream (subtables)
333 self.write_indexSubTable1 (glyph_maps[start_id:last_id+2])
334 self.pop_stream ()
335
336 start = gmap.glyph
337 start_id = last_id + 1
338 last_glyph = gmap.glyph
339 last_image_format = gmap.image_format
340 last_id += 1
341 headers.extend (struct.pack(">HHL", start, last_glyph, headersLen + len (subtables)))
342 self.push_stream (subtables)
343 self.write_indexSubTable1 (glyph_maps[start_id:last_id+2])
344 self.pop_stream ()
345
346 indexTablesSize = len (headers) + len (subtables)
347 numberOfIndexSubTables = count
348 bitmapSizeTableSize = 48 * self.num_strikes
349
350 indexSubTableArrayOffset = 8 + bitmapSizeTableSize + len (self.otherTables)
351
352 self.push_stream (self.bitmapSizeTables)
353 # bitmapSizeTable
354 # Type Name Description
355 # ULONG indexSubTableArrayOffset offset to index subtable from beginning of CBLC.
356 self.write (struct.pack(">L", indexSubTableArrayOffset))
357 # ULONG indexTablesSize number of bytes in corresponding index subtables and array
358 self.write (struct.pack(">L", indexTablesSize))
359 # ULONG numberOfIndexSubTables an index subtable for each range or format change
360 self.write (struct.pack(">L", numberOfIndexSubTables))
361 # ULONG colorRef not used; set to 0.
362 self.write (struct.pack(">L", 0))
363 # sbitLineMetrics hori line metrics for text rendered horizontally
364 self.write_sbitLineMetrics_hori ()
365 self.write_sbitLineMetrics_vert ()
366 # sbitLineMetrics vert line metrics for text rendered vertically
367 # USHORT startGlyphIndex lowest glyph index for this size
368 self.write (struct.pack(">H", glyph_maps[0].glyph))
369 # USHORT endGlyphIndex highest glyph index for this size
370 self.write (struct.pack(">H", glyph_maps[-2].glyph))
371 # BYTE ppemX horizontal pixels per Em
372 self.write (struct.pack(">B", self.strike_metrics.x_ppem))
373 # BYTE ppemY vertical pixels per Em
374 self.write (struct.pack(">B", self.strike_metrics.y_ppem))
375 # BYTE bitDepth the Microsoft rasterizer v.1.7 or greater supports the
376 # following bitDepth values, as described below: 1, 2, 4, and 8.
377 self.write (struct.pack(">B", 32))
378 # CHAR flags vertical or horizontal (see bitmapFlags)
379 self.write (struct.pack(">b", 0x01))
380 self.pop_stream ()
381
382 self.push_stream (self.otherTables)
383 self.write (headers)
384 self.write (subtables)
385 self.pop_stream ()
386
387
388 def main (argv):
389 import glob
390 from fontTools import ttx, ttLib
391
392 options = []
393
394 option_map = {
395 "-V": "verbose",
396 "-O": "keep_outlines",
397 "-U": "uncompressed",
398 "-S": "small_glyph_metrics",
399 "-C": "keep_chunks",
400 }
401
402 for key, value in option_map.items ():
403 if key in argv:
404 options.append (value)
405 argv.remove (key)
406
407 if len (argv) < 4:
408 print("""
409 Usage:
410
411 emoji_builder.py [-V] [-O] [-U] [-S] [-A] font.ttf out-font.ttf strike-prefix...
412
413 This will search for files that have strike-prefix followed
414 by a hex number, and end in ".png". For example, if strike-prefix
415 is "icons/uni", then files with names like "icons/uni1f4A9.png" will
416 be loaded. All images for the same strike should have the same size
417 for best results.
418
419 If multiple strike-prefix parameters are provided, multiple
420 strikes will be embedded, in the order provided.
421
422 The script then embeds color bitmaps in the font, for characters
423 that the font already supports, and writes the new font out.
424
425 If -V is given, verbose mode is enabled.
426
427 If -U is given, uncompressed images are stored (imageFormat=1).
428
429 If -S is given, PNG images are stored with small glyph metrics (imageFormat=17).
430
431 By default, PNG images are stored with big glyph metrics (imageFormat=18).
432
433 If -O is given, the outline tables ('glyf', 'CFF ') and
434 related tables are NOT dropped from the font.
435 By default they are dropped.
436
437 If -C is given, unused chunks (color profile, etc) are NOT
438 dropped from the PNG images when embedding.
439 By default they are dropped.
440 """, file=sys.stderr)
441 sys.exit (1)
442
443 font_file = argv[1]
444 out_file = argv[2]
445 img_prefixes = argv[3:]
446 del argv
447
448 def add_font_table (font, tag, data):
449 tab = ttLib.tables.DefaultTable.DefaultTable (tag)
450 tab.data = data
451 font[tag] = tab
452
453 def drop_outline_tables (font):
454 for tag in ['cvt ', 'fpgm', 'glyf', 'loca', 'prep', 'CFF ', 'VORG']:
455 try:
456 del font[tag]
457 except KeyError:
458 pass
459
460
461 print()
462
463 font = ttx.TTFont (font_file)
464 print("Loaded font '%s'." % font_file)
465
466 font_metrics = FontMetrics (font['head'].unitsPerEm,
467 font['hhea'].ascent,
468 -font['hhea'].descent)
469 print("Font metrics: upem=%d ascent=%d descent=%d." % \
470 (font_metrics.upem, font_metrics.ascent, font_metrics.descent))
471 glyph_metrics = font['hmtx'].metrics
472 unicode_cmap = font['cmap'].getcmap (3, 10)
473 if not unicode_cmap:
474 unicode_cmap = font['cmap'].getcmap (3, 1)
475 if not unicode_cmap:
476 raise Exception ("Failed to find a Unicode cmap.")
477
478 image_format = 1 if 'uncompressed' in options else (17
479 if 'small_glyph_metrics' in options else 18)
480
481 ebdt = CBDT (font_metrics, options)
482 ebdt.write_header ()
483 eblc = CBLC (font_metrics, options)
484 eblc.write_header ()
485 eblc.start_strikes (len (img_prefixes))
486
487 def is_vs(cp):
488 return cp >= 0xfe00 and cp <= 0xfe0f
489
490 for img_prefix in img_prefixes:
491 print()
492
493 img_files = {}
494 glb = "%s*.png" % img_prefix
495 print("Looking for images matching '%s'." % glb)
496 for img_file in glob.glob (glb):
497 codes = img_file[len (img_prefix):-4]
498 if "_" in codes:
499 pieces = codes.split ("_")
500 cps = [int(code, 16) for code in pieces]
501 uchars = "".join (unichr(cp) for cp in cps if not is_vs(cp))
502 else:
503 cp = int(codes, 16)
504 if is_vs(cp):
505 print("ignoring unexpected vs input %04x" % cp)
506 continue
507 uchars = unichr(cp)
508 img_files[uchars] = img_file
509 if not img_files:
510 raise Exception ("No image files found in '%s'." % glb)
511 print("Found images for %d characters in '%s'." % (len (img_files), glb))
512
513 glyph_imgs = {}
514 advance = width = height = 0
515 for uchars, img_file in img_files.items ():
516 if len (uchars) == 1:
517 try:
518 glyph_name = unicode_cmap.cmap[ord (uchars)]
519 except:
520 print("no cmap entry for %x" % ord(uchars))
521 raise ValueError("%x" % ord(uchars))
522 else:
523 glyph_name = get_glyph_name_from_gsub (uchars, font, unicode_cmap.cmap)
524 glyph_id = font.getGlyphID (glyph_name)
525 glyph_imgs[glyph_id] = img_file
526 if "verbose" in options:
527 uchars_name = ",".join (["%04X" % ord (char) for char in uchars])
528 # print "Matched U+%s: id=%d name=%s image=%s" % (
529 # uchars_name, glyph_id, glyph_name, img_file)
530
531 advance += glyph_metrics[glyph_name][0]
532 w, h = PNG (img_file).get_size ()
533 width += w
534 height += h
535
536 glyphs = sorted (glyph_imgs.keys ())
537 if not glyphs:
538 raise Exception ("No common characters found between font and '%s'." % glb)
539 print("Embedding images for %d glyphs for this strike." % len (glyphs))
540
541 advance, width, height = (div (x, len (glyphs)) for x in (advance, width, height))
542 strike_metrics = StrikeMetrics (font_metrics, advance, width, height)
543 print("Strike ppem set to %d." % (strike_metrics.y_ppem))
544
545 ebdt.start_strike (strike_metrics)
546 ebdt.write_glyphs (glyphs, glyph_imgs, image_format)
547 glyph_maps = ebdt.end_strike ()
548
549 eblc.write_strike (strike_metrics, glyph_maps)
550
551 print()
552
553 ebdt = ebdt.data ()
554 add_font_table (font, 'CBDT', ebdt)
555 print("CBDT table synthesized: %d bytes." % len (ebdt))
556 eblc.end_strikes ()
557 eblc = eblc.data ()
558 add_font_table (font, 'CBLC', eblc)
559 print("CBLC table synthesized: %d bytes." % len (eblc))
560
561 print()
562
563 if 'keep_outlines' not in options:
564 drop_outline_tables (font)
565 print("Dropped outline ('glyf', 'CFF ') and related tables.")
566
567 # hack removal of cmap pua entry for unknown flag glyph. If we try to
568 # remove it earlier, getGlyphID dies. Need to restructure all of this
569 # code.
570 font_data.delete_from_cmap(font, [0xfe82b])
571 font.save (out_file)
572 print("Output font '%s' generated." % out_file)
573
574
575 if __name__ == '__main__':
576 main (sys.argv)