-
Notifications
You must be signed in to change notification settings - Fork 0
/
translate.py
executable file
·78 lines (66 loc) · 2.27 KB
/
translate.py
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import subprocess
import sys
import re
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('--keymap-source', dest='source', choices=["linux/input.h","xmodmap"],
default="xmodmap",help='specify which keymap to use')
parser.add_argument('--dumpfile', type=str, dest="dumpfile",
help='the path to the dumpfile, if not specified stdin will be used')
args = parser.parse_args()
if args.dumpfile:
try:
dump = open(args.dumpfile)
except:
print("%s is not readable or does not exist."%args.dumpfile)
sys.exit(1)
else:
dump = sys.stdin
positions_to_translate = [0,1,2]
offset = -8
def load_mapping_from_xmodmap():
keymap = subprocess.check_output(["xmodmap","-pke"]).decode("utf-8")
mapping = {}
for line in keymap.split("\n"):
parts = line.split()
if len(parts) > 4:
mapping[int(parts[1])+offset] = parts[3]
return mapping
def load_mapping_from_linux_input_h():
mapping = {}
with open("/usr/include/linux/input.h") as headerfile:
regex = "^#define KEY_([^\s]*)\s*(\d*)"
finds = re.findall(regex, headerfile.read(), flags=re.MULTILINE)
for keyname, scancode in finds:
if keyname and scancode:
mapping[int(scancode)] = keyname
return mapping
def cmd_exists(cmd): # from http://stackoverflow.com/a/11069822/3890934
return subprocess.call("type " + cmd, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0
if args.source == "linux/input.h":
mapping = load_mapping_from_linux_input_h()
elif args.source == "xmodmap":
if cmd_exists("xmodmap"):
try:
mapping = load_mapping_from_xmodmap()
except:
print("Could not load mapping from xmodmap.")
sys.exit(1)
table = []
for line in dump:
parts = line.split()
if int(parts[3]) > 0:
for position in positions_to_translate:
parts[position] = mapping[int(parts[position])]
table.append(parts)
table.sort(key=lambda x: int(x[3]), reverse=True)
for x in table:
x[3] = x[3].lstrip("0");
for row in table:
try:
print(" ".join(row))
except Exception:
break