keyboard.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import traceback
  2. from typing import Awaitable, Callable, Optional, Union
  3. from ..events import KeyEventArguments, KeyboardAction, KeyboardKey, KeyboardModifiers, handle_event
  4. from .custom_view import CustomView
  5. from .element import Element
  6. class KeyboardView(CustomView):
  7. def __init__(self, on_key: Callable):
  8. super().__init__('keyboard', __file__, activeJSEvents=['keydown', 'keyup', 'keypress'])
  9. self.allowed_events = ['keyboardEvent']
  10. self.style = 'display: none'
  11. self.initialize(temp=False, on_keyboardEvent=on_key)
  12. class Keyboard(Element):
  13. def __init__(self,
  14. *,
  15. on_key: Optional[Union[Callable, Awaitable]] = None,
  16. active: bool = True,
  17. ):
  18. """
  19. Keyboard
  20. Adds global keyboard event tracking.
  21. :param handle_keys: callback to be executed when keyboard events occur.
  22. :param active: boolean flag indicating whether the callback should be executed or not
  23. """
  24. super().__init__(KeyboardView(on_key=self.handle_key))
  25. self.active = active
  26. self.key_handler = on_key
  27. def handle_key(self, msg: dict):
  28. if not self.active:
  29. return
  30. try:
  31. action = KeyboardAction(
  32. keypress=msg.key_data.action == 'keypress',
  33. keydown=msg.key_data.action == 'keydown',
  34. keyup=msg.key_data.action == 'keyup',
  35. repeat=msg.key_data.repeat,
  36. )
  37. modifiers = KeyboardModifiers(
  38. alt=msg.key_data.altKey,
  39. ctrl=msg.key_data.ctrlKey,
  40. meta=msg.key_data.metaKey,
  41. shift=msg.key_data.shiftKey,
  42. )
  43. key = KeyboardKey(
  44. name=msg.key_data.key,
  45. code=msg.key_data.code,
  46. location=msg.key_data.location,
  47. )
  48. handle_event(self.key_handler, KeyEventArguments(sender=self, action=action, modifiers=modifiers, key=key))
  49. except Exception:
  50. traceback.print_exc()