Set write encoding on open rather than encoding each line
[xorg/xkbtools] / keysymdata.py
1 #!/usr/bin/env python
2
3 from __future__ import with_statement
4
5 import os
6 import re
7
8 _re = re.compile('^#define XK_([a-zA-Z_0-9]+)\s+0x([0-9A-Fa-f]+)\s*/\*\s*U\+([0-9A-Fa-f]{4,6}) (.*)\s+\*/\s*$')
9
10 # TODO provide defaults from current X.org
11 _uni2name = {}
12 _name2uni = {}
13 _keysym = {}
14
15 _hfile = os.path.join('X11', 'keysymdef.h')
16
17 _include = None
18
19 # TODO include dirs: should be portable
20 _candidates = ['/usr/local/include', '/usr/include', '/usr/share/include']
21 for dir in _candidates:
22     _include = os.path.join(dir, _hfile)
23     if os.path.exists(_include):
24         break
25
26 if _include is not None:
27     try:
28         with open(_include, 'r') as file:
29             for line in file:
30                 match = _re.match(line.strip())
31                 if match:
32                     name = match.group(1)
33                     code = match.group(2)
34                     uni = match.group(3).lower()
35                     uniname = match.group(4)
36                     _uni2name[uni] = name # FIXME what to do with duplicates?
37                     _name2uni[name] = uni
38                     _keysym[name] = code
39     except IOError:
40         pass
41
42 def name(uni):
43     if uni is None:
44         return "NoSymbol"
45     key = None
46     if isinstance(uni, int):
47         key = "%04x" % uni
48     elif isinstance(uni, basestring):
49         if len(uni) == 1:
50             key = "%04x" % ord(uni)
51         elif len(uni) == 4:
52             key = uni
53     if key is None:
54         raise ValueError
55     if key in _uni2name:
56         return _uni2name[key]
57     return "U%s" % key.upper()
58
59 if __name__ == '__main__':
60     for u in range(0,0xffff):
61         print "U+%04X\t%s" % tuple([u, name(u)])
62