#!/usr/bin/env python
from gtk import *
from GDK import *

"""Access to the gtk-selection buffer.
Selection can be used as a one-shot thing, independent of any real
Gtk+ programming.

Sample use:

    from selection import Selection
    s = Selection()
    print s.getSelection()

For setSelection(), we must keep an instance to the instantiated
selection.  Otherwise, we'll lose our handle.  Also, a mainloop()
should be in effect, or nothing happens.  Setting the selection, then,
is a bit harder to do.

"""

## Module constants
_stringatom = atom_intern("STRING", FALSE)
# I found these in gdktypes.h.  Used in setting up the signal handlers.
GDK_CURRENT_TIME = 0
GDK_SELECTION_PRIMARY = 1

class Selection:
    def __init__(self):
        self.entry = GtkEntry()
        self.window = GtkWindow(WINDOW_TOPLEVEL)
        self.window.add(self.entry)
        self.window.connect("selection_received", self._produceData)
        # need to do this because self.entry isn't visible but still does stuff
        self.entry.realize()
        
    def getSelection(self):
        """Return the primary selection as a string."""
        self.window.selection_convert(GDK_SELECTION_PRIMARY,
                              _stringatom, GDK_CURRENT_TIME);
        mainloop()  # waits till the processing is done.
        return self.data

    def _produceData(self, widget, data, val):
        """A quick callback to feed a string into data.
        Attach this to the selection_received signal."""
        self.data = data.data
        mainquit()

    def setSelection(self, str):
        """Set the primary selection.  Requires a mainloop() to be
        running when we call this; otherwise things scream at us."""
        self.entry.set_text(str)
        self.entry.select_region(0, len(str))


def _test1():
    s = Selection()
    print "This is what's in the buffer:", s.getSelection()


    print "Let's try to change it."
    mystr = raw_input("Please enter a string: ")

    window = GtkWindow()
    window.connect("destroy", mainquit)
    button = GtkButton("Press me to set the selection")
    button.connect("clicked", lambda widget, s=s, mystr=mystr:
                   s.setSelection(mystr))
    window.add(button)
    window.show_all()
    mainloop()
    
if __name__ == '__main__':
    _test1()
