libinput-measure-touch-size.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. #!/usr/bin/env python3
  2. # vim: set expandtab shiftwidth=4:
  3. # -*- Mode: python; coding: utf-8; indent-tabs-mode: nil -*- */
  4. #
  5. # Copyright © 2017 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 subprocess
  28. import sys
  29. try:
  30. import libevdev
  31. import pyudev
  32. except ModuleNotFoundError as e:
  33. print(f"Error: {e!s}", 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. class Range:
  40. """Class to keep a min/max of a value around"""
  41. def __init__(self):
  42. self.min = float("inf")
  43. self.max = float("-inf")
  44. def update(self, value):
  45. self.min = min(self.min, value)
  46. self.max = max(self.max, value)
  47. class Touch:
  48. """A single data point of a sequence (i.e. one event frame)"""
  49. def __init__(self, major=None, minor=None, orientation=None):
  50. self._major = major
  51. self._minor = minor
  52. self._orientation = orientation
  53. self.dirty = False
  54. @property
  55. def major(self):
  56. return self._major
  57. @major.setter
  58. def major(self, major):
  59. self._major = major
  60. self.dirty = True
  61. @property
  62. def minor(self):
  63. return self._minor
  64. @minor.setter
  65. def minor(self, minor):
  66. self._minor = minor
  67. self.dirty = True
  68. @property
  69. def orientation(self):
  70. return self._orientation
  71. @orientation.setter
  72. def orientation(self, orientation):
  73. self._orientation = orientation
  74. self.dirty = True
  75. def __str__(self):
  76. s = f"Touch: major {self.major:3d}"
  77. if self.minor is not None:
  78. s += f", minor {self.minor:3d}"
  79. if self.orientation is not None:
  80. s += f", orientation {self.orientation:+3d}"
  81. return s
  82. class TouchSequence:
  83. """A touch sequence from beginning to end"""
  84. def __init__(self, device, tracking_id):
  85. self.device = device
  86. self.tracking_id = tracking_id
  87. self.points = []
  88. self.is_active = True
  89. self.is_down = False
  90. self.was_down = False
  91. self.is_palm = False
  92. self.was_palm = False
  93. self.is_thumb = False
  94. self.was_thumb = False
  95. self.major_range = Range()
  96. self.minor_range = Range()
  97. def append(self, touch):
  98. """Add a Touch to the sequence"""
  99. self.points.append(touch)
  100. self.major_range.update(touch.major)
  101. self.minor_range.update(touch.minor)
  102. if touch.major < self.device.up or touch.minor < self.device.up:
  103. self.is_down = False
  104. elif touch.major > self.device.down or touch.minor > self.device.down:
  105. self.is_down = True
  106. self.was_down = True
  107. self.is_palm = touch.major > self.device.palm
  108. if self.is_palm:
  109. self.was_palm = True
  110. self.is_thumb = self.device.thumb != 0 and touch.major > self.device.thumb
  111. if self.is_thumb:
  112. self.was_thumb = True
  113. def finalize(self):
  114. """Mark the TouchSequence as complete (finger is up)"""
  115. self.is_active = False
  116. def __str__(self):
  117. return self._str_state() if self.is_active else self._str_summary()
  118. def _str_summary(self):
  119. if not self.points:
  120. return f"{'Sequence: no major/minor values recorded':78s}"
  121. s = f"Sequence: major: [{self.major_range.min:3d}..{self.major_range.max:3d}] "
  122. if self.device.has_minor:
  123. s += f"minor: [{self.minor_range.min:3d}..{self.minor_range.max:3d}] "
  124. if self.was_down:
  125. s += " down"
  126. if self.was_palm:
  127. s += " palm"
  128. if self.was_thumb:
  129. s += " thumb"
  130. return s
  131. def _str_state(self):
  132. touch = self.points[-1]
  133. s = (
  134. f"{touch}, tags:"
  135. f" {'down' if self.is_down else ' '}"
  136. f" {'palm' if self.is_palm else ' '}"
  137. f" {'thumb' if self.is_thumb else ' '}"
  138. )
  139. return s
  140. class InvalidDeviceError(Exception):
  141. pass
  142. class Device(libevdev.Device):
  143. def __init__(self, path):
  144. if path is None:
  145. self.path = self.find_touch_device()
  146. else:
  147. self.path = path
  148. fd = open(self.path, "rb") # noqa: SIM115
  149. super().__init__(fd)
  150. print(f"Using {self.name}: {self.path}\n")
  151. if not self.has(libevdev.EV_ABS.ABS_MT_TOUCH_MAJOR):
  152. raise InvalidDeviceError("Device does not have ABS_MT_TOUCH_MAJOR")
  153. self.has_minor = self.has(libevdev.EV_ABS.ABS_MT_TOUCH_MINOR)
  154. self.has_orientation = self.has(libevdev.EV_ABS.ABS_MT_ORIENTATION)
  155. self.up = 0
  156. self.down = 0
  157. self.palm = 0
  158. self.thumb = 0
  159. self._init_thresholds_from_quirks()
  160. self.sequences = []
  161. self.touch = Touch(0, 0)
  162. self.warned = False
  163. def find_touch_device(self):
  164. context = pyudev.Context()
  165. for device in context.list_devices(subsystem="input"):
  166. if not device.get("ID_INPUT_TOUCHPAD", 0) and not device.get(
  167. "ID_INPUT_TOUCHSCREEN", 0
  168. ):
  169. continue
  170. if not device.device_node or not device.device_node.startswith(
  171. "/dev/input/event"
  172. ):
  173. continue
  174. return device.device_node
  175. print("Unable to find a touch device.", file=sys.stderr)
  176. sys.exit(1)
  177. def _init_thresholds_from_quirks(self):
  178. command = ["libinput", "quirks", "list", self.path]
  179. cmd = subprocess.run(command, capture_output=True, check=False)
  180. if cmd.returncode != 0:
  181. print(
  182. f"Error querying quirks: {cmd.stderr.decode('utf-8')}",
  183. file=sys.stderr,
  184. )
  185. return
  186. stdout = cmd.stdout.decode("utf-8")
  187. quirks = [q.split("=") for q in stdout.split("\n")]
  188. for q in quirks:
  189. if q[0] == "AttrPalmSizeThreshold":
  190. self.palm = int(q[1])
  191. elif q[0] == "AttrTouchSizeRange":
  192. self.down, self.up = colon_tuple(q[1])
  193. elif q[0] == "AttrThumbSizeThreshold":
  194. self.thumb = int(q[1])
  195. def start_new_sequence(self, tracking_id):
  196. self.sequences.append(TouchSequence(self, tracking_id))
  197. def current_sequence(self):
  198. return self.sequences[-1]
  199. def handle_key(self, event):
  200. tapcodes = [
  201. libevdev.EV_KEY.BTN_TOOL_DOUBLETAP,
  202. libevdev.EV_KEY.BTN_TOOL_TRIPLETAP,
  203. libevdev.EV_KEY.BTN_TOOL_QUADTAP,
  204. libevdev.EV_KEY.BTN_TOOL_QUINTTAP,
  205. ]
  206. if event.code in tapcodes and event.value > 0: # noqa: SIM102
  207. if not self.warned:
  208. self.warned = True
  209. print(
  210. "\rThis tool cannot handle multiple fingers, "
  211. "output will be invalid",
  212. file=sys.stderr,
  213. )
  214. def handle_abs(self, event):
  215. if event.matches(libevdev.EV_ABS.ABS_MT_TRACKING_ID):
  216. if event.value > -1:
  217. self.start_new_sequence(event.value)
  218. else:
  219. try:
  220. s = self.current_sequence()
  221. s.finalize()
  222. print(f"\r{s}")
  223. except IndexError:
  224. # If the finger was down during start
  225. pass
  226. elif event.matches(libevdev.EV_ABS.ABS_MT_TOUCH_MAJOR):
  227. self.touch.major = event.value
  228. elif event.matches(libevdev.EV_ABS.ABS_MT_TOUCH_MINOR):
  229. self.touch.minor = event.value
  230. elif event.matches(libevdev.EV_ABS.ABS_MT_ORIENTATION):
  231. self.touch.orientation = event.value
  232. def handle_syn(self, event):
  233. if self.touch.dirty:
  234. try:
  235. self.current_sequence().append(self.touch)
  236. print(f"\r{self.current_sequence()}", end="")
  237. self.touch = Touch(
  238. major=self.touch.major,
  239. minor=self.touch.minor,
  240. orientation=self.touch.orientation,
  241. )
  242. except IndexError:
  243. pass
  244. def handle_event(self, event):
  245. if event.matches(libevdev.EV_ABS):
  246. self.handle_abs(event)
  247. elif event.matches(libevdev.EV_KEY):
  248. self.handle_key(event)
  249. elif event.matches(libevdev.EV_SYN):
  250. self.handle_syn(event)
  251. def read_events(self):
  252. print("Ready for recording data.")
  253. print(f"Touch sizes used: {self.down}:{self.up}")
  254. print(f"Palm size used: {self.palm}")
  255. print(f"Thumb size used: {self.thumb}")
  256. print(
  257. "Place a single finger on the device to measure touch size.\n"
  258. "Ctrl+C to exit\n"
  259. )
  260. while True:
  261. for event in self.events():
  262. self.handle_event(event)
  263. def colon_tuple(string):
  264. try:
  265. ts = string.split(":")
  266. t = tuple([int(x) for x in ts])
  267. if len(t) == 2 and t[0] >= t[1]:
  268. return t
  269. except: # noqa
  270. pass
  271. msg = f"{string} is not in format N:M (N >= M)"
  272. raise argparse.ArgumentTypeError(msg)
  273. def main(args):
  274. parser = argparse.ArgumentParser(description="Measure touch size and orientation")
  275. parser.add_argument(
  276. "path",
  277. metavar="/dev/input/event0",
  278. nargs="?",
  279. type=str,
  280. help="Path to device (optional)",
  281. )
  282. parser.add_argument(
  283. "--touch-thresholds",
  284. metavar="down:up",
  285. type=colon_tuple,
  286. help="Thresholds when a touch is logically down or up",
  287. )
  288. parser.add_argument(
  289. "--palm-threshold",
  290. metavar="t",
  291. type=int,
  292. help="Threshold when a touch is a palm",
  293. )
  294. args = parser.parse_args()
  295. try:
  296. device = Device(args.path)
  297. if args.touch_thresholds is not None:
  298. device.down, device.up = args.touch_thresholds
  299. if args.palm_threshold is not None:
  300. device.palm = args.palm_threshold
  301. device.read_events()
  302. except KeyboardInterrupt:
  303. pass
  304. except (PermissionError, OSError):
  305. print("Error: failed to open device")
  306. except InvalidDeviceError as e:
  307. print(
  308. "This device does not have the capabilities for size-based touch detection."
  309. )
  310. print(f"Details: {e}")
  311. if __name__ == "__main__":
  312. main(sys.argv)