Skip to content

Commit 8d549b9

Browse files
committed
Add the allow_unknown argument to KeyEvent
1 parent 05fd3fa commit 8d549b9

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

docs/changelog.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,11 @@ Master
99
- Add functionality to query device properties. See ``InputDevice.input_props``
1010
and the ``input_props`` argument to ``Uinput``.
1111

12+
- ``KeyEvent`` received an ``allow_unknown`` constructor argument, which
13+
determines what will happen when an event code cannot be mapped to a keycode.
14+
The default and behavior so far has been to raise ``KeyError``. If set to
15+
``True``, the keycode will be set to the event code formatted as a hex number.
16+
1217

1318
1.2.0 (Apr 7, 2019)
1419
====================

evdev/events.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -86,18 +86,29 @@ class KeyEvent(object):
8686

8787
__slots__ = 'scancode', 'keycode', 'keystate', 'event'
8888

89-
def __init__(self, event):
89+
def __init__(self, event, allow_unknown=False):
90+
'''
91+
The ``allow_unknown`` argument determines what to do in the event of a event code
92+
for which a key code cannot be found. If ``False`` a ``KeyError`` will be raised.
93+
If ``True`` the keycode will be set to the hex value of the event code.
94+
'''
95+
96+
self.scancode = event.code
97+
9098
if event.value == 0:
9199
self.keystate = KeyEvent.key_up
92100
elif event.value == 2:
93101
self.keystate = KeyEvent.key_hold
94102
elif event.value == 1:
95103
self.keystate = KeyEvent.key_down
96104

97-
if not (event.code in keys):
98-
keys[event.code] = ''.join('{:02X}'.format(event.code))
99-
self.keycode = keys[event.code]
100-
self.scancode = event.code
105+
try:
106+
self.keycode = keys[event.code]
107+
except KeyError:
108+
if allow_unknown:
109+
self.keycode = '0x{:02X}'.format(event.code)
110+
else:
111+
raise
101112

102113
#: Reference to an :class:`InputEvent` instance.
103114
self.event = event

0 commit comments

Comments
 (0)