1
0

libinput-replay.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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. import argparse
  26. import math
  27. import multiprocessing
  28. import os
  29. import sys
  30. import time
  31. from pathlib import Path
  32. from tempfile import NamedTemporaryFile
  33. try:
  34. import libevdev
  35. import pyudev
  36. import yaml
  37. except ModuleNotFoundError as e:
  38. print(f"Error: {e}", file=sys.stderr)
  39. print(
  40. "One or more python modules are missing. Please install those "
  41. "modules and re-run this tool."
  42. )
  43. sys.exit(1)
  44. SUPPORTED_FILE_VERSION = 1
  45. def error(msg, **kwargs):
  46. print(msg, **kwargs, file=sys.stderr)
  47. class YamlException(Exception):
  48. pass
  49. def fetch(yaml, key):
  50. """Helper function to avoid confusing a YAML error with a
  51. normal KeyError bug"""
  52. try:
  53. return yaml[key]
  54. except KeyError:
  55. raise YamlException(f"Failed to get '{key}' from recording.")
  56. def check_udev_properties(yaml_data, uinput):
  57. """
  58. Compare the properties our new uinput device has with the ones from the
  59. recording and ring the alarm bell if one of them is off.
  60. """
  61. yaml_udev_section = fetch(yaml_data, "udev")
  62. yaml_udev_props = fetch(yaml_udev_section, "properties")
  63. ignore = ["LIBINPUT_DEVICE_GROUP", "DRIVER"]
  64. yaml_props = {
  65. k: v
  66. for (k, v) in [prop.split("=", maxsplit=1) for prop in yaml_udev_props]
  67. if k not in ignore
  68. }
  69. # give udev some time to catch up
  70. time.sleep(0.2)
  71. context = pyudev.Context()
  72. udev_device = pyudev.Devices.from_device_file(context, uinput.devnode)
  73. for name, value in udev_device.properties.items():
  74. if name in yaml_props:
  75. if yaml_props[name] != value:
  76. error(
  77. f"Warning: udev property mismatch: recording has {name}={yaml_props[name]}, device has {name}={value}"
  78. )
  79. del yaml_props[name]
  80. else:
  81. # The list of properties we add to the recording, see libinput-record.c
  82. prefixes = (
  83. "ID_INPUT",
  84. "LIBINPUT",
  85. "EVDEV_ABS",
  86. "MOUSE_DPI",
  87. "POINTINGSTICK_",
  88. )
  89. for prefix in prefixes:
  90. if name.startswith(prefix):
  91. error(f"Warning: unexpected property: {name}={value}")
  92. # the ones we found above were removed from the dict
  93. for name, value in yaml_props.items():
  94. error(f"Warning: device is missing recorded udev property: {name}={value}")
  95. def create(device):
  96. evdev = fetch(device, "evdev")
  97. d = libevdev.Device()
  98. d.name = fetch(evdev, "name")
  99. ids = fetch(evdev, "id")
  100. if len(ids) != 4:
  101. raise YamlException(f"Invalid ID format: {ids}")
  102. d.id = dict(zip(["bustype", "vendor", "product", "version"], ids))
  103. codes = fetch(evdev, "codes")
  104. for evtype, evcodes in codes.items():
  105. for code in evcodes:
  106. data = None
  107. if evtype == libevdev.EV_ABS.value:
  108. values = fetch(evdev, "absinfo")[code]
  109. absinfo = libevdev.InputAbsInfo(
  110. minimum=values[0],
  111. maximum=values[1],
  112. fuzz=values[2],
  113. flat=values[3],
  114. resolution=values[4],
  115. )
  116. data = absinfo
  117. elif evtype == libevdev.EV_REP.value:
  118. if code == libevdev.EV_REP.REP_DELAY.value:
  119. data = 500
  120. elif code == libevdev.EV_REP.REP_PERIOD.value:
  121. data = 20
  122. d.enable(libevdev.evbit(evtype, code), data=data)
  123. properties = fetch(evdev, "properties")
  124. for prop in properties:
  125. d.enable(libevdev.propbit(prop))
  126. uinput = d.create_uinput_device()
  127. check_udev_properties(device, uinput)
  128. return uinput
  129. def print_events(devnode, indent, evs):
  130. devnode = os.path.basename(devnode)
  131. for e in evs:
  132. if e.type != libevdev.EV_SYN:
  133. print(
  134. f"{devnode}: {' ' * (indent * 8)}"
  135. f"{e.sec:-6d}.{e.usec:06d} {e.type.name} / {e.code.name:<20s} {e.value:6d}"
  136. )
  137. if e.type == libevdev.EV_SYN:
  138. print(
  139. f"{devnode}: {' ' * (indent * 8)}"
  140. f"----------------- SYN_REPORT ({e.value}) -----------------"
  141. )
  142. def collect_events(frame):
  143. evs = []
  144. events_skipped = False
  145. for sec, usec, evtype, evcode, value in frame:
  146. if evtype == libevdev.EV_KEY.value and value == 2: # key repeat
  147. events_skipped = True
  148. continue
  149. e = libevdev.InputEvent(
  150. libevdev.evbit(evtype, evcode), value=value, sec=sec, usec=usec
  151. )
  152. evs.append(e)
  153. # If we skipped some events and now all we have left is the
  154. # SYN_REPORTs, we drop the SYN_REPORTs as well.
  155. if events_skipped and all(e for e in evs if e.matches(libevdev.EV_SYN.SYN_REPORT)):
  156. return []
  157. else:
  158. return evs
  159. def replay(device, verbose):
  160. events = fetch(device, "events")
  161. if events is None:
  162. return
  163. uinput = device["__uinput"]
  164. # The first event may have a nonzero offset but we want to replay
  165. # immediately regardless. When replaying multiple devices, the first
  166. # offset is the offset from the first event on any device.
  167. offset = time.time() - device["__first_event_offset"]
  168. if offset < 0:
  169. error("WARNING: event time offset is in the future, refusing to replay")
  170. return
  171. # each 'evdev' set contains one SYN_REPORT so we only need to check for
  172. # the time offset once per event
  173. for event in events:
  174. try:
  175. evdev = fetch(event, "evdev")
  176. except YamlException:
  177. continue
  178. evs = collect_events(evdev)
  179. if not evs:
  180. continue
  181. evtime = evs[0].sec + evs[0].usec / 1e6 + offset
  182. now = time.time()
  183. if evtime - now > 150 / 1e6: # 150 µs error margin
  184. time.sleep(evtime - now - 150 / 1e6)
  185. uinput.send_events(evs)
  186. if verbose:
  187. print_events(uinput.devnode, device["__index"], evs)
  188. def first_timestamp(device):
  189. events = fetch(device, "events")
  190. for e in events or []:
  191. try:
  192. evdev = fetch(e, "evdev")
  193. (sec, usec, *_) = evdev[0]
  194. return sec + usec / 1.0e6
  195. except YamlException:
  196. pass
  197. return None
  198. def wrap(func, *args):
  199. try:
  200. func(*args)
  201. except KeyboardInterrupt:
  202. pass
  203. def loop(args, recording):
  204. devices = fetch(recording, "devices")
  205. first_timestamps = tuple(
  206. filter(lambda x: x is not None, [first_timestamp(d) for d in devices])
  207. )
  208. # All devices need to start replaying at the same time, so let's find
  209. # the very first event and offset everything by that timestamp.
  210. toffset = min(first_timestamps or [math.inf])
  211. for idx, d in enumerate(devices):
  212. uinput = create(d)
  213. print(f"{uinput.devnode}: {uinput.name}")
  214. d["__uinput"] = uinput # cheaper to hide it in the dict then work around it
  215. d["__index"] = idx
  216. d["__first_event_offset"] = toffset
  217. if not first_timestamps:
  218. input("No events in recording. Hit enter to quit")
  219. return
  220. while True:
  221. if args.replay_after >= 0:
  222. time.sleep(args.replay_after)
  223. else:
  224. input("Hit enter to start replaying")
  225. try:
  226. processes = [
  227. multiprocessing.Process(target=wrap, args=(replay, d, args.verbose))
  228. for d in devices
  229. ]
  230. for p in processes:
  231. p.start()
  232. for p in processes:
  233. p.join()
  234. if args.once:
  235. break
  236. except KeyboardInterrupt:
  237. print("Event replay interrupted, press Ctrl+C again to exit.")
  238. print("Note that the device may not be in a neutral state now.")
  239. def create_device_quirk(device, quirks):
  240. # Where the device has a quirk, we match on name, vendor and product.
  241. # That's the best match we can assemble here from the info we have.
  242. evdev = fetch(device, "evdev")
  243. name = fetch(evdev, "name")
  244. id = fetch(evdev, "id")
  245. quirk = (
  246. f"[libinput-replay {name}]\n"
  247. f"MatchName={name}\n"
  248. f"MatchVendor=0x{id[1]:04X}\n"
  249. f"MatchProduct=0x{id[2]:04X}\n"
  250. )
  251. quirk += "\n".join(quirks)
  252. return quirk
  253. def setup_quirks(recording) -> Path | None:
  254. devices = fetch(recording, "devices")
  255. quirks = []
  256. for d in devices:
  257. qs = d.get("quirks") or []
  258. if not any(q.startswith("AttrIsVirtual=") for q in qs):
  259. try:
  260. is_virtual = d["udev"]["virtual"]
  261. except (KeyError, TypeError):
  262. is_virtual = False
  263. qs.append(f"AttrIsVirtual={int(is_virtual)}")
  264. quirks.append(create_device_quirk(d, qs))
  265. if not quirks:
  266. return None
  267. runtime_dir = (
  268. Path(os.getenv("XDG_RUNTIME_DIR", f"/run/user/{os.geteuid()}")) / "libinput"
  269. )
  270. runtime_dir.mkdir(exist_ok=True, parents=True)
  271. with NamedTemporaryFile(
  272. mode="w+",
  273. dir=runtime_dir,
  274. suffix=".quirks",
  275. prefix="libinput-replay",
  276. delete=False,
  277. ) as fd:
  278. fd.write("# This file was generated by libinput replay\n")
  279. fd.write("# Unless libinput replay is running right now, remove this file.\n")
  280. fd.write("\n\n".join(quirks))
  281. return Path(fd.name)
  282. def check_file(recording):
  283. version = fetch(recording, "version")
  284. if version != SUPPORTED_FILE_VERSION:
  285. raise YamlException(
  286. f"Invalid file format: {version}, expected {SUPPORTED_FILE_VERSION}"
  287. )
  288. ndevices = fetch(recording, "ndevices")
  289. devices = fetch(recording, "devices")
  290. if ndevices != len(devices):
  291. error(
  292. f"WARNING: truncated file, expected {ndevices} devices, got {len(devices)}"
  293. )
  294. def main():
  295. multiprocessing.set_start_method("fork")
  296. parser = argparse.ArgumentParser(description="Replay a device recording")
  297. parser.add_argument(
  298. "recording",
  299. metavar="recorded-file.yaml",
  300. type=str,
  301. help="Path to device recording",
  302. )
  303. parser.add_argument(
  304. "--replay-after",
  305. type=int,
  306. default=-1,
  307. help="Automatically replay once after N seconds",
  308. )
  309. parser.add_argument(
  310. "--once",
  311. action="store_true",
  312. default=False,
  313. help="Stop and exit after one replay",
  314. )
  315. parser.add_argument("--verbose", action="store_true")
  316. args = parser.parse_args()
  317. quirks_file = None
  318. try:
  319. with open(args.recording) as f:
  320. y = yaml.safe_load(f)
  321. check_file(y)
  322. quirks_file = setup_quirks(y)
  323. loop(args, y)
  324. except KeyboardInterrupt:
  325. pass
  326. except (PermissionError, OSError) as e:
  327. error(f"Error: failed to open device: {e}")
  328. except YamlException as e:
  329. error(f"Error: failed to parse recording: {e}")
  330. finally:
  331. if quirks_file:
  332. quirks_file.unlink()
  333. try:
  334. quirks_file.parent.rmdir()
  335. except OSError as e:
  336. import errno
  337. if e.errno != errno.ENOTEMPTY:
  338. raise
  339. if __name__ == "__main__":
  340. main()