#!/usr/bin/env python
import time
import os
import math
from trackball import TrackBall

print("""Trackball: Mouse

Use the trackball as a mouse in Raspbian, with right-click
when the switch is pressed.

Press Ctrl+C to exit!
""")

trackball = TrackBall(interrupt_pin=4)
trackball.set_rgbw(0, 0, 0, 0)

# Check for xte (used to control mouse)
use_xte = os.system('which xte') == 0

if use_xte == 0:
    raise RuntimeError("xte not found. Did you sudo apt install xautomation?")

while True:
    up, down, left, right, switch, state = trackball.read()

    # Send movements and clicks to xte
    if switch:
        cmd = 'xte "mouseclick 1"'
        os.system(cmd)
    elif right or up or left or down:
        x = right - left
        x = math.copysign(x**2, x)
        y = down - up
        y = math.copysign(y**2, y)
        cmd = 'xte "mousermove {} {}"'.format(int(x), int(y))
        os.system(cmd)

    time.sleep(0.0001)

[((15, 12, 15, 38), 'trackball.TrackBall', 'TrackBall', (), '', False, 'from trackball import TrackBall\n'), ((19, 10, 19, 32), 'os.system', 'os.system', ({(19, 20, 19, 31): '"""which xte"""'}, {}), "('which xte')", False, 'import os\n'), ((39, 4, 39, 22), 'time.sleep', 'time.sleep', ({(39, 15, 39, 21): '(0.0001)'}, {}), '(0.0001)', False, 'import time\n'), ((30, 8, 30, 22), 'os.system', 'os.system', ({(30, 18, 30, 21): 'cmd'}, {}), '(cmd)', False, 'import os\n'), ((33, 12, 33, 34), 'math.copysign', 'math.copysign', ({(33, 26, 33, 30): 'x ** 2', (33, 32, 33, 33): 'x'}, {}), '(x ** 2, x)', False, 'import math\n'), ((35, 12, 35, 34), 'math.copysign', 'math.copysign', ({(35, 26, 35, 30): 'y ** 2', (35, 32, 35, 33): 'y'}, {}), '(y ** 2, y)', False, 'import math\n'), ((37, 8, 37, 22), 'os.system', 'os.system', ({(37, 18, 37, 21): 'cmd'}, {}), '(cmd)', False, 'import os\n')]