#!/usr/bin/python

# memory for calculator

import pygtk
import gtk
import sys

class Memory:
    """Class to hold a set of calculator memory locations in a separate win."""
    def __init__(self, count=3, x=300, y=100):
        self.N = count
        self.tBuffers = []
        self.x = x
        self.y = y
        self.draw()
        

    def draw(self):
        """Main window layout setup."""
        self.win = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.win.set_destroy_with_parent(True)
        self.win.connect("delete_event", self.delete)
        self.win.set_title("Calculator memories") 
        self.win.set_size_request(200, 25*self.N)   # size
        self.win.move(self.x, self.y)   # place
        table = gtk.Table(2, self.N, False)     # table layout
        self.win.add(table)

        # setup memory location
        for i in range(self.N):
            # label
            label = gtk.Label("M" + str(i) + ":")
            table.attach(label, 0, 1, i, i+1, 0, 0)
            label.show()

            # actual memory
            textV = gtk.TextView()
            textV.show()
            textV.set_editable(False)
            textV.set_cursor_visible(False)

            # setup DnD, accept connectios from all applications
            textV.drag_dest_set(gtk.DEST_DEFAULT_DROP,
                [("text", 0, 80)], gtk.gdk.ACTION_COPY)
                #[("text/plain", gtk.TARGET_SAME_APP, 80)], gtk.gdk.ACTION_COPY)
            textV.connect('drag_motion', self.motion_cb)
            textV.connect('drag_data_received', self.receiveCallBack)

            textV.drag_source_set(gtk.gdk.BUTTON1_MASK,
                [("text", 0, 80)], gtk.gdk.ACTION_COPY)
            textV.connect("drag_data_get", self.sendCallBack)

            table.attach(textV, 1, 2, i, i+1)
            self.tBuffers.append(textV.get_buffer())
        table.show()
        self.win.show()


    # DnD handlers
    def sendCallBack(self, widget, context, selection, targetType, eventTime):
        #print 'MsendCallBack'
        textbuf = widget.get_buffer()
        selection.set(selection.target, 8, textbuf.get_text(
                          textbuf.get_start_iter(),
                          textbuf.get_end_iter()))


    def receiveCallBack(self, widget, context, x, y, selection, targetType,    time):
        #print 'MreceiveCallBack'
        tBuf = widget.get_buffer()
        tBuf.set_text(selection.data)
        
    def motion_cb(self, wid, context, x, y, time):
        #print 'Mmotion_cb'
        context.drag_status(gtk.gdk.ACTION_COPY, time)
        return True


    def delete(self, widget, event=None):
        """Memory win quit callback."""
        self.win.destroy()
        return False

    def main(self):
        gtk.main()

# call main metkod
if __name__ == "__main__":
    n = 5
    if (len(sys.argv) > 1 and int(sys.argv[1]) > 0):
        n = int(sys.argv[1])
    mem_object = Memory(n)
    mem_object.main()


