Debian Codegraph @

tools/fonts/fontchain_linter.py

raw symbols SCIP
1 #!/usr/bin/env python
2
3 import collections
4 import copy
5 import glob
6 from os import path
7 import re
8 import sys
9 from xml.etree import ElementTree
10
11 from fontTools import ttLib
12
13 EMOJI_VS = 0xFE0F
14
15 LANG_TO_SCRIPT = {
16 'af': 'Latn',
17 'as': 'Beng',
18 'am': 'Latn',
19 'be': 'Cyrl',
20 'bg': 'Cyrl',
21 'bn': 'Beng',
22 'cs': 'Latn',
23 'cu': 'Cyrl',
24 'cy': 'Latn',
25 'da': 'Latn',
26 'de': 'Latn',
27 'el': 'Latn',
28 'en': 'Latn',
29 'es': 'Latn',
30 'et': 'Latn',
31 'eu': 'Latn',
32 'fr': 'Latn',
33 'ga': 'Latn',
34 'gl': 'Latn',
35 'gu': 'Gujr',
36 'hi': 'Deva',
37 'hr': 'Latn',
38 'hu': 'Latn',
39 'hy': 'Armn',
40 'it': 'Latn',
41 'ja': 'Jpan',
42 'ka': 'Latn',
43 'kn': 'Knda',
44 'ko': 'Kore',
45 'la': 'Latn',
46 'lt': 'Latn',
47 'lv': 'Latn',
48 'ml': 'Mlym',
49 'mn': 'Cyrl',
50 'mr': 'Deva',
51 'nb': 'Latn',
52 'nl': 'Latn',
53 'nn': 'Latn',
54 'or': 'Orya',
55 'pa': 'Guru',
56 'pt': 'Latn',
57 'ru': 'Latn',
58 'sk': 'Latn',
59 'sl': 'Latn',
60 'sq': 'Latn',
61 'sv': 'Latn',
62 'ta': 'Taml',
63 'te': 'Telu',
64 'tk': 'Latn',
65 'uk': 'Latn',
66 }
67
68 def lang_to_script(lang_code):
69 lang = lang_code.lower()
70 while lang not in LANG_TO_SCRIPT:
71 hyphen_idx = lang.rfind('-')
72 assert hyphen_idx != -1, (
73 'We do not know what script the "%s" language is written in.'
74 % lang_code)
75 assumed_script = lang[hyphen_idx+1:]
76 if len(assumed_script) == 4 and assumed_script.isalpha():
77 # This is actually the script
78 return assumed_script.title()
79 lang = lang[:hyphen_idx]
80 return LANG_TO_SCRIPT[lang]
81
82
83 def printable(inp):
84 if type(inp) is set: # set of character sequences
85 return '{' + ', '.join([printable(seq) for seq in inp]) + '}'
86 if type(inp) is tuple: # character sequence
87 return '<' + (', '.join([printable(ch) for ch in inp])) + '>'
88 else: # single character
89 return 'U+%04X' % inp
90
91
92 def open_font(font):
93 font_file, index = font
94 font_path = path.join(_fonts_dir, font_file)
95 if index is not None:
96 return ttLib.TTFont(font_path, fontNumber=index)
97 else:
98 return ttLib.TTFont(font_path)
99
100
101 def get_best_cmap(font):
102 ttfont = open_font(font)
103 all_unicode_cmap = None
104 bmp_cmap = None
105 for cmap in ttfont['cmap'].tables:
106 specifier = (cmap.format, cmap.platformID, cmap.platEncID)
107 if specifier == (4, 3, 1):
108 assert bmp_cmap is None, 'More than one BMP cmap in %s' % (font, )
109 bmp_cmap = cmap
110 elif specifier == (12, 3, 10):
111 assert all_unicode_cmap is None, (
112 'More than one UCS-4 cmap in %s' % (font, ))
113 all_unicode_cmap = cmap
114
115 return all_unicode_cmap.cmap if all_unicode_cmap else bmp_cmap.cmap
116
117
118 def get_variation_sequences_cmap(font):
119 ttfont = open_font(font)
120 vs_cmap = None
121 for cmap in ttfont['cmap'].tables:
122 specifier = (cmap.format, cmap.platformID, cmap.platEncID)
123 if specifier == (14, 0, 5):
124 assert vs_cmap is None, 'More than one VS cmap in %s' % (font, )
125 vs_cmap = cmap
126 return vs_cmap
127
128
129 def get_emoji_map(font):
130 # Add normal characters
131 emoji_map = copy.copy(get_best_cmap(font))
132 reverse_cmap = {glyph: code for code, glyph in emoji_map.items() if not contains_pua(code) }
133
134 # Add variation sequences
135 vs_cmap = get_variation_sequences_cmap(font)
136 if vs_cmap:
137 for vs in vs_cmap.uvsDict:
138 for base, glyph in vs_cmap.uvsDict[vs]:
139 if glyph is None:
140 emoji_map[(base, vs)] = emoji_map[base]
141 else:
142 emoji_map[(base, vs)] = glyph
143
144 # Add GSUB rules
145 ttfont = open_font(font)
146 for lookup in ttfont['GSUB'].table.LookupList.Lookup:
147 if lookup.LookupType != 4:
148 # Other lookups are used in the emoji font for fallback.
149 # We ignore them for now.
150 continue
151 for subtable in lookup.SubTable:
152 ligatures = subtable.ligatures
153 for first_glyph in ligatures:
154 for ligature in ligatures[first_glyph]:
155 sequence = [first_glyph] + ligature.Component
156 sequence = [reverse_cmap[glyph] for glyph in sequence]
157 sequence = tuple(sequence)
158 # Make sure no starting subsequence of 'sequence' has been
159 # seen before.
160 for sub_len in range(2, len(sequence)+1):
161 subsequence = sequence[:sub_len]
162 assert subsequence not in emoji_map
163 emoji_map[sequence] = ligature.LigGlyph
164
165 return emoji_map
166
167
168 def assert_font_supports_any_of_chars(font, chars):
169 best_cmap = get_best_cmap(font)
170 for char in chars:
171 if char in best_cmap:
172 return
173 sys.exit('None of characters in %s were found in %s' % (chars, font))
174
175
176 def assert_font_supports_all_of_chars(font, chars):
177 best_cmap = get_best_cmap(font)
178 for char in chars:
179 assert char in best_cmap, (
180 'U+%04X was not found in %s' % (char, font))
181
182
183 def assert_font_supports_none_of_chars(font, chars, fallbackName):
184 best_cmap = get_best_cmap(font)
185 for char in chars:
186 if fallbackName:
187 assert char not in best_cmap, 'U+%04X was found in %s' % (char, font)
188 else:
189 assert char not in best_cmap, (
190 'U+%04X was found in %s in fallback %s' % (char, font, fallbackName))
191
192
193 def assert_font_supports_all_sequences(font, sequences):
194 vs_dict = get_variation_sequences_cmap(font).uvsDict
195 for base, vs in sorted(sequences):
196 assert vs in vs_dict and (base, None) in vs_dict[vs], (
197 '<U+%04X, U+%04X> was not found in %s' % (base, vs, font))
198
199
200 def check_hyphens(hyphens_dir):
201 # Find all the scripts that need automatic hyphenation
202 scripts = set()
203 for hyb_file in glob.iglob(path.join(hyphens_dir, '*.hyb')):
204 hyb_file = path.basename(hyb_file)
205 assert hyb_file.startswith('hyph-'), (
206 'Unknown hyphenation file %s' % hyb_file)
207 lang_code = hyb_file[hyb_file.index('-')+1:hyb_file.index('.')]
208 scripts.add(lang_to_script(lang_code))
209
210 HYPHENS = {0x002D, 0x2010}
211 for script in scripts:
212 fonts = _script_to_font_map[script]
213 assert fonts, 'No fonts found for the "%s" script' % script
214 for font in fonts:
215 assert_font_supports_any_of_chars(font, HYPHENS)
216
217
218 class FontRecord(object):
219 def __init__(self, name, psName, scripts, variant, weight, style, fallback_for, font):
220 self.name = name
221 self.psName = psName
222 self.scripts = scripts
223 self.variant = variant
224 self.weight = weight
225 self.style = style
226 self.fallback_for = fallback_for
227 self.font = font
228
229
230 def parse_fonts_xml(fonts_xml_path):
231 global _script_to_font_map, _fallback_chains, _all_fonts
232 _script_to_font_map = collections.defaultdict(set)
233 _fallback_chains = {}
234 _all_fonts = []
235 tree = ElementTree.parse(fonts_xml_path)
236 families = tree.findall('family')
237 # Minikin supports up to 254 but users can place their own font at the first
238 # place. Thus, 253 is the maximum allowed number of font families in the
239 # default collection.
240 assert len(families) < 254, (
241 'System font collection can contains up to 253 font families.')
242 for family in families:
243 name = family.get('name')
244 variant = family.get('variant')
245 langs = family.get('lang')
246 ignoreAttr = family.get('ignore')
247
248 if name:
249 assert variant is None, (
250 'No variant expected for LGC font %s.' % name)
251 assert langs is None, (
252 'No language expected for LGC fonts %s.' % name)
253 assert name not in _fallback_chains, 'Duplicated name entry %s' % name
254 _fallback_chains[name] = []
255 else:
256 assert variant in {None, 'elegant', 'compact'}, (
257 'Unexpected value for variant: %s' % variant)
258
259 trim_re = re.compile(r"^[ \n\r\t]*(.+)[ \n\r\t]*$")
260 for family in families:
261 name = family.get('name')
262 variant = family.get('variant')
263 langs = family.get('lang')
264 ignoreAttr = family.get('ignore')
265 ignore = ignoreAttr == 'true' or ignoreAttr == '1'
266
267 if ignore:
268 continue
269
270 if langs:
271 langs = langs.split()
272 scripts = {lang_to_script(lang) for lang in langs}
273 else:
274 scripts = set()
275
276 for child in family:
277 assert child.tag == 'font', (
278 'Unknown tag <%s>' % child.tag)
279 font_file = child.text.rstrip()
280
281 m = trim_re.match(font_file)
282 font_file = m.group(1)
283
284 weight = int(child.get('weight'))
285 assert weight % 100 == 0, (
286 'Font weight "%d" is not a multiple of 100.' % weight)
287
288 style = child.get('style')
289 assert style in {'normal', 'italic'}, (
290 'Unknown style "%s"' % style)
291
292 fallback_for = child.get('fallbackFor')
293
294 assert not name or not fallback_for, (
295 'name and fallbackFor cannot be present at the same time')
296 assert not fallback_for or fallback_for in _fallback_chains, (
297 'Unknown fallback name: %s' % fallback_for)
298
299 index = child.get('index')
300 if index:
301 index = int(index)
302
303 if not path.exists(path.join(_fonts_dir, m.group(1))):
304 continue # Missing font is a valid case. Just ignore the missing font files.
305
306 record = FontRecord(
307 name,
308 child.get('postScriptName'),
309 frozenset(scripts),
310 variant,
311 weight,
312 style,
313 fallback_for,
314 (font_file, index))
315
316 _all_fonts.append(record)
317
318 if not fallback_for:
319 if not name or name == 'sans-serif':
320 for _, fallback in _fallback_chains.items():
321 fallback.append(record)
322 else:
323 _fallback_chains[name].append(record)
324 else:
325 _fallback_chains[fallback_for].append(record)
326
327 if name: # non-empty names are used for default LGC fonts
328 map_scripts = {'Latn', 'Grek', 'Cyrl'}
329 else:
330 map_scripts = scripts
331 for script in map_scripts:
332 _script_to_font_map[script].add((font_file, index))
333
334
335 def check_emoji_coverage(all_emoji, equivalent_emoji):
336 emoji_fonts = get_emoji_fonts()
337 check_emoji_font_coverage(emoji_fonts, all_emoji, equivalent_emoji)
338
339
340 def get_emoji_fonts():
341 return [ record.font for record in _all_fonts if 'Zsye' in record.scripts ]
342
343 def seq_any(sequence, pred):
344 if type(sequence) is tuple:
345 return any([pred(x) for x in sequence])
346 else:
347 return pred(sequence)
348
349 def seq_all(sequence, pred):
350 if type(sequence) is tuple:
351 return all([pred(x) for x in sequence])
352 else:
353 return pred(sequence)
354
355 def is_regional_indicator(x):
356 # regional indicator A..Z
357 return 0x1F1E6 <= x <= 0x1F1FF
358
359 def is_tag(x):
360 # tag block
361 return 0xE0000 <= x <= 0xE007F
362
363 def is_pua(x):
364 return 0xE000 <= x <= 0xF8FF or 0xF0000 <= x <= 0xFFFFD or 0x100000 <= x <= 0x10FFFD
365
366 def contains_pua(sequence):
367 return seq_any(sequence, is_pua)
368
369 def contains_regional_indicator(sequence):
370 return seq_any(sequence, is_regional_indicator)
371
372 def only_tags(sequence):
373 return seq_all(sequence, is_tag)
374
375 def get_psname(ttf):
376 return str(next(x for x in ttf['name'].names
377 if x.platformID == 3 and x.platEncID == 1 and x.nameID == 6))
378
379 def hex_strs(sequence):
380 if type(sequence) is tuple:
381 return tuple(f"{s:X}" for s in sequence)
382 return hex(sequence)
383
384 def check_emoji_not_compat(all_emoji, equivalent_emoji):
385 compat_psnames = set()
386 for emoji_font in get_emoji_fonts():
387 ttf = open_font(emoji_font)
388 psname = get_psname(ttf)
389
390 if "meta" in ttf:
391 assert 'Emji' not in ttf["meta"].data, 'NotoColorEmoji MUST NOT be a compat font'
392
393
394 def check_emoji_font_coverage(emoji_fonts, all_emoji, equivalent_emoji):
395 coverages = []
396 for emoji_font in emoji_fonts:
397 coverages.append(get_emoji_map(emoji_font))
398
399 errors = []
400
401 for sequence in all_emoji:
402 if all([sequence not in coverage for coverage in coverages]):
403 errors.append('%s is not supported in the emoji font.' % printable(sequence))
404
405 for coverage in coverages:
406 for sequence in coverage:
407 if sequence in {0x0000, 0x000D, 0x0020}:
408 # The font needs to support a few extra characters, which is OK
409 continue
410
411 if contains_pua(sequence):
412 # The font needs to have some PUA for EmojiCompat library.
413 continue
414
415 if sequence not in all_emoji:
416 errors.append('%s support unexpected in the emoji font.' % printable(sequence))
417
418 for first, second in equivalent_emoji.items():
419 for coverage in coverages:
420 if first not in coverage or second not in coverage:
421 continue # sequence will be reported missing
422 if coverage[first] != coverage[second]:
423 errors.append('%s and %s should map to the same glyph.' % (
424 printable(first),
425 printable(second)))
426
427 for coverage in coverages:
428 for glyph in set(coverage.values()):
429 maps_to_glyph = [
430 seq for seq in coverage if coverage[seq] == glyph and not contains_pua(seq) ]
431 if len(maps_to_glyph) > 1:
432 # There are more than one sequences mapping to the same glyph. We
433 # need to make sure they were expected to be equivalent.
434 equivalent_seqs = set()
435 for seq in maps_to_glyph:
436 equivalent_seq = seq
437 while equivalent_seq in equivalent_emoji:
438 equivalent_seq = equivalent_emoji[equivalent_seq]
439 equivalent_seqs.add(equivalent_seq)
440 if len(equivalent_seqs) != 1:
441 errors.append('The sequences %s should not result in the same glyph %s' % (
442 printable(equivalent_seqs),
443 glyph))
444
445 assert not errors, '%d emoji font errors:\n%s\n%d emoji font coverage errors' % (len(errors), '\n'.join(errors), len(errors))
446
447
448 def check_emoji_defaults(default_emoji):
449 missing_text_chars = _emoji_properties['Emoji'] - default_emoji
450 for name, fallback_chain in _fallback_chains.items():
451 emoji_font_seen = False
452 for record in fallback_chain:
453 if 'Zsye' in record.scripts:
454 emoji_font_seen = True
455 # No need to check the emoji font
456 continue
457 # For later fonts, we only check them if they have a script
458 # defined, since the defined script may get them to a higher
459 # score even if they appear after the emoji font. However,
460 # we should skip checking the text symbols font, since
461 # symbol fonts should be able to override the emoji display
462 # style when 'Zsym' is explicitly specified by the user.
463 if emoji_font_seen and (not record.scripts or 'Zsym' in record.scripts):
464 continue
465
466 # Check default emoji-style characters
467 assert_font_supports_none_of_chars(record.font, default_emoji, name)
468
469 # Mark default text-style characters appearing in fonts above the emoji
470 # font as seen
471 if not emoji_font_seen:
472 missing_text_chars -= set(get_best_cmap(record.font))
473
474 # Noto does not have monochrome glyphs for Unicode 7.0 wingdings and
475 # webdings yet.
476 missing_text_chars -= _chars_by_age['7.0']
477 assert missing_text_chars == set(), (
478 'Text style version of some emoji characters are missing: ' +
479 repr(missing_text_chars))
480
481
482 # Setting reverse to true returns a dictionary that maps the values to sets of
483 # characters, useful for some binary properties. Otherwise, we get a
484 # dictionary that maps characters to the property values, assuming there's only
485 # one property in the file.
486 def parse_unicode_datafile(file_path, reverse=False):
487 if reverse:
488 output_dict = collections.defaultdict(set)
489 else:
490 output_dict = {}
491 with open(file_path) as datafile:
492 for line in datafile:
493 if '#' in line:
494 line = line[:line.index('#')]
495 line = line.strip()
496 if not line:
497 continue
498
499 chars, prop = line.split(';')[:2]
500 chars = chars.strip()
501 prop = prop.strip()
502
503 if ' ' in chars: # character sequence
504 sequence = [int(ch, 16) for ch in chars.split(' ')]
505 additions = [tuple(sequence)]
506 elif '..' in chars: # character range
507 char_start, char_end = chars.split('..')
508 char_start = int(char_start, 16)
509 char_end = int(char_end, 16)
510 additions = range(char_start, char_end+1)
511 else: # singe character
512 additions = [int(chars, 16)]
513 if reverse:
514 output_dict[prop].update(additions)
515 else:
516 for addition in additions:
517 assert addition not in output_dict
518 output_dict[addition] = prop
519 return output_dict
520
521
522 def parse_emoji_variants(file_path):
523 emoji_set = set()
524 text_set = set()
525 with open(file_path) as datafile:
526 for line in datafile:
527 if '#' in line:
528 line = line[:line.index('#')]
529 line = line.strip()
530 if not line:
531 continue
532 sequence, description, _ = line.split(';')
533 sequence = sequence.strip().split(' ')
534 base = int(sequence[0], 16)
535 vs = int(sequence[1], 16)
536 description = description.strip()
537 if description == 'text style':
538 text_set.add((base, vs))
539 elif description == 'emoji style':
540 emoji_set.add((base, vs))
541 return text_set, emoji_set
542
543
544 def parse_ucd(ucd_path):
545 global _emoji_properties, _chars_by_age
546 global _text_variation_sequences, _emoji_variation_sequences
547 global _emoji_sequences, _emoji_zwj_sequences
548 _emoji_properties = parse_unicode_datafile(
549 path.join(ucd_path, 'emoji-data.txt'), reverse=True)
550 emoji_properties_additions = parse_unicode_datafile(
551 path.join(ucd_path, 'additions', 'emoji-data.txt'), reverse=True)
552 for prop in emoji_properties_additions.keys():
553 _emoji_properties[prop].update(emoji_properties_additions[prop])
554
555 _chars_by_age = parse_unicode_datafile(
556 path.join(ucd_path, 'DerivedAge.txt'), reverse=True)
557 sequences = parse_emoji_variants(
558 path.join(ucd_path, 'emoji-variation-sequences.txt'))
559 _text_variation_sequences, _emoji_variation_sequences = sequences
560 _emoji_sequences = parse_unicode_datafile(
561 path.join(ucd_path, 'emoji-sequences.txt'))
562 _emoji_sequences.update(parse_unicode_datafile(
563 path.join(ucd_path, 'additions', 'emoji-sequences.txt')))
564 _emoji_zwj_sequences = parse_unicode_datafile(
565 path.join(ucd_path, 'emoji-zwj-sequences.txt'))
566 _emoji_zwj_sequences.update(parse_unicode_datafile(
567 path.join(ucd_path, 'additions', 'emoji-zwj-sequences.txt')))
568
569 exclusions = parse_unicode_datafile(path.join(ucd_path, 'additions', 'emoji-exclusions.txt'))
570 _emoji_sequences = remove_emoji_exclude(_emoji_sequences, exclusions)
571 _emoji_zwj_sequences = remove_emoji_exclude(_emoji_zwj_sequences, exclusions)
572 _emoji_variation_sequences = remove_emoji_variation_exclude(_emoji_variation_sequences, exclusions)
573 # Unicode 12.0 adds Basic_Emoji in emoji-sequences.txt. We ignore them here since we are already
574 # checking the emoji presentations with emoji-variation-sequences.txt.
575 # Please refer to http://unicode.org/reports/tr51/#def_basic_emoji_set .
576 _emoji_sequences = {k: v for k, v in _emoji_sequences.items() if not v == 'Basic_Emoji' }
577
578
579 def remove_emoji_variation_exclude(source, items):
580 return source.difference(items.keys())
581
582 def remove_emoji_exclude(source, items):
583 return {k: v for k, v in source.items() if k not in items}
584
585 def flag_sequence(territory_code):
586 return tuple(0x1F1E6 + ord(ch) - ord('A') for ch in territory_code)
587
588 EQUIVALENT_FLAGS = {
589 flag_sequence('BV'): flag_sequence('NO'),
590 flag_sequence('CP'): flag_sequence('FR'),
591 flag_sequence('HM'): flag_sequence('AU'),
592 flag_sequence('SJ'): flag_sequence('NO'),
593 flag_sequence('UM'): flag_sequence('US'),
594 }
595
596 COMBINING_KEYCAP = 0x20E3
597
598 LEGACY_ANDROID_EMOJI = {
599 0xFE4E5: flag_sequence('JP'),
600 0xFE4E6: flag_sequence('US'),
601 0xFE4E7: flag_sequence('FR'),
602 0xFE4E8: flag_sequence('DE'),
603 0xFE4E9: flag_sequence('IT'),
604 0xFE4EA: flag_sequence('GB'),
605 0xFE4EB: flag_sequence('ES'),
606 0xFE4EC: flag_sequence('RU'),
607 0xFE4ED: flag_sequence('CN'),
608 0xFE4EE: flag_sequence('KR'),
609 0xFE82C: (ord('#'), COMBINING_KEYCAP),
610 0xFE82E: (ord('1'), COMBINING_KEYCAP),
611 0xFE82F: (ord('2'), COMBINING_KEYCAP),
612 0xFE830: (ord('3'), COMBINING_KEYCAP),
613 0xFE831: (ord('4'), COMBINING_KEYCAP),
614 0xFE832: (ord('5'), COMBINING_KEYCAP),
615 0xFE833: (ord('6'), COMBINING_KEYCAP),
616 0xFE834: (ord('7'), COMBINING_KEYCAP),
617 0xFE835: (ord('8'), COMBINING_KEYCAP),
618 0xFE836: (ord('9'), COMBINING_KEYCAP),
619 0xFE837: (ord('0'), COMBINING_KEYCAP),
620 }
621
622 # This is used to define the emoji that should have the same glyph.
623 # i.e. previously we had gender based Kiss (0x1F48F), which had the same glyph
624 # with Kiss: Woman, Man (0x1F469, 0x200D, 0x2764, 0x200D, 0x1F48B, 0x200D, 0x1F468)
625 # in that case a valid row would be:
626 # (0x1F469, 0x200D, 0x2764, 0x200D, 0x1F48B, 0x200D, 0x1F468): 0x1F48F,
627 ZWJ_IDENTICALS = {
628 }
629
630 SAME_FLAG_MAPPINGS = [
631 # Diego Garcia and British Indian Ocean Territory
632 ((0x1F1EE, 0x1F1F4), (0x1F1E9, 0x1F1EC)),
633 # St. Martin and France
634 ((0x1F1F2, 0x1F1EB), (0x1F1EB, 0x1F1F7)),
635 # Spain and Ceuta & Melilla
636 ((0x1F1EA, 0x1F1F8), (0x1F1EA, 0x1F1E6)),
637 ]
638
639 ZWJ = 0x200D
640
641 EMPTY_FLAG_SEQUENCE = (0x1F3F4, 0xE007F)
642
643 def is_fitzpatrick_modifier(cp):
644 return 0x1F3FB <= cp <= 0x1F3FF
645
646
647 def reverse_emoji(seq):
648 rev = list(reversed(seq))
649 # if there are fitzpatrick modifiers in the sequence, keep them after
650 # the emoji they modify
651 for i in range(1, len(rev)):
652 if is_fitzpatrick_modifier(rev[i-1]):
653 rev[i], rev[i-1] = rev[i-1], rev[i]
654 return tuple(rev)
655
656
657 def compute_expected_emoji():
658 equivalent_emoji = {}
659 sequence_pieces = set()
660 all_sequences = set()
661 all_sequences.update(_emoji_variation_sequences)
662
663 # add zwj sequences not in the current emoji-zwj-sequences.txt
664 adjusted_emoji_zwj_sequences = dict(_emoji_zwj_sequences)
665 adjusted_emoji_zwj_sequences.update(_emoji_zwj_sequences)
666
667 # Add empty flag tag sequence that is supported as fallback
668 _emoji_sequences[EMPTY_FLAG_SEQUENCE] = 'Emoji_Tag_Sequence'
669
670 for sequence in _emoji_sequences.keys():
671 sequence = tuple(ch for ch in sequence if ch != EMOJI_VS)
672 all_sequences.add(sequence)
673 sequence_pieces.update(sequence)
674
675 for sequence in adjusted_emoji_zwj_sequences.keys():
676 sequence = tuple(ch for ch in sequence if ch != EMOJI_VS)
677 all_sequences.add(sequence)
678 sequence_pieces.update(sequence)
679
680 for first, second in SAME_FLAG_MAPPINGS:
681 equivalent_emoji[first] = second
682
683 # Add all tag characters used in flags
684 sequence_pieces.update(range(0xE0030, 0xE0039 + 1))
685 sequence_pieces.update(range(0xE0061, 0xE007A + 1))
686
687 all_emoji = (
688 _emoji_properties['Emoji'] |
689 all_sequences |
690 sequence_pieces |
691 set(LEGACY_ANDROID_EMOJI.keys()))
692 default_emoji = (
693 _emoji_properties['Emoji_Presentation'] |
694 all_sequences |
695 set(LEGACY_ANDROID_EMOJI.keys()))
696
697 equivalent_emoji.update(EQUIVALENT_FLAGS)
698 equivalent_emoji.update(LEGACY_ANDROID_EMOJI)
699 equivalent_emoji.update(ZWJ_IDENTICALS)
700
701 for seq in _emoji_variation_sequences:
702 equivalent_emoji[seq] = seq[0]
703
704 return all_emoji, default_emoji, equivalent_emoji
705
706
707 def check_compact_only_fallback():
708 for name, fallback_chain in _fallback_chains.items():
709 for record in fallback_chain:
710 if record.variant == 'compact':
711 same_script_elegants = [x for x in fallback_chain
712 if x.scripts == record.scripts and x.variant == 'elegant']
713 assert same_script_elegants, (
714 '%s must be in elegant of %s as fallback of "%s" too' % (
715 record.font, record.scripts, record.fallback_for),)
716
717
718 def check_vertical_metrics():
719 for record in _all_fonts:
720 if record.name in ['sans-serif', 'sans-serif-condensed']:
721 font = open_font(record.font)
722 assert font['head'].yMax == 2163 and font['head'].yMin == -555, (
723 'yMax and yMin of %s do not match expected values.' % (
724 record.font,))
725
726 if record.name in ['sans-serif', 'sans-serif-condensed',
727 'serif', 'monospace']:
728 font = open_font(record.font)
729 assert (font['hhea'].ascent == 1900 and
730 font['hhea'].descent == -500), (
731 'ascent and descent of %s do not match expected '
732 'values.' % (record.font,))
733
734
735 def check_cjk_punctuation():
736 cjk_scripts = {'Hans', 'Hant', 'Jpan', 'Kore'}
737 cjk_punctuation = range(0x3000, 0x301F + 1)
738 for name, fallback_chain in _fallback_chains.items():
739 for record in fallback_chain:
740 if record.scripts.intersection(cjk_scripts):
741 # CJK font seen. Stop checking the rest of the fonts.
742 break
743 assert_font_supports_none_of_chars(record.font, cjk_punctuation, name)
744
745 def getPostScriptName(font):
746 font_file, index = font
747 font_path = path.join(_fonts_dir, font_file)
748 if index is not None:
749 # Use the first font file in the collection for resolving post script name.
750 ttf = ttLib.TTFont(font_path, fontNumber=0)
751 else:
752 ttf = ttLib.TTFont(font_path)
753
754 nameTable = ttf['name']
755 for name in nameTable.names:
756 if (name.nameID == 6 and name.platformID == 3 and name.platEncID == 1
757 and name.langID == 0x0409):
758 return str(name)
759
760 def check_canonical_name():
761 for record in _all_fonts:
762 file_name, index = record.font
763
764 psName = getPostScriptName(record.font)
765 if record.psName:
766 # If fonts element has postScriptName attribute, it should match with the PostScript
767 # name in the name table.
768 assert psName == record.psName, ('postScriptName attribute %s should match with %s' % (
769 record.psName, psName))
770 else:
771 # If fonts element doesn't have postScriptName attribute, the file name should match
772 # with the PostScript name in the name table.
773 assert psName == file_name[:-4], ('file name %s should match with %s' % (
774 file_name, psName))
775
776
777 def main():
778 global _fonts_dir
779 target_out = sys.argv[1]
780 _fonts_dir = path.join(target_out, 'fonts')
781
782 fonts_xml_path = path.join(target_out, 'etc', 'fonts.xml')
783
784 parse_fonts_xml(fonts_xml_path)
785
786 check_compact_only_fallback()
787
788 check_vertical_metrics()
789
790 hyphens_dir = path.join(target_out, 'usr', 'hyphen-data')
791 check_hyphens(hyphens_dir)
792
793 check_cjk_punctuation()
794
795 check_canonical_name()
796
797 check_emoji = sys.argv[2]
798 if check_emoji == 'true':
799 ucd_path = sys.argv[3]
800 parse_ucd(ucd_path)
801 all_emoji, default_emoji, equivalent_emoji = compute_expected_emoji()
802 check_emoji_not_compat(all_emoji, equivalent_emoji)
803 check_emoji_coverage(all_emoji, equivalent_emoji)
804 check_emoji_defaults(default_emoji)
805
806
807 if __name__ == '__main__':
808 main()