libinput-analyze-recording.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. #!/usr/bin/env python3
  2. # vim: set expandtab shiftwidth=4:
  3. # -*- Mode: python; coding: utf-8; indent-tabs-mode: nil -*- */
  4. #
  5. # Copyright © 2021 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. # Prints the data from a libinput recording in a table format to ease
  27. # debugging.
  28. #
  29. # Input is a libinput record yaml file
  30. import argparse
  31. import os
  32. import sys
  33. import libevdev
  34. import yaml
  35. # minimum width of a field in the table
  36. MIN_FIELD_WIDTH = 6
  37. # Default is to just return the value of an axis, but some axes want special
  38. # formatting.
  39. def format_value(code, value):
  40. if code in (libevdev.EV_ABS.ABS_MISC, libevdev.EV_MSC.MSC_SERIAL):
  41. return f"{value & 0xFFFFFFFF:#x}"
  42. # Rel axes we always print the sign
  43. if code.type == libevdev.EV_REL:
  44. return f"{value:+d}"
  45. return f"{value}"
  46. # The list of axes we want to track
  47. def is_tracked_axis(code, allowlist, denylist):
  48. if code.type in (libevdev.EV_KEY, libevdev.EV_SW, libevdev.EV_SYN):
  49. return False
  50. # We don't do slots in this tool
  51. if (
  52. code.type == libevdev.EV_ABS
  53. and libevdev.EV_ABS.ABS_MT_SLOT <= code <= libevdev.EV_ABS.ABS_MAX
  54. ):
  55. return False
  56. if allowlist:
  57. return code in allowlist
  58. else:
  59. return code not in denylist
  60. def main(argv):
  61. parser = argparse.ArgumentParser(
  62. description="Display a recording in a tabular format"
  63. )
  64. parser.add_argument(
  65. "path", metavar="recording", nargs=1, help="Path to libinput-record YAML file"
  66. )
  67. parser.add_argument(
  68. "--ignore",
  69. metavar="ABS_X,ABS_Y,...",
  70. default="",
  71. help="A comma-separated list of axis names to ignore",
  72. )
  73. parser.add_argument(
  74. "--only",
  75. metavar="ABS_X,ABS_Y,...",
  76. default="",
  77. help="A comma-separated list of axis names to print, ignoring all others",
  78. )
  79. parser.add_argument(
  80. "--print-state",
  81. action="store_true",
  82. default=False,
  83. help="Always print all axis values, even unchanged ones",
  84. )
  85. args = parser.parse_args()
  86. if args.ignore and args.only:
  87. print("Only one of --ignore and --only may be given", file=sys.stderr)
  88. sys.exit(2)
  89. ignored_axes = [libevdev.evbit(axis) for axis in args.ignore.split(",") if axis]
  90. only_axes = [libevdev.evbit(axis) for axis in args.only.split(",") if axis]
  91. isatty = os.isatty(sys.stdout.fileno())
  92. with open(args.path[0]) as f:
  93. yml = yaml.safe_load(f)
  94. if yml["ndevices"] > 1:
  95. print(f"WARNING: Using only first {yml['ndevices']} devices in recording")
  96. device = yml["devices"][0]
  97. if not device["events"]:
  98. print("No events found in recording")
  99. sys.exit(1)
  100. def events():
  101. """
  102. Yields the next event in the recording
  103. """
  104. for event in device["events"]:
  105. for evdev in event.get("evdev", []):
  106. yield libevdev.InputEvent(
  107. code=libevdev.evbit(evdev[2], evdev[3]),
  108. value=evdev[4],
  109. sec=evdev[0],
  110. usec=evdev[1],
  111. )
  112. def interesting_axes(events):
  113. """
  114. Yields the libevdev codes with the axes in this recording
  115. """
  116. used_axes = []
  117. for e in events:
  118. if e.code not in used_axes and is_tracked_axis(
  119. e.code, only_axes, ignored_axes
  120. ):
  121. yield e.code
  122. used_axes.append(e.code)
  123. # Compile all axes that we want to print first
  124. axes = sorted(
  125. interesting_axes(events()), key=lambda x: x.type.value * 1000 + x.value
  126. )
  127. # Strip the REL_/ABS_ prefix for the headers
  128. headers = [a.name[4:].rjust(MIN_FIELD_WIDTH) for a in axes]
  129. # for easier formatting later, we keep the header field width in a dict
  130. axes = {a: len(h) for a, h in zip(axes, headers)}
  131. # Time is a special case, always the first entry
  132. # Format uses ms only, we rarely ever care about µs
  133. headers = [f"{'Time':<7s}"] + headers + ["Keys"]
  134. header_line = f"{' | '.join(headers)}"
  135. print(header_line)
  136. print("-" * len(header_line))
  137. current_codes = []
  138. current_frame = {} # {evdev-code: value}
  139. axes_in_use = {} # to print axes never sending events
  140. last_fields = [] # to skip duplicate lines
  141. continuation_count = 0
  142. keystate = {}
  143. keystate_changed = False
  144. for e in events():
  145. axes_in_use[e.code] = True
  146. if e.code.type == libevdev.EV_KEY:
  147. keystate[e.code] = e.value
  148. keystate_changed = True
  149. elif is_tracked_axis(e.code, only_axes, ignored_axes):
  150. current_frame[e.code] = e.value
  151. current_codes.append(e.code)
  152. elif e.code == libevdev.EV_SYN.SYN_REPORT:
  153. fields = []
  154. for a in axes:
  155. if args.print_state or a in current_codes:
  156. s = format_value(a, current_frame.get(a, 0))
  157. else:
  158. s = ""
  159. fields.append(s.rjust(max(MIN_FIELD_WIDTH, axes[a])))
  160. current_codes = []
  161. if last_fields != fields or keystate_changed:
  162. last_fields = fields.copy()
  163. keystate_changed = False
  164. if continuation_count:
  165. if not isatty:
  166. print(f" ... +{continuation_count}", end="")
  167. print()
  168. continuation_count = 0
  169. fields.insert(0, f"{e.sec: 3d}.{e.usec // 1000:03d}")
  170. keys_down = [k.name for k, v in keystate.items() if v]
  171. fields.append(", ".join(keys_down))
  172. print(" | ".join(fields))
  173. else:
  174. continuation_count += 1
  175. if isatty:
  176. print(f"\r ... +{continuation_count}", end="", flush=True)
  177. # Print out any rel/abs axes that not generate events in
  178. # this recording
  179. unused_axes = []
  180. for evtype, evcodes in device["evdev"]["codes"].items():
  181. for c in evcodes:
  182. code = libevdev.evbit(int(evtype), int(c))
  183. if (
  184. is_tracked_axis(code, only_axes, ignored_axes)
  185. and code not in axes_in_use
  186. ):
  187. unused_axes.append(code)
  188. if unused_axes:
  189. print(
  190. f"Axes present but without events: {', '.join([a.name for a in unused_axes])}"
  191. )
  192. for e in events():
  193. if libevdev.EV_ABS.ABS_MT_SLOT <= code <= libevdev.EV_ABS.ABS_MAX:
  194. print(
  195. "WARNING: This recording contains multitouch data that is not supported by this tool."
  196. )
  197. break
  198. if __name__ == "__main__":
  199. try:
  200. main(sys.argv)
  201. except BrokenPipeError:
  202. pass