"""Wrapper classes for use with tkinter.

This module provides the following classes:

Gui: a sublass of Tk that provides wrappers for most
of the widget-creating methods from Tk.  The advantages of
these wrappers is that they use Python's optional argument capability
to provide appropriate default values, and that they combine widget
creation and packing into a single step.  They also eliminate the need
to name the parent widget explicitly by keeping track of a current
frame and packing new objects into it.

GuiCanvas: a subclass of Canvas that provides wrappers for most of the
item-creating methods from Canvas.  The advantages of the wrappers
are, again, that they use optional arguments to provide appropriate
defaults, and that they perform coordinate transformations.

Transform: an abstract class that provides basic methods inherited
by CanvasTransform and the other transforms.

CanvasTransform: a transformation that maps standard Cartesian
coordinates onto the 'graphics' coordinates used by Canvas objects.

Callable: the standard recipe from Python Cookbook for encapsulating
a funcation and its arguments in an object that can be used as a
callback.

Thread: a wrapper class for threading.Thread that improves the
interface.

Watcher: a workaround for the problem multithreaded programs have
handling signals, especially the SIGINT generated by a
KeyboardInterrupt.


The most important idea about this module is the idea of using
a stack of frames to avoid keeping track of parent widgets explicitly.


  Copyright 2005 Allen B. Downey

    This file contains wrapper classes I use with tkinter.  It is
    mostly for my own use; I don't support it, and it is not very
    well documented.

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, see
    http://www.gnu.org/licenses/gpl.html or write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
    02110-1301 USA
    
"""



from math import *
from Tkinter import *

import threading, time, os, signal, sys, operator

class Thread(threading.Thread):
    """this is a wrapper for threading.Thread that improves
    the syntax for creating and starting threads.  See Appendix A
    of The Little Book of Semaphores, http://greenteapress.com/semaphores/
    """
    def __init__(self, target, *args):
        threading.Thread.__init__(self, target=target, args=args)
        self.start()

class Semaphore(threading._Semaphore):
    """this is a wrapper class that makes signal and wait
    synonyms for acquire and release, and also makes signal
    take an optional argument.
    """
    wait = threading._Semaphore.acquire
    
    def signal(self, n=1):
        for i in range(n): self.release()

    def value(self):
        return self._Semaphore__value



def pairiter(seq):
    """return an iterator that yields consecutive pairs from seq"""
    it = iter(seq)
    while True:
        yield [it.next(), it.next()]

def pair(seq):
    """return a list of consecutive pairs from seq"""
    return [x for x in pairiter(seq)]

def flatten(seq):
    return sum(seq, [])

# Gui provides wrappers for many of the methods in the Tk
# class; also, it keeps track of the current frame so that
# you can create new widgets without naming the parent frame
# explicitly.

def underride(d, **kwds):
    """Add kwds to the dictionary only if they are not already set"""
    for key, val in kwds.iteritems():
        if key not in d:
            d[key] = val

def override(d, **kwds):
    """Add kwds to the dictionary even if they are already set"""
    d.update(kwds)


class Gui(Tk):
    def __init__(self, debug=False):
        """initialize the gui.
        turning on debugging changes the behavior of Gui.fr so
        that the nested frame structure is apparent
        """
        Tk.__init__(self)
        self.debug = debug
        self.frames = [self]           # the stack of nested frames

    frame = property(lambda self: self.frames[-1])

    def endfr(self):
        """end the current frame (and return it)"""
        return self.frames.pop()

    popfr = endfr
    endgr = endfr

    def pushfr(self, frame):
        """push a frame onto the frame stack"""
        self.frames.append(frame)

    def tl(self, **options):
        """make a return a top level window."""
        return Toplevel(**options)

    """The following widget wrappers all invoke widget to
    create and pack the new widget.  The first four positional
    arguments determine how the widget is packed.  Some widgets
    take additional positional arguments.  In most cases, the
    keyword arguments are passed as options to the widget
    constructor.

    The default pack arguments are
    side=TOP, fill=NONE, expand=0, anchor=CENTER
    Widgets that use these defaults can just pass along
    args and options unmolested.  Widgets (like fr and en)
    that want different defaults have to roll the arguments
    in with the other options and then underride them.
    """

    argnames = ['side', 'fill', 'expand', 'anchor']

    def fr(self, *args, **options):
        """make a return a frame.
        As a side effect, the new frame becomes the current frame
        """
        options.update(dict(zip(Gui.argnames,args)))
        underride(options, fill=BOTH, expand=1)
        if self.debug:
            override(options, bd=5, relief=RIDGE)

        # create the new frame and push it onto the stack
        frame = self.widget(Frame, **options)
        self.pushfr(frame)
        return frame

    def gr(self, cols, cweights=[1], rweights=[1], **options):
        """create a frame and switch to grid mode.
        cols is the number of columns in the grid (no need to
        specify the number of rows).  cweight and rweight control
        how the widgets expand if the frame expands (see colweights
        and rowweights below).  options are passed along to the frame
        """
        fr = self.fr(**options)
        fr.gridding = True
        fr.cols = cols
        fr.i = 0
        fr.j = 0
        self.colweights(cweights)
        self.rowweights(rweights)
        return fr

    def colweights(self, weights):
        """attach weights to the columns of the current grid.
        These weights control how the columns in the grid expand
        when the grid expands.  The default weight is 0, which
        means that the column doesn't expand.  If only one
        column has a value, it gets all the extra space.
        """
        for i, weight in enumerate(weights):
            self.frame.columnconfigure(i, weight=weight)

    def rowweights(self, weights):
        """attach weights to the rows of the current grid.
        These weights control how the rows in the grid expand
        when the grid expands.  The default weight is 0, which
        means that the row doesn't expand.  If only one
        row has a value, it gets all the extra space.
        """
        for i, weight in enumerate(weights):
            self.frame.rowconfigure(i, weight=weight)

    def grid(self, widget, i=None, j=None, **options):
        """pack the given widget in the current grid.
        By default, the widget is packed in the next available
        space, but i and j can override.
        """
        if i == None: i = self.frame.i
        if j == None: j = self.frame.j
        widget.grid(row=i, column=j, **options)

        # increment j by 1, or by columnspan
        # if the widget spans more than one column.
        try:
            incr = options['columnspan']
        except KeyError:
            incr = 1

        self.frame.j += 1
        if self.frame.j == self.frame.cols:
            self.frame.j = 0
            self.frame.i += 1

    # entry
    def en(self, *args, **options):
        options.update(dict(zip(Gui.argnames,args)))
        underride(options, fill=BOTH, expand=1)
        text = options.pop('text', '')
        en = self.widget(Entry, **options)
        en.insert(0, text)
        return en

    # canvas
    def ca(self, *args, **options):
        underride(options, fill=BOTH, expand=1)
        return self.widget(GuiCanvas, *args, **options)

    # label
    def la(self, *args, **options):
        return self.widget(Label, *args, **options)

    # button
    def bu(self, *args, **options):
        return self.widget(Button, *args, **options)

    # menu button
    def mb(self, *args, **options):
        mb = self.widget(Menubutton, *args, **options)
        mb.menu = Menu(mb, relief=SUNKEN)
        mb['menu'] = mb.menu
        return mb

    # menu item
    def mi(self, mb, label='', **options):
        mb.menu.add_command(label=label, **options)        

    # text entry
    def te(self, *args, **options):
        return self.widget(Text, *args, **options)

    # scrollbar
    def sb(self, *args, **options):
        return self.widget(Scrollbar, *args, **options)

    class ScrollableText:
        def __init__(self, gui,
                     *args, **options):
            self.frame = gui.fr(*args, **options)
            self.scrollbar = gui.sb(RIGHT, fill=Y)
            self.text = gui.te(LEFT, wrap=WORD,
                                 yscrollcommand=self.scrollbar.set)
            self.scrollbar.config(command=self.text.yview)
            gui.endfr()

    # scrollable text
    # returns a ScrollableText object that contains a frame, a
    # text entry and a scrollbar.
    # note: the options provided to st apply to the frame only;
    # if you want to configure the other widgets, you have to do
    # it after invoking st
    def st(self, *args, **options):
        return self.ScrollableText(self, *args, **options)

    class ScrollableCanvas:
        def __init__(self, gui, width=500, height=500, **options):
            self.grid = gui.gr(2, **options)
            self.canvas = gui.ca(width=width, height=height, bg='white')

            self.yb = self.sb(command=self.canvas.yview, sticky=N+S)
            self.xb = self.sb(command=self.canvas.xview, orient=HORIZONTAL,
                              sticky=E+W)

            self.canvas.configure(xscrollcommand=self.xb.set,
                                  yscrollcommand=self.yb.set)
            gui.endgr()

    def sc(self, *args, **options):
        return self.ScrollableCanvas(self, *args, **options)

    def widget(self, constructor, *args, **options):
        """this is the mother of all widget constructors.
        the constructor argument is the function that will
        be called to build the new widget. args is rolled
        into options, and then options is split into widget
        option, pack options and grid options
        """
        options.update(dict(zip(Gui.argnames,args)))
        widopt, packopt, gridopt = split_options(options)

        # make the widget and either pack or grid it
        widget = constructor(self.frame, **widopt)
        if hasattr(self.frame, 'gridding'):
            self.grid(widget, **gridopt)
        else:
            widget.pack(**packopt)
        return widget

def pop_options(options, names):
    """remove names from options and return a new dictionary
    that contains the names and values from options
    """
    new = {}
    for name in names:
        if name in options:
            new[name] = options.pop(name)
    return new

def split_options(options):
    """take a dictionary of options and split it into pack
    options, grid options, and anything left is assumed to
    be a widget option
    """
    
    packnames = ['side', 'fill', 'expand', 'anchor']
    gridnames = ['column', 'columnspan', 'row', 'rowspan',
                 'padx', 'pady', 'ipadx', 'ipady', 'sticky']

    packopts = pop_options(options, packnames)
    gridopts = pop_options(options, gridnames)

    return options, packopts, gridopts


class BBox(list):
    __slots__ = ()
    """a bounding box is a list of coordinates, where each
    coordinate is a list of numbers.

    Creating a new bounding box makes a _shallow_ copy of
    the list of coordinates.  For a deep copy, use copy().
    """
    def copy(self):
        t = [Pos(coord) for coord in bbox]
        return BBox(t)

    # top, bottom, left, and right can be accessed as attributes
    def setleft(bbox, val): bbox[0][0] = val 
    def settop(bbox, val): bbox[0][1] = val 
    def setright(bbox, val): bbox[1][0] = val 
    def setbottom(bbox, val): bbox[1][1] = val 
    
    left = property(lambda bbox: bbox[0][0], setleft)
    top = property(lambda bbox: bbox[0][1], settop)
    right = property(lambda bbox: bbox[1][0], setright)
    bottom = property(lambda bbox: bbox[1][1], setbottom)

    def width(bbox): return bbox.right - bbox.left
    def height(bbox): return bbox.bottom - bbox.top

    def upperleft(bbox): return Pos(bbox[0])
    def lowerright(bbox): return Pos(bbox[1])

    def midright(bbox):
        x = bbox.right
        y = (bbox.top + bbox.bottom) / 2.0
        return Pos([x, y])

    def midleft(bbox):
        x = bbox.left
        y = (bbox.top + bbox.bottom) / 2.0
        return Pos([x, y])

    def offset(bbox, pos):
        """return the vector between the upper-left corner of bbox and pos"""
        return Pos([pos[0]-bbox.left, pos[1]-bbox.top])

    def pos(bbox, offset):
        """return the position at the given offset from bbox upper-left"""
        return Pos([offset[0]+bbox.left, offset[1]+bbox.top])

    def flatten(bbox):
        """return a list of four coordinates"""
        return bbox[0] + bbox[1]


class Pos(list):
    __slots__ = ()
    """a position is a list of coordinates.

    Because Pos inherits __init__ from list, it makes a copy
    of the argument to the constructor.
    """
    copy = lambda pos: Pos(pos)

    # x and y can be accessed as attributes
    def setx(pos, val): pos[0] = val 
    def sety(pos, val): pos[1] = val 
    
    x = property(lambda pos: pos[0], setx)
    y = property(lambda pos: pos[1], sety)


class GuiCanvas(Canvas):
    """this is a wrapper for the Canvas provided by tkinter.
    The primary difference is that it supports coordinate
    transformations, the most common of which is the CanvasTranform,
    which make canvas coordinates Cartesian (origin in the middle,
    positive y axis going up).

    It also provides methods like circle that provide a
    nice interface to the underlying canvas methods.
    """
    def __init__(self, w, transforms=None, **options):
        Canvas.__init__(self, w, **options)

        # the default transform is a standard CanvasTransform
        if transforms == None:
            self.transforms = [CanvasTransform(self)]
        else:
            self.transforms = transforms

    # the following properties make it possbile to access
    # the width and height of the canvas as if they were attributes
    width = property(lambda self: int(self['width']))
    height = property(lambda self: int(self['height']))

    def add_transform(self, transform, pos=None):
        if pos == None:
            self.transforms.append(transform)
        else:
            self.transforms.insert(pos, transform)            
            
    
    def trans(self, coords):
        """apply each of the transforms for this canvas, in order"""
        for trans in self.transforms:
            coords = trans.trans_list(coords)
        return coords

    def invert(self, coords):
        t = self.transforms[:]
        t.reverse()
        for trans in t:
            coords = trans.invert_list(coords)
        return coords

    def bbox(self, item):
        if isinstance(item, list):
            item = item[0]
        bbox = Canvas.bbox(self, item)
        if bbox == None: return bbox
        bbox = pair(bbox)
        bbox = self.invert(bbox)
        return BBox(bbox)

    def coords(self, item, coords=None):
        if coords:
            coords = self.trans(coords)
            coords = flatten(coords)
            Canvas.coords(self, item, *coords)
        else:
            "have to get the coordinates and invert them"

    def move(self, item, dx=0, dy=0):
        coords = self.trans([[dx, dy]])
        pos = coords[0]
        Canvas.move(self, item, pos[0], pos[1])

    def flipx(self, item):
        coords = Canvas.coords(self, item)
        for i in range(0, len(coords), 2):
            coords[i] *= -1
        Canvas.coords(self, item, *coords)

    def circle(self, x, y, r, fill='', **options):
        options['fill'] = fill
        coords = self.trans([[x-r, y-r], [x+r, y+r]])
        tag = self.create_oval(coords, options)
        return tag
    
    def oval(self, coords, fill='', **options):
        options['fill'] = fill
        return self.create_oval(self.trans(coords), options)

    def rectangle(self, coords, fill='', **options):
        options['fill'] = fill
        return self.create_rectangle(self.trans(coords), options)

    def line(self, coords, fill='black', **options):
        options['fill'] = fill
        tag = self.create_line(self.trans(coords), options)
        return tag
    
    def polygon(self, coords, fill='', **options):
        options['fill'] = fill
        return self.create_polygon(self.trans(coords), options)

    def text(self, coord, text='', fill='black', **options):
        options['text'] = text
        options['fill'] = fill
        return self.create_text(self.trans([coord]), options)

    def image(self, coord, image, **options):
        options['image'] = image
        return self.create_image(self.trans([coord]), options)

    def dump(self, filename='canvas.eps'):
        bbox = Canvas.bbox(self, ALL)
        x, y, width, height = bbox
        width -= x
        height -= y
        ps = self.postscript(x=x, y=y, width=width, height=height)
        fp = open(filename, 'w')
        fp.write(ps)
        fp.close()


class Transform:
    """the parent class of transforms, Transform provides methods
    for transforming lists of coordinates.  Subclasses of Transform
    are supposed to implement trans() and invert()
    """
    def trans_list(self, points, func=None):
        # the default func is trans; invert_list overrides this
        # with invert
        if func == None:
            func = self.trans

        if isinstance(points[0], (list, tuple)):
            return [Pos(func(p)) for p in points]
        else:
            return Pos(func(points))

    def invert_list(self, points):
        return self.trans_list(points, self.invert)
    

class CanvasTransform(Transform):
    """under a CanvasTransform, the origin is in the middle of
    the canvas, the positive y-axis is up, and the coordinate
    [1, 1] maps to the point specified by scale.
    """
    def __init__(self, ca, scale=[1, 1]):
        self.ca = ca
        self.scale = scale
    
    def trans(self, p):
        x =  p[0] * self.scale[0] + self.ca.width/2
        y = -p[1] * self.scale[1] + self.ca.height/2      
        return [x, y]


class ScaleTransform(Transform):
    """scale the coordinate system by the given factors.
    The origin is half a unit from the upper-left corner.
    """
    def __init__(self, scale=[1, 1]):
        self.scale = scale
    
    def trans(self, p):
        x = p[0] * self.scale[0]
        y = p[1] * self.scale[1]
        return [x, y]

    def invert(self, p):
        x = p[0] / self.scale[0]
        y = p[1] / self.scale[1]
        return [x, y]


class RotateTransform(Transform):
    """rotate the coordinate system theta degrees clockwise
    """
    def __init__(self, theta):
        self.theta = theta

    def rotate(self, p, theta):
        s = sin(theta)
        c = cos(theta)
        x =   c * p[0] + s * p[1]
        y =  -s * p[0] + c * p[1]
        return [x, y]
    
    def trans(self, p):
        return self.rotate(p, self.theta)

    def invert(self, p):
        return self.rotate(p, -self.theta)


class SwirlTransform(RotateTransform):

    def trans(self, p):
        d = sqrt(p[0]*p[0] + p[1]*p[1])
        return self.rotate(p, self.theta*d)

    def invert(self, p):
        d = sqrt(p[0]*p[0] + p[1]*p[1])
        return self.rotate(p, -self.theta*d)


class Callable:
    """this class is used to wrap a function and its arguments
    into an object that can be passed as a callback parameter
    and invoked later.  It is from the Python Cookbook 9.1, page 302
    """
    
    def __init__(self, func, *args, **kwds):
        self.func = func
        self.args = args
        self.kwds = kwds

    def __call__(self):
        return apply(self.func, self.args, self.kwds)

    def __str__(self):
        return self.func.__name__


class Watcher:
    """this class solves two problems with multithreaded
    programs in Python, (1) a signal might be delivered
    to any thread (which is just a malfeature) and (2) if
    the thread that gets the signal is waiting, the signal
    is ignored (which is a bug).

    The watcher is a concurrent process (not thread) that
    waits for a signal and the process that contains the
    threads.  See Appendix A of The Little Book of Semaphores.

    I have only tested this on Linux.  I would expect it to
    work on the Macintosh and not work on Windows.
    """
    
    def __init__(self):
        """ Creates a child thread, which returns.  The parent
            thread waits for a KeyboardInterrupt and then kills
            the child thread.
        """
        self.child = os.fork()
        if self.child == 0:
            return
        else:
            self.watch()

    def watch(self):
        try:
            os.wait()
        except KeyboardInterrupt:
            # I put the capital B in KeyBoardInterrupt so I can
            # tell when the Watcher gets the SIGINT
            print 'KeyBoardInterrupt'
            self.kill()
        sys.exit()

    def kill(self):
        try:
            os.kill(self.child, signal.SIGKILL)
        except OSError: pass


def tk_example():
    tk = Tk()
    
    def hello():
        ca.create_text(100, 100, text='hello', fill='blue')
    
    ca = Canvas(tk, bg='white')
    ca.pack(side=LEFT)

    fr = Frame(tk)
    fr.pack(side=LEFT)

    bu1 = Button(fr, text='Hello', command=hello)
    bu1.pack()
    bu2 = Button(fr, text='Quit', command=tk.quit)
    bu2.pack()
    
    tk.mainloop()

def gui_example():
    gui = Gui()

    ca = gui.ca(LEFT, bg='white')
    def hello():
        ca.text([0,0], 'hello', 'blue')
    
    gui.fr(LEFT)
    gui.bu(text='Hello', command=hello)
    gui.bu(text='Quit', command=gui.quit)
    gui.endfr()
    
    gui.mainloop()


def main(script, n=0, *args):
    if n == 0:
        tk_example()
    else:
        gui_example()

if __name__ == '__main__':
    main(*sys.argv)
