]> Pileus Git - ~andy/gtk/blob - gtk/gtkclipboard.c
gtk/gtkclipboard.c: Use accessor functions to access GtkSelectionData
[~andy/gtk] / gtk / gtkclipboard.c
1 /* GTK - The GIMP Toolkit
2  * Copyright (C) 2000 Red Hat, Inc.
3  * Copyright (C) 2004 Nokia Corporation
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Global clipboard abstraction. 
21  */
22
23 #include "config.h"
24 #include <string.h>
25
26 #include "gtkclipboard.h"
27 #include "gtkinvisible.h"
28 #include "gtkmain.h"
29 #include "gtkmarshalers.h"
30 #include "gtktextbufferrichtext.h"
31 #include "gtkintl.h"
32
33 #ifdef GDK_WINDOWING_X11
34 #include "x11/gdkx.h"
35 #endif
36
37 #ifdef GDK_WINDOWING_WIN32
38 #include "win32/gdkwin32.h"
39 #endif
40
41 enum {
42   OWNER_CHANGE,
43   LAST_SIGNAL
44 };
45
46 typedef struct _GtkClipboardClass GtkClipboardClass;
47
48 typedef struct _RequestContentsInfo RequestContentsInfo;
49 typedef struct _RequestTextInfo RequestTextInfo;
50 typedef struct _RequestRichTextInfo RequestRichTextInfo;
51 typedef struct _RequestImageInfo RequestImageInfo;
52 typedef struct _RequestURIInfo RequestURIInfo;
53 typedef struct _RequestTargetsInfo RequestTargetsInfo;
54
55 struct _GtkClipboard 
56 {
57   GObject parent_instance;
58
59   GdkAtom selection;
60
61   GtkClipboardGetFunc get_func;
62   GtkClipboardClearFunc clear_func;
63   gpointer user_data;
64   gboolean have_owner;
65
66   guint32 timestamp;
67
68   gboolean have_selection;
69   GdkDisplay *display;
70
71   GdkAtom *cached_targets;
72   gint     n_cached_targets;
73
74   gulong     notify_signal_id;
75   gboolean   storing_selection;
76   GMainLoop *store_loop;
77   guint      store_timeout;
78   gint       n_storable_targets;
79   GdkAtom   *storable_targets;
80 };
81
82 struct _GtkClipboardClass
83 {
84   GObjectClass parent_class;
85
86   void (*owner_change) (GtkClipboard        *clipboard,
87                         GdkEventOwnerChange *event);
88 };
89
90 struct _RequestContentsInfo
91 {
92   GtkClipboardReceivedFunc callback;
93   gpointer user_data;
94 };
95
96 struct _RequestTextInfo
97 {
98   GtkClipboardTextReceivedFunc callback;
99   gpointer user_data;
100 };
101
102 struct _RequestRichTextInfo
103 {
104   GtkClipboardRichTextReceivedFunc callback;
105   GdkAtom *atoms;
106   gint     n_atoms;
107   gint     current_atom;
108   gpointer user_data;
109 };
110
111 struct _RequestImageInfo
112 {
113   GtkClipboardImageReceivedFunc callback;
114   gpointer user_data;
115 };
116
117 struct _RequestURIInfo
118 {
119   GtkClipboardURIReceivedFunc callback;
120   gpointer user_data;
121 };
122
123 struct _RequestTargetsInfo
124 {
125   GtkClipboardTargetsReceivedFunc callback;
126   gpointer user_data;
127 };
128
129 static void gtk_clipboard_class_init   (GtkClipboardClass   *class);
130 static void gtk_clipboard_finalize     (GObject             *object);
131 static void gtk_clipboard_owner_change (GtkClipboard        *clipboard,
132                                         GdkEventOwnerChange *event);
133
134 static void          clipboard_unset      (GtkClipboard     *clipboard);
135 static void          selection_received   (GtkWidget        *widget,
136                                            GtkSelectionData *selection_data,
137                                            guint             time);
138 static GtkClipboard *clipboard_peek       (GdkDisplay       *display,
139                                            GdkAtom           selection,
140                                            gboolean          only_if_exists);
141 static GtkWidget *   get_clipboard_widget (GdkDisplay       *display);
142
143
144 enum {
145   TARGET_STRING,
146   TARGET_TEXT,
147   TARGET_COMPOUND_TEXT,
148   TARGET_UTF8_STRING,
149   TARGET_SAVE_TARGETS
150 };
151
152 static const gchar request_contents_key[] = "gtk-request-contents";
153 static GQuark request_contents_key_id = 0;
154
155 static const gchar clipboards_owned_key[] = "gtk-clipboards-owned";
156 static GQuark clipboards_owned_key_id = 0;
157
158 static guint         clipboard_signals[LAST_SIGNAL] = { 0 };
159
160 G_DEFINE_TYPE (GtkClipboard, gtk_clipboard, G_TYPE_OBJECT)
161
162 static void
163 gtk_clipboard_init (GtkClipboard *object)
164 {
165 }
166
167 static void
168 gtk_clipboard_class_init (GtkClipboardClass *class)
169 {
170   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
171
172   gobject_class->finalize = gtk_clipboard_finalize;
173
174   class->owner_change = gtk_clipboard_owner_change;
175
176   /**
177    * GtkClipboard::owner-change:
178    * @clipboard: the #GtkClipboard on which the signal is emitted
179    * @event: the @GdkEventOwnerChange event 
180    *
181    * The ::owner-change signal is emitted when GTK+ receives an
182    * event that indicates that the ownership of the selection 
183    * associated with @clipboard has changed.
184    *
185    * Since: 2.6
186    */ 
187   clipboard_signals[OWNER_CHANGE] =
188     g_signal_new (I_("owner-change"),
189                   G_TYPE_FROM_CLASS (gobject_class),
190                   G_SIGNAL_RUN_FIRST,
191                   G_STRUCT_OFFSET (GtkClipboardClass, owner_change),
192                   NULL, NULL,
193                   _gtk_marshal_VOID__BOXED,
194                   G_TYPE_NONE, 1,
195                   GDK_TYPE_EVENT | G_SIGNAL_TYPE_STATIC_SCOPE);
196 }
197
198 static void
199 gtk_clipboard_finalize (GObject *object)
200 {
201   GtkClipboard *clipboard;
202   GtkWidget *clipboard_widget = NULL;
203   GSList *clipboards = NULL;
204
205   clipboard = GTK_CLIPBOARD (object);
206
207   if (clipboard->display)
208     {
209       clipboards = g_object_get_data (G_OBJECT (clipboard->display), "gtk-clipboard-list");
210
211       if (g_slist_index (clipboards, clipboard) >= 0)
212         g_warning ("GtkClipboard prematurely finalized");
213
214       clipboards = g_slist_remove (clipboards, clipboard);
215
216       g_object_set_data (G_OBJECT (clipboard->display), "gtk-clipboard-list", 
217                          clipboards);
218
219       /* don't use get_clipboard_widget() here because it would create the
220        * widget if it doesn't exist.
221        */
222       clipboard_widget = g_object_get_data (G_OBJECT (clipboard->display),
223                                             "gtk-clipboard-widget");
224     }
225
226   clipboard_unset (clipboard);
227
228   if (clipboard->store_loop && g_main_loop_is_running (clipboard->store_loop))
229     g_main_loop_quit (clipboard->store_loop);
230
231   if (clipboard->store_timeout != 0)
232     g_source_remove (clipboard->store_timeout);
233
234   if (clipboard->notify_signal_id != 0)
235     g_signal_handler_disconnect (clipboard_widget, clipboard->notify_signal_id);
236   
237   g_free (clipboard->storable_targets);
238   g_free (clipboard->cached_targets);
239
240   G_OBJECT_CLASS (gtk_clipboard_parent_class)->finalize (object);
241 }
242
243 static void
244 clipboard_display_closed (GdkDisplay   *display,
245                           gboolean      is_error,
246                           GtkClipboard *clipboard)
247 {
248   GSList *clipboards;
249
250   clipboards = g_object_get_data (G_OBJECT (display), "gtk-clipboard-list");
251   g_object_run_dispose (G_OBJECT (clipboard));
252   clipboards = g_slist_remove (clipboards, clipboard);
253   g_object_set_data (G_OBJECT (display), I_("gtk-clipboard-list"), clipboards);
254   g_object_unref (clipboard);
255 }
256
257 /**
258  * gtk_clipboard_get_for_display:
259  * @display: the display for which the clipboard is to be retrieved or created
260  * @selection: a #GdkAtom which identifies the clipboard
261  *             to use.
262  * 
263  * Returns the clipboard object for the given selection.
264  * Cut/copy/paste menu items and keyboard shortcuts should use
265  * the default clipboard, returned by passing %GDK_SELECTION_CLIPBOARD for @selection.
266  * (%GDK_NONE is supported as a synonym for GDK_SELECTION_CLIPBOARD
267  * for backwards compatibility reasons.)
268  * The currently-selected object or text should be provided on the clipboard
269  * identified by #GDK_SELECTION_PRIMARY. Cut/copy/paste menu items
270  * conceptually copy the contents of the #GDK_SELECTION_PRIMARY clipboard
271  * to the default clipboard, i.e. they copy the selection to what the
272  * user sees as the clipboard.
273  *
274  * (Passing #GDK_NONE is the same as using <literal>gdk_atom_intern
275  * ("CLIPBOARD", FALSE)</literal>. See <ulink
276  * url="http://www.freedesktop.org/Standards/clipboards-spec">
277  * http://www.freedesktop.org/Standards/clipboards-spec</ulink>
278  * for a detailed discussion of the "CLIPBOARD" vs. "PRIMARY"
279  * selections under the X window system. On Win32 the
280  * #GDK_SELECTION_PRIMARY clipboard is essentially ignored.)
281  *
282  * It's possible to have arbitrary named clipboards; if you do invent
283  * new clipboards, you should prefix the selection name with an
284  * underscore (because the ICCCM requires that nonstandard atoms are
285  * underscore-prefixed), and namespace it as well. For example,
286  * if your application called "Foo" has a special-purpose
287  * clipboard, you might call it "_FOO_SPECIAL_CLIPBOARD".
288  * 
289  * Return value: (transfer none): the appropriate clipboard object. If no
290  *             clipboard already exists, a new one will
291  *             be created. Once a clipboard object has
292  *             been created, it is persistent and, since
293  *             it is owned by GTK+, must not be freed or
294  *             unrefd.
295  *
296  * Since: 2.2
297  **/
298 GtkClipboard *
299 gtk_clipboard_get_for_display (GdkDisplay *display, 
300                                GdkAtom     selection)
301 {
302   g_return_val_if_fail (display != NULL, NULL); /* See bgo#463773; this is needed because Flash Player sucks */
303   g_return_val_if_fail (GDK_IS_DISPLAY (display), NULL);
304   g_return_val_if_fail (!display->closed, NULL);
305
306   return clipboard_peek (display, selection, FALSE);
307 }
308
309
310 /**
311  * gtk_clipboard_get:
312  * @selection: a #GdkAtom which identifies the clipboard to use
313  *
314  * Returns the clipboard object for the given selection.
315  * See gtk_clipboard_get_for_display() for complete details.
316  *
317  * Return value: (transfer none): the appropriate clipboard object. If no clipboard
318  *     already exists, a new one will be created. Once a clipboard
319  *     object has been created, it is persistent and, since it is
320  *     owned by GTK+, must not be freed or unreffed.
321  */
322 GtkClipboard *
323 gtk_clipboard_get (GdkAtom selection)
324 {
325   return gtk_clipboard_get_for_display (gdk_display_get_default (), selection);
326 }
327
328 static void 
329 selection_get_cb (GtkWidget          *widget,
330                   GtkSelectionData   *selection_data,
331                   guint               info,
332                   guint               time)
333 {
334   GtkClipboard *clipboard;
335
336   clipboard = gtk_widget_get_clipboard (widget,
337                                         gtk_selection_data_get_selection (selection_data));
338
339   if (clipboard && clipboard->get_func)
340     clipboard->get_func (clipboard, selection_data, info, clipboard->user_data);
341 }
342
343 static gboolean
344 selection_clear_event_cb (GtkWidget         *widget,
345                           GdkEventSelection *event)
346 {
347   GtkClipboard *clipboard = gtk_widget_get_clipboard (widget, event->selection);
348
349   if (clipboard)
350     {
351       clipboard_unset (clipboard);
352
353       return TRUE;
354     }
355
356   return FALSE;
357 }
358
359 static GtkWidget *
360 make_clipboard_widget (GdkDisplay *display, 
361                        gboolean    provider)
362 {
363   GtkWidget *widget = gtk_invisible_new_for_screen (gdk_display_get_default_screen (display));
364
365   g_signal_connect (widget, "selection-received",
366                     G_CALLBACK (selection_received), NULL);
367
368   if (provider)
369     {
370       /* We need this for gdk_x11_get_server_time() */
371       gtk_widget_add_events (widget, GDK_PROPERTY_CHANGE_MASK);
372       
373       g_signal_connect (widget, "selection-get",
374                         G_CALLBACK (selection_get_cb), NULL);
375       g_signal_connect (widget, "selection-clear-event",
376                         G_CALLBACK (selection_clear_event_cb), NULL);
377     }
378
379   return widget;
380 }
381
382 static GtkWidget *
383 get_clipboard_widget (GdkDisplay *display)
384 {
385   GtkWidget *clip_widget = g_object_get_data (G_OBJECT (display), "gtk-clipboard-widget");
386   if (!clip_widget)
387     {
388       clip_widget = make_clipboard_widget (display, TRUE);
389       g_object_set_data (G_OBJECT (display), I_("gtk-clipboard-widget"), clip_widget);
390     }
391
392   return clip_widget;
393 }
394
395 /* This function makes a very good guess at what the correct
396  * timestamp for a selection request should be. If there is
397  * a currently processed event, it uses the timestamp for that
398  * event, otherwise it uses the current server time. However,
399  * if the time resulting from that is older than the time used
400  * last time, it uses the time used last time instead.
401  *
402  * In order implement this correctly, we never use CurrentTime,
403  * but actually retrieve the actual timestamp from the server.
404  * This is a little slower but allows us to make the guarantee
405  * that the times used by this application will always ascend
406  * and we won't get selections being rejected just because
407  * we are using a correct timestamp from an event, but used
408  * CurrentTime previously.
409  */
410 static guint32
411 clipboard_get_timestamp (GtkClipboard *clipboard)
412 {
413   GtkWidget *clipboard_widget = get_clipboard_widget (clipboard->display);
414   guint32 timestamp = gtk_get_current_event_time ();
415
416   if (timestamp == GDK_CURRENT_TIME)
417     {
418 #ifdef GDK_WINDOWING_X11
419       timestamp = gdk_x11_get_server_time (gtk_widget_get_window (clipboard_widget));
420 #elif defined GDK_WINDOWING_WIN32
421       timestamp = GetMessageTime ();
422 #endif
423     }
424   else
425     {
426       if (clipboard->timestamp != GDK_CURRENT_TIME)
427         {
428           /* Check to see if clipboard->timestamp is newer than
429            * timestamp, accounting for wraparound.
430            */
431
432           guint32 max = timestamp + 0x80000000;
433
434           if ((max > timestamp &&
435                (clipboard->timestamp > timestamp &&
436                 clipboard->timestamp <= max)) ||
437               (max <= timestamp &&
438                (clipboard->timestamp > timestamp ||
439                 clipboard->timestamp <= max)))
440             {
441               timestamp = clipboard->timestamp;
442             }
443         }
444     }
445
446   clipboard->timestamp = timestamp;
447
448   return timestamp;
449 }
450
451 static void
452 clipboard_owner_destroyed (gpointer data)
453 {
454   GSList *clipboards = data;
455   GSList *tmp_list;
456
457   tmp_list = clipboards;
458   while (tmp_list)
459     {
460       GtkClipboard *clipboard = tmp_list->data;
461
462       clipboard->get_func = NULL;
463       clipboard->clear_func = NULL;
464       clipboard->user_data = NULL;
465       clipboard->have_owner = FALSE;
466
467       gtk_clipboard_clear (clipboard);
468
469       tmp_list = tmp_list->next;
470     }
471   
472   g_slist_free (clipboards);
473 }
474
475 static void
476 clipboard_add_owner_notify (GtkClipboard *clipboard)
477 {
478   if (!clipboards_owned_key_id)
479     clipboards_owned_key_id = g_quark_from_static_string (clipboards_owned_key);
480   
481   if (clipboard->have_owner)
482     g_object_set_qdata_full (clipboard->user_data, clipboards_owned_key_id,
483                              g_slist_prepend (g_object_steal_qdata (clipboard->user_data,
484                                                                     clipboards_owned_key_id),
485                                               clipboard),
486                              clipboard_owner_destroyed);
487 }
488
489 static void
490 clipboard_remove_owner_notify (GtkClipboard *clipboard)
491 {
492   if (clipboard->have_owner)
493      g_object_set_qdata_full (clipboard->user_data, clipboards_owned_key_id,
494                               g_slist_remove (g_object_steal_qdata (clipboard->user_data,
495                                                                     clipboards_owned_key_id),
496                                               clipboard),
497                               clipboard_owner_destroyed);
498 }
499           
500 static gboolean
501 gtk_clipboard_set_contents (GtkClipboard         *clipboard,
502                             const GtkTargetEntry *targets,
503                             guint                 n_targets,
504                             GtkClipboardGetFunc   get_func,
505                             GtkClipboardClearFunc clear_func,
506                             gpointer              user_data,
507                             gboolean              have_owner)
508 {
509   GtkWidget *clipboard_widget = get_clipboard_widget (clipboard->display);
510
511   if (gtk_selection_owner_set_for_display (clipboard->display,
512                                            clipboard_widget,
513                                            clipboard->selection,
514                                            clipboard_get_timestamp (clipboard)))
515     {
516       clipboard->have_selection = TRUE;
517
518       if (clipboard->n_cached_targets != -1)
519         {
520           g_free (clipboard->cached_targets);
521           clipboard->cached_targets = NULL;
522           clipboard->n_cached_targets = -1;
523         }
524
525       if (!(clipboard->have_owner && have_owner) ||
526           clipboard->user_data != user_data)
527         {
528           clipboard_unset (clipboard);
529
530           if (clipboard->get_func)
531             {
532               /* Calling unset() caused the clipboard contents to be reset!
533                * Avoid leaking and return 
534                */
535               if (!(clipboard->have_owner && have_owner) ||
536                   clipboard->user_data != user_data)
537                 {
538                   (*clear_func) (clipboard, user_data);
539                   return FALSE;
540                 }
541               else
542                 return TRUE;
543             }
544           else
545             {
546               clipboard->user_data = user_data;
547               clipboard->have_owner = have_owner;
548               if (have_owner)
549                 clipboard_add_owner_notify (clipboard);
550             }
551           
552         }
553
554       clipboard->get_func = get_func;
555       clipboard->clear_func = clear_func;
556
557       gtk_selection_clear_targets (clipboard_widget, clipboard->selection);
558       gtk_selection_add_targets (clipboard_widget, clipboard->selection,
559                                  targets, n_targets);
560
561       return TRUE;
562     }
563   else
564     return FALSE;
565 }
566
567 /**
568  * gtk_clipboard_set_with_data:
569  * @clipboard: a #GtkClipboard
570  * @targets: array containing information about the available forms for the
571  *     clipboard data
572  * @n_targets: number of elements in @targets
573  * @get_func: (scope async): function to call to get the actual clipboard data
574  * @clear_func: (scope async): when the clipboard contents are set again,
575  *     this function will be called, and @get_func will not be subsequently
576  *     called.
577  * @user_data: user data to pass to @get_func and @clear_func.
578  *
579  * Virtually sets the contents of the specified clipboard by providing
580  * a list of supported formats for the clipboard data and a function
581  * to call to get the actual data when it is requested.
582  *
583  * Return value: %TRUE if setting the clipboard data succeeded.
584  *    If setting the clipboard data failed the provided callback
585  *    functions will be ignored.
586  **/
587 gboolean
588 gtk_clipboard_set_with_data (GtkClipboard          *clipboard,
589                              const GtkTargetEntry  *targets,
590                              guint                  n_targets,
591                              GtkClipboardGetFunc    get_func,
592                              GtkClipboardClearFunc  clear_func,
593                              gpointer               user_data)
594 {
595   g_return_val_if_fail (clipboard != NULL, FALSE);
596   g_return_val_if_fail (targets != NULL, FALSE);
597   g_return_val_if_fail (get_func != NULL, FALSE);
598
599   return gtk_clipboard_set_contents (clipboard, targets, n_targets,
600                                      get_func, clear_func, user_data,
601                                      FALSE);
602 }
603
604 /**
605  * gtk_clipboard_set_with_owner:
606  * @clipboard: a #GtkClipboard
607  * @targets: array containing information about the available forms for
608  *     the clipboard data
609  * @n_targets: number of elements in @targets
610  * @get_func: (scope async): function to call to get the actual clipboard data
611  * @clear_func: (scope async): when the clipboard contents are set again,
612  *     this function will be called, and @get_func will not be subsequently
613  *     called
614  * @owner: an object that "owns" the data. This object will be passed
615  *     to the callbacks when called
616  *
617  * Virtually sets the contents of the specified clipboard by providing
618  * a list of supported formats for the clipboard data and a function
619  * to call to get the actual data when it is requested.
620  *
621  * The difference between this function and gtk_clipboard_set_with_data()
622  * is that instead of an generic @user_data pointer, a #GObject is passed
623  * in.
624  *
625  * Return value: %TRUE if setting the clipboard data succeeded.
626  *     If setting the clipboard data failed the provided callback
627  *     functions will be ignored.
628  **/
629 gboolean
630 gtk_clipboard_set_with_owner (GtkClipboard          *clipboard,
631                               const GtkTargetEntry  *targets,
632                               guint                  n_targets,
633                               GtkClipboardGetFunc    get_func,
634                               GtkClipboardClearFunc  clear_func,
635                               GObject               *owner)
636 {
637   g_return_val_if_fail (clipboard != NULL, FALSE);
638   g_return_val_if_fail (targets != NULL, FALSE);
639   g_return_val_if_fail (get_func != NULL, FALSE);
640   g_return_val_if_fail (G_IS_OBJECT (owner), FALSE);
641
642   return gtk_clipboard_set_contents (clipboard, targets, n_targets,
643                                      get_func, clear_func, owner,
644                                      TRUE);
645 }
646
647 /**
648  * gtk_clipboard_get_owner:
649  * @clipboard: a #GtkClipboard
650  *
651  * If the clipboard contents callbacks were set with
652  * gtk_clipboard_set_with_owner(), and the gtk_clipboard_set_with_data() or
653  * gtk_clipboard_clear() has not subsequently called, returns the owner set
654  * by gtk_clipboard_set_with_owner().
655  *
656  * Return value: (transfer none): the owner of the clipboard, if any;
657  *     otherwise %NULL.
658  **/
659 GObject *
660 gtk_clipboard_get_owner (GtkClipboard *clipboard)
661 {
662   g_return_val_if_fail (clipboard != NULL, NULL);
663
664   if (clipboard->have_owner)
665     return clipboard->user_data;
666   else
667     return NULL;
668 }
669
670 static void
671 clipboard_unset (GtkClipboard *clipboard)
672 {
673   GtkClipboardClearFunc old_clear_func;
674   gpointer old_data;
675   gboolean old_have_owner;
676   gint old_n_storable_targets;
677   
678   old_clear_func = clipboard->clear_func;
679   old_data = clipboard->user_data;
680   old_have_owner = clipboard->have_owner;
681   old_n_storable_targets = clipboard->n_storable_targets;
682   
683   if (old_have_owner)
684     {
685       clipboard_remove_owner_notify (clipboard);
686       clipboard->have_owner = FALSE;
687     }
688
689   clipboard->n_storable_targets = -1;
690   g_free (clipboard->storable_targets);
691   clipboard->storable_targets = NULL;
692       
693   clipboard->get_func = NULL;
694   clipboard->clear_func = NULL;
695   clipboard->user_data = NULL;
696   
697   if (old_clear_func)
698     old_clear_func (clipboard, old_data);
699
700   /* If we've transferred the clipboard data to the manager,
701    * unref the owner
702    */
703   if (old_have_owner &&
704       old_n_storable_targets != -1)
705     g_object_unref (old_data);
706 }
707
708 /**
709  * gtk_clipboard_clear:
710  * @clipboard:  a #GtkClipboard
711  * 
712  * Clears the contents of the clipboard. Generally this should only
713  * be called between the time you call gtk_clipboard_set_with_owner()
714  * or gtk_clipboard_set_with_data(),
715  * and when the @clear_func you supplied is called. Otherwise, the
716  * clipboard may be owned by someone else.
717  **/
718 void
719 gtk_clipboard_clear (GtkClipboard *clipboard)
720 {
721   g_return_if_fail (clipboard != NULL);
722
723   if (clipboard->have_selection)
724     gtk_selection_owner_set_for_display (clipboard->display, 
725                                          NULL,
726                                          clipboard->selection,
727                                          clipboard_get_timestamp (clipboard));
728 }
729
730 static void 
731 text_get_func (GtkClipboard     *clipboard,
732                GtkSelectionData *selection_data,
733                guint             info,
734                gpointer          data)
735 {
736   gtk_selection_data_set_text (selection_data, data, -1);
737 }
738
739 static void 
740 text_clear_func (GtkClipboard *clipboard,
741                  gpointer      data)
742 {
743   g_free (data);
744 }
745
746
747 /**
748  * gtk_clipboard_set_text:
749  * @clipboard: a #GtkClipboard object
750  * @text:      a UTF-8 string.
751  * @len:       length of @text, in bytes, or -1, in which case
752  *             the length will be determined with <function>strlen()</function>.
753  * 
754  * Sets the contents of the clipboard to the given UTF-8 string. GTK+ will
755  * make a copy of the text and take responsibility for responding
756  * for requests for the text, and for converting the text into
757  * the requested format.
758  **/
759 void 
760 gtk_clipboard_set_text (GtkClipboard *clipboard,
761                         const gchar  *text,
762                         gint          len)
763 {
764   GtkTargetList *list;
765   GtkTargetEntry *targets;
766   gint n_targets;
767
768   g_return_if_fail (clipboard != NULL);
769   g_return_if_fail (text != NULL);
770
771   list = gtk_target_list_new (NULL, 0);
772   gtk_target_list_add_text_targets (list, 0);
773
774   targets = gtk_target_table_new_from_list (list, &n_targets);
775   
776   if (len < 0)
777     len = strlen (text);
778   
779   gtk_clipboard_set_with_data (clipboard, 
780                                targets, n_targets,
781                                text_get_func, text_clear_func,
782                                g_strndup (text, len));
783   gtk_clipboard_set_can_store (clipboard, NULL, 0);
784
785   gtk_target_table_free (targets, n_targets);
786   gtk_target_list_unref (list);
787 }
788
789 static void 
790 pixbuf_get_func (GtkClipboard     *clipboard,
791                  GtkSelectionData *selection_data,
792                  guint             info,
793                  gpointer          data)
794 {
795   gtk_selection_data_set_pixbuf (selection_data, data);
796 }
797
798 static void 
799 pixbuf_clear_func (GtkClipboard *clipboard,
800                    gpointer      data)
801 {
802   g_object_unref (data);
803 }
804
805 /**
806  * gtk_clipboard_set_image:
807  * @clipboard: a #GtkClipboard object
808  * @pixbuf:    a #GdkPixbuf 
809  * 
810  * Sets the contents of the clipboard to the given #GdkPixbuf. 
811  * GTK+ will take responsibility for responding for requests 
812  * for the image, and for converting the image into the 
813  * requested format.
814  * 
815  * Since: 2.6
816  **/
817 void
818 gtk_clipboard_set_image (GtkClipboard *clipboard,
819                           GdkPixbuf    *pixbuf)
820 {
821   GtkTargetList *list;
822   GtkTargetEntry *targets;
823   gint n_targets;
824
825   g_return_if_fail (clipboard != NULL);
826   g_return_if_fail (GDK_IS_PIXBUF (pixbuf));
827
828   list = gtk_target_list_new (NULL, 0);
829   gtk_target_list_add_image_targets (list, 0, TRUE);
830
831   targets = gtk_target_table_new_from_list (list, &n_targets);
832
833   gtk_clipboard_set_with_data (clipboard, 
834                                targets, n_targets,
835                                pixbuf_get_func, pixbuf_clear_func,
836                                g_object_ref (pixbuf));
837   gtk_clipboard_set_can_store (clipboard, NULL, 0);
838
839   gtk_target_table_free (targets, n_targets);
840   gtk_target_list_unref (list);
841 }
842
843 static void
844 set_request_contents_info (GtkWidget           *widget,
845                            RequestContentsInfo *info)
846 {
847   if (!request_contents_key_id)
848     request_contents_key_id = g_quark_from_static_string (request_contents_key);
849
850   g_object_set_qdata (G_OBJECT (widget), request_contents_key_id, info);
851 }
852
853 static RequestContentsInfo *
854 get_request_contents_info (GtkWidget *widget)
855 {
856   if (!request_contents_key_id)
857     return NULL;
858   else
859     return g_object_get_qdata (G_OBJECT (widget), request_contents_key_id);
860 }
861
862 static void 
863 selection_received (GtkWidget            *widget,
864                     GtkSelectionData     *selection_data,
865                     guint                 time)
866 {
867   RequestContentsInfo *request_info = get_request_contents_info (widget);
868   set_request_contents_info (widget, NULL);
869
870   request_info->callback (gtk_widget_get_clipboard (widget, gtk_selection_data_get_selection (selection_data)),
871                           selection_data,
872                           request_info->user_data);
873
874   g_free (request_info);
875
876   if (widget != get_clipboard_widget (gtk_widget_get_display (widget)))
877     gtk_widget_destroy (widget);
878 }
879
880 /**
881  * gtk_clipboard_request_contents:
882  * @clipboard: a #GtkClipboard
883  * @target: an atom representing the form into which the clipboard
884  *     owner should convert the selection.
885  * @callback: (scope async): A function to call when the results are received
886  *     (or the retrieval fails). If the retrieval fails the length field of
887  *     @selection_data will be negative.
888  * @user_data: user data to pass to @callback
889  *
890  * Requests the contents of clipboard as the given target.
891  * When the results of the result are later received the supplied callback
892  * will be called.
893  **/
894 void 
895 gtk_clipboard_request_contents (GtkClipboard            *clipboard,
896                                 GdkAtom                  target,
897                                 GtkClipboardReceivedFunc callback,
898                                 gpointer                 user_data)
899 {
900   RequestContentsInfo *info;
901   GtkWidget *widget;
902   GtkWidget *clipboard_widget;
903
904   g_return_if_fail (clipboard != NULL);
905   g_return_if_fail (target != GDK_NONE);
906   g_return_if_fail (callback != NULL);
907   
908   clipboard_widget = get_clipboard_widget (clipboard->display);
909
910   if (get_request_contents_info (clipboard_widget))
911     widget = make_clipboard_widget (clipboard->display, FALSE);
912   else
913     widget = clipboard_widget;
914
915   info = g_new (RequestContentsInfo, 1);
916   info->callback = callback;
917   info->user_data = user_data;
918
919   set_request_contents_info (widget, info);
920
921   gtk_selection_convert (widget, clipboard->selection, target,
922                          clipboard_get_timestamp (clipboard));
923 }
924
925 static void 
926 request_text_received_func (GtkClipboard     *clipboard,
927                             GtkSelectionData *selection_data,
928                             gpointer          data)
929 {
930   RequestTextInfo *info = data;
931   gchar *result = NULL;
932
933   result = (gchar *) gtk_selection_data_get_text (selection_data);
934
935   if (!result)
936     {
937       /* If we asked for UTF8 and didn't get it, try compound_text;
938        * if we asked for compound_text and didn't get it, try string;
939        * If we asked for anything else and didn't get it, give up.
940        */
941       GdkAtom target = gtk_selection_data_get_target (selection_data);
942
943       if (target == gdk_atom_intern_static_string ("UTF8_STRING"))
944         {
945           gtk_clipboard_request_contents (clipboard,
946                                           gdk_atom_intern_static_string ("COMPOUND_TEXT"), 
947                                           request_text_received_func, info);
948           return;
949         }
950       else if (target == gdk_atom_intern_static_string ("COMPOUND_TEXT"))
951         {
952           gtk_clipboard_request_contents (clipboard,
953                                           GDK_TARGET_STRING, 
954                                           request_text_received_func, info);
955           return;
956         }
957     }
958
959   info->callback (clipboard, result, info->user_data);
960   g_free (info);
961   g_free (result);
962 }
963
964 /**
965  * gtk_clipboard_request_text:
966  * @clipboard: a #GtkClipboard
967  * @callback: (scope async): a function to call when the text is received,
968  *     or the retrieval fails. (It will always be called one way or the other.)
969  * @user_data: user data to pass to @callback.
970  *
971  * Requests the contents of the clipboard as text. When the text is
972  * later received, it will be converted to UTF-8 if necessary, and
973  * @callback will be called.
974  *
975  * The @text parameter to @callback will contain the resulting text if
976  * the request succeeded, or %NULL if it failed. This could happen for
977  * various reasons, in particular if the clipboard was empty or if the
978  * contents of the clipboard could not be converted into text form.
979  **/
980 void 
981 gtk_clipboard_request_text (GtkClipboard                *clipboard,
982                             GtkClipboardTextReceivedFunc callback,
983                             gpointer                     user_data)
984 {
985   RequestTextInfo *info;
986   
987   g_return_if_fail (clipboard != NULL);
988   g_return_if_fail (callback != NULL);
989   
990   info = g_new (RequestTextInfo, 1);
991   info->callback = callback;
992   info->user_data = user_data;
993
994   gtk_clipboard_request_contents (clipboard, gdk_atom_intern_static_string ("UTF8_STRING"),
995                                   request_text_received_func,
996                                   info);
997 }
998
999 static void
1000 request_rich_text_received_func (GtkClipboard     *clipboard,
1001                                  GtkSelectionData *selection_data,
1002                                  gpointer          data)
1003 {
1004   RequestRichTextInfo *info = data;
1005   guint8 *result = NULL;
1006   gsize length = 0;
1007
1008   result = (guint8 *) gtk_selection_data_get_data (selection_data);
1009   length = gtk_selection_data_get_length (selection_data);
1010
1011   info->current_atom++;
1012
1013   if ((!result || length < 1) && (info->current_atom < info->n_atoms))
1014     {
1015       gtk_clipboard_request_contents (clipboard, info->atoms[info->current_atom],
1016                                       request_rich_text_received_func,
1017                                       info);
1018       return;
1019     }
1020
1021   info->callback (clipboard, gtk_selection_data_get_target (selection_data),
1022                   result, length,
1023                   info->user_data);
1024   g_free (info->atoms);
1025   g_free (info);
1026 }
1027
1028 /**
1029  * gtk_clipboard_request_rich_text:
1030  * @clipboard: a #GtkClipboard
1031  * @buffer: a #GtkTextBuffer
1032  * @callback: (scope async): a function to call when the text is received,
1033  *     or the retrieval fails. (It will always be called one way or the other.)
1034  * @user_data: user data to pass to @callback.
1035  *
1036  * Requests the contents of the clipboard as rich text. When the rich
1037  * text is later received, @callback will be called.
1038  *
1039  * The @text parameter to @callback will contain the resulting rich
1040  * text if the request succeeded, or %NULL if it failed. The @length
1041  * parameter will contain @text's length. This function can fail for
1042  * various reasons, in particular if the clipboard was empty or if the
1043  * contents of the clipboard could not be converted into rich text form.
1044  *
1045  * Since: 2.10
1046  **/
1047 void
1048 gtk_clipboard_request_rich_text (GtkClipboard                    *clipboard,
1049                                  GtkTextBuffer                   *buffer,
1050                                  GtkClipboardRichTextReceivedFunc callback,
1051                                  gpointer                         user_data)
1052 {
1053   RequestRichTextInfo *info;
1054
1055   g_return_if_fail (clipboard != NULL);
1056   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
1057   g_return_if_fail (callback != NULL);
1058
1059   info = g_new (RequestRichTextInfo, 1);
1060   info->callback = callback;
1061   info->atoms = NULL;
1062   info->n_atoms = 0;
1063   info->current_atom = 0;
1064   info->user_data = user_data;
1065
1066   info->atoms = gtk_text_buffer_get_deserialize_formats (buffer, &info->n_atoms);
1067
1068   gtk_clipboard_request_contents (clipboard, info->atoms[info->current_atom],
1069                                   request_rich_text_received_func,
1070                                   info);
1071 }
1072
1073 static void 
1074 request_image_received_func (GtkClipboard     *clipboard,
1075                              GtkSelectionData *selection_data,
1076                              gpointer          data)
1077 {
1078   RequestImageInfo *info = data;
1079   GdkPixbuf *result = NULL;
1080
1081   result = gtk_selection_data_get_pixbuf (selection_data);
1082
1083   if (!result)
1084     {
1085       /* If we asked for image/png and didn't get it, try image/jpeg;
1086        * if we asked for image/jpeg and didn't get it, try image/gif;
1087        * if we asked for image/gif and didn't get it, try image/bmp;
1088        * If we asked for anything else and didn't get it, give up.
1089        */
1090       GdkAtom target = gtk_selection_data_get_target (selection_data);
1091
1092       if (target == gdk_atom_intern_static_string ("image/png"))
1093         {
1094           gtk_clipboard_request_contents (clipboard,
1095                                           gdk_atom_intern_static_string ("image/jpeg"), 
1096                                           request_image_received_func, info);
1097           return;
1098         }
1099       else if (target == gdk_atom_intern_static_string ("image/jpeg"))
1100         {
1101           gtk_clipboard_request_contents (clipboard,
1102                                           gdk_atom_intern_static_string ("image/gif"), 
1103                                           request_image_received_func, info);
1104           return;
1105         }
1106       else if (target == gdk_atom_intern_static_string ("image/gif"))
1107         {
1108           gtk_clipboard_request_contents (clipboard,
1109                                           gdk_atom_intern_static_string ("image/bmp"), 
1110                                           request_image_received_func, info);
1111           return;
1112         }
1113     }
1114
1115   info->callback (clipboard, result, info->user_data);
1116   g_free (info);
1117
1118   if (result)
1119     g_object_unref (result);
1120 }
1121
1122 /**
1123  * gtk_clipboard_request_image:
1124  * @clipboard: a #GtkClipboard
1125  * @callback: (scope async): a function to call when the image is received,
1126  *     or the retrieval fails. (It will always be called one way or the other.)
1127  * @user_data: user data to pass to @callback.
1128  *
1129  * Requests the contents of the clipboard as image. When the image is
1130  * later received, it will be converted to a #GdkPixbuf, and
1131  * @callback will be called.
1132  *
1133  * The @pixbuf parameter to @callback will contain the resulting
1134  * #GdkPixbuf if the request succeeded, or %NULL if it failed. This
1135  * could happen for various reasons, in particular if the clipboard
1136  * was empty or if the contents of the clipboard could not be
1137  * converted into an image.
1138  *
1139  * Since: 2.6
1140  **/
1141 void 
1142 gtk_clipboard_request_image (GtkClipboard                  *clipboard,
1143                              GtkClipboardImageReceivedFunc  callback,
1144                              gpointer                       user_data)
1145 {
1146   RequestImageInfo *info;
1147   
1148   g_return_if_fail (clipboard != NULL);
1149   g_return_if_fail (callback != NULL);
1150   
1151   info = g_new (RequestImageInfo, 1);
1152   info->callback = callback;
1153   info->user_data = user_data;
1154
1155   gtk_clipboard_request_contents (clipboard, 
1156                                   gdk_atom_intern_static_string ("image/png"),
1157                                   request_image_received_func,
1158                                   info);
1159 }
1160
1161 static void 
1162 request_uris_received_func (GtkClipboard     *clipboard,
1163                             GtkSelectionData *selection_data,
1164                             gpointer          data)
1165 {
1166   RequestURIInfo *info = data;
1167   gchar **uris;
1168
1169   uris = gtk_selection_data_get_uris (selection_data);
1170   info->callback (clipboard, uris, info->user_data);
1171   g_strfreev (uris);
1172
1173   g_slice_free (RequestURIInfo, info);
1174 }
1175
1176 /**
1177  * gtk_clipboard_request_uris:
1178  * @clipboard: a #GtkClipboard
1179  * @callback: (scope async): a function to call when the URIs are received,
1180  *     or the retrieval fails. (It will always be called one way or the other.)
1181  * @user_data: user data to pass to @callback.
1182  *
1183  * Requests the contents of the clipboard as URIs. When the URIs are
1184  * later received @callback will be called.
1185  *
1186  * The @uris parameter to @callback will contain the resulting array of
1187  * URIs if the request succeeded, or %NULL if it failed. This could happen
1188  * for various reasons, in particular if the clipboard was empty or if the
1189  * contents of the clipboard could not be converted into URI form.
1190  *
1191  * Since: 2.14
1192  **/
1193 void 
1194 gtk_clipboard_request_uris (GtkClipboard                *clipboard,
1195                             GtkClipboardURIReceivedFunc  callback,
1196                             gpointer                     user_data)
1197 {
1198   RequestURIInfo *info;
1199   
1200   g_return_if_fail (clipboard != NULL);
1201   g_return_if_fail (callback != NULL);
1202   
1203   info = g_slice_new (RequestURIInfo);
1204   info->callback = callback;
1205   info->user_data = user_data;
1206
1207   gtk_clipboard_request_contents (clipboard, gdk_atom_intern_static_string ("text/uri-list"),
1208                                   request_uris_received_func,
1209                                   info);
1210 }
1211
1212 static void 
1213 request_targets_received_func (GtkClipboard     *clipboard,
1214                                GtkSelectionData *selection_data,
1215                                gpointer          data)
1216 {
1217   RequestTargetsInfo *info = data;
1218   GdkAtom *targets = NULL;
1219   gint n_targets = 0;
1220
1221   gtk_selection_data_get_targets (selection_data, &targets, &n_targets);
1222
1223   info->callback (clipboard, targets, n_targets, info->user_data);
1224
1225   g_free (info);
1226   g_free (targets);
1227 }
1228
1229 /**
1230  * gtk_clipboard_request_targets:
1231  * @clipboard: a #GtkClipboard
1232  * @callback: (scope async): a function to call when the targets are
1233  *     received, or the retrieval fails. (It will always be called
1234  *     one way or the other.)
1235  * @user_data: user data to pass to @callback.
1236  *
1237  * Requests the contents of the clipboard as list of supported targets.
1238  * When the list is later received, @callback will be called.
1239  *
1240  * The @targets parameter to @callback will contain the resulting targets if
1241  * the request succeeded, or %NULL if it failed.
1242  *
1243  * Since: 2.4
1244  **/
1245 void 
1246 gtk_clipboard_request_targets (GtkClipboard                *clipboard,
1247                                GtkClipboardTargetsReceivedFunc callback,
1248                                gpointer                     user_data)
1249 {
1250   RequestTargetsInfo *info;
1251   
1252   g_return_if_fail (clipboard != NULL);
1253   g_return_if_fail (callback != NULL);
1254
1255   /* If the display supports change notification we cache targets */
1256   if (gdk_display_supports_selection_notification (gtk_clipboard_get_display (clipboard)) &&
1257       clipboard->n_cached_targets != -1)
1258     {
1259       (* callback) (clipboard, clipboard->cached_targets, clipboard->n_cached_targets, user_data);
1260       return;
1261     }
1262   
1263   info = g_new (RequestTargetsInfo, 1);
1264   info->callback = callback;
1265   info->user_data = user_data;
1266
1267   gtk_clipboard_request_contents (clipboard, gdk_atom_intern_static_string ("TARGETS"),
1268                                   request_targets_received_func,
1269                                   info);
1270 }
1271
1272 typedef struct
1273 {
1274   GMainLoop *loop;
1275   gpointer data;
1276   GdkAtom format; /* used by rich text */
1277   gsize length; /* used by rich text */
1278 } WaitResults;
1279
1280 static void 
1281 clipboard_received_func (GtkClipboard     *clipboard,
1282                          GtkSelectionData *selection_data,
1283                          gpointer          data)
1284 {
1285   WaitResults *results = data;
1286
1287   if (gtk_selection_data_get_length (selection_data) >= 0)
1288     results->data = gtk_selection_data_copy (selection_data);
1289   
1290   g_main_loop_quit (results->loop);
1291 }
1292
1293 /**
1294  * gtk_clipboard_wait_for_contents:
1295  * @clipboard: a #GtkClipboard
1296  * @target: an atom representing the form into which the clipboard
1297  *          owner should convert the selection.
1298  * 
1299  * Requests the contents of the clipboard using the given target.
1300  * This function waits for the data to be received using the main 
1301  * loop, so events, timeouts, etc, may be dispatched during the wait.
1302  * 
1303  * Return value: a newly-allocated #GtkSelectionData object or %NULL
1304  *               if retrieving the given target failed. If non-%NULL,
1305  *               this value must be freed with gtk_selection_data_free() 
1306  *               when you are finished with it.
1307  **/
1308 GtkSelectionData *
1309 gtk_clipboard_wait_for_contents (GtkClipboard *clipboard,
1310                                  GdkAtom       target)
1311 {
1312   WaitResults results;
1313
1314   g_return_val_if_fail (clipboard != NULL, NULL);
1315   g_return_val_if_fail (target != GDK_NONE, NULL);
1316   
1317   results.data = NULL;
1318   results.loop = g_main_loop_new (NULL, TRUE);
1319
1320   gtk_clipboard_request_contents (clipboard, target, 
1321                                   clipboard_received_func,
1322                                   &results);
1323
1324   if (g_main_loop_is_running (results.loop))
1325     {
1326       GDK_THREADS_LEAVE ();
1327       g_main_loop_run (results.loop);
1328       GDK_THREADS_ENTER ();
1329     }
1330
1331   g_main_loop_unref (results.loop);
1332
1333   return results.data;
1334 }
1335
1336 static void 
1337 clipboard_text_received_func (GtkClipboard *clipboard,
1338                               const gchar  *text,
1339                               gpointer      data)
1340 {
1341   WaitResults *results = data;
1342
1343   results->data = g_strdup (text);
1344   g_main_loop_quit (results->loop);
1345 }
1346
1347 /**
1348  * gtk_clipboard_wait_for_text:
1349  * @clipboard: a #GtkClipboard
1350  * 
1351  * Requests the contents of the clipboard as text and converts
1352  * the result to UTF-8 if necessary. This function waits for
1353  * the data to be received using the main loop, so events,
1354  * timeouts, etc, may be dispatched during the wait.
1355  * 
1356  * Return value: a newly-allocated UTF-8 string which must
1357  *               be freed with g_free(), or %NULL if retrieving
1358  *               the selection data failed. (This could happen
1359  *               for various reasons, in particular if the
1360  *               clipboard was empty or if the contents of the
1361  *               clipboard could not be converted into text form.)
1362  **/
1363 gchar *
1364 gtk_clipboard_wait_for_text (GtkClipboard *clipboard)
1365 {
1366   WaitResults results;
1367
1368   g_return_val_if_fail (clipboard != NULL, NULL);
1369   
1370   results.data = NULL;
1371   results.loop = g_main_loop_new (NULL, TRUE);
1372
1373   gtk_clipboard_request_text (clipboard,
1374                               clipboard_text_received_func,
1375                               &results);
1376
1377   if (g_main_loop_is_running (results.loop))
1378     {
1379       GDK_THREADS_LEAVE ();
1380       g_main_loop_run (results.loop);
1381       GDK_THREADS_ENTER ();
1382     }
1383
1384   g_main_loop_unref (results.loop);
1385
1386   return results.data;
1387 }
1388
1389 static void
1390 clipboard_rich_text_received_func (GtkClipboard *clipboard,
1391                                    GdkAtom       format,
1392                                    const guint8 *text,
1393                                    gsize         length,
1394                                    gpointer      data)
1395 {
1396   WaitResults *results = data;
1397
1398   results->data = g_memdup (text, length);
1399   results->format = format;
1400   results->length = length;
1401   g_main_loop_quit (results->loop);
1402 }
1403
1404 /**
1405  * gtk_clipboard_wait_for_rich_text:
1406  * @clipboard: a #GtkClipboard
1407  * @buffer: a #GtkTextBuffer
1408  * @format: return location for the format of the returned data
1409  * @length: return location for the length of the returned data
1410  *
1411  * Requests the contents of the clipboard as rich text.  This function
1412  * waits for the data to be received using the main loop, so events,
1413  * timeouts, etc, may be dispatched during the wait.
1414  *
1415  * Return value: a newly-allocated binary block of data which must
1416  *               be freed with g_free(), or %NULL if retrieving
1417  *               the selection data failed. (This could happen
1418  *               for various reasons, in particular if the
1419  *               clipboard was empty or if the contents of the
1420  *               clipboard could not be converted into text form.)
1421  *
1422  * Since: 2.10
1423  **/
1424 guint8 *
1425 gtk_clipboard_wait_for_rich_text (GtkClipboard  *clipboard,
1426                                   GtkTextBuffer *buffer,
1427                                   GdkAtom       *format,
1428                                   gsize         *length)
1429 {
1430   WaitResults results;
1431
1432   g_return_val_if_fail (clipboard != NULL, NULL);
1433   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
1434   g_return_val_if_fail (format != NULL, NULL);
1435   g_return_val_if_fail (length != NULL, NULL);
1436
1437   results.data = NULL;
1438   results.loop = g_main_loop_new (NULL, TRUE);
1439
1440   gtk_clipboard_request_rich_text (clipboard, buffer,
1441                                    clipboard_rich_text_received_func,
1442                                    &results);
1443
1444   if (g_main_loop_is_running (results.loop))
1445     {
1446       GDK_THREADS_LEAVE ();
1447       g_main_loop_run (results.loop);
1448       GDK_THREADS_ENTER ();
1449     }
1450
1451   g_main_loop_unref (results.loop);
1452
1453   *format = results.format;
1454   *length = results.length;
1455
1456   return results.data;
1457 }
1458
1459 static void 
1460 clipboard_image_received_func (GtkClipboard *clipboard,
1461                                GdkPixbuf    *pixbuf,
1462                                gpointer      data)
1463 {
1464   WaitResults *results = data;
1465
1466   if (pixbuf)
1467     results->data = g_object_ref (pixbuf);
1468
1469   g_main_loop_quit (results->loop);
1470 }
1471
1472 /**
1473  * gtk_clipboard_wait_for_image:
1474  * @clipboard: a #GtkClipboard
1475  *
1476  * Requests the contents of the clipboard as image and converts
1477  * the result to a #GdkPixbuf. This function waits for
1478  * the data to be received using the main loop, so events,
1479  * timeouts, etc, may be dispatched during the wait.
1480  *
1481  * Return value: (transfer full): a newly-allocated #GdkPixbuf
1482  *     object which must be disposed with g_object_unref(), or
1483  *     %NULL if retrieving the selection data failed. (This could
1484  *     happen for various reasons, in particular if the clipboard
1485  *     was empty or if the contents of the clipboard could not be
1486  *     converted into an image.)
1487  *
1488  * Since: 2.6
1489  **/
1490 GdkPixbuf *
1491 gtk_clipboard_wait_for_image (GtkClipboard *clipboard)
1492 {
1493   WaitResults results;
1494
1495   g_return_val_if_fail (clipboard != NULL, NULL);
1496   
1497   results.data = NULL;
1498   results.loop = g_main_loop_new (NULL, TRUE);
1499
1500   gtk_clipboard_request_image (clipboard,
1501                                clipboard_image_received_func,
1502                                &results);
1503
1504   if (g_main_loop_is_running (results.loop))
1505     {
1506       GDK_THREADS_LEAVE ();
1507       g_main_loop_run (results.loop);
1508       GDK_THREADS_ENTER ();
1509     }
1510
1511   g_main_loop_unref (results.loop);
1512
1513   return results.data;
1514 }
1515
1516 static void 
1517 clipboard_uris_received_func (GtkClipboard *clipboard,
1518                               gchar       **uris,
1519                               gpointer      data)
1520 {
1521   WaitResults *results = data;
1522
1523   results->data = g_strdupv (uris);
1524   g_main_loop_quit (results->loop);
1525 }
1526
1527 /**
1528  * gtk_clipboard_wait_for_uris:
1529  * @clipboard: a #GtkClipboard
1530  * 
1531  * Requests the contents of the clipboard as URIs. This function waits
1532  * for the data to be received using the main loop, so events,
1533  * timeouts, etc, may be dispatched during the wait.
1534  *
1535  * Return value: (array zero-terminated=1) (element-type utf8) (transfer full): a newly-allocated
1536  *               %NULL-terminated array of strings which must
1537  *               be freed with g_strfreev(), or %NULL if
1538  *               retrieving the selection data failed. (This
1539  *               could happen for various reasons, in particular
1540  *               if the clipboard was empty or if the contents of
1541  *               the clipboard could not be converted into URI form.)
1542  *
1543  * Since: 2.14
1544  **/
1545 gchar **
1546 gtk_clipboard_wait_for_uris (GtkClipboard *clipboard)
1547 {
1548   WaitResults results;
1549
1550   g_return_val_if_fail (clipboard != NULL, NULL);
1551   
1552   results.data = NULL;
1553   results.loop = g_main_loop_new (NULL, TRUE);
1554
1555   gtk_clipboard_request_uris (clipboard,
1556                               clipboard_uris_received_func,
1557                               &results);
1558
1559   if (g_main_loop_is_running (results.loop))
1560     {
1561       GDK_THREADS_LEAVE ();
1562       g_main_loop_run (results.loop);
1563       GDK_THREADS_ENTER ();
1564     }
1565
1566   g_main_loop_unref (results.loop);
1567
1568   return results.data;
1569 }
1570
1571 /**
1572  * gtk_clipboard_get_display:
1573  * @clipboard: a #GtkClipboard
1574  *
1575  * Gets the #GdkDisplay associated with @clipboard
1576  *
1577  * Return value: (transfer none): the #GdkDisplay associated with @clipboard
1578  *
1579  * Since: 2.2
1580  **/
1581 GdkDisplay *
1582 gtk_clipboard_get_display (GtkClipboard *clipboard)
1583 {
1584   g_return_val_if_fail (clipboard != NULL, NULL);
1585
1586   return clipboard->display;
1587 }
1588
1589 /**
1590  * gtk_clipboard_wait_is_text_available:
1591  * @clipboard: a #GtkClipboard
1592  * 
1593  * Test to see if there is text available to be pasted
1594  * This is done by requesting the TARGETS atom and checking
1595  * if it contains any of the supported text targets. This function 
1596  * waits for the data to be received using the main loop, so events, 
1597  * timeouts, etc, may be dispatched during the wait.
1598  *
1599  * This function is a little faster than calling
1600  * gtk_clipboard_wait_for_text() since it doesn't need to retrieve
1601  * the actual text.
1602  * 
1603  * Return value: %TRUE is there is text available, %FALSE otherwise.
1604  **/
1605 gboolean
1606 gtk_clipboard_wait_is_text_available (GtkClipboard *clipboard)
1607 {
1608   GtkSelectionData *data;
1609   gboolean result = FALSE;
1610
1611   data = gtk_clipboard_wait_for_contents (clipboard, gdk_atom_intern_static_string ("TARGETS"));
1612   if (data)
1613     {
1614       result = gtk_selection_data_targets_include_text (data);
1615       gtk_selection_data_free (data);
1616     }
1617
1618   return result;
1619 }
1620
1621 /**
1622  * gtk_clipboard_wait_is_rich_text_available:
1623  * @clipboard: a #GtkClipboard
1624  * @buffer: a #GtkTextBuffer
1625  *
1626  * Test to see if there is rich text available to be pasted
1627  * This is done by requesting the TARGETS atom and checking
1628  * if it contains any of the supported rich text targets. This function
1629  * waits for the data to be received using the main loop, so events,
1630  * timeouts, etc, may be dispatched during the wait.
1631  *
1632  * This function is a little faster than calling
1633  * gtk_clipboard_wait_for_rich_text() since it doesn't need to retrieve
1634  * the actual text.
1635  *
1636  * Return value: %TRUE is there is rich text available, %FALSE otherwise.
1637  *
1638  * Since: 2.10
1639  **/
1640 gboolean
1641 gtk_clipboard_wait_is_rich_text_available (GtkClipboard  *clipboard,
1642                                            GtkTextBuffer *buffer)
1643 {
1644   GtkSelectionData *data;
1645   gboolean result = FALSE;
1646
1647   g_return_val_if_fail (GTK_IS_CLIPBOARD (clipboard), FALSE);
1648   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
1649
1650   data = gtk_clipboard_wait_for_contents (clipboard, gdk_atom_intern_static_string ("TARGETS"));
1651   if (data)
1652     {
1653       result = gtk_selection_data_targets_include_rich_text (data, buffer);
1654       gtk_selection_data_free (data);
1655     }
1656
1657   return result;
1658 }
1659
1660 /**
1661  * gtk_clipboard_wait_is_image_available:
1662  * @clipboard: a #GtkClipboard
1663  * 
1664  * Test to see if there is an image available to be pasted
1665  * This is done by requesting the TARGETS atom and checking
1666  * if it contains any of the supported image targets. This function 
1667  * waits for the data to be received using the main loop, so events, 
1668  * timeouts, etc, may be dispatched during the wait.
1669  *
1670  * This function is a little faster than calling
1671  * gtk_clipboard_wait_for_image() since it doesn't need to retrieve
1672  * the actual image data.
1673  * 
1674  * Return value: %TRUE is there is an image available, %FALSE otherwise.
1675  *
1676  * Since: 2.6
1677  **/
1678 gboolean
1679 gtk_clipboard_wait_is_image_available (GtkClipboard *clipboard)
1680 {
1681   GtkSelectionData *data;
1682   gboolean result = FALSE;
1683
1684   data = gtk_clipboard_wait_for_contents (clipboard, 
1685                                           gdk_atom_intern_static_string ("TARGETS"));
1686   if (data)
1687     {
1688       result = gtk_selection_data_targets_include_image (data, FALSE);
1689       gtk_selection_data_free (data);
1690     }
1691
1692   return result;
1693 }
1694
1695 /**
1696  * gtk_clipboard_wait_is_uris_available:
1697  * @clipboard: a #GtkClipboard
1698  * 
1699  * Test to see if there is a list of URIs available to be pasted
1700  * This is done by requesting the TARGETS atom and checking
1701  * if it contains the URI targets. This function
1702  * waits for the data to be received using the main loop, so events, 
1703  * timeouts, etc, may be dispatched during the wait.
1704  *
1705  * This function is a little faster than calling
1706  * gtk_clipboard_wait_for_uris() since it doesn't need to retrieve
1707  * the actual URI data.
1708  * 
1709  * Return value: %TRUE is there is an URI list available, %FALSE otherwise.
1710  *
1711  * Since: 2.14
1712  **/
1713 gboolean
1714 gtk_clipboard_wait_is_uris_available (GtkClipboard *clipboard)
1715 {
1716   GtkSelectionData *data;
1717   gboolean result = FALSE;
1718
1719   data = gtk_clipboard_wait_for_contents (clipboard, 
1720                                           gdk_atom_intern_static_string ("TARGETS"));
1721   if (data)
1722     {
1723       result = gtk_selection_data_targets_include_uri (data);
1724       gtk_selection_data_free (data);
1725     }
1726
1727   return result;
1728 }
1729
1730 /**
1731  * gtk_clipboard_wait_for_targets
1732  * @clipboard: a #GtkClipboard
1733  * @targets: location to store an array of targets. The result
1734  *           stored here must be freed with g_free().
1735  * @n_targets: location to store number of items in @targets.
1736  *
1737  * Returns a list of targets that are present on the clipboard, or %NULL
1738  * if there aren't any targets available. The returned list must be 
1739  * freed with g_free().
1740  * This function waits for the data to be received using the main 
1741  * loop, so events, timeouts, etc, may be dispatched during the wait.
1742  *
1743  * Return value: %TRUE if any targets are present on the clipboard,
1744  *               otherwise %FALSE.
1745  *
1746  * Since: 2.4
1747  */
1748 gboolean
1749 gtk_clipboard_wait_for_targets (GtkClipboard  *clipboard, 
1750                                 GdkAtom      **targets,
1751                                 gint          *n_targets)
1752 {
1753   GtkSelectionData *data;
1754   gboolean result = FALSE;
1755   
1756   g_return_val_if_fail (clipboard != NULL, FALSE);
1757
1758   /* If the display supports change notification we cache targets */
1759   if (gdk_display_supports_selection_notification (gtk_clipboard_get_display (clipboard)) &&
1760       clipboard->n_cached_targets != -1)
1761     {
1762       if (n_targets)
1763         *n_targets = clipboard->n_cached_targets;
1764  
1765       if (targets)
1766         *targets = g_memdup (clipboard->cached_targets,
1767                              clipboard->n_cached_targets * sizeof (GdkAtom));
1768
1769        return TRUE;
1770     }
1771   
1772   if (n_targets)
1773     *n_targets = 0;
1774       
1775   if (targets)
1776     *targets = NULL;      
1777
1778   data = gtk_clipboard_wait_for_contents (clipboard, gdk_atom_intern_static_string ("TARGETS"));
1779
1780   if (data)
1781     {
1782       GdkAtom *tmp_targets;
1783       gint tmp_n_targets;
1784        
1785       result = gtk_selection_data_get_targets (data, &tmp_targets, &tmp_n_targets);
1786  
1787       if (gdk_display_supports_selection_notification (gtk_clipboard_get_display (clipboard)))
1788         {
1789           clipboard->n_cached_targets = tmp_n_targets;
1790           clipboard->cached_targets = g_memdup (tmp_targets,
1791                                                 tmp_n_targets * sizeof (GdkAtom));
1792         }
1793  
1794       if (n_targets)
1795         *n_targets = tmp_n_targets;
1796  
1797       if (targets)
1798         *targets = tmp_targets;
1799       else
1800         g_free (tmp_targets);
1801       
1802       gtk_selection_data_free (data);
1803     }
1804
1805   return result;
1806 }
1807
1808 static GtkClipboard *
1809 clipboard_peek (GdkDisplay *display, 
1810                 GdkAtom     selection,
1811                 gboolean    only_if_exists)
1812 {
1813   GtkClipboard *clipboard = NULL;
1814   GSList *clipboards;
1815   GSList *tmp_list;
1816
1817   if (selection == GDK_NONE)
1818     selection = GDK_SELECTION_CLIPBOARD;
1819
1820   clipboards = g_object_get_data (G_OBJECT (display), "gtk-clipboard-list");
1821
1822   tmp_list = clipboards;
1823   while (tmp_list)
1824     {
1825       clipboard = tmp_list->data;
1826       if (clipboard->selection == selection)
1827         break;
1828
1829       tmp_list = tmp_list->next;
1830     }
1831
1832   if (!tmp_list && !only_if_exists)
1833     {
1834       clipboard = g_object_new (GTK_TYPE_CLIPBOARD, NULL);
1835       clipboard->selection = selection;
1836       clipboard->display = display;
1837       clipboard->n_cached_targets = -1;
1838       clipboard->n_storable_targets = -1;
1839       clipboards = g_slist_prepend (clipboards, clipboard);
1840       g_object_set_data (G_OBJECT (display), I_("gtk-clipboard-list"), clipboards);
1841       g_signal_connect (display, "closed",
1842                         G_CALLBACK (clipboard_display_closed), clipboard);
1843       gdk_display_request_selection_notification (display, selection);
1844     }
1845   
1846   return clipboard;
1847 }
1848
1849 static void
1850 gtk_clipboard_owner_change (GtkClipboard        *clipboard,
1851                             GdkEventOwnerChange *event)
1852 {
1853   if (clipboard->n_cached_targets != -1)
1854     {
1855       g_free (clipboard->cached_targets);
1856       clipboard->cached_targets = NULL;
1857       clipboard->n_cached_targets = -1;
1858     }
1859 }
1860
1861 /**
1862  * gtk_clipboard_wait_is_target_available:
1863  * @clipboard: a #GtkClipboard
1864  * @target:    A #GdkAtom indicating which target to look for.
1865  *
1866  * Checks if a clipboard supports pasting data of a given type. This
1867  * function can be used to determine if a "Paste" menu item should be
1868  * insensitive or not.
1869  *
1870  * If you want to see if there's text available on the clipboard, use
1871  * gtk_clipboard_wait_is_text_available () instead.
1872  *
1873  * Return value: %TRUE if the target is available, %FALSE otherwise.
1874  *
1875  * Since: 2.6
1876  */
1877 gboolean
1878 gtk_clipboard_wait_is_target_available (GtkClipboard *clipboard,
1879                                         GdkAtom       target)
1880 {
1881   GdkAtom *targets;
1882   gint i, n_targets;
1883   gboolean retval = FALSE;
1884     
1885   if (!gtk_clipboard_wait_for_targets (clipboard, &targets, &n_targets))
1886     return FALSE;
1887
1888   for (i = 0; i < n_targets; i++)
1889     {
1890       if (targets[i] == target)
1891         {
1892           retval = TRUE;
1893           break;
1894         }
1895     }
1896
1897   g_free (targets);
1898   
1899   return retval;
1900 }
1901
1902 /**
1903  * _gtk_clipboard_handle_event:
1904  * @event: a owner change event
1905  * 
1906  * Emits the #GtkClipboard::owner-change signal on the appropriate @clipboard.
1907  *
1908  * Since: 2.6
1909  **/
1910 void 
1911 _gtk_clipboard_handle_event (GdkEventOwnerChange *event)
1912 {
1913   GdkDisplay *display;
1914   GtkClipboard *clipboard;
1915   
1916   display = gdk_window_get_display (event->window);
1917   clipboard = clipboard_peek (display, event->selection, TRUE);
1918       
1919   if (clipboard)
1920     g_signal_emit (clipboard, 
1921                    clipboard_signals[OWNER_CHANGE], 0, event, NULL);
1922 }
1923
1924 static gboolean
1925 gtk_clipboard_store_timeout (GtkClipboard *clipboard)
1926 {
1927   g_main_loop_quit (clipboard->store_loop);
1928   
1929   return FALSE;
1930 }
1931
1932 /**
1933  * gtk_clipboard_set_can_store:
1934  * @clipboard: a #GtkClipboard
1935  * @targets: (allow-none): array containing information about which forms 
1936  *           should be stored or %NULL to indicate that all forms should 
1937  *           be stored.
1938  * @n_targets: number of elements in @targets
1939  *
1940  * Hints that the clipboard data should be stored somewhere when the
1941  * application exits or when gtk_clipboard_store () is called.
1942  *
1943  * This value is reset when the clipboard owner changes.
1944  * Where the clipboard data is stored is platform dependent,
1945  * see gdk_display_store_clipboard () for more information.
1946  * 
1947  * Since: 2.6
1948  */
1949 void
1950 gtk_clipboard_set_can_store (GtkClipboard         *clipboard,
1951                              const GtkTargetEntry *targets,
1952                              gint                  n_targets)
1953 {
1954   GtkWidget *clipboard_widget;
1955   int i;
1956   static const GtkTargetEntry save_targets[] = {
1957     { "SAVE_TARGETS", 0, TARGET_SAVE_TARGETS }
1958   };
1959   
1960   g_return_if_fail (GTK_IS_CLIPBOARD (clipboard));
1961   g_return_if_fail (n_targets >= 0);
1962
1963   if (clipboard->selection != GDK_SELECTION_CLIPBOARD)
1964     return;
1965   
1966   g_free (clipboard->storable_targets);
1967   
1968   clipboard_widget = get_clipboard_widget (clipboard->display);
1969
1970   /* n_storable_targets being -1 means that
1971    * gtk_clipboard_set_can_store hasn't been called since the
1972    * clipboard owner changed. We only want to add SAVE_TARGETS and 
1973    * ref the owner once , so we do that here
1974    */  
1975   if (clipboard->n_storable_targets == -1)
1976     {
1977       gtk_selection_add_targets (clipboard_widget, clipboard->selection,
1978                                  save_targets, 1);
1979
1980       /* Ref the owner so it won't go away */
1981       if (clipboard->have_owner)
1982         g_object_ref (clipboard->user_data);
1983     }
1984   
1985   clipboard->n_storable_targets = n_targets;
1986   clipboard->storable_targets = g_new (GdkAtom, n_targets);
1987   for (i = 0; i < n_targets; i++)
1988     clipboard->storable_targets[i] = gdk_atom_intern (targets[i].target, FALSE);
1989 }
1990
1991 static gboolean
1992 gtk_clipboard_selection_notify (GtkWidget         *widget,
1993                                 GdkEventSelection *event,
1994                                 GtkClipboard      *clipboard)
1995 {
1996   if (event->selection == gdk_atom_intern_static_string ("CLIPBOARD_MANAGER") &&
1997       clipboard->storing_selection)
1998     g_main_loop_quit (clipboard->store_loop);
1999
2000   return FALSE;
2001 }
2002
2003 /**
2004  * gtk_clipboard_store:
2005  * @clipboard: a #GtkClipboard
2006  *
2007  * Stores the current clipboard data somewhere so that it will stay
2008  * around after the application has quit.
2009  *
2010  * Since: 2.6
2011  */
2012 void
2013 gtk_clipboard_store (GtkClipboard *clipboard)
2014 {
2015   GtkWidget *clipboard_widget;
2016
2017   g_return_if_fail (GTK_IS_CLIPBOARD (clipboard));
2018
2019   if (clipboard->n_storable_targets < 0)
2020     return;
2021   
2022   if (!gdk_display_supports_clipboard_persistence (clipboard->display))
2023     return;
2024
2025   g_object_ref (clipboard);
2026
2027   clipboard_widget = get_clipboard_widget (clipboard->display);
2028   clipboard->notify_signal_id = g_signal_connect (clipboard_widget,
2029                                                   "selection-notify-event",
2030                                                   G_CALLBACK (gtk_clipboard_selection_notify),
2031                                                   clipboard);
2032
2033   gdk_display_store_clipboard (clipboard->display,
2034                                gtk_widget_get_window (clipboard_widget),
2035                                clipboard_get_timestamp (clipboard),
2036                                clipboard->storable_targets,
2037                                clipboard->n_storable_targets);
2038
2039   clipboard->storing_selection = TRUE;
2040
2041   clipboard->store_loop = g_main_loop_new (NULL, TRUE);
2042   clipboard->store_timeout = g_timeout_add_seconds (10, (GSourceFunc) gtk_clipboard_store_timeout, clipboard);
2043
2044   if (g_main_loop_is_running (clipboard->store_loop))
2045     {
2046       GDK_THREADS_LEAVE ();
2047       g_main_loop_run (clipboard->store_loop);
2048       GDK_THREADS_ENTER ();
2049     }
2050   
2051   g_main_loop_unref (clipboard->store_loop);
2052   clipboard->store_loop = NULL;
2053   
2054   g_source_remove (clipboard->store_timeout);
2055   clipboard->store_timeout = 0;
2056   g_signal_handler_disconnect (clipboard_widget, clipboard->notify_signal_id);
2057   clipboard->notify_signal_id = 0;
2058   
2059   clipboard->storing_selection = FALSE;
2060
2061   g_object_unref (clipboard);
2062 }
2063
2064 /* Stores all clipboard selections on all displays, called from
2065  * gtk_main_quit ().
2066  */
2067 void
2068 _gtk_clipboard_store_all (void)
2069 {
2070   GtkClipboard *clipboard;
2071   GSList *displays, *list;
2072   
2073   displays = gdk_display_manager_list_displays (gdk_display_manager_get ());
2074
2075   list = displays;
2076   while (list)
2077     {
2078       GdkDisplay *display = list->data;
2079
2080       clipboard = clipboard_peek (display, GDK_SELECTION_CLIPBOARD, TRUE);
2081
2082       if (clipboard)
2083         gtk_clipboard_store (clipboard);
2084       
2085       list = list->next;
2086     }
2087   g_slist_free (displays);
2088   
2089 }