Search code examples
linuxbashmousexinput

Write mouse coordinates and mouse clicks with timestamps to file?


I'm trying to create a bash script that records the location of the mouse every 5 milliseconds. I also want to record the timestamps and locations of mouse-clicks.

Recording the mouse location has been easy with xdotool getmouselocation. I've been able to record mouse clicks using some of the suggestions here: https://unix.stackexchange.com/questions/106736/detect-if-mouse-button-is-pressed-then-invoke-a-script-or-command However, I've not been able to combine the two.

Is there any way to accomplish this? Thank you in advance!


Solution

  • In accepted answer of https://unix.stackexchange.com/questions/106736/detect-if-mouse-button-is-pressed-then-invoke-a-script-or-command have an example to get mouse status change. With little modification you get print the mouse location upon mouse button down.

    @Gem Taylor mentioned using script language for this is not an optional way.

    During test run, I experienced cases when clicks are not get captured.

    #!/bin/bash
    
    MOUSE_ID=$(xinput --list | grep -i -m 1 'mouse' | grep -o 'id=[0-9]\+' | grep -o '[0-9]\+')
    
    STATE1=$(xinput --query-state $MOUSE_ID | grep 'button\['"."'\]=down' | sort)
    while true; do
            sleep 0.005
            STATE2=$(xinput --query-state $MOUSE_ID | grep 'button\['"."'\]=down' | sort)
            CLICK=$(comm -13 <(echo "$STATE1") <(echo "$STATE2"))
            if [[ -n $CLICK ]]; then
                    echo "$CLICK"
                    xinput --query-state $MOUSE_ID | grep 'valuator\['
            fi
            STATE1=$STATE2
    done