10-wheel-to-button.lua 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. -- SPDX-License-Identifier: MIT
  2. --
  3. -- This is an example libinput plugin
  4. --
  5. -- This plugin maps a downwards mouse wheel to a button down event and
  6. -- an upwards wheel movement to a button up event.
  7. -- UNCOMMENT THIS LINE TO ACTIVATE THE PLUGIN
  8. -- libinput:register({1})
  9. -- The button we want to press on wheel events
  10. local wheel_button = evdev.BTN_EXTRA
  11. local button_states = {}
  12. local function evdev_frame(device, frame, timestamp)
  13. local events = {}
  14. local modified = false
  15. for _, v in ipairs(frame) do
  16. if v.usage == evdev.REL_WHEEL then
  17. -- REL_WHEEL is inverted, neg value -> down, pos value -> up
  18. if v.value < 0 then
  19. if not button_states[device] then
  20. table.insert(events, { usage = wheel_button, value = 1 })
  21. button_states[device] = true
  22. end
  23. else
  24. if button_states[device] then
  25. table.insert(events, { usage = wheel_button, value = 0 })
  26. button_states[device] = false
  27. end
  28. end
  29. modified = true
  30. -- Because REL_WHEEL is no longer a wheel, the high-res
  31. -- events are dropped
  32. elseif v.usage == evdev.REL_WHEEL_HI_RES then
  33. modified = true
  34. else
  35. table.insert(events, v)
  36. end
  37. end
  38. if modified then
  39. return events
  40. else
  41. return nil
  42. end
  43. end
  44. local function device_new(device)
  45. local usages = device:usages()
  46. if usages[evdev.REL_WHEEL] then
  47. button_states[device] = false
  48. if not usages[wheel_button] then
  49. device:enable_evdev_usage(wheel_button)
  50. end
  51. device:connect("evdev-frame", evdev_frame)
  52. device:connect("device-removed", function(dev)
  53. button_states[dev] = nil
  54. end)
  55. end
  56. end
  57. libinput:connect("new-evdev-device", device_new)