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