#!/usr/bin/python
import sys, os
BASE = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), ".."))
sys.path.insert(0, os.path.join(BASE, "lib", "python"))

import hal
h = hal.component("mousejog")
h.newpin("countsx", hal.HAL_S32, hal.HAL_WR)
h.newpin("countsy", hal.HAL_S32, hal.HAL_WR)
h.newpin("countsw", hal.HAL_S32, hal.HAL_WR)
h.ready()

def toggle_grab(evt):
    global x, y, grabbed
    if grabbed:
        grabbed = False
        t.grab_release()
        t.configure(cursor="")
    else:
        grabbed = True
        t.grab_set_global()
        t.configure(cursor="sizing")
        x = evt.x_root
        y = evt.y_root

def motion(evt):
    global x, y
    if not grabbed: return
    dx = evt.x_root - x
    dy = evt.y_root - y

    h.countsx += dx
    h.countsy += dy

    x = evt.x_root
    y = evt.y_root

def wheel_up(evt):
    h.countsw += 1

def wheel_down(evt):
    h.countsw -= 1

after = None
grabbed = 0
x = y = 0

import Tkinter
t = Tkinter.Tk()
l = Tkinter.Label(wraplength=250, text="""\
Left-click in this window to enable XY jogging, then left click again to stop.

Use the mouse wheel to perform Z jogging""")
l.pack()
t.bind("<ButtonPress-1>", toggle_grab)
t.bind("<Motion>", motion)
t.bind("<ButtonPress-4>", wheel_up)
t.bind("<ButtonPress-5>", wheel_down)
t.mainloop()
