gvalkov / python-evdev

Python bindings for the Linux input subsystem
https://python-evdev.rtfd.org/
BSD 3-Clause "New" or "Revised" License
334 stars 112 forks source link

Cannot right click? #222

Closed chapmanjacobd closed 2 months ago

chapmanjacobd commented 2 months ago

I'm not able to press a button if the grabbed device is already pressing it :/

Here is a small reproducible example:

import evdev
from evdev import UInput
from evdev import ecodes as e

device = None
for path in evdev.list_devices():
    dev = evdev.InputDevice(path)
    if 'mouse' in dev.name.lower():
        capabilities = dev.capabilities()
        if e.REL_WHEEL in capabilities.get(e.EV_REL, []):
            device = dev
            break
if device is None:
    raise RuntimeError("No mouse found that has a wheel.")
print(f"Listening for events on {device.name}")

ui = UInput(
    {
        e.EV_KEY: (
            e.BTN_LEFT,
            e.BTN_MIDDLE,
            e.BTN_RIGHT,
            e.BTN_WHEEL,
        ),
        e.EV_REL: (e.REL_X, e.REL_Y),
    }
)

with device.grab_context():  # get exclusive access
    for event in device.read_loop():
        if event.type == e.EV_KEY:
            if event.code == e.BTN_RIGHT:
                if event.value == 1:  # Right Button Pressed
                    pass
                elif event.value == 0:  # Right Button Released
                    ui.write(e.EV_KEY, e.BTN_RIGHT, 1)
                    ui.write(e.EV_KEY, e.BTN_RIGHT, 0)
                    ui.syn()
            else:
                ui.write(event.type, event.code, event.value)
                ui.syn()
        else:
            ui.write(event.type, event.code, event.value)
            ui.syn()

It would be nice to be able to do this... Here is my full script: https://github.com/chapmanjacobd/computer/blob/main/bin/wheel.py

I guess in the meanwhile I can use xdotool https://github.com/chapmanjacobd/computer/commit/79a22c77f9232bde396d26606846c0cd28693fcf

sezanzeb commented 2 months ago

Are you trying to write a right-click on release? If so, you need to do

                    ui.write(e.EV_KEY, e.BTN_RIGHT, 1)
                    ui.syn()
                    ui.write(e.EV_KEY, e.BTN_RIGHT, 0)
                    ui.syn()

I think your code could benefit from this pattern by the way: https://refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html

chapmanjacobd commented 2 months ago

that works, thanks