Debian Codegraph @

subprojects/fontconfig/fc-case/fc-case.py

raw
1 #!/usr/bin/env python3
2 #
3 # fontconfig/fc-case/fc-case.py
4 #
5 # Copyright © 2004 Keith Packard
6 # Copyright © 2019 Tim-Philipp Müller
7 #
8 # Permission to use, copy, modify, distribute, and sell this software and its
9 # documentation for any purpose is hereby granted without fee, provided that
10 # the above copyright notice appear in all copies and that both that
11 # copyright notice and this permission notice appear in supporting
12 # documentation, and that the name of the author(s) not be used in
13 # advertising or publicity pertaining to distribution of the software without
14 # specific, written prior permission. The authors make no
15 # representations about the suitability of this software for any purpose. It
16 # is provided "as is" without express or implied warranty.
17 #
18 # THE AUTHOR(S) DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
19 # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
20 # EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY SPECIAL, INDIRECT OR
21 # CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
22 # DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
23 # TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
24 # PERFORMANCE OF THIS SOFTWARE.
25
26 from enum import Enum
27 import argparse
28 import string
29 import sys
30
31
32 class CaseFoldClass(Enum):
33 COMMON = 1
34 FULL = 2
35 SIMPLE = 3
36 TURKIC = 4
37
38
39 class CaseFoldMethod(Enum):
40 RANGE = 0
41 EVEN_ODD = 1
42 FULL = 2
43
44
45 caseFoldClassMap = {
46 'C': CaseFoldClass.COMMON,
47 'F': CaseFoldClass.FULL,
48 'S': CaseFoldClass.SIMPLE,
49 'T': CaseFoldClass.TURKIC
50 }
51
52 folds = []
53
54 def ucs4_to_utf8(ucs4):
55 utf8_rep = []
56
57 if ucs4 < 0x80:
58 utf8_rep.append(ucs4)
59 bits = -6
60 elif ucs4 < 0x800:
61 utf8_rep.append(((ucs4 >> 6) & 0x1F) | 0xC0)
62 bits = 0
63 elif ucs4 < 0x10000:
64 utf8_rep.append(((ucs4 >> 12) & 0x0F) | 0xE0)
65 bits = 6
66 elif ucs4 < 0x200000:
67 utf8_rep.append(((ucs4 >> 18) & 0x07) | 0xF0)
68 bits = 12
69 elif ucs4 < 0x4000000:
70 utf8_rep.append(((ucs4 >> 24) & 0x03) | 0xF8)
71 bits = 18
72 elif ucs4 < 0x80000000:
73 utf8_rep.append(((ucs4 >> 30) & 0x01) | 0xFC)
74 bits = 24
75 else:
76 return []
77
78 while bits >= 0:
79 utf8_rep.append(((ucs4 >> bits) & 0x3F) | 0x80)
80 bits -= 6
81
82 return utf8_rep
83
84
85 def utf8_size(ucs4):
86 return len(ucs4_to_utf8(ucs4))
87
88
89 case_fold_method_name_map = {
90 CaseFoldMethod.RANGE: 'FC_CASE_FOLD_RANGE,',
91 CaseFoldMethod.EVEN_ODD: 'FC_CASE_FOLD_EVEN_ODD,',
92 CaseFoldMethod.FULL: 'FC_CASE_FOLD_FULL,',
93 }
94
95 if __name__=='__main__':
96 parser = argparse.ArgumentParser()
97 parser.add_argument('case_folding_file')
98 parser.add_argument('--template', dest='template_file', default=None)
99 parser.add_argument('--output', dest='output_file', default=None)
100
101 args = parser.parse_args()
102
103 minFoldChar = None
104 maxFoldChar = None
105 fold = None
106
107 foldChars = []
108 maxFoldChars = 0
109
110 maxExpand = 0
111
112 # Read the standard Unicode CaseFolding.txt file
113 with open(args.case_folding_file, 'r', encoding='utf-8') as casefile:
114 for cnt, line in enumerate(casefile):
115 if not line or not line[0] in string.hexdigits:
116 continue
117
118 # print('Line {}: {}'.format(cnt, line.strip()))
119
120 tokens = line.split('; ')
121
122 if len(tokens) < 3:
123 print('Not enough tokens in line {}'.format(cnt),
124 file=sys.stderr)
125 sys.exit(1)
126
127 # Get upper case value
128 upper = int(tokens.pop(0), 16)
129
130 # Get class
131 cfclass = caseFoldClassMap[tokens.pop(0)]
132
133 # Get list of result characters
134 lower = list(map(lambda s: int(s, 16), tokens.pop(0).split()))
135
136 # print('\t----> {:04X} {} {}'.format(upper, cfclass, lower))
137
138 if not minFoldChar:
139 minFoldChar = upper
140
141 maxFoldChar = upper
142
143 if cfclass in [CaseFoldClass.COMMON, CaseFoldClass.FULL]:
144 if len(lower) == 1:
145 # foldExtends
146 if fold and fold['method'] == CaseFoldMethod.RANGE:
147 foldExtends = (lower[0] - upper) == fold['offset'] and upper == fold['upper'] + fold['count']
148 elif fold and fold['method'] == CaseFoldMethod.EVEN_ODD:
149 foldExtends = (lower[0] - upper) == 1 and upper == (fold['upper'] + fold['count'] + 1)
150 else:
151 foldExtends = False
152
153 if foldExtends:
154 # This modifies the last fold item in the array too
155 fold['count'] = upper - fold['upper'] + 1
156 else:
157 fold = {}
158 fold['upper'] = upper
159 fold['offset'] = lower[0] - upper
160 if fold['offset'] == 1:
161 fold['method'] = CaseFoldMethod.EVEN_ODD
162 else:
163 fold['method'] = CaseFoldMethod.RANGE
164 fold['count'] = 1
165 folds.append(fold)
166 expand = utf8_size(lower[0]) - utf8_size(upper)
167 else:
168 fold = {}
169 fold['upper'] = upper
170 fold['method'] = CaseFoldMethod.FULL
171 fold['offset'] = len(foldChars)
172
173 # add chars
174 for c in lower:
175 utf8_rep = ucs4_to_utf8(c)
176 # print('{} -> {}'.format(c,utf8_rep))
177 for utf8_char in utf8_rep:
178 foldChars.append(utf8_char)
179
180 fold['count'] = len(foldChars) - fold['offset']
181 folds.append(fold)
182
183 if fold['count'] > maxFoldChars:
184 maxFoldChars = fold['count']
185
186 expand = fold['count'] - utf8_size(upper)
187 if expand > maxExpand:
188 maxExpand = expand
189
190 # Open output file
191 if args.output_file:
192 sys.stdout = open(args.output_file, 'w', encoding='utf-8')
193
194 print('/*')
195 print(' * This file was generated against CaseFolding.txt from'
196 ' Unicode.org.')
197 print(' * All the data in array is a part of them and licensed'
198 ' under a terms of use:')
199 print(' * https://www.unicode.org/terms_of_use.html')
200 print(' */')
201 print('')
202 # Dump these tables
203 print('#define FC_NUM_CASE_FOLD\t{}'.format(len(folds)))
204 print('#define FC_NUM_CASE_FOLD_CHARS\t{}'.format(len(foldChars)))
205 print('#define FC_MAX_CASE_FOLD_CHARS\t{}'.format(maxFoldChars))
206 print('#define FC_MAX_CASE_FOLD_EXPAND\t{}'.format(maxExpand))
207 print('#define FC_MIN_FOLD_CHAR\t0x{:08x}'.format(minFoldChar))
208 print('#define FC_MAX_FOLD_CHAR\t0x{:08x}'.format(maxFoldChar))
209 print('')
210
211 # Dump out ranges
212 print('static const FcCaseFold fcCaseFold[FC_NUM_CASE_FOLD] = {')
213 for f in folds:
214 short_offset = f['offset']
215 if short_offset < -32367:
216 short_offset += 65536
217 if short_offset > 32368:
218 short_offset -= 65536
219 print(f' {{ 0x{f["upper"]:08x}, '
220 f'{case_fold_method_name_map[f["method"]]:22s} '
221 f'0x{f["count"]:04x}, {short_offset:6d} }},')
222 print('};\n')
223
224 # Dump out "other" values
225 print('static const FcChar8\tfcCaseFoldChars[FC_NUM_CASE_FOLD_CHARS] = {')
226 for n, c in enumerate(foldChars):
227 if n == len(foldChars) - 1:
228 end = ''
229 elif n % 16 == 15:
230 end = ',\n'
231 else:
232 end = ','
233 print('0x{:02x}'.format(c), end=end)
234 print('\n};')
235
236 sys.stdout.flush()