libinput-measure-fuzz.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. #!/usr/bin/env python3
  2. # vim: set expandtab shiftwidth=4:
  3. # -*- Mode: python; coding: utf-8; indent-tabs-mode: nil -*- */
  4. #
  5. # Copyright © 2018 Red Hat, Inc.
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a
  8. # copy of this software and associated documentation files (the 'Software'),
  9. # to deal in the Software without restriction, including without limitation
  10. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  11. # and/or sell copies of the Software, and to permit persons to whom the
  12. # Software is furnished to do so, subject to the following conditions:
  13. #
  14. # The above copyright notice and this permission notice (including the next
  15. # paragraph) shall be included in all copies or substantial portions of the
  16. # Software.
  17. #
  18. # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  21. # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  23. # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  24. # DEALINGS IN THE SOFTWARE.
  25. #
  26. import argparse
  27. import os
  28. import subprocess
  29. import sys
  30. try:
  31. import libevdev
  32. import pyudev
  33. except ModuleNotFoundError as e:
  34. print(f"Error: {e!s}", file=sys.stderr)
  35. print(
  36. "One or more python modules are missing. Please install those "
  37. "modules and re-run this tool."
  38. )
  39. sys.exit(1)
  40. DEFAULT_HWDB_FILE = "/usr/lib/udev/hwdb.d/60-evdev.hwdb"
  41. OVERRIDE_HWDB_FILE = "/etc/udev/hwdb.d/99-touchpad-fuzz-override.hwdb"
  42. class tcolors:
  43. GREEN = "\033[92m"
  44. RED = "\033[91m"
  45. YELLOW = "\033[93m"
  46. BOLD = "\033[1m"
  47. NORMAL = "\033[0m"
  48. def print_bold(msg, **kwargs):
  49. print(tcolors.BOLD + msg + tcolors.NORMAL, **kwargs)
  50. def print_green(msg, **kwargs):
  51. print(tcolors.BOLD + tcolors.GREEN + msg + tcolors.NORMAL, **kwargs)
  52. def print_yellow(msg, **kwargs):
  53. print(tcolors.BOLD + tcolors.YELLOW + msg + tcolors.NORMAL, **kwargs)
  54. def print_red(msg, **kwargs):
  55. print(tcolors.BOLD + tcolors.RED + msg + tcolors.NORMAL, **kwargs)
  56. class InvalidConfigurationError(Exception):
  57. pass
  58. class InvalidDeviceError(Exception):
  59. pass
  60. class Device(libevdev.Device):
  61. def __init__(self, path):
  62. if path is None:
  63. self.path = self.find_touch_device()
  64. else:
  65. self.path = path
  66. fd = open(self.path, "rb") # noqa: SIM115
  67. super().__init__(fd)
  68. context = pyudev.Context()
  69. self.udev_device = pyudev.Devices.from_device_file(context, self.path)
  70. def find_touch_device(self):
  71. context = pyudev.Context()
  72. for device in context.list_devices(subsystem="input"):
  73. if not device.get("ID_INPUT_TOUCHPAD", 0):
  74. continue
  75. if not device.device_node or not device.device_node.startswith(
  76. "/dev/input/event"
  77. ):
  78. continue
  79. return device.device_node
  80. print("Unable to find a touch device.", file=sys.stderr)
  81. sys.exit(1)
  82. def check_property(self):
  83. """Return a tuple of (xfuzz, yfuzz) with the fuzz as set in the libinput
  84. property. Returns None if the property doesn't exist"""
  85. axes = {
  86. 0x00: self.udev_device.get("LIBINPUT_FUZZ_00"),
  87. 0x01: self.udev_device.get("LIBINPUT_FUZZ_01"),
  88. 0x35: self.udev_device.get("LIBINPUT_FUZZ_35"),
  89. 0x36: self.udev_device.get("LIBINPUT_FUZZ_36"),
  90. }
  91. if axes[0x35] is not None and axes[0x35] != axes[0x00]:
  92. print_bold(
  93. f"WARNING: fuzz mismatch ABS_X: {axes[0x00]}, ABS_MT_POSITION_X: {axes[0x35]}"
  94. )
  95. if axes[0x36] is not None and axes[0x36] != axes[0x01]:
  96. print_bold(
  97. f"WARNING: fuzz mismatch ABS_Y: {axes[0x01]}, ABS_MT_POSITION_Y: {axes[0x36]}"
  98. )
  99. xfuzz = axes[0x35] or axes[0x00]
  100. yfuzz = axes[0x36] or axes[0x01]
  101. if xfuzz is None and yfuzz is None:
  102. return None
  103. if (xfuzz is not None and yfuzz is None) or (
  104. xfuzz is None and yfuzz is not None
  105. ):
  106. raise InvalidConfigurationError("fuzz should be set for both axes")
  107. return (int(xfuzz), int(yfuzz))
  108. def check_axes(self):
  109. """
  110. Returns a tuple of (xfuzz, yfuzz) with the fuzz as set on the device
  111. axis. Returns None if no fuzz is set.
  112. """
  113. if not self.has(libevdev.EV_ABS.ABS_X) or not self.has(libevdev.EV_ABS.ABS_Y):
  114. raise InvalidDeviceError("device does not have x/y axes")
  115. if self.has(libevdev.EV_ABS.ABS_MT_POSITION_X) != self.has(
  116. libevdev.EV_ABS.ABS_MT_POSITION_Y
  117. ):
  118. raise InvalidDeviceError("device does not have both multitouch axes")
  119. xfuzz = (
  120. self.absinfo[libevdev.EV_ABS.ABS_X].fuzz
  121. or self.absinfo[libevdev.EV_ABS.ABS_MT_POSITION_X].fuzz
  122. )
  123. yfuzz = (
  124. self.absinfo[libevdev.EV_ABS.ABS_Y].fuzz
  125. or self.absinfo[libevdev.EV_ABS.ABS_MT_POSITION_Y].fuzz
  126. )
  127. if xfuzz == 0 and yfuzz == 0:
  128. return None
  129. return (xfuzz, yfuzz)
  130. def print_fuzz(what, fuzz):
  131. print(f" Checking {what}... ", end="")
  132. if fuzz is None:
  133. print("not set")
  134. elif fuzz == (0, 0):
  135. print("is zero")
  136. else:
  137. print(f"x={fuzz[0]} y={fuzz[1]}")
  138. def handle_existing_entry(device, fuzz):
  139. # This is getting messy because we don't really know where the entry
  140. # could be or how the match rule looks like. So we just check the
  141. # default location only.
  142. # For the match comparison, we search for the property value in the
  143. # file. If there is more than one entry that uses the same
  144. # overrides this will generate false positives.
  145. # If the lines aren't in the same order in the file, it'll be a false
  146. # negative.
  147. overrides = {
  148. 0x00: device.udev_device.get("EVDEV_ABS_00"),
  149. 0x01: device.udev_device.get("EVDEV_ABS_01"),
  150. 0x35: device.udev_device.get("EVDEV_ABS_35"),
  151. 0x36: device.udev_device.get("EVDEV_ABS_36"),
  152. }
  153. has_existing_rules = False
  154. for value in overrides.values():
  155. if value is not None:
  156. has_existing_rules = True
  157. break
  158. if not has_existing_rules:
  159. return False
  160. print_red("Error! ", end="")
  161. print("This device already has axis overrides defined")
  162. print()
  163. print_bold("Searching for existing override...")
  164. # Construct a template that looks like a hwdb entry (values only) from
  165. # the udev property values
  166. template = [
  167. f" EVDEV_ABS_00={overrides[0x00]}",
  168. f" EVDEV_ABS_01={overrides[0x01]}",
  169. ]
  170. if overrides[0x35] is not None:
  171. template += [
  172. f" EVDEV_ABS_35={overrides[0x35]}",
  173. f" EVDEV_ABS_36={overrides[0x36]}",
  174. ]
  175. print(f"Checking in {OVERRIDE_HWDB_FILE}... ", end="")
  176. entry, prefix, lineno = check_file_for_lines(OVERRIDE_HWDB_FILE, template)
  177. if entry is not None:
  178. print_green("found")
  179. print("The existing hwdb entry can be overwritten")
  180. return False
  181. else:
  182. print_red("not found")
  183. print(f"Checking in {DEFAULT_HWDB_FILE}... ", end="")
  184. entry, prefix, lineno = check_file_for_lines(DEFAULT_HWDB_FILE, template)
  185. if entry is not None:
  186. print_green("found")
  187. else:
  188. print_red("not found")
  189. print(
  190. "The device has a hwdb override defined but it's not where I expected it to be."
  191. )
  192. print("Please look at the libinput documentation for more details.")
  193. print("Exiting now.")
  194. return True
  195. print_bold(f"Probable entry for this device found in line {lineno}:")
  196. print("\n".join(prefix + entry))
  197. print()
  198. print_bold("Suggested new entry for this device:")
  199. new_entry = []
  200. for i in range(len(template)):
  201. parts = entry[i].split(":")
  202. while len(parts) < 4:
  203. parts.append("")
  204. parts[3] = str(fuzz)
  205. new_entry.append(":".join(parts))
  206. print("\n".join(prefix + new_entry))
  207. print()
  208. # Not going to overwrite the 60-evdev.hwdb entry with this program, too
  209. # risky. And it may not be our device match anyway.
  210. print_bold("You must now:")
  211. print(
  212. "\n".join(
  213. (
  214. "1. Check the above suggestion for sanity. Does it match your device?",
  215. f"2. Open {DEFAULT_HWDB_FILE} and amend the existing entry",
  216. " as recommended above",
  217. "",
  218. " The property format is:",
  219. " EVDEV_ABS_00=min:max:resolution:fuzz",
  220. "",
  221. " Leave the entry as-is and only add or amend the fuzz value.",
  222. " A non-existent value can be skipped, e.g. this entry sets the ",
  223. " resolution to 32 and the fuzz to 8",
  224. " EVDEV_ABS_00=::32:8",
  225. "",
  226. "3. Save the edited file",
  227. "4. Say Y to the next prompt",
  228. )
  229. )
  230. )
  231. cont = input("Continue? [Y/n] ")
  232. if cont == "n":
  233. raise KeyboardInterrupt
  234. if test_hwdb_entry(device, fuzz):
  235. print_bold("Please test the new fuzz setting by restarting libinput")
  236. print_bold(
  237. "Then submit a pull request for this hwdb entry change to "
  238. "to systemd at http://github.com/systemd/systemd"
  239. )
  240. else:
  241. print_bold("The new fuzz setting did not take effect.")
  242. print_bold("Did you edit the correct file?")
  243. print("Please look at the libinput documentation for more details.")
  244. print("Exiting now.")
  245. return True
  246. def reload_and_trigger_udev(device):
  247. import time
  248. print("Running systemd-hwdb update")
  249. subprocess.run(["systemd-hwdb", "update"], check=True)
  250. syspath = device.path.replace("/dev/input/", "/sys/class/input/")
  251. time.sleep(2)
  252. print(f"Running udevadm trigger {syspath}")
  253. subprocess.run(["udevadm", "trigger", syspath], check=True)
  254. time.sleep(2)
  255. def test_hwdb_entry(device, fuzz):
  256. reload_and_trigger_udev(device)
  257. print_bold("Testing... ", end="")
  258. d = Device(device.path)
  259. f = d.check_axes()
  260. if f is not None:
  261. if f == (fuzz, fuzz):
  262. print_yellow("Warning")
  263. print_bold(
  264. "The hwdb applied to the device but libinput's udev "
  265. "rules have not picked it up. This should only happen"
  266. "if libinput is not installed"
  267. )
  268. return True
  269. else:
  270. print_red("Error")
  271. return False
  272. else:
  273. f = d.check_property()
  274. if f is not None and f == (fuzz, fuzz):
  275. print_green("Success")
  276. return True
  277. else:
  278. print_red("Error")
  279. return False
  280. def check_file_for_lines(path, template):
  281. """
  282. Checks file at path for the lines given in template. If found, the
  283. return value is a tuple of the matching lines and the prefix (i.e. the
  284. two lines before the matching lines)
  285. """
  286. try:
  287. with open(path) as f:
  288. lines = [l[:-1] for l in f]
  289. idx = -1
  290. try:
  291. while idx < len(lines) - 1:
  292. idx += 1
  293. line = lines[idx]
  294. if not line.startswith(" EVDEV_ABS_00"):
  295. continue
  296. if lines[idx : idx + len(template)] != template:
  297. continue
  298. return (lines[idx : idx + len(template)], lines[idx - 2 : idx], idx)
  299. except IndexError:
  300. pass
  301. except FileNotFoundError:
  302. pass
  303. return (None, None, None)
  304. def write_udev_rule(device, fuzz):
  305. """Write out a udev rule that may match the device, run udevadm trigger and
  306. check if the udev rule worked. Of course, there's plenty to go wrong...
  307. """
  308. print()
  309. print_bold("Guessing a udev rule to overwrite the fuzz")
  310. # Some devices match better on pvr, others on pn, so we get to try both. yay
  311. with open("/sys/class/dmi/id/modalias") as f:
  312. modalias = f.readlines()[0]
  313. ms = modalias.split(":")
  314. svn, pn, pvr = None, None, None
  315. for m in ms:
  316. if m.startswith("svn"):
  317. svn = m
  318. elif m.startswith("pn"):
  319. pn = m
  320. elif m.startswith("pvr"):
  321. pvr = m
  322. # Let's print out both to inform and/or confuse the user
  323. template = "\n".join( # noqa: FLY002
  324. (
  325. "# {} {}",
  326. "evdev:name:{}:dmi:*:{}*:{}*:",
  327. " EVDEV_ABS_00=:::{}",
  328. " EVDEV_ABS_01=:::{}",
  329. " EVDEV_ABS_35=:::{}",
  330. " EVDEV_ABS_36=:::{}",
  331. "",
  332. )
  333. )
  334. rule1 = template.format(
  335. svn[3:], device.name, device.name, svn, pvr, fuzz, fuzz, fuzz, fuzz
  336. )
  337. rule2 = template.format(
  338. svn[3:], device.name, device.name, svn, pn, fuzz, fuzz, fuzz, fuzz
  339. )
  340. print(f"Full modalias is: {modalias}")
  341. print()
  342. print_bold("Suggested udev rule, option 1:")
  343. print(rule1)
  344. print()
  345. print_bold("Suggested udev rule, option 2:")
  346. print(rule2)
  347. print()
  348. # The weird hwdb matching behavior means we match on the least specific
  349. # rule (i.e. most wildcards) first although that was supposed to be fixed in
  350. # systemd 3a04b789c6f1.
  351. # Our rule uses dmi strings and will be more specific than what 60-evdev.hwdb
  352. # already has. So we basically throw up our hands because we can't do anything
  353. # then.
  354. if handle_existing_entry(device, fuzz):
  355. return
  356. while True:
  357. print_bold("Wich rule do you want to to test? 1 or 2? ", end="")
  358. yesno = input("Ctrl+C to exit ")
  359. if yesno == "1":
  360. rule = rule1
  361. break
  362. elif yesno == "2":
  363. rule = rule2
  364. break
  365. fname = OVERRIDE_HWDB_FILE
  366. try:
  367. fd = open(fname, "x") # noqa: SIM115
  368. except FileExistsError:
  369. yesno = input(f"File {fname} exists, overwrite? [Y/n] ")
  370. if yesno.lower() == "n":
  371. return
  372. fd = open(fname, "w") # noqa: SIM115
  373. with fd:
  374. fd.write("# File generated by libinput measure fuzz\n\n")
  375. fd.write(rule)
  376. if test_hwdb_entry(device, fuzz):
  377. print(f"Your hwdb override file is in {fname}")
  378. print_bold("Please test the new fuzz setting by restarting libinput")
  379. print_bold(
  380. "Then submit a pull request for this hwdb entry to "
  381. "systemd at http://github.com/systemd/systemd"
  382. )
  383. else:
  384. print("The hwdb entry failed to apply to the device.")
  385. print("Removing hwdb file again.")
  386. os.remove(fname)
  387. reload_and_trigger_udev(device)
  388. print_bold("What now?")
  389. print(
  390. "1. Re-run this program and try the other suggested udev rule. If that fails,"
  391. )
  392. print(
  393. "2. File a bug with the suggested udev rule at http://github.com/systemd/systemd"
  394. )
  395. def main(args):
  396. parser = argparse.ArgumentParser(
  397. description="Print fuzz settings and/or suggest udev rules for the fuzz to be adjusted."
  398. )
  399. parser.add_argument(
  400. "path",
  401. metavar="/dev/input/event0",
  402. nargs="?",
  403. type=str,
  404. help="Path to device (optional)",
  405. )
  406. parser.add_argument("--fuzz", type=int, help="Suggested fuzz")
  407. args = parser.parse_args()
  408. try:
  409. device = Device(args.path)
  410. print_bold(f"Using {device.name}: {device.path}")
  411. fuzz = device.check_property()
  412. print_fuzz("udev property", fuzz)
  413. fuzz = device.check_axes()
  414. print_fuzz("axes", fuzz)
  415. userfuzz = args.fuzz
  416. if userfuzz is not None:
  417. write_udev_rule(device, userfuzz)
  418. except PermissionError:
  419. print("Permission denied, please re-run as root")
  420. except InvalidConfigurationError as e:
  421. print(f"Error: {e}")
  422. except InvalidDeviceError as e:
  423. print(f"Error: {e}")
  424. except KeyboardInterrupt:
  425. print("Exited on user request")
  426. if __name__ == "__main__":
  427. main(sys.argv)