1# This Source Code Form is subject to the terms of the Mozilla Public
2# License, v. 2.0. If a copy of the MPL was not distributed with this file,
3# You can obtain one at http://mozilla.org/MPL/2.0/.
4
5from __future__ import absolute_import
6import os.path
7import re
8import sys
9
10f = open(sys.argv[1] if len(sys.argv) > 1 else 'StandardizedVariants.txt')
11
12line = f.readline()
13m = re.compile('^# (StandardizedVariants(-\d+(\.\d+)*)?\.txt)').search(line)
14fileversion = m.group(1)
15vsdict = {}
16r = re.compile('^([0-9A-F]{4,6}) (FE0[0-9A-F]); CJK COMPATIBILITY IDEOGRAPH-([0-9A-F]{4,6});')
17while True:
18    line = f.readline()
19    if not line:
20        break
21    if 'CJK COMPATIBILITY IDEOGRAPH-' not in line:
22        continue
23
24    m = r.search(line)
25    unified = int(m.group(1), 16)
26    vs = int(m.group(2), 16)
27    compat = int(m.group(3), 16)
28
29    if vs not in vsdict:
30        vsdict[vs] = {}
31    vsdict[vs][unified] = compat
32
33f.close
34
35offsets = []
36length = 10 + 11 * len(vsdict)
37for (k, mappings) in sorted(vsdict.items()):
38    offsets.append(length)
39    length += 4 + 5 * len(mappings)
40
41f = open(sys.argv[2] if len(sys.argv) > 2 else 'CJKCompatSVS.cpp', 'wb')
42f.write("""// Generated by %s. Do not edit.
43
44#include <stdint.h>
45
46#define U16(v) (((v) >> 8) & 0xFF), ((v) & 0xFF)
47#define U24(v) (((v) >> 16) & 0xFF), (((v) >> 8) & 0xFF), ((v) & 0xFF)
48#define U32(v) (((v) >> 24) & 0xFF), (((v) >> 16) & 0xFF), (((v) >> 8) & 0xFF), ((v) & 0xFF)
49#define GLYPH(v) U16(v >= 0x2F800 ? (v) - (0x2F800 - 0xFB00) : (v))
50
51// Fallback mappings for CJK Compatibility Ideographs Standardized Variants
52// taken from %s.
53// Using OpenType format 14 cmap subtable structure to reuse the lookup code
54// for fonts. The glyphID field is used to store the corresponding codepoints
55// CJK Compatibility Ideographs. To fit codepoints into the 16-bit glyphID
56// field, CJK Compatibility Ideographs Supplement (U+2F800..U+2FA1F) will be
57// mapped to 0xFB00..0xFD1F.
58extern const uint8_t sCJKCompatSVSTable[] = {
59""" % (os.path.basename(sys.argv[0]), fileversion))
60f.write('  U16(14), // format\n')
61f.write('  U32(%d), // length\n' % length)
62f.write('  U32(%d), // numVarSelectorRecords\n' % len(vsdict))
63for i, k in enumerate(sorted(vsdict.keys())):
64    f.write('    U24(0x%04X), U32(0), U32(%d), // varSelectorRecord[%d]\n' % (k, offsets[i], i))
65for (k, mappings) in sorted(vsdict.items()):
66    f.write('  // 0x%04X\n' % k)
67    f.write('  U32(%d), // numUVSMappings\n' % len(mappings))
68    for (unified, compat) in sorted(mappings.items()):
69        f.write('    U24(0x%04X), GLYPH(0x%04X),\n' % (unified, compat))
70f.write("""};
71
72#undef U16
73#undef U24
74#undef U32
75#undef GLYPH
76
77static_assert(sizeof sCJKCompatSVSTable == %d, "Table generator has a bug.");
78""" % length)
79