"""mems.instrument.client.tk.focus_frame

Contains the FocusFrame class, which provides the UI for changing the
microscope's focus.
"""

# created 2002/01/23, AMK

__revision__ = "$Id: focus_frame.py,v 1.2 2002/01/31 21:01:06 akuchlin Exp $"

import Tkinter

class FocusFrame (Tkinter.Frame):
    
    def __init__ (self,client,*args):
        self.client = client
        apply(Tkinter.Frame.__init__,(self,) + args)

        self.indicator = Tkinter.Label(self, text='Autofocus is off')
        self.button = Tkinter.Button(self, text='Use Autofocus',
                                     command = self.use_autofocus)

        self.slider = Tkinter.Scale(self, from_=50.0, to=-50.0,
                                    orient=Tkinter.VERTICAL,
				    digits=2,
#                                    command=self.adjust_z,
                                   )
#        self.slider.bind('<Enter>', self.client.warn_about_leave)
        self.slider.bind('<ButtonRelease-1>', self.adjust_z)
        
        f = Tkinter.Frame(self)
        L1 = Tkinter.Label(f, text='Current\nposition (um)') 
        L1.pack(side=Tkinter.TOP)

        self.indicator.pack(side=Tkinter.TOP)
        self.button.pack(side=Tkinter.BOTTOM)
        self.slider.pack(side=Tkinter.RIGHT)
        f.pack(side=Tkinter.LEFT)

    #
    # Callbacks that send commands to the microscope, called from the GUI
    #

    
    def use_autofocus (self):
        self.client.send_message("autofocus")


    def adjust_z (self, event):
        if not self.client.state.in_control: return

        z_delta = self.slider.get()
        self.client.move(z = z_delta)

    #
    # Callback used when the microscope's state has been changed
    #
    
    def update (self, state):
        "Update GUI to match the microscope's current state"
        if state.autofocus:
            self.button.configure(state=Tkinter.DISABLED)
	    self.slider.set(0.0)
        else: 
            self.button.configure(state=Tkinter.ACTIVE)

#        if self.client.state.in_control: return
#        return 
        increm = self.get_increment(state)
        self.slider.configure(from_ = 50*increm, to=-50*increm)
        
        self.slider.set(state.z / increm)


    def get_increment (self, state):
        """get_increment (state:MicroscopeState) -> float
        Return the units to be used for the Z axis, measured in microns.
        """
        if state.magnification == 5: increm = 0.5
        elif state.magnification == 10: increm = 1.0
        elif state.magnification == 20: increm = .5
        elif state.magnification == 50: increm = .1
        elif state.magnification == 100: increm = .1
	
        return increm
    

