/packages/sx05re/reicastsa/evdev/util.py

https://github.com/shantigilbert/Sx05RE
Python | 96 lines | 49 code | 25 blank | 22 comment | 15 complexity | 42006da5fb21b5c70ba99ecb3839caeb MD5 | raw file
  1. # encoding: utf-8
  2. import os
  3. import stat
  4. import glob
  5. from evdev import ecodes
  6. from evdev.events import event_factory
  7. def list_devices(input_device_dir='/dev/input'):
  8. '''List readable character devices.'''
  9. fns = glob.glob('{}/event*'.format(input_device_dir))
  10. fns = list(filter(is_device, fns))
  11. return fns
  12. def is_device(fn):
  13. '''Determine if a file exists, is readable and is a character device.'''
  14. if not os.path.exists(fn):
  15. return False
  16. m = os.stat(fn)[stat.ST_MODE]
  17. if not stat.S_ISCHR(m):
  18. return False
  19. if not os.access(fn, os.R_OK):
  20. return False
  21. return True
  22. def categorize(event):
  23. '''
  24. Categorize an event according to its type.
  25. The :data:`event_factory <evdev.events.event_factory>` dictionary maps
  26. event types to their classes. If there is no corresponding key, the event
  27. is returned as it was.
  28. '''
  29. if event.type in event_factory:
  30. return event_factory[event.type](event)
  31. else:
  32. return event
  33. def resolve_ecodes(typecodemap, unknown='?'):
  34. '''
  35. Resolve event codes and types to their verbose names.
  36. :param typecodemap: mapping of event types to lists of event codes
  37. :param unknown: symbol to which unknown types or codes will be resolved
  38. Example::
  39. resolve_ecodes({ 1 : [272, 273, 274] })
  40. { ('EV_KEY', 1) : [('BTN_MOUSE', 272), ('BTN_RIGHT', 273), ('BTN_MIDDLE', 274)] }
  41. If the typecodemap contains absolute axis info (wrapped in
  42. instances of `AbsInfo <evdev.device.AbsInfo>`) the result would
  43. look like::
  44. resove_ecodes({ 3 : [(0, AbsInfo(...))] })
  45. { ('EV_ABS', 3L): [(('ABS_X', 0L), AbsInfo(...))] }
  46. '''
  47. for etype, codes in typecodemap.items():
  48. type_name = ecodes.EV[etype]
  49. # ecodes.keys are a combination of KEY_ and BTN_ codes
  50. if etype == ecodes.EV_KEY:
  51. code_names = ecodes.keys
  52. else:
  53. code_names = getattr(ecodes, type_name.split('_')[-1])
  54. res = []
  55. for i in codes:
  56. # elements with AbsInfo(), eg { 3 : [(0, AbsInfo(...)), (1, AbsInfo(...))] }
  57. if isinstance(i, tuple):
  58. l = ((code_names[i[0]], i[0]), i[1]) if i[0] in code_names \
  59. else ((unknown, i[0]), i[1])
  60. # just ecodes { 0 : [0, 1, 3], 1 : [30, 48] }
  61. else:
  62. l = (code_names[i], i) if i in code_names else (unknown, i)
  63. res.append(l)
  64. yield (type_name, etype), res
  65. __all__ = ('list_devices', 'is_device', 'categorize', 'resolve_ecodes')