Imported Upstream version 2.6.7
[platform/upstream/harfbuzz.git] / src / gen-arabic-table.py
1 #!/usr/bin/env python3
2
3 """usage: ./gen-arabic-table.py ArabicShaping.txt UnicodeData.txt Blocks.txt
4
5 Input files:
6 * https://unicode.org/Public/UCD/latest/ucd/ArabicShaping.txt
7 * https://unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
8 * https://unicode.org/Public/UCD/latest/ucd/Blocks.txt
9 """
10
11 import os.path, sys
12
13 if len (sys.argv) != 4:
14         sys.exit (__doc__)
15
16 files = [open (x, encoding='utf-8') for x in sys.argv[1:]]
17
18 headers = [[files[0].readline (), files[0].readline ()], [files[2].readline (), files[2].readline ()]]
19 headers.append (["UnicodeData.txt does not have a header."])
20 while files[0].readline ().find ('##################') < 0:
21         pass
22
23 blocks = {}
24 def read_blocks(f):
25         global blocks
26         for line in f:
27
28                 j = line.find ('#')
29                 if j >= 0:
30                         line = line[:j]
31
32                 fields = [x.strip () for x in line.split (';')]
33                 if len (fields) == 1:
34                         continue
35
36                 uu = fields[0].split ('..')
37                 start = int (uu[0], 16)
38                 if len (uu) == 1:
39                         end = start
40                 else:
41                         end = int (uu[1], 16)
42
43                 t = fields[1]
44
45                 for u in range (start, end + 1):
46                         blocks[u] = t
47
48 def print_joining_table(f):
49
50         values = {}
51         for line in f:
52
53                 if line[0] == '#':
54                         continue
55
56                 fields = [x.strip () for x in line.split (';')]
57                 if len (fields) == 1:
58                         continue
59
60                 u = int (fields[0], 16)
61
62                 if fields[3] in ["ALAPH", "DALATH RISH"]:
63                         value = "JOINING_GROUP_" + fields[3].replace(' ', '_')
64                 else:
65                         value = "JOINING_TYPE_" + fields[2]
66                 values[u] = value
67
68         short_value = {}
69         for value in sorted (set ([v for v in values.values ()] + ['JOINING_TYPE_X'])):
70                 short = ''.join(x[0] for x in value.split('_')[2:])
71                 assert short not in short_value.values()
72                 short_value[value] = short
73
74         print ()
75         for value,short in short_value.items():
76                 print ("#define %s      %s" % (short, value))
77
78         uu = sorted(values.keys())
79         num = len(values)
80         all_blocks = set([blocks[u] for u in uu])
81
82         last = -100000
83         ranges = []
84         for u in uu:
85                 if u - last <= 1+16*5:
86                         ranges[-1][-1] = u
87                 else:
88                         ranges.append([u,u])
89                 last = u
90
91         print ()
92         print ("static const uint8_t joining_table[] =")
93         print ("{")
94         last_block = None
95         offset = 0
96         for start,end in ranges:
97
98                 print ()
99                 print ("#define joining_offset_0x%04xu %d" % (start, offset))
100
101                 for u in range(start, end+1):
102
103                         block = blocks.get(u, last_block)
104                         value = values.get(u, "JOINING_TYPE_X")
105
106                         if block != last_block or u == start:
107                                 if u != start:
108                                         print ()
109                                 if block in all_blocks:
110                                         print ("\n  /* %s */" % block)
111                                 else:
112                                         print ("\n  /* FILLER */")
113                                 last_block = block
114                                 if u % 32 != 0:
115                                         print ()
116                                         print ("  /* %04X */" % (u//32*32), "  " * (u % 32), end="")
117
118                         if u % 32 == 0:
119                                 print ()
120                                 print ("  /* %04X */ " % u, end="")
121                         print ("%s," % short_value[value], end="")
122                 print ()
123
124                 offset += end - start + 1
125         print ()
126         occupancy = num * 100. / offset
127         print ("}; /* Table items: %d; occupancy: %d%% */" % (offset, occupancy))
128         print ()
129
130         page_bits = 12
131         print ()
132         print ("static unsigned int")
133         print ("joining_type (hb_codepoint_t u)")
134         print ("{")
135         print ("  switch (u >> %d)" % page_bits)
136         print ("  {")
137         pages = set([u>>page_bits for u in [s for s,e in ranges]+[e for s,e in ranges]])
138         for p in sorted(pages):
139                 print ("    case 0x%0Xu:" % p)
140                 for (start,end) in ranges:
141                         if p not in [start>>page_bits, end>>page_bits]: continue
142                         offset = "joining_offset_0x%04xu" % start
143                         print ("      if (hb_in_range<hb_codepoint_t> (u, 0x%04Xu, 0x%04Xu)) return joining_table[u - 0x%04Xu + %s];" % (start, end, start, offset))
144                 print ("      break;")
145                 print ("")
146         print ("    default:")
147         print ("      break;")
148         print ("  }")
149         print ("  return X;")
150         print ("}")
151         print ()
152         for value,short in short_value.items():
153                 print ("#undef %s" % (short))
154         print ()
155
156 def print_shaping_table(f):
157
158         shapes = {}
159         ligatures = {}
160         names = {}
161         for line in f:
162
163                 fields = [x.strip () for x in line.split (';')]
164                 if fields[5][0:1] != '<':
165                         continue
166
167                 items = fields[5].split (' ')
168                 shape, items = items[0][1:-1], tuple (int (x, 16) for x in items[1:])
169
170                 if not shape in ['initial', 'medial', 'isolated', 'final']:
171                         continue
172
173                 c = int (fields[0], 16)
174                 if len (items) != 1:
175                         # We only care about lam-alef ligatures
176                         if len (items) != 2 or items[0] != 0x0644 or items[1] not in [0x0622, 0x0623, 0x0625, 0x0627]:
177                                 continue
178
179                         # Save ligature
180                         names[c] = fields[1]
181                         if items not in ligatures:
182                                 ligatures[items] = {}
183                         ligatures[items][shape] = c
184                         pass
185                 else:
186                         # Save shape
187                         if items[0] not in names:
188                                 names[items[0]] = fields[1]
189                         else:
190                                 names[items[0]] = os.path.commonprefix ([names[items[0]], fields[1]]).strip ()
191                         if items[0] not in shapes:
192                                 shapes[items[0]] = {}
193                         shapes[items[0]][shape] = c
194
195         print ()
196         print ("static const uint16_t shaping_table[][4] =")
197         print ("{")
198
199         keys = shapes.keys ()
200         min_u, max_u = min (keys), max (keys)
201         for u in range (min_u, max_u + 1):
202                 s = [shapes[u][shape] if u in shapes and shape in shapes[u] else 0
203                      for shape in  ['initial', 'medial', 'final', 'isolated']]
204                 value = ', '.join ("0x%04Xu" % c for c in s)
205                 print ("  {%s}, /* U+%04X %s */" % (value, u, names[u] if u in names else ""))
206
207         print ("};")
208         print ()
209         print ("#define SHAPING_TABLE_FIRST     0x%04Xu" % min_u)
210         print ("#define SHAPING_TABLE_LAST      0x%04Xu" % max_u)
211         print ()
212
213         ligas = {}
214         for pair in ligatures.keys ():
215                 for shape in ligatures[pair]:
216                         c = ligatures[pair][shape]
217                         if shape == 'isolated':
218                                 liga = (shapes[pair[0]]['initial'], shapes[pair[1]]['final'])
219                         elif shape == 'final':
220                                 liga = (shapes[pair[0]]['medial'], shapes[pair[1]]['final'])
221                         else:
222                                 raise Exception ("Unexpected shape", shape)
223                         if liga[0] not in ligas:
224                                 ligas[liga[0]] = []
225                         ligas[liga[0]].append ((liga[1], c))
226         max_i = max (len (ligas[l]) for l in ligas)
227         print ()
228         print ("static const struct ligature_set_t {")
229         print (" uint16_t first;")
230         print (" struct ligature_pairs_t {")
231         print ("   uint16_t second;")
232         print ("   uint16_t ligature;")
233         print (" } ligatures[%d];" % max_i)
234         print ("} ligature_table[] =")
235         print ("{")
236         for first in sorted (ligas.keys ()):
237
238                 print ("  { 0x%04Xu, {" % (first))
239                 for liga in ligas[first]:
240                         print ("    { 0x%04Xu, 0x%04Xu }, /* %s */" % (liga[0], liga[1], names[liga[1]]))
241                 print ("  }},")
242
243         print ("};")
244         print ()
245
246
247
248 print ("/* == Start of generated table == */")
249 print ("/*")
250 print (" * The following table is generated by running:")
251 print (" *")
252 print (" *   ./gen-arabic-table.py ArabicShaping.txt UnicodeData.txt Blocks.txt")
253 print (" *")
254 print (" * on files with these headers:")
255 print (" *")
256 for h in headers:
257         for l in h:
258                 print (" * %s" % (l.strip()))
259 print (" */")
260 print ()
261 print ("#ifndef HB_OT_SHAPE_COMPLEX_ARABIC_TABLE_HH")
262 print ("#define HB_OT_SHAPE_COMPLEX_ARABIC_TABLE_HH")
263 print ()
264
265 read_blocks (files[2])
266 print_joining_table (files[0])
267 print_shaping_table (files[1])
268
269 print ()
270 print ("#endif /* HB_OT_SHAPE_COMPLEX_ARABIC_TABLE_HH */")
271 print ()
272 print ("/* == End of generated table == */")