#!/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)

[((244, 270), 'trackball.TrackBall', 'TrackBall', ([], {'interrupt_pin': '(4)'}), '(interrupt_pin=4)\n', (253, 270), False, 'from trackball import TrackBall\n'), ((353, 375), 'os.system', 'os.system', (['"""which xte"""'], {}), "('which xte')\n", (362, 375), False, 'import os\n'), ((909, 927), 'time.sleep', 'time.sleep', (['(0.0001)'], {}), '(0.0001)\n', (919, 927), False, 'import time\n'), ((649, 663), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (658, 663), False, 'import os\n'), ((739, 763), 'math.copysign', 'math.copysign', (['(x ** 2)', 'x'], {}), '(x ** 2, x)\n', (752, 763), False, 'import math\n'), ((796, 820), 'math.copysign', 'math.copysign', (['(y ** 2)', 'y'], {}), '(y ** 2, y)\n', (809, 820), False, 'import math\n'), ((889, 903), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (898, 903), False, 'import os\n')]