Debian Codegraph @

tools/test/unicode_data.py

raw
1 #!/usr/bin/python
2
3 from __future__ import print_function
4 __license__ = """
5 This file is part of GNU FreeFont.
6
7 GNU FreeFont is free software: you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free Software
9 Foundation, either version 3 of the License, or (at your option) any later
10 version.
11
12 GNU FreeFont is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License along with
17 GNU FreeFont. If not, see <http://www.gnu.org/licenses/>.
18 """
19 __author__ = "Stevan White"
20 __email__ = "[email protected]"
21 __copyright__ = "Copyright 2017, 2018 Stevan White"
22 __date__ = "$Date: $"
23 __version__ = "$Revision: 1.5 $"
24
25 __doc__ = """
26 Makes a dictionaries of characters in a local text file
27 UnicodeData.txt
28 obtainable from unicode.org, which has fields:
29 "codept", "uname", "cat", "comb", "bidi", "dcmp",
30 "deci", "digi", "num", "mir", "U1", "cmmt", "uppr", "lowr", "titl"
31 Provides lookup methods for some of these.
32
33 Note the Python unicodedata module should do all of this and more:
34 https://docs.python.org/2/library/unicodedata.html
35 However, the Python 2.7 implementation covers only Unicode 5.1, and at the
36 time of this writing, the Python 3 implementation covers only to Unicode 8.
37 I wonder why so old?
38 """
39
40 import re
41 from sys import argv, exit, stdout as out, stderr as err
42
43 def _explain_error_and_quit( e='' ):
44 if e:
45 print( 'Error {%s}'.format( e ), file=err )
46 print( 'Usage', file=err )
47 print( ' unicodedata [filepath]', file=err )
48 exit( 1 )
49
50 _charlineRe = '^([A-F0-9]*);([^;]*);([^;]*);([^;]*);([^;]*);([^;]*);([^;]*);([^;]*);([^;]*);([^;]*);([^;]*);([^;]*);([^;]*);([^;]*);'
51
52 _charline = re.compile( _charlineRe )
53
54 fields = ( "codept", "uname", "cat", "comb", "bidi", "dcmp",
55 "deci", "digi", "num", "mir", "U1", "cmmt", "uppr", "lowr", "titl" )
56
57 class character:
58 def __init__( self, *arglist ):
59 self.vals = zip( fields, arglist )
60 for i in range( len( fields ) ):
61 self.__dict__[fields[i]] = arglist[i]
62 self.unicodeval = int( self.codept, 16 )
63 self.name = self.uname
64
65 def __str__( self ):
66 return "U+{0:s} {1:s}".format( self.codept, self.name )
67
68 class controlchar(character):
69 def __init__( self, *arglist ):
70 character.__init__(self, *arglist )
71 self.name = self.U1
72
73 class rangestartchar(character):
74 def __init__( self, *arglist ):
75 character.__init__(self, *arglist )
76 self.name = self.uname[1:-8]
77
78 class rangeendchar(character):
79 def __init__( self, *arglist ):
80 character.__init__(self, *arglist )
81 self.name = self.uname[1:-7]
82
83 def makeCharacter( *arglist ):
84 codept = arglist[ 0 ]
85 name = arglist[ 1 ]
86
87 if name == "<control>":
88 return controlchar( *arglist )
89 elif name.endswith(", First>"):
90 return rangestartchar( *arglist )
91 elif name.endswith(", Last>"):
92 return rangeendchar( *arglist )
93 else:
94 return character( *arglist )
95
96 def build_charsByUnicode( f ):
97 charsByUnicode = {}
98 for line in f:
99 m = line.split( ';' )
100
101 if len( m ) < 14:
102 print( str( len( m ) ), file=err )
103 print( "didn't find all fields in line:\n%s"
104 % (line), file=err )
105 else:
106 c = makeCharacter( *m )
107 charsByUnicode[c.unicodeval] = c
108 return charsByUnicode
109
110 class characters:
111 def __init__( self ):
112 self._charsByUnicode = None
113
114 def _build( self, filename='UnicodeData.txt' ):
115 try:
116 f = open( filename )
117 self._charsByUnicode = build_charsByUnicode( f )
118 except:
119 print( 'UnicodeData.txt from latest Unicode specs '
120 'should be in current directory.', file=err )
121 exit( 1 )
122
123 def byUnicode( self ):
124 if not self._charsByUnicode:
125 self._build()
126 return self._charsByUnicode
127
128 _characters = characters()
129
130 def _char_arg_OK( character ):
131 if isinstance( character, unicode ):
132 if len( character ) == 1:
133 return True
134 else:
135 raise Exception( "expected string of length 1, got "
136 + str( len( character ) ) )
137 else:
138 raise Exception( "expected unicode string of length 1, got "
139 + str( type( character ) ) )
140 return False
141
142 def combining( character ):
143 if _char_arg_OK( character ):
144 charsByUnicode = _characters.byUnicode()
145 cp = ord( character )
146 if cp in charsByUnicode:
147 return int( charsByUnicode[cp].comb )
148 return 0
149
150 _comb_char_cls = ( 'Mc', 'Mn', 'Me' )
151
152 def is_combining_character( character ):
153 """ See Uncode Standard ch 3 Conformance, sect 3.6 Combination.
154 """
155 if _char_arg_OK( character ):
156 charsByUnicode = _characters.byUnicode()
157 cp = ord( character )
158 if cp in charsByUnicode:
159 return ( ( charsByUnicode[cp].cat in _comb_char_cls )
160 or ( combining( character ) > 0 ) )
161 return False
162
163 def name( character ):
164 if _char_arg_OK( character ):
165 charsByUnicode = _characters.byUnicode()
166 cp = ord( character )
167 if cp in charsByUnicode:
168 return charsByUnicode[cp].name
169 raise ValueError( "Character not found." )
170
171 def category( character ):
172 if _char_arg_OK( character ):
173 charsByUnicode = _characters.byUnicode()
174 cp = ord( character )
175 if cp in charsByUnicode:
176 return charsByUnicode[cp].cat
177 raise ValueError( "Character not found." )
178
179 def lookup( name ):
180 if isinstance( name, str ) and len( str ) > 0:
181 charsByName = _characters.byName()
182 if cp in charsByName:
183 return charsName[cp]
184 else:
185 raise ValueError( "Name not found in Unicode "
186 + name )
187 raise Exception( "Expected nonempty string for name." )
188
189 """
190 if err.isatty():
191 filename = 'UnicodeData.txt'
192
193 if len( argv ) == 2:
194 filename = argv[1]
195 if len( argv ) > 2:
196 _explain_error_and_quit()
197 initialize( filename )
198
199 for cp in sorted( _charsByUnicode ):
200 #print( str( charsByUnicode[cp] ) )
201 c = _charsByUnicode[cp]
202 print( str( c ) )
203 #out.write( "\tcategory=" + c.cat )
204 #if c.uppr:
205 # out.write( "\tuc_is=" + c.uppr )
206 #if c.lowr:
207 # out.write( "\tlc_is=" + c.lowr )
208 #if c.cat == "Mc":
209 # out.write( "\tis_combining(" + c.cat + ")" )
210 if c.comb != '0':
211 out.write( "\tcombining_type(" + c.comb + ")" )
212 out.write( "\n" )
213
214 #out.write( str( len( charsByUnicode ) ) + "\n" )
215 """