Debian Codegraph @

daemon/openrazer_daemon/misc/key_event_management.py

raw
1 # SPDX-License-Identifier: GPL-2.0-or-later
2
3 """
4 Receives events from /dev/input/by-id/somedevice
5
6 Events are 24 bytes long and are emitted from a character device in 24 byte chunks.
7 As the keyboards have "2" keyboard interfaces we need to listen on both of them in case some n00b
8 switches to game mode.
9
10 Each event is in the format of
11 * signed int of seconds
12 * signed int of microseconds
13 * unsigned short of event type
14 * unsigned short code
15 * signed int value
16 """
17 import datetime
18 import fcntl
19 import json
20 import logging
21 import os
22 import random
23 import select
24 import struct
25 import threading
26 import time
27
28 # pylint: disable=import-error
29 from openrazer_daemon.keyboard import KEY_MAPPING, TARTARUS_KEY_MAPPING, EVENT_MAPPING, TARTARUS_EVENT_MAPPING, NAGA_HEX_V2_EVENT_MAPPING, NAGA_HEX_V2_KEY_MAPPING, ORBWEAVER_EVENT_MAPPING, ORBWEAVER_KEY_MAPPING
30 from .macro import MacroKey, MacroRunner, macro_dict_to_obj
31
32 EVENT_FORMAT = '@llHHI'
33 EVENT_SIZE = struct.calcsize(EVENT_FORMAT)
34
35 EPOLL_TIMEOUT = 0.01
36 SPIN_SLEEP = 0.01
37
38 EVIOCGRAB = 0x40044590
39
40 COLOUR_CHOICES = (
41 (255, 0, 0), # Red
42 (0, 255, 0), # Green
43 (0, 0, 255), # Blue
44 (255, 255, 0), # Yellow
45 (0, 255, 255), # Cyan
46 (255, 0, 255), # Magenta
47 )
48
49
50 def random_colour_picker(last_choice, iterable):
51 """
52 Chose a random choice but not the last one
53
54 :param last_choice: Last choice
55 :type last_choice: object
56
57 :param iterable: Iterable object
58 :type iterable: iterable
59
60 :return: Choice
61 :rtype: object
62 """
63 result = random.choice(iterable)
64 while result == last_choice:
65 result = random.choice(iterable)
66 return result
67
68
69 class KeyWatcher(threading.Thread):
70 """
71 Thread to watch keyboard event files and return keypresses
72 """
73 @staticmethod
74 def parse_event_record(data):
75 """
76 Parse Input event record
77
78 :param data: Binary data
79 :type data: bytes
80
81 :return: Tuple of event time, key_action, key_code
82 :rtype: tuple
83 """
84 # Event Seconds, Event Microseconds, Event Type, Event Code, Event Value
85 ev_sec, ev_usec, ev_type, ev_code, ev_value = struct.unpack(EVENT_FORMAT, data)
86
87 if ev_type != 0x01: # input-event-codes.h EV_KEY 0x01
88 return None, None, None
89
90 if ev_value == 0:
91 key_action = 'release'
92 elif ev_value == 1:
93 key_action = 'press'
94 elif ev_value == 2:
95 key_action = 'autorepeat'
96 else:
97 key_action = 'unknown'
98
99 seconds = ev_sec + (ev_usec * 0.000001)
100 date = datetime.datetime.fromtimestamp(seconds)
101
102 result = (date, key_action, ev_code)
103
104 if ev_type == ev_code == ev_value == 0:
105 return None, None, None
106
107 return result
108
109 def __init__(self, device_id, event_files, parent, use_epoll=True):
110 super().__init__()
111
112 self._logger = logging.getLogger('razer.device{0}.keywatcher'.format(device_id))
113 self._event_files = event_files
114 self._shutdown = False
115 self._use_epoll = use_epoll
116 self._parent = parent
117
118 self.open_event_files = [open(event_file, 'rb') for event_file in self._event_files]
119 # Set open files to non blocking mode
120 for event_file in self.open_event_files:
121 flags = fcntl.fcntl(event_file.fileno(), fcntl.F_GETFL)
122 fcntl.fcntl(event_file.fileno(), fcntl.F_SETFL, flags | os.O_NONBLOCK)
123
124 def run(self):
125 """
126 Main event loop
127 """
128 # Create dict of Event File Descriptor: Event File Object
129 event_file_map = {event_file.fileno(): event_file for event_file in self.open_event_files}
130
131 # Create epoll object
132 poll_object = select.epoll()
133
134 # Register files with select
135 for event_fd in event_file_map.keys():
136 poll_object.register(event_fd, select.EPOLLIN | select.EPOLLPRI)
137
138 # Loop
139 while not self._shutdown:
140 # epoll is nice but it wasn't getting events properly :(
141
142 try: # Cheap hack until i merged new code
143 if self._use_epoll:
144 self._poll_epoll(poll_object, event_file_map)
145 else:
146 self._poll_read()
147 except (IOError, OSError): # Basically if there's an error, most likely device has been removed then it'll get deleted properly
148 pass
149
150 time.sleep(SPIN_SLEEP)
151
152 # Unbind files and close them
153 for event_fd, event_file in event_file_map.items():
154 poll_object.unregister(event_fd)
155 event_file.close()
156
157 poll_object.close()
158
159 def _poll_epoll(self, poll_object, event_file_map):
160 events = poll_object.poll(EPOLL_TIMEOUT)
161
162 if len(events) != 0:
163 # pylint: disable=unused-variable
164 for event_fd, mask in events:
165 while True:
166 key_data = event_file_map[event_fd].read(EVENT_SIZE)
167 if not key_data:
168 break
169
170 date, key_action, key_code = self.parse_event_record(key_data)
171
172 # Skip if date, key_action and key_code is none as that's a spacer record
173 if date is None:
174 continue
175
176 # Now if key is pressed then we record
177 self._parent.key_action(date, key_code, key_action)
178
179 def _poll_read(self):
180 for event_file in self.open_event_files:
181
182 key_data = event_file.read(EVENT_SIZE)
183
184 if key_data is None:
185 continue
186
187 date, key_action, key_code = self.parse_event_record(key_data)
188
189 # Skip if date, key_action and key_code is none as that's a spacer record
190 if date is None:
191 continue
192
193 # Now if key is pressed then we record
194 self._parent.key_action(date, key_code, key_action)
195
196 @property
197 def shutdown(self):
198 """
199 Thread shutdown condition
200
201 :return: Shutdown condition
202 :rtype: bool
203 """
204 return self._shutdown
205
206 @shutdown.setter
207 def shutdown(self, value):
208 """
209 Set thread shutdown condition
210
211 :param value: Boolean, normally only True would be used
212 :type value: str
213 """
214 self._shutdown = value
215
216
217 class KeyboardKeyManager(object):
218 """
219 Key management class.
220
221 This class deals with anything to do with keypresses. Currently it does:
222 * Receiving keypresses from the KeyWatcher
223 * Logic to deal with GameMode shortcut not working when macro's not enabled
224 * Logic to deal with recording on the fly macros and replaying them
225
226 It will be used to store keypresses in a list (for at most 2 seconds) if enabled for the ripple effect, when I
227 get round to making the effect.
228 """
229 KEY_MAP = KEY_MAPPING
230 EVENT_MAP = EVENT_MAPPING
231
232 # pylint: disable=too-many-instance-attributes
233 def __init__(self, device_id, event_files, parent, use_epoll=False, testing=False, should_grab_event_files=False):
234
235 self._device_id = device_id
236 self._logger = logging.getLogger('razer.device{0}.keymanager'.format(device_id))
237 self._parent = parent
238 self._parent.register_observer(self)
239 self._testing = testing
240
241 self._event_files = event_files
242 self._access_lock = threading.Lock()
243 self._keywatcher = KeyWatcher(device_id, event_files, self, use_epoll=use_epoll)
244 self._open_event_files = self._keywatcher.open_event_files
245
246 if len(event_files) > 0:
247 self._logger.debug("Starting KeyWatcher")
248 self._keywatcher.start()
249 else:
250 self._logger.warning("No event files for KeyWatcher")
251
252 self._recording_macro = False
253 self._macros = {}
254
255 self._current_macro_bind_key = None
256 self._current_macro_combo = []
257
258 self._threads = set()
259 self._clean_counter = 0
260
261 self._temp_key_store_active = False
262 self._temp_key_store = []
263 self._temp_expire_time = datetime.timedelta(seconds=2)
264
265 self._last_colour_choice = None
266
267 self._should_grab_event_files = should_grab_event_files
268 self._event_files_locked = False
269
270 if self._should_grab_event_files:
271 self.grab_event_files(True)
272
273 @property
274 def temp_key_store(self):
275 """
276 Get the temporary key store
277
278 :return: List of keys
279 :rtype: list
280 """
281 # Locking so it doesn't mutate whilst copying
282 self._access_lock.acquire()
283 now = datetime.datetime.now()
284
285 # Remove expired keys from store
286 try:
287 # Get date and if its less than now its expired
288 while self._temp_key_store[0][0] < now:
289 self._temp_key_store.pop(0)
290 except IndexError:
291 pass
292
293 # Creating a copy as then it doesn't mutate whilst iterating
294 result = self._temp_key_store[:]
295 self._access_lock.release()
296 return result
297
298 @property
299 def temp_key_store_state(self):
300 """
301 Get the state of the temporary key store
302
303 :return: Active state
304 :rtype: bool
305 """
306 return self._temp_key_store_active
307
308 @temp_key_store_state.setter
309 def temp_key_store_state(self, value):
310 """
311 Set the state of the temporary key store
312
313 :param value: Active state
314 :type value: bool
315 """
316 self._temp_key_store_active = value
317
318 def grab_event_files(self, grab):
319 """
320 Grab the event files exclusively
321
322 :param grab: True to grab, False to release
323 :type grab: bool
324 """
325 if not self._testing:
326 for event_file in self._open_event_files:
327 fcntl.ioctl(event_file.fileno(), EVIOCGRAB, int(grab))
328 self._event_files_locked = grab
329
330 def key_action(self, event_time, key_id, key_press='press'):
331 """
332 Process a key press event
333
334 Ok an attempt to explain the logic
335 * The function sets a value _fn_down depending on the state of FN.
336 * Adds keypress and release events to a macro list if recording a macro.
337 * Pressing FN+F9 starts recording a macro, then selecting any key marks that as a macro key,
338 then it will record keys, then pressing FN+F9 will save macro.
339 * Pressing any macro key will run macro.
340 * Pressing FN+F10 will toggle game mode.
341 :param event_time: Time event occurred
342 :type event_time: datetime.datetime
343
344 :param key_id: Key Event ID
345 :type key_id: int
346
347 :param key_press: Can either be press, release, autorepeat
348 :type key_press: bool
349 """
350 # Disable pylints complaining for this part, #PerformanceOverNeatness
351 # pylint: disable=too-many-branches,too-many-statements
352
353 # Get event files if they arnt locked #nasty hack
354 if not self._event_files_locked and self._should_grab_event_files:
355 self.grab_event_files(True)
356
357 if key_press == 'autorepeat': # TODO not done right yet
358 # If its brightness then convert autorepeat to key presses
359 # Brightness keys are defined in keyboard.py and razerkbd_driver.c
360 if key_id in (0x2ab, 0x2aa):
361 key_press = 'press'
362 else:
363 # Quit out early
364 return
365
366 now = datetime.datetime.now()
367
368 # Remove expired keys from store
369 try:
370 # Get date and if its less than now its expired
371 while self._temp_key_store[0][0] < now:
372 self._temp_key_store.pop(0)
373 except IndexError:
374 pass
375
376 # Clean up any threads
377 if self._clean_counter > 20 and len(self._threads) > 0:
378 self._clean_counter = 0
379 self.clean_macro_threads()
380
381 try:
382 # Convert event ID to key name
383 key_name = self.EVENT_MAP[key_id]
384
385 # self._logger.info("Got key: {0}, state: {1}".format(key_name, 'DOWN' if key_press else 'UP'))
386
387 # Key release
388 if key_press == 'release':
389 if self._recording_macro:
390 # Skip as don't care about releasing macro bind key
391 if key_name not in (self._current_macro_bind_key, 'MACROMODE'):
392 # Record key release events
393 self._current_macro_combo.append((event_time, key_name, 'UP'))
394
395 else:
396 # Key press
397
398 if self._temp_key_store_active:
399 colour = random_colour_picker(self._last_colour_choice, COLOUR_CHOICES)
400 self._last_colour_choice = colour
401 self._temp_key_store.append((now + self._temp_expire_time, self.KEY_MAP[key_name], colour))
402
403 # Macro FN+F9 logic
404 if key_name == 'MACROMODE':
405 self._logger.info("Got macro combo")
406
407 if not self._recording_macro:
408 # Starting to record macro
409 self._recording_macro = True
410 self._current_macro_bind_key = None
411 self._current_macro_combo = []
412
413 self._parent.setMacroEffect(0x01)
414 self._parent.setMacroMode(True)
415
416 else:
417 self._logger.debug("Finished recording macro")
418 # Finish recording macro
419 if self._current_macro_bind_key is not None:
420 if len(self._current_macro_combo) > 0:
421 self.add_kb_macro()
422 else:
423 # Clear macro
424 self.dbus_delete_macro(self._current_macro_bind_key)
425 self._recording_macro = False
426 self._parent.setMacroEffect(0x00)
427 self._parent.setMacroMode(False)
428 # Sets up game mode as when enabling macro keys it stops the key working
429 elif key_name == 'GAMEMODE':
430 self._logger.info("Got game mode combo")
431
432 game_mode = self._parent.getGameMode()
433 self._parent.setGameMode(not game_mode)
434
435 # Brightness logic
436 elif key_name == 'BRIGHTNESSDOWN':
437 # Get brightness value
438 current_brightness = self._parent.method_args.get('brightness', None)
439 if current_brightness is None:
440 current_brightness = self._parent.getBrightness()
441
442 if current_brightness > 0:
443 current_brightness -= 10
444 if current_brightness < 0:
445 current_brightness = 0
446
447 self._parent.setBrightness(current_brightness)
448 # self._parent.method_args['brightness'] = current_brightness
449 elif key_name == 'BRIGHTNESSUP':
450 # Get brightness value
451 current_brightness = self._parent.method_args.get('brightness', None)
452 if current_brightness is None:
453 current_brightness = self._parent.getBrightness()
454
455 if current_brightness < 100:
456 current_brightness += 10
457 if current_brightness > 100:
458 current_brightness = 100
459
460 self._parent.setBrightness(current_brightness)
461 # self._parent.method_args['brightness'] = current_brightness
462
463 elif self._recording_macro:
464
465 if self._current_macro_bind_key is None:
466 # Restrict macro bind keys to M1-M5
467 if key_name not in ('M1', 'M2', 'M3', 'M4', 'M5', 'M6'):
468 self._logger.warning("Macros are only for M1-M6 for now.")
469 self._recording_macro = False
470 self._parent.setMacroMode(False)
471 else:
472 self._current_macro_bind_key = key_name
473 self._parent.setMacroEffect(0x00)
474 # Don't want no recursion, cancel macro, don't let one call macro in a macro
475 elif key_name == self._current_macro_bind_key:
476 self._logger.warning("Skipping macro assignment as would cause recursion")
477 self._recording_macro = False
478 self._parent.setMacroMode(False)
479 # Anything else just record it
480 else:
481 self._current_macro_combo.append((event_time, key_name, 'DOWN'))
482 # Not recording anything so if a macro key is pressed then run
483 else:
484 # If key has a macro, play it
485 if key_name in self._macros:
486 self.play_macro(key_name)
487
488 except KeyError as err:
489 self._logger.exception("Got key error. Couldn't convert event to key name", exc_info=err)
490
491 def add_kb_macro(self):
492 """
493 Tidy up the recorded macro and add it to the store
494
495 Goes through the macro and generated relative delays between key events
496 """
497 new_macro = []
498
499 start_time = self._current_macro_combo[0][0]
500 for event_time, key, state in self._current_macro_combo:
501 delay = (event_time - start_time).microseconds
502 start_time = event_time
503 new_macro.append(MacroKey(key, delay, state))
504
505 self._macros[self._current_macro_bind_key] = new_macro
506
507 def clean_macro_threads(self):
508 """
509 Threadless-threadpool
510
511 Goes though the threads (macro play jobs) and removed the threads if they have finished.
512 #SetMagic
513 """
514 self._logger.debug("Cleaning up macro threads")
515 to_remove = set()
516
517 for macro_thread in self._threads:
518 macro_thread.join(timeout=0.05)
519 if not macro_thread.is_alive():
520 to_remove.add(macro_thread)
521
522 self._threads -= to_remove
523
524 def play_macro(self, macro_key):
525 """
526 Play macro for a given key
527
528 Launches a thread and adds it to the pool
529 :param macro_key: Macro Key
530 :type macro_key: str
531 """
532 self._logger.info("Running Macro %s:%s", macro_key, str(self._macros[macro_key]))
533 macro_thread = MacroRunner(self._device_id, macro_key, self._macros[macro_key])
534 macro_thread.start()
535 self._threads.add(macro_thread)
536
537 # Methods to be used with DBus
538 def dbus_delete_macro(self, key_name):
539 """
540 Delete a macro from a key
541
542 :param key_name: Key Name
543 :type key_name: str
544 """
545 try:
546 del self._macros[key_name]
547 except KeyError:
548 pass
549
550 def dbus_get_macros(self):
551 """
552 Get macros in JSON format
553
554 Returns a JSON blob of all active macros in the format of
555 {BIND_KEY: [MACRO_DICT...]}
556
557 MACRO_DICT is a dict representation of an action that can be performed. The dict will have a
558 type key which determines what type of action it will perform.
559 For example there are key press macros, URL opening macros, Script running macros etc...
560 :return: JSON of macros
561 :rtype: str
562 """
563 result_dict = {}
564 for macro_key, macro_combo in self._macros.items():
565 str_combo = [value.to_dict() for value in macro_combo]
566 result_dict[macro_key] = str_combo
567
568 return json.dumps(result_dict)
569
570 def dbus_add_macro(self, macro_key, macro_json):
571 """
572 Add macro from JSON
573
574 The macro_json will be a list of macro objects which is then converted into JSON
575 :param macro_key: Macro bind key
576 :type macro_key: str
577
578 :param macro_json: Macro JSON
579 :type macro_json: str
580 """
581 macro_list = [macro_dict_to_obj(macro_object_dict) for macro_object_dict in json.loads(macro_json)]
582 self._macros[macro_key] = macro_list
583
584 def close(self):
585 """
586 Cleanup function
587 """
588 if self._keywatcher.is_alive():
589 self._parent.remove_observer(self)
590
591 self._logger.debug("Stopping key manager")
592 self._keywatcher.shutdown = True
593 self._keywatcher.join(timeout=2)
594 if self._keywatcher.is_alive():
595 self._logger.error("Could not stop KeyWatcher thread")
596
597 def __del__(self):
598 self.close()
599
600 def notify(self, msg):
601 """
602 Receive notificatons from the device (we only care about effects)
603
604 :param msg: Notification
605 :type msg: tuple
606 """
607 if not isinstance(msg, tuple):
608 self._logger.warning("Got msg that was not a tuple")
609 elif msg[0] == 'effect':
610 # We have a message directed at us
611 # MSG format
612 # 0 1 2 3
613 # ('effect', Device, 'effectName', 'effectparams'...)
614 # Device is the device the msg originated from (could be parent device)
615 if msg[2] != 'setRipple':
616 # If we are not doing ripple effect then disable the storing of keys
617 # self.temp_key_store_state = False
618 pass
619
620
621 class NagaHexV2KeyManager(KeyboardKeyManager):
622 KEY_MAP = NAGA_HEX_V2_KEY_MAPPING
623 EVENT_MAP = NAGA_HEX_V2_EVENT_MAPPING
624
625
626 class GamepadKeyManager(KeyboardKeyManager):
627 GAMEPAD_EVENT_MAPPING = TARTARUS_EVENT_MAPPING
628 GAMEPAD_KEY_MAPPING = TARTARUS_KEY_MAPPING
629
630 def __init__(self, device_id, event_files, parent, use_epoll=True, testing=False):
631 super().__init__(device_id, event_files, parent, use_epoll, testing=testing)
632
633 self._mode_modifier = False
634 self._mode_modifier_combo = []
635 self._mode_modifier_key_down = False
636
637 def key_action(self, event_time, key_id, key_press=True):
638 """
639 Process a key press event
640
641 Ok an attempt to explain the logic
642 * The function sets a value _fn_down depending on the state of FN.
643 * Adds keypress and release events to a macro list if recording a macro.
644 * Pressing FN+F9 starts recording a macro, then selecting any key marks that as a macro key,
645 then it will record keys, then pressing FN+F9 will save macro.
646 * Pressing any macro key will run macro.
647 * Pressing FN+F10 will toggle game mode.
648 :param event_time: Time event occurred
649 :type event_time: datetime.datetime
650
651 :param key_id: Key Event ID
652 :type key_id: int
653
654 :param key_press: If true then its a press, else its a release
655 :type key_press: bool
656 """
657 # Disable pylints complaining for this part, #PerformanceOverNeatness
658 # pylint: disable=too-many-branches,too-many-statements
659 self._access_lock.acquire()
660
661 if not self._event_files_locked:
662 self.grab_event_files(True)
663
664 now = datetime.datetime.now()
665
666 # Remove expired keys from store
667 try:
668 # Get date and if its less than now its expired
669 while self._temp_key_store[0][0] < now:
670 self._temp_key_store.pop(0)
671 except IndexError:
672 pass
673
674 # Clean up any threads
675 if self._clean_counter > 20 and len(self._threads) > 0:
676 self._clean_counter = 0
677 self.clean_macro_threads()
678
679 try:
680 # Convert event ID to key name
681
682 key_name = self.GAMEPAD_EVENT_MAPPING[key_id]
683 # Key press
684
685 if self._temp_key_store_active:
686 colour = random_colour_picker(self._last_colour_choice, COLOUR_CHOICES)
687 self._last_colour_choice = colour
688 self._temp_key_store.append((now + self._temp_expire_time, self.GAMEPAD_KEY_MAPPING[key_name], colour))
689
690 # if self._testing:
691 # if key_press:
692 # self._logger.debug("Got Key: {0} Down".format(key_name))
693 # else:
694 # self._logger.debug("Got Key: {0} Up".format(key_name))
695
696 # Logic for mode switch modifier
697 if self._mode_modifier:
698 if key_name == 'MODE_SWITCH' and key_press:
699 # Start the macro string
700 self._mode_modifier_key_down = True
701 self._mode_modifier_combo.clear()
702 self._mode_modifier_combo.append('MODE')
703
704 elif key_name == 'MODE_SWITCH' and not key_press:
705 # Release mode_switch
706 self._mode_modifier_key_down = False
707
708 elif key_press and self._mode_modifier_key_down:
709 # Any keys pressed whilst mode_switch is down
710 self._mode_modifier_combo.append(key_name)
711
712 # Override keyname so it now equals a macro
713 key_name = '+'.join(self._mode_modifier_combo)
714
715 self._logger.debug("Macro String: {0}".format(key_name))
716
717 if key_name in self._macros and key_press:
718 self.play_macro(key_name)
719
720 except KeyError as err:
721 self._logger.exception("Got key error. Couldn't convert event to key name", exc_info=err)
722
723 self._access_lock.release()
724
725 @property
726 def mode_modifier(self):
727 """
728 Get if the MODE_SWTICH key is to act as a modifier
729
730 :return: True if a modifier, false if not
731 :rtype: bool
732 """
733 return self._mode_modifier
734
735 @mode_modifier.setter
736 def mode_modifier(self, value):
737 """
738 Set MODE_SWITCH modifier state
739
740 :param value: Modifier state
741 :type value: bool
742 """
743 self._mode_modifier = True if value else False
744
745
746 class OrbweaverKeyManager(GamepadKeyManager):
747 GAMEPAD_EVENT_MAPPING = ORBWEAVER_EVENT_MAPPING
748 GAMEPAD_KEY_MAPPING = ORBWEAVER_KEY_MAPPING