forked from wbolster/evcape
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevcape.py
executable file
·280 lines (235 loc) · 8.6 KB
/
evcape.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
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
#!/usr/bin/env python3
import argparse
import collections
import errno
import functools
import logging
import selectors
import evdev
import pyudev
logger = logging.getLogger('evcape')
DEFAULT_RULES = [
'press:leftctrl,release:leftctrl=press:esc,release:esc',
'press:capslock,release:capslock=press:esc,release:esc',
]
DEFAULT_TIMEOUT = 1000
KEY_EVENT_VALUE_TO_ACTION = {
0: 'release',
1: 'press',
}
ACTION_TO_KEY_EVENT_VALUE = {
value: key
for key, value in KEY_EVENT_VALUE_TO_ACTION.items()
}
MODIFIERS = [evdev.ecodes.KEY_LEFTSHIFT]
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'rules', nargs='*', metavar='rule', default=DEFAULT_RULES)
parser.add_argument(
'--timeout', type=int, default=DEFAULT_TIMEOUT)
args = parser.parse_args()
logging.basicConfig(level=logging.INFO)
timeout = args.timeout / 1000
logger.info("using timeout {}ms".format(args.timeout))
for s in args.rules:
logger.info("adding rule {!r}".format(s))
rules = [
Rule.from_string(s)
for s in args.rules
]
assert len(rules) > 0
rules_by_last_event = {}
for rule in rules:
key = rule.patterns[-1]
rules_by_last_event.setdefault(key, []).append(rule)
uinput = evdev.UInput(name='evcape')
logger.info("created uinput device {0.device.path}".format(uinput))
keyboard_monitor = KeyboardMonitor(
ignored_devices=[uinput.device.path])
# the buffer is as long as the longest sequence in rules
window_size = max(
[len(rule.patterns) for rule in rules])
buffer = collections.deque(maxlen=window_size)
# put keypresses into a buffer and try to match rules
previous_event_timestamp = 0.0
pressed_modifiers = set()
with uinput, keyboard_monitor:
for event in keyboard_monitor:
lookup_key = (event.value, event.code)
if event.code in MODIFIERS:
if event.value == 1:
pressed_modifiers.add(event.code)
else:
pressed_modifiers.remove(event.code)
continue
buffer.append(lookup_key)
ts_diff = event.timestamp() - previous_event_timestamp
previous_event_timestamp = event.timestamp()
if ts_diff >= timeout:
continue
possibly_matching_rules = rules_by_last_event.get(lookup_key)
if not possibly_matching_rules:
continue
for rule in possibly_matching_rules:
buffer_slice = list(buffer)[-len(rule.patterns):]
if rule.patterns != buffer_slice:
continue
for mod in pressed_modifiers:
uinput.write(
evdev.ecodes.EV_KEY,
mod,
1)
for value, code in rule.actions:
uinput.write(
evdev.ecodes.EV_KEY,
code,
value)
for mod in pressed_modifiers:
uinput.write(
evdev.ecodes.EV_KEY,
mod,
0)
uinput.syn()
class KeyboardMonitor:
def __init__(self, ignored_devices):
self.udev_context = pyudev.Context()
self.selector = selectors.DefaultSelector()
self.ignored_devices = ignored_devices
self.input_devices_by_name = set()
self.start_udev_monitor()
self.add_existing_keyboards()
def start_udev_monitor(self):
"""
Start an udev monitor to detect hotplug events.
This detects when external keyboards are (dis)connected.
"""
monitor = pyudev.Monitor.from_netlink(self.udev_context)
monitor.filter_by(subsystem='input')
monitor.start()
self.selector.register(
monitor, events=selectors.EVENT_READ, data='udev')
def add_existing_keyboards(self):
enumerator = self.udev_context.list_devices()
enumerator.match_subsystem('input')
enumerator.match_property('ID_INPUT_KEYBOARD', '1')
for device in enumerator:
device_name = udev_keyboard_device_name(device)
if device_name is not None:
self.add_keyboard(device_name)
def add_keyboard(self, device_name):
if device_name in self.ignored_devices:
return
try:
input_device = evdev.InputDevice(device_name)
except OSError as exc:
if exc.errno != errno.ENOTTY:
raise
logger.warning(
"could not create input device for {}"
.format(device_name))
return
self.selector.register(
input_device, events=selectors.EVENT_READ, data='keyboard')
logger.info(
"monitoring {0.path} ({0.name})"
.format(input_device))
def remove_keyboard(self, device_name):
for selector_key in self.selector.get_map().values():
input_device = selector_key.fileobj
if not isinstance(input_device, evdev.InputDevice):
continue
if input_device.path != device_name:
continue
self.selector.unregister(input_device)
logger.info(
"no longer monitoring {0.path} ({0.name})"
.format(input_device))
break
def __iter__(self):
def read_forever_from_selector():
while True:
for selector_key, mask in self.selector.select():
yield selector_key
for selector_key in read_forever_from_selector():
if selector_key.data == 'keyboard': # keyboard event
input_device = selector_key.fileobj
for event in read_input_device_events(input_device):
if event.type != evdev.ecodes.EV_KEY:
continue
if event.value not in KEY_EVENT_VALUE_TO_ACTION:
continue # e.g. key repeat
yield event
elif selector_key.data == 'udev': # hotplug event
poll_monitor = functools.partial(
selector_key.fileobj.poll,
timeout=0)
for device in iter(poll_monitor, None):
device_name = udev_keyboard_device_name(device)
if device_name is None:
continue
if device.action == 'add':
self.add_keyboard(device_name)
elif device.action == 'remove':
self.remove_keyboard(device_name)
else:
assert False
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def close(self):
for selector_key in list(self.selector.get_map().values()):
self.selector.unregister(selector_key.fileobj)
self.selector.close()
def read_input_device_events(input_device):
try:
yield from input_device.read()
except OSError as exc:
if exc.errno == errno.ENODEV:
pass # Device has disappeared.
else:
raise
def udev_keyboard_device_name(device):
if device.properties.get('ID_INPUT_JOYSTICK') == '1':
return None
if device.properties.get('ID_INPUT_KEYBOARD') != '1':
return None # This is not a keyboard.
try:
return device.properties['DEVNAME']
except KeyError:
return None
_Rule = collections.namedtuple('Rule', ['patterns', 'actions'])
class Rule(_Rule):
@classmethod
def from_string(cls, s):
"""
Create a rule from a string.
Sample input:
press:leftctrl,release:leftctrl=press:esc,release:esc
Sample output:
Rule(
patterns=[(1, 29), (0, 29)],
actions=[(1, 1), (0, 1)])
Key codes:
KEY_LEFTCTRL == 29
KEY_ESC == 1
Key values:
press == 1
release == 0
"""
patterns, _, actions = s.partition('=')
return cls(
patterns=cls.parse_sequence(patterns),
actions=cls.parse_sequence(actions))
@staticmethod
def parse_sequence(s):
out = []
for chunk in s.split(','):
action, _, key = chunk.partition(':')
value = ACTION_TO_KEY_EVENT_VALUE[action]
code = getattr(evdev.ecodes, 'KEY_{}'.format(key.upper()))
out.append((value, code))
return out
if __name__ == '__main__':
main()