Debian Codegraph @

tools/show-stylus.py

raw
1 #!/usr/bin/env python3
2 #
3 # Permission to use, copy, modify, distribute, and sell this software
4 # and its documentation for any purpose is hereby granted without
5 # fee, provided that the above copyright notice appear in all copies
6 # and that both that copyright notice and this permission notice
7 # appear in supporting documentation, and that the name of Red Hat
8 # not be used in advertising or publicity pertaining to distribution
9 # of the software without specific, written prior permission. Red
10 # Hat makes no representations about the suitability of this software
11 # for any purpose. It is provided "as is" without express or implied
12 # warranty.
13 #
14 # THE AUTHORS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
15 # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
16 # NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
17 # CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
18 # OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
19 # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
20 # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21 #
22
23 import argparse
24 import configparser
25 import os
26 import sys
27 from pathlib import Path
28
29 try:
30 import libevdev
31 import pyudev
32 except ModuleNotFoundError as e:
33 print("Error: {}".format(str(e)), file=sys.stderr)
34 print(
35 "One or more python modules are missing. Please install those "
36 "modules and re-run this tool."
37 )
38 sys.exit(1)
39
40
41 def xdg_dir():
42 return Path(os.getenv("XDG_CONFIG_HOME", Path.home() / ".config")) / "libwacom"
43
44
45 class Ansi:
46 clearline = "\x1b[K"
47
48 @classmethod
49 def up(cls, count):
50 return f"\x1b[{count}A"
51
52 @classmethod
53 def down(cls, count):
54 return f"\x1b[{count}B"
55
56 @classmethod
57 def right(cls, count):
58 return f"\x1b[{count}C"
59
60 @classmethod
61 def left(cls, count):
62 return f"\x1b[{count}D"
63
64
65 def die(msg):
66 print(msg, file=sys.stderr)
67 sys.exit(1)
68
69
70 def select_device():
71 context = pyudev.Context()
72 for device in context.list_devices(subsystem="input"):
73 if device.get("ID_INPUT_TABLET", 0) and (device.device_node or "").startswith(
74 "/dev/input/event"
75 ):
76 name = device.get("NAME", None)
77 if not name:
78 name = next(
79 (p.get("NAME") for p in device.ancestors if p.get("NAME")),
80 "unknown",
81 )
82
83 print("Using {}: {}".format(name or "unknown", device.device_node))
84 return device.device_node
85
86 die("Unable to find a tablet device.")
87
88
89 def record_events(ns):
90 with open(ns.device_path, "rb") as fd:
91 d = libevdev.Device(fd)
92 if not d.absinfo[libevdev.EV_ABS.ABS_MISC]:
93 die("Device only supports generic styli")
94
95 tool_bits = set(
96 c for c in libevdev.EV_KEY.codes if c.name.startswith("BTN_TOOL_")
97 )
98 styli = {} # dict of (type, serial) = proximity_state
99 current_type, current_serial = 0, 0
100 in_prox = False
101 dirty = False
102
103 print("Please put tool in proximity")
104
105 try:
106 while True:
107 for event in d.events():
108 if event.matches(libevdev.EV_ABS.ABS_MISC):
109 if event.value != 0:
110 current_type = event.value
111 dirty = True
112 elif event.matches(libevdev.EV_MSC.MSC_SERIAL):
113 if event.value != 0:
114 current_serial = event.value & 0xFFFFFFFF
115 dirty = True
116 elif event.code in tool_bits:
117 # print(f'Current prox: {event.value}')
118 in_prox = event.value != 0
119 dirty = True
120 elif event.matches(libevdev.EV_SYN.SYN_REPORT) and dirty:
121 dirty = False
122 print(
123 f"{Ansi.up(len(styli))}{Ansi.left(10000)}{Ansi.clearline}",
124 end="",
125 )
126 styli[(current_type, current_serial)] = in_prox
127 for s, prox in styli.items():
128 tid, serial = s
129 print(
130 f"Tool id {tid:#x} serial {serial:#x} in-proximity: {prox} "
131 )
132 except KeyboardInterrupt:
133 print("Terminating")
134
135 return [s[0] for s in styli.keys()]
136
137
138 def load_data_files():
139 lookup_paths = (
140 ("./data/",),
141 ("@DATADIR@", "@ETCDIR@", xdg_dir()),
142 ("/usr/share/libwacom/", "/etc/libwacom/"),
143 )
144 stylusfiles = []
145 for paths in lookup_paths:
146 stylusfiles = []
147 for p in paths:
148 files = list(Path(p).glob("*.stylus"))
149 if files:
150 stylusfiles += files
151
152 if any(stylusfiles):
153 break
154 else:
155 die("Unable to find a libwacom.stylus data file")
156
157 print(f"Using stylus file(s): {', '.join([str(s) for s in stylusfiles])}")
158
159 styli = {}
160
161 for path in stylusfiles:
162 config = configparser.ConfigParser()
163 config.read(path)
164 for stylus_id in config.sections():
165 ids = stylus_id.split(":")
166 if len(ids) > 1:
167 _, sid = map(lambda x: int(x, 16), ids)
168 else:
169 _ = 0x56A # vid
170 sid = int(ids[0], 16)
171 # FIXME: vendor should be used here, let's do that when we figure out
172 # who needs it.
173 styli[sid] = config[stylus_id].get("Group", stylus_id)
174
175 return styli
176
177
178 def main():
179 parser = argparse.ArgumentParser(description="Tool to show tablet stylus ids")
180 parser.add_argument(
181 "device_path", nargs="?", default=None, help="Path to the /dev/input/event node"
182 )
183
184 ns = parser.parse_args()
185 if not ns.device_path:
186 ns.device_path = select_device()
187
188 all_styli = load_data_files()
189 styli = record_events(ns)
190 groups = []
191 for sid in styli:
192 if sid in all_styli:
193 groups.append(all_styli[sid])
194 else:
195 print(f"Unknown stylus id {sid:#x}. New entry needed")
196 print("Suggested line for .tablet file:")
197 print(f"Styli={';'.join(set(groups))}")
198
199
200 if __name__ == "__main__":
201 try:
202 main()
203 except PermissionError:
204 die("Insufficient permissions, please run me as root")