#!/usr/bin/env python # example getselection.py import gtk import GDK import struct class GetSelectionExample: SELECTION_PRIMARY = 1 CURRENT_TIME = 0 # Signal handler invoked when user clicks on the # "Get String Target" button def get_stringtarget(self, widget): # Get the atom corresponding to the string "STRING" if self.string_atom == None: self.string_atom = gtk.atom_intern("STRING", gtk.FALSE) # And request the "STRING" target for the primary selection ret = widget.selection_convert(self.SELECTION_PRIMARY, self.string_atom, self.CURRENT_TIME) return # Signal handler invoked when user clicks on the "Get Targets" button def get_targets(self, widget): # Get the atom corresponding to the string "TARGETS" if self.targets_atom == None: self.targets_atom = gtk.atom_intern("TARGETS", gtk.FALSE) # And request the "TARGETS" target for the primary selection widget.selection_convert(self.SELECTION_PRIMARY, self.targets_atom, self.CURRENT_TIME) return # Signal handler called when the selections owner returns the data def selection_received(self, widget, selection_data, data): # **** IMPORTANT **** Check to see if retrieval succeeded if selection_data.length < 0: print "Selection retrieval failed" return # Make sure we got the data in the expected form if selection_data.type == GDK.SELECTION_TYPE_STRING: # Print out the string we received print "STRING TARGET: %s" % selection_data.data elif selection_data.type == GDK.SELECTION_TYPE_ATOM: # Print out the atoms we received atoms = struct.unpack( 'L'*(selection_data.length*8/selection_data.format), selection_data.data) for atom in atoms: name = gtk.atom_name(atom) if name != None: print "%s" % name else: print "(bad atom)" else: print "Selection was not returned as \"STRING\" or \"ATOM\"!" return def __init__(self): self.string_atom = None self.targets_atom = None # Create the toplevel window window = gtk.GtkWindow(gtk.WINDOW_TOPLEVEL) window.set_title("Get Selection") window.set_border_width(10) window.connect("destroy", gtk.mainquit) vbox = gtk.GtkVBox(gtk.FALSE, 0) window.add(vbox) vbox.show() # Create a button the user can click to get the string target button = gtk.GtkButton("Get String Target") button.connect("clicked", self.get_stringtarget) button.connect("selection_received", self.selection_received) vbox.pack_start(button) button.show() # Create a button the user can click to get targets button = gtk.GtkButton("Get Targets") button.connect("clicked", self.get_targets) button.connect("selection_received", self.selection_received) vbox.pack_start(button) button.show() window.show() def main(): gtk.mainloop() return 0 if __name__ == "__main__": GetSelectionExample() main()