Debian Codegraph @

tools/libwacom-update-db.py

raw
1 #!/usr/bin/env python3
2 #
3 # Copyright © 2012 Red Hat, Inc.
4 #
5 # Permission to use, copy, modify, distribute, and sell this software
6 # and its documentation for any purpose is hereby granted without
7 # fee, provided that the above copyright notice appear in all copies
8 # and that both that copyright notice and this permission notice
9 # appear in supporting documentation, and that the name of Red Hat
10 # not be used in advertising or publicity pertaining to distribution
11 # of the software without specific, written prior permission. Red
12 # Hat makes no representations about the suitability of this software
13 # for any purpose. It is provided "as is" without express or implied
14 # warranty.
15 #
16 # THE AUTHORS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
17 # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
18 # NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
19 # CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
20 # OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
21 # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
22 # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23
24 import argparse
25 import configparser
26 import os
27 import sys
28 import subprocess
29 import tempfile
30 from pathlib import Path
31
32
33 def xdg_dir():
34 return Path(os.getenv("XDG_CONFIG_HOME", Path.home() / ".config")) / "libwacom"
35
36
37 class Tablet(object):
38 def __init__(self, name, bus, vid, pid):
39 self.name = name
40 self.bus = bus
41 self.vid = vid # Note: this is a string
42 self.pid = pid # Note: this is a string
43 self.has_touch = False
44 self.has_pad = False
45 self.is_touchscreen = False
46
47 # We have everything in strings so let's use that for sorting later
48 # This will sort bluetooth before usb but meh
49 self.cmpstr = ":".join((bus, vid, pid, name))
50
51 def __lt__(self, other):
52 return self.cmpstr < other.cmpstr
53
54 def __str__(self):
55 return f"{self.bus}:{self.vid}:{self.pid}:{self.name}"
56
57
58 class HWDBFile:
59 def __init__(self):
60 self.tablets = []
61
62 def _tablet_entry(self, tablet):
63 vid = tablet.vid.upper()
64 pid = tablet.pid.upper()
65 bustypes = {
66 "usb": "0003",
67 "bluetooth": "0005",
68 }
69 # serial devices have their own rules, so we skip anything that
70 # doesn't have straight conversion
71 try:
72 bus = bustypes[tablet.bus]
73 except KeyError:
74 return
75
76 match = f"b{bus}v{vid}p{pid}"
77 entries = {"*": ["ID_INPUT=1", "ID_INPUT_TABLET=1", "ID_INPUT_JOYSTICK=0"]}
78 if tablet.has_touch:
79 if tablet.is_touchscreen:
80 entries["* Finger"] = ["ID_INPUT_TOUCHSCREEN=1"]
81 else:
82 entries["* Finger"] = ["ID_INPUT_TOUCHPAD=1"]
83
84 if tablet.has_pad:
85 entries["* Pad"] = ["ID_INPUT_TABLET_PAD=1"]
86
87 # Non-Wacom devices often have a Keyboard node instead of a Pad
88 # device. If they share the USB ID with the tablet, we likely just
89 # assigned ID_INPUT_TABLET to a keyboard device - and libinput refuses
90 # to accept those.
91 # Let's add a generic exclusion rule for anything we know of with a
92 # Keyboard device name.
93 entries["* Keyboard"] = ["ID_INPUT_TABLET=0", "ID_INPUT_TABLET_PAD=0"]
94 entries["* Mouse"] = ["ID_INPUT_TABLET=0", "ID_INPUT_TABLET_PAD=0"]
95
96 lines = [f"# {tablet.name}"]
97 for name, props in entries.items():
98 lines.append(f"libwacom:name:{name}:input:{match}*")
99 lines.extend([f" {p}" for p in props])
100 lines.append("")
101
102 return "\n".join(lines)
103
104 def print(self, file=sys.stdout):
105 header = (
106 "# hwdb entries for libwacom supported devices",
107 "# This file is generated by libwacom, do not edit",
108 "#",
109 "# The lookup key is a contract between the udev rules and the hwdb entries.",
110 "# It is not considered public API and may change.",
111 "",
112 )
113 print("\n".join(header), file=file)
114
115 for t in self.tablets:
116 entry = self._tablet_entry(t)
117 if entry:
118 print(entry, file=file)
119
120
121 class TabletDatabase:
122 def __init__(self, path):
123 self.path = path
124 self.tablets = sorted(self._load(path))
125
126 def _load(self, path):
127 for file in Path(path).glob("*.tablet"):
128 config = configparser.ConfigParser()
129 config.read(file)
130 for match in config["Device"]["DeviceMatch"].split(";"):
131 # ignore trailing semicolons
132 if not match or match == "generic":
133 continue
134
135 # For hwdb entries we don't care about name matches,
136 # it'll just result in duplicate ID_INPUT_TABLET assignments
137 # for tablets with re-used usbids and that doesn't matter
138 try:
139 bus, vid, pid, *_ = match.split("|")
140 except ValueError as e:
141 print(f"Failed to process match {match} in {file}", file=sys.stderr)
142 raise e
143
144 name = config["Device"]["Name"]
145 t = Tablet(name, bus, vid, pid)
146
147 try:
148 t.has_touch = config["Features"]["Touch"].lower() == "true"
149 if t.has_touch:
150 integration = config["Device"]["IntegratedIn"]
151 t.is_touchscreen = (
152 "Display" in integration or "System" in integration
153 )
154 except KeyError:
155 pass
156 t.has_pad = any(config.has_section(s) for s in ["Buttons", "Keys"])
157 yield t
158
159
160 # Guess the udev directory based on path. For the case of /usr/share, the
161 # udev directory is probably in /usr/lib so let's fallback to that.
162 def find_udev_base_dir(paths):
163 for path in paths:
164 for parent in path.parents:
165 d = Path(parent / "udev" / "rules.d")
166 if d.exists():
167 return d.parent
168
169 # /usr/share but also any custom prefixes
170 for parent in path.parents:
171 d = Path(parent / "lib" / "udev" / "rules.d")
172 if d.exists():
173 return d.parent
174
175 raise FileNotFoundError(paths)
176
177
178 # udev's behaviour is that where a file X exists in two locations,
179 # only the highest-precedence one is read. Our files are supposed to be
180 # complimentary to the system-installed ones (which default to
181 # 65-libwacom.hwdb) so we bump the filename number.
182 def guess_hwdb_filename(basedir):
183 hwdbdir = Path(basedir) / "hwdb.d"
184 if not hwdbdir.exists():
185 raise FileNotFoundError(hwdbdir)
186
187 fname = hwdbdir / "66-libwacom.hwdb"
188 return fname
189
190
191 if __name__ == "__main__":
192 parser = argparse.ArgumentParser(
193 description="Update the system according to the current set of tablet data files"
194 )
195 parser.add_argument(
196 "path",
197 nargs="?",
198 type=Path,
199 default=None,
200 help="Directory to load .tablet files from. Default: $XDG_CONFIG_HOME/libwacom and /etc/libwacom",
201 )
202 # buildsystem-mode is what we use from meson, it changes the
203 # the behavior to just generate the file and print it
204 parser.add_argument(
205 "--buildsystem-mode",
206 action="store_true",
207 default=False,
208 help="be used by the build system only",
209 )
210 parser.add_argument(
211 "--skip-systemd-hwdb-update",
212 action="store_true",
213 default=False,
214 help="Do not run systemd-hwdb --update (Note: updates to tablet files will not be reflected in udev)",
215 )
216 parser.add_argument(
217 "--udev-base-dir",
218 type=Path,
219 default=None,
220 help="The udev base directory (default: guessed based on the path)",
221 )
222 ns = parser.parse_args()
223
224 if ns.path is None:
225 paths = [xdg_dir(), Path("/etc/libwacom")]
226 else:
227 paths = [ns.path]
228
229 # Reverse the list so the most important one is last and takes precedence
230 paths.reverse()
231 dbs = [TabletDatabase(p) for p in paths]
232
233 hwdb = HWDBFile()
234 # Bamboo and Intuos devices connected to the system via Wacom's
235 # Wireless Accessory Kit appear to udev as having the PID of the
236 # dongle rather than the actual tablet. Make sure we properly tag
237 # such devices.
238 #
239 # We only really care about this in the official hwdb files
240 if ns.buildsystem_mode:
241 wwak = Tablet("Wacom Wireless Accessory Kit", "usb", "056A", "0084")
242 wwak.has_pad = True
243 wwak.has_touch = True
244 hwdb.tablets.append(wwak)
245
246 for db in dbs:
247 hwdb.tablets.extend(db.tablets)
248
249 if ns.buildsystem_mode:
250 hwdb.print()
251 else:
252 if os.geteuid() == 0:
253 print(
254 "WARNING: Running this command as root will not pick up .tablet files in $XDG_CONFIG_HOME/libwacom"
255 )
256
257 try:
258 udevdir = ns.udev_base_dir or find_udev_base_dir(paths)
259 hwdbfile = guess_hwdb_filename(udevdir)
260
261 with tempfile.NamedTemporaryFile(
262 mode="w+", prefix=f"{hwdbfile.name}-XXXXXX", encoding="utf-8"
263 ) as fd:
264 hwdb.print(fd)
265 print(f"Using sudo to copy hwdb file to {hwdbfile}")
266 subprocess.run(["sudo", "cp", f"{fd.name}", hwdbfile.absolute()])
267
268 if not ns.skip_systemd_hwdb_update:
269 print("Using sudo to run systemd-hwdb update")
270 subprocess.run(
271 ["sudo", "systemd-hwdb", "update"],
272 capture_output=True,
273 check=True,
274 text=True,
275 )
276 print("Finished, please unplug and replug your device")
277 except PermissionError as e:
278 print(f"{e}, please run me as root")
279 except FileNotFoundError as e:
280 print(f"Unable to find udev base directory: {e}")
281 except subprocess.CalledProcessError as e:
282 print(f"hwdb update failed: {e.stderr}")
283 except KeyboardInterrupt:
284 pass