Debian Codegraph @

src/evdev/util.py

raw
1 import collections
2 import glob
3 import os
4 import re
5 import stat
6
7 from . import ecodes
8 from .events import InputEvent, event_factory, KeyEvent, RelEvent, AbsEvent, SynEvent
9
10
11 def list_devices(input_device_dir: str | bytes | os.PathLike = "/dev/input", writable: bool = True) -> list[str]:
12 """List readable (and optionally writable) character devices in ``input_device_dir``.
13
14 Arguments
15 ---------
16 input_device_dir
17 Path to the input device directory. Default is ``/dev/input``.
18 writable
19 Only list devices that are both readable and writable.
20 """
21
22 fns = glob.glob("{}/event*".format(input_device_dir))
23 return [fn for fn in fns if is_device(fn, writable=writable)]
24
25
26 def is_device(fn: str | bytes | os.PathLike, writable: bool = True) -> bool:
27 """Check if ``fn`` is a readable (and optionally writable) character device."""
28
29 if not os.path.exists(fn):
30 return False
31
32 m = os.stat(fn)[stat.ST_MODE]
33 if not stat.S_ISCHR(m):
34 return False
35
36 access = (os.R_OK | os.W_OK) if writable else os.R_OK
37 if not os.access(fn, access):
38 return False
39
40 return True
41
42
43 def categorize(event: InputEvent) -> InputEvent | KeyEvent | RelEvent | AbsEvent | SynEvent:
44 """
45 Categorize an event according to its type.
46
47 The :data:`event_factory <evdev.events.event_factory>` dictionary
48 maps event types to sub-classes of :class:`InputEvent
49 <evdev.events.InputEvent>`. If the event cannot be categorized, it
50 is returned unmodified."""
51
52 if event.type in event_factory:
53 return event_factory[event.type](event)
54 else:
55 return event
56
57
58 def resolve_ecodes_dict(typecodemap, unknown="?"):
59 """
60 Resolve event codes and types to their verbose names.
61
62 :param typecodemap: mapping of event types to lists of event codes.
63 :param unknown: symbol to which unknown types or codes will be resolved.
64
65 Example
66 -------
67 >>> resolve_ecodes_dict({ 1: [272, 273, 274] })
68 { ('EV_KEY', 1): [('BTN_MOUSE', 272),
69 ('BTN_RIGHT', 273),
70 ('BTN_MIDDLE', 274)] }
71
72 If ``typecodemap`` contains absolute axis info (instances of
73 :class:`AbsInfo <evdev.device.AbsInfo>` ) the result would look
74 like:
75
76 >>> resolve_ecodes_dict({ 3: [(0, AbsInfo(...))] })
77 { ('EV_ABS', 3L): [(('ABS_X', 0L), AbsInfo(...))] }
78 """
79
80 for etype, codes in typecodemap.items():
81 type_name = ecodes.EV[etype]
82
83 # ecodes.keys are a combination of KEY_ and BTN_ codes
84 if etype == ecodes.EV_KEY:
85 ecode_dict = ecodes.keys
86 else:
87 ecode_dict = getattr(ecodes, type_name.split("_")[-1])
88
89 resolved = resolve_ecodes(ecode_dict, codes, unknown)
90 yield (type_name, etype), resolved
91
92
93 def resolve_ecodes(ecode_dict, ecode_list, unknown="?"):
94 """
95 Resolve event codes and types to their verbose names.
96
97 Example
98 -------
99 >>> resolve_ecodes(ecodes.BTN, [272, 273, 274])
100 [(['BTN_LEFT', 'BTN_MOUSE'], 272), ('BTN_RIGHT', 273), ('BTN_MIDDLE', 274)]
101 """
102 res = []
103 for ecode in ecode_list:
104 # elements with AbsInfo(), eg { 3 : [(0, AbsInfo(...)), (1, AbsInfo(...))] }
105 if isinstance(ecode, tuple):
106 if ecode[0] in ecode_dict:
107 l = ((ecode_dict[ecode[0]], ecode[0]), ecode[1])
108 else:
109 l = ((unknown, ecode[0]), ecode[1])
110
111 # just ecodes, e.g: { 0 : [0, 1, 3], 1 : [30, 48] }
112 else:
113 if ecode in ecode_dict:
114 l = (ecode_dict[ecode], ecode)
115 else:
116 l = (unknown, ecode)
117 res.append(l)
118
119 return res
120
121
122 def find_ecodes_by_regex(regex):
123 """
124 Find ecodes matching a regex and return a mapping of event type to event codes.
125
126 regex can be a pattern string or a compiled regular expression object.
127
128 Example
129 -------
130 >>> find_ecodes_by_regex(r'(ABS|KEY)_BR(AKE|EAK)')
131 {1: [411], 3: [10]}
132 >>> res = find_ecodes_by_regex(r'(ABS|KEY)_BR(AKE|EAK)')
133 >>> resolve_ecodes_dict(res)
134 {
135 ('EV_KEY', 1): [('KEY_BREAK', 411)],
136 ('EV_ABS', 3): [('ABS_BRAKE', 10)]
137 }
138 """
139
140 regex = re.compile(regex) # re.compile is idempotent
141 result = collections.defaultdict(list)
142
143 for type_code, codes in ecodes.bytype.items():
144 for code, names in codes.items():
145 names = (names,) if isinstance(names, str) else names
146 for name in names:
147 if regex.match(name):
148 result[type_code].append(code)
149 break
150
151 return dict(result)
152
153
154 __all__ = ("list_devices", "is_device", "categorize", "resolve_ecodes", "resolve_ecodes_dict", "find_ecodes_by_regex")