1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
|
#!/usr/bin/python
# -*- python -*-
#
# Keycode Map Generator
#
# Copyright (C) 2009-2017 Red Hat, Inc.
#
# This file is dual license under the terms of the GPLv2 or later
# and 3-clause BSD licenses.
#
# Requires >= 2.6
from __future__ import print_function
import csv
import argparse
import hashlib
import time
class Database:
# Linux: linux/input.h
MAP_LINUX = "linux"
# OS-X: Carbon/HIToolbox/Events.h
MAP_OSX = "osx"
# AT Set 1: linux/drivers/input/keyboard/atkbd.c
# (atkbd_set2_keycode + atkbd_unxlate_table)
MAP_ATSET1 = "atset1"
# AT Set 2: linux/drivers/input/keyboard/atkbd.c
# (atkbd_set2_keycode)
MAP_ATSET2 = "atset2"
# AT Set 3: linux/drivers/input/keyboard/atkbd.c
# (atkbd_set3_keycode)
MAP_ATSET3 = "atset3"
# XT: linux/drivers/input/keyboard/xt.c (xtkbd_keycode)
MAP_XT = "xt"
# Linux RAW: linux/drivers/char/keyboard.c (x86_keycodes)
MAP_XTKBD = "xtkbd"
# USB HID: linux/drivers/hid/usbhid/usbkbd.c (usb_kbd_keycode)
MAP_USB = "usb"
# Win32: mingw32/winuser.h
MAP_WIN32 = "win32"
# XWin XT: xorg-server/hw/xwin/{winkeybd.c,winkeynames.h}
# (xt + manually transcribed)
MAP_XWINXT = "xwinxt"
# X11: http://cgit.freedesktop.org/xorg/proto/x11proto/plain/keysymdef.h
MAP_X11 = "x11"
# XKBD XT: xf86-input-keyboard/src/at_scancode.c
# (xt + manually transcribed)
MAP_XKBDXT = "xkbdxt"
# Xorg with evdev: linux + an offset
MAP_XORGEVDEV = "xorgevdev"
# Xorg with kbd: xkbdxt + an offset
MAP_XORGKBD = "xorgkbd"
# Xorg with OS-X: osx + an offset
MAP_XORGXQUARTZ = "xorgxquartz"
# Xorg + Cygwin: xwinxt + an offset
MAP_XORGXWIN = "xorgxwin"
# XT over RFB: xtkbd + special re-encoding of high bit
MAP_RFB = "rfb"
MAP_LIST = (
MAP_LINUX,
MAP_OSX,
MAP_ATSET1,
MAP_ATSET2,
MAP_ATSET3,
MAP_XT,
MAP_XTKBD,
MAP_USB,
MAP_WIN32,
MAP_XWINXT,
MAP_XKBDXT,
MAP_X11,
# These are derived from maps above
MAP_XORGEVDEV,
MAP_XORGKBD,
MAP_XORGXQUARTZ,
MAP_XORGXWIN,
MAP_RFB,
)
CODE_COLUMNS = {
MAP_LINUX: 1,
MAP_OSX: 3,
MAP_ATSET1: 4,
MAP_ATSET2: 5,
MAP_ATSET3: 6,
MAP_XT: 7,
MAP_XTKBD: 8,
MAP_USB: 9,
MAP_WIN32: 11,
MAP_XWINXT: 12,
MAP_XKBDXT: 13,
MAP_X11: 15,
}
NAME_COLUMNS = {
MAP_LINUX: 0,
MAP_OSX: 2,
MAP_WIN32: 10,
MAP_X11: 14,
}
def __init__(self):
self.mapto = {}
self.mapfrom = {}
self.mapname = {}
self.mapchecksum = None
for name in self.MAP_LIST:
# Key is a MAP_LINUX, value is a MAP_XXX
self.mapto[name] = {}
# key is a MAP_XXX, value is a MAP_LINUX
self.mapfrom[name] = {}
for name in self.NAME_COLUMNS.keys():
# key is a MAP_LINUX, value is a string
self.mapname[name] = {}
def _generate_checksum(self, filename):
hash = hashlib.sha256()
with open(filename, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash.update(chunk)
self.mapchecksum = hash.hexdigest()
def load(self, filename):
self._generate_checksum(filename)
with open(filename, 'r') as f:
reader = csv.reader(f)
first = True
for row in reader:
# Discard column headings
if first:
first = False
continue
# We special case MAP_LINUX since that is out
# master via which all other mappings are done
linux = self.load_linux(row)
# Now load all the remaining master data values
self.load_data(row, linux)
# Then load all the keycode names
self.load_names(row, linux)
# Finally calculate derived key maps
self.derive_data(row, linux)
def load_linux(self, row):
col = self.CODE_COLUMNS[self.MAP_LINUX]
linux = row[col]
if linux.startswith("0x"):
linux = int(linux, 16)
else:
linux = int(linux, 10)
self.mapto[self.MAP_LINUX][linux] = linux
self.mapfrom[self.MAP_LINUX][linux] = linux
return linux
def load_data(self, row, linux):
for mapname in self.CODE_COLUMNS:
if mapname == self.MAP_LINUX:
continue
col = self.CODE_COLUMNS[mapname]
val = row[col]
if val == "":
continue
if val.startswith("0x"):
val = int(val, 16)
else:
val = int(val, 10)
self.mapto[mapname][linux] = val
self.mapfrom[mapname][val] = linux
def load_names(self, row, linux):
for mapname in self.NAME_COLUMNS:
col = self.NAME_COLUMNS[mapname]
val = row[col]
if val == "":
continue
self.mapname[mapname][linux] = val
def derive_data(self, row, linux):
# Xorg KBD is XKBD XT offset by 8
if linux in self.mapto[self.MAP_XKBDXT]:
xorgkbd = self.mapto[self.MAP_XKBDXT][linux] + 8
self.mapto[self.MAP_XORGKBD][linux] = xorgkbd
self.mapfrom[self.MAP_XORGKBD][xorgkbd] = linux
# Xorg evdev is Linux offset by 8
self.mapto[self.MAP_XORGEVDEV][linux] = linux + 8
self.mapfrom[self.MAP_XORGEVDEV][linux + 8] = linux
# Xorg XQuartx is OS-X offset by 8
if linux in self.mapto[self.MAP_OSX]:
xorgxquartz = self.mapto[self.MAP_OSX][linux] + 8
self.mapto[self.MAP_XORGXQUARTZ][linux] = xorgxquartz
self.mapfrom[self.MAP_XORGXQUARTZ][xorgxquartz] = linux
# Xorg Xwin (aka Cygwin) is XWin XT offset by 8
if linux in self.mapto[self.MAP_XWINXT]:
xorgxwin = self.mapto[self.MAP_XWINXT][linux] + 8
self.mapto[self.MAP_XORGXWIN][linux] = xorgxwin
self.mapfrom[self.MAP_XORGXWIN][xorgxwin] = linux
# RFB keycodes are XT kbd keycodes with a slightly
# different encoding of 0xe0 scan codes. RFB uses
# the high bit of the first byte, instead of the low
# bit of the second byte
if linux in self.mapto[self.MAP_XTKBD]:
xtkbd = self.mapto[self.MAP_XTKBD][linux]
if xtkbd != 0:
rfb = ((xtkbd & 0x100) >> 1) | (xtkbd & 0x7f)
else:
rfb = 0
self.mapto[self.MAP_RFB][linux] = rfb
self.mapfrom[self.MAP_RFB][rfb] = linux
class LanguageGenerator(object):
def generate_header(self, database, args):
today = time.strftime("%Y-%m-%d %H:%M")
self._boilerplate([
"This file is auto-generated from keymaps.csv on %s" % today,
"Database checksum sha256(%s)" % database.mapchecksum,
"To re-generate, run:",
" %s" % args,
])
def generate_code_map(self, varname, database, frommapname, tomapname):
if frommapname not in database.mapfrom:
raise Exception("Unknown map %s, expected %s",
frommapname, ",".join(database.mapfrom.keys()))
if tomapname not in database.mapto:
raise Exception("Unknown map %s, expected %s",
tomapname, ",".join(database.mapto.keys()))
tolinux = database.mapfrom[frommapname]
fromlinux = database.mapto[tomapname]
if varname is None:
varname = "code_map_%s_to_%s" % (frommapname, tomapname)
frommax = 0
for key in tolinux.keys():
if key > frommax:
frommax = key
self._array_start_code(varname, frommax + 1)
for src in range(frommax + 1):
linux = tolinux.get(src, None)
if linux is None:
dst = None
else:
dst = fromlinux.get(linux, None)
comment = "%s -> %s -> %s" % (self._label(database, frommapname, src),
self._label(database, Database.MAP_LINUX, linux),
self._label(database, tomapname, dst))
self._array_entry_code(src, dst, comment)
self._array_end()
def generate_code_table(self, varname, database, mapname):
if mapname not in database.mapto:
raise Exception("Unknown map %s, expected %s",
mapname, ",".join(database.mapto.keys()))
keys = database.mapto[Database.MAP_LINUX].keys()
keys.sort()
names = [database.mapname[Database.MAP_LINUX].get(key, "unnamed") for key in keys]
if varname is None:
varname = "code_table_%s" % mapname
self._array_start_code(varname, len(keys))
for i in range(len(keys)):
key = keys[i]
dst = database.mapto[mapname].get(key, None)
self._array_entry_code(i, dst, names[i])
self._array_end()
def generate_name_map(self, varname, database, frommapname, tomapname):
if frommapname not in database.mapfrom:
raise Exception("Unknown map %s, expected %s",
frommapname, ",".join(database.mapfrom.keys()))
if tomapname not in database.mapname:
raise Exception("Unknown map %s, expected %s",
tomapname, ",".join(database.mapname.keys()))
tolinux = database.mapfrom[frommapname]
fromlinux = database.mapname[tomapname]
if varname is None:
varname = "name_map_%s_to_%s" % (frommapname, tomapname)
frommax = 0
for key in tolinux.keys():
if key > frommax:
frommax = key
self._array_start_name(varname, frommax + 1)
for src in range(frommax + 1):
linux = tolinux.get(src, None)
if linux is None:
dst = None
else:
dst = fromlinux.get(linux, None)
comment = "%s -> %s -> %s" % (self._label(database, frommapname, src),
self._label(database, Database.MAP_LINUX, linux),
self._label(database, tomapname, dst))
self._array_entry_name(src, dst, comment)
self._array_end()
def generate_name_table(self, varname, database, mapname):
if mapname not in database.mapname:
raise Exception("Unknown map %s, expected %s",
mapname, ",".join(database.mapname.keys()))
keys = database.mapto[Database.MAP_LINUX].keys()
keys.sort()
names = [database.mapname[Database.MAP_LINUX].get(key, "unnamed") for key in keys]
if varname is None:
varname = "name_table_%s" % mapname
self._array_start_name(varname, len(keys))
for i in range(len(keys)):
key = keys[i]
dst = database.mapname[mapname].get(key, None)
self._array_entry_name(i, dst, names[i])
self._array_end()
def _label(self, database, mapname, val):
if mapname in database.mapname:
return "%s:%s (%s)" % (mapname, val, database.mapname[mapname].get(val, "unnamed"))
else:
return "%s:%s" % (mapname, val)
class CLanguageGenerator(LanguageGenerator):
def __init__(self, inttypename, strtypename):
self.inttypename = inttypename
self.strtypename = strtypename
def _boilerplate(self, lines):
print("/*")
for line in lines:
print(" * %s" % line)
print("*/")
def _array_start_code(self, varname, length):
print("const %s %s[%d] = {" % (self.inttypename, varname, length))
def _array_start_name(self, varname, length):
print("const %s %s[%d] = {" % (self.strtypename, varname, length))
def _array_end(self):
print("};")
def _array_entry_code(self, index, value, comment):
if value is not None:
print(" [0x%x] = 0x%x, /* %s */" % (index, value, comment))
def _array_entry_name(self, index, value, comment):
if value is not None:
print(" [0x%x] = \"%s\", /* %s */" % (index, value, comment))
class StdCLanguageGenerator(CLanguageGenerator):
def __init__(self):
super(StdCLanguageGenerator, self).__init__("unsigned short", "char *")
class GLib2LanguageGenerator(CLanguageGenerator):
def __init__(self):
super(GLib2LanguageGenerator, self).__init__("guint16", "gchar *")
class PythonLanguageGenerator(LanguageGenerator):
def _boilerplate(self, lines):
print("#")
for line in lines:
print("# %s" % line)
print("#")
def _array_start_code(self, varname, length):
print("%s = [" % varname)
def _array_start_name(self, varname, length):
print("%s = [" % varname)
def _array_end(self):
print("]")
def _array_entry_code(self, index, value, comment):
if value is None:
print(" None, # %s" % (comment))
else:
print(" 0x%x, # %s" % (value, comment))
def _array_entry_name(self, index, value, comment):
if value is None:
print(" None, # %s" % (comment))
else:
print(" \"%s\", # %s" % (value, comment))
class PerlLanguageGenerator(LanguageGenerator):
def _boilerplate(self, lines):
print("#")
for line in lines:
print("# %s" % line)
print("#")
def _array_start_code(self, varname, length):
print("my @%s = (" % varname)
def _array_start_name(self, varname, length):
print("my @%s = (" % varname)
def _array_end(self):
print(");")
def _array_entry_code(self, index, value, comment):
if value is None:
print(" undef, # %s" % (comment))
else:
print(" 0x%x, # %s" % (value, comment))
def _array_entry_name(self, index, value, comment):
if value is None:
print(" undef, # %s" % (comment))
else:
print(" \"%s\", # %s" % (value, comment))
GENERATORS = {
"stdc": StdCLanguageGenerator(),
"glib2": GLib2LanguageGenerator(),
"python2": PythonLanguageGenerator(),
"python3": PythonLanguageGenerator(),
"perl": PerlLanguageGenerator(),
}
def code_map(args):
database = Database()
database.load(args.keymaps)
cliargs = ["keymap-gen", "--lang=%s" % args.lang]
if args.varname is not None:
cliargs.append("--varname=%s" % args.varname)
cliargs.extend(["code-map", "keymaps.csv", args.frommapname, args.tomapname])
GENERATORS[args.lang].generate_header(database, " ".join(cliargs))
GENERATORS[args.lang].generate_code_map(args.varname, database, args.frommapname, args.tomapname)
def code_table(args):
database = Database()
database.load(args.keymaps)
cliargs = ["keymap-gen", "--lang=%s" % args.lang]
if args.varname is not None:
cliargs.append("--varname=%s" % args.varname)
cliargs.extend(["code-table", "keymaps.csv", args.mapname])
GENERATORS[args.lang].generate_header(database, " ".join(cliargs))
GENERATORS[args.lang].generate_code_table(args.varname, database, args.mapname)
def name_map(args):
database = Database()
database.load(args.keymaps)
cliargs = ["keymap-gen", "--lang=%s" % args.lang]
if args.varname is not None:
cliargs.append("--varname=%s" % args.varname)
cliargs.extend(["name-map", "keymaps.csv", args.frommapname, args.tomapname])
GENERATORS[args.lang].generate_header(database, " ".join(cliargs))
GENERATORS[args.lang].generate_name_map(args.varname, database, args.frommapname, args.tomapname)
def name_table(args):
database = Database()
database.load(args.keymaps)
cliargs = ["keymap-gen", "--lang=%s" % args.lang]
if args.varname is not None:
cliargs.append("--varname=%s" % args.varname)
cliargs.extend(["name-table", "keymaps.csv", args.mapname])
GENERATORS[args.lang].generate_header(database, " ".join(cliargs))
GENERATORS[args.lang].generate_name_table(args.varname, database, args.mapname)
def usage(args):
print ("Please select a command:")
print (" 'code-map', 'code-table', 'name-map', 'name-table'")
sys.exit(1)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--lang", default="stdc",
help="Output language, %s" % ",".join(GENERATORS.keys()))
parser.add_argument("--varname", default=None,
help="Data variable name")
parser.set_defaults(func=usage)
subparsers = parser.add_subparsers(help="sub-command help")
codemapparser = subparsers.add_parser("code-map", help="Generate a mapping between code tables")
codemapparser.add_argument("keymaps", help="Path to keymap CSV data file")
codemapparser.add_argument("frommapname", help="Source code table name")
codemapparser.add_argument("tomapname", help="Target code table name")
codemapparser.set_defaults(func=code_map)
codetableparser = subparsers.add_parser("code-table", help="Generate a flat code table")
codetableparser.add_argument("keymaps", help="Path to keymap CSV data file")
codetableparser.add_argument("mapname", help="Code table name")
codetableparser.set_defaults(func=code_table)
namemapparser = subparsers.add_parser("name-map", help="Generate a mapping to names")
namemapparser.add_argument("keymaps", help="Path to keymap CSV data file")
namemapparser.add_argument("frommapname", help="Source code table name")
namemapparser.add_argument("tomapname", help="Target name table name")
namemapparser.set_defaults(func=name_map)
nametableparser = subparsers.add_parser("name-table", help="Generate a flat name table")
nametableparser.add_argument("keymaps", help="Path to keymap CSV data file")
nametableparser.add_argument("mapname", help="Name table name")
nametableparser.set_defaults(func=name_table)
args = parser.parse_args()
args.func(args)
main()
|