21.3. Supplying the Selection

Supplying the selection is a bit more complicated. You must
register handlers that will be called when your selection is requested. For
each selection-target pair you will handle, you make a call to:

widget.selection_add_target(selection, target, info)

widget, selection,
and target identify the requests this handler will
manage. When a request for a selection is received, the "selection_get"
signal will be called. info is an integer that can be
used as an enumerator to identify the specific target within the
callback.

The callback has the signature:

def selection_get(widget, selection_data, info, time):

The gtk.SelectionData is the same as above,
but this time, we're responsible for filling in the fields
type, format and
data. (The format field is
actually important here - the X server uses it to figure out whether the
data needs to be byte-swapped or not. Usually it will
be 8 - i.e. a character - or 32 - i.e. a integer.) This is done by calling
the method:

selection_data.set(type, format, data)

This PyGTK method can only handle string data so the
data must be loaded into a Python string but
format will be whatever the appropriate size is
(e.g. 32 for atoms and integers, 8 for strings). The Python
struct or StringIO modules can
be used to convert non-string data to string data. For example, you can
convert a list of integers to a string and set the
selection_data by:

When prompted by the user, you claim ownership of the selection
by calling:

result = widget.selection_owner_set(selection, time=0L)

result will be TRUE if
program successfully claimed the selection. If
another application claims ownership of the
selection, you will receive a
"selection_clear_event".

As an example of supplying the selection, the setselection.py
program adds selection functionality to a toggle button enclosed in a
gtk.EventBox. (The
gtk.Eventbox is needed because the selection must be
associated with a gtk.gdk.Window and a
gtk.Button is a "windowless" object in GTK+ 2.0.)
When the toggle button is depressed, the program claims the primary
selection. The only target supported (aside from certain targets like
"TARGETS" supplied by GTK+ itself), is the "STRING" target. When this target
is requested, a string representation of the time is returned. Figure 21.2, “Set Selection Example” illustrates the program display when the program
has taken the primary selection ownership: