]> Pileus Git - ~andy/gtk/blob - gtk/gtkclipboard.c
e918495ffc7a52e7a2dba1ad2f06e6b6f5eda537
[~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: (type Gdk.EventOwnerChange): 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 (!gdk_display_is_closed (display), 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: (skip)
569  * @clipboard: a #GtkClipboard
570  * @targets: (array length=n_targets): array containing information
571  *     about the available forms for the 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: (skip)
606  * @clipboard: a #GtkClipboard
607  * @targets: (array length=n_targets): array containing information
608  *     about the available forms for 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: (out): 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: (array length=length) (transfer full): a
1416  *               newly-allocated binary block of data which must be
1417  *               freed with g_free(), or %NULL if retrieving the
1418  *               selection data failed. (This could happen for various
1419  *               reasons, in particular if the clipboard was empty or
1420  *               if the contents of the clipboard could not be
1421  *               converted into text form.)
1422  *
1423  * Since: 2.10
1424  **/
1425 guint8 *
1426 gtk_clipboard_wait_for_rich_text (GtkClipboard  *clipboard,
1427                                   GtkTextBuffer *buffer,
1428                                   GdkAtom       *format,
1429                                   gsize         *length)
1430 {
1431   WaitResults results;
1432
1433   g_return_val_if_fail (clipboard != NULL, NULL);
1434   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
1435   g_return_val_if_fail (format != NULL, NULL);
1436   g_return_val_if_fail (length != NULL, NULL);
1437
1438   results.data = NULL;
1439   results.loop = g_main_loop_new (NULL, TRUE);
1440
1441   gtk_clipboard_request_rich_text (clipboard, buffer,
1442                                    clipboard_rich_text_received_func,
1443                                    &results);
1444
1445   if (g_main_loop_is_running (results.loop))
1446     {
1447       GDK_THREADS_LEAVE ();
1448       g_main_loop_run (results.loop);
1449       GDK_THREADS_ENTER ();
1450     }
1451
1452   g_main_loop_unref (results.loop);
1453
1454   *format = results.format;
1455   *length = results.length;
1456
1457   return results.data;
1458 }
1459
1460 static void 
1461 clipboard_image_received_func (GtkClipboard *clipboard,
1462                                GdkPixbuf    *pixbuf,
1463                                gpointer      data)
1464 {
1465   WaitResults *results = data;
1466
1467   if (pixbuf)
1468     results->data = g_object_ref (pixbuf);
1469
1470   g_main_loop_quit (results->loop);
1471 }
1472
1473 /**
1474  * gtk_clipboard_wait_for_image:
1475  * @clipboard: a #GtkClipboard
1476  *
1477  * Requests the contents of the clipboard as image and converts
1478  * the result to a #GdkPixbuf. This function waits for
1479  * the data to be received using the main loop, so events,
1480  * timeouts, etc, may be dispatched during the wait.
1481  *
1482  * Return value: (transfer full): a newly-allocated #GdkPixbuf
1483  *     object which must be disposed with g_object_unref(), or
1484  *     %NULL if retrieving the selection data failed. (This could
1485  *     happen for various reasons, in particular if the clipboard
1486  *     was empty or if the contents of the clipboard could not be
1487  *     converted into an image.)
1488  *
1489  * Since: 2.6
1490  **/
1491 GdkPixbuf *
1492 gtk_clipboard_wait_for_image (GtkClipboard *clipboard)
1493 {
1494   WaitResults results;
1495
1496   g_return_val_if_fail (clipboard != NULL, NULL);
1497   
1498   results.data = NULL;
1499   results.loop = g_main_loop_new (NULL, TRUE);
1500
1501   gtk_clipboard_request_image (clipboard,
1502                                clipboard_image_received_func,
1503                                &results);
1504
1505   if (g_main_loop_is_running (results.loop))
1506     {
1507       GDK_THREADS_LEAVE ();
1508       g_main_loop_run (results.loop);
1509       GDK_THREADS_ENTER ();
1510     }
1511
1512   g_main_loop_unref (results.loop);
1513
1514   return results.data;
1515 }
1516
1517 static void 
1518 clipboard_uris_received_func (GtkClipboard *clipboard,
1519                               gchar       **uris,
1520                               gpointer      data)
1521 {
1522   WaitResults *results = data;
1523
1524   results->data = g_strdupv (uris);
1525   g_main_loop_quit (results->loop);
1526 }
1527
1528 /**
1529  * gtk_clipboard_wait_for_uris:
1530  * @clipboard: a #GtkClipboard
1531  * 
1532  * Requests the contents of the clipboard as URIs. This function waits
1533  * for the data to be received using the main loop, so events,
1534  * timeouts, etc, may be dispatched during the wait.
1535  *
1536  * Return value: (array zero-terminated=1) (element-type utf8) (transfer full): a newly-allocated
1537  *               %NULL-terminated array of strings which must
1538  *               be freed with g_strfreev(), or %NULL if
1539  *               retrieving the selection data failed. (This
1540  *               could happen for various reasons, in particular
1541  *               if the clipboard was empty or if the contents of
1542  *               the clipboard could not be converted into URI form.)
1543  *
1544  * Since: 2.14
1545  **/
1546 gchar **
1547 gtk_clipboard_wait_for_uris (GtkClipboard *clipboard)
1548 {
1549   WaitResults results;
1550
1551   g_return_val_if_fail (clipboard != NULL, NULL);
1552   
1553   results.data = NULL;
1554   results.loop = g_main_loop_new (NULL, TRUE);
1555
1556   gtk_clipboard_request_uris (clipboard,
1557                               clipboard_uris_received_func,
1558                               &results);
1559
1560   if (g_main_loop_is_running (results.loop))
1561     {
1562       GDK_THREADS_LEAVE ();
1563       g_main_loop_run (results.loop);
1564       GDK_THREADS_ENTER ();
1565     }
1566
1567   g_main_loop_unref (results.loop);
1568
1569   return results.data;
1570 }
1571
1572 /**
1573  * gtk_clipboard_get_display:
1574  * @clipboard: a #GtkClipboard
1575  *
1576  * Gets the #GdkDisplay associated with @clipboard
1577  *
1578  * Return value: (transfer none): the #GdkDisplay associated with @clipboard
1579  *
1580  * Since: 2.2
1581  **/
1582 GdkDisplay *
1583 gtk_clipboard_get_display (GtkClipboard *clipboard)
1584 {
1585   g_return_val_if_fail (clipboard != NULL, NULL);
1586
1587   return clipboard->display;
1588 }
1589
1590 /**
1591  * gtk_clipboard_wait_is_text_available:
1592  * @clipboard: a #GtkClipboard
1593  * 
1594  * Test to see if there is text available to be pasted
1595  * This is done by requesting the TARGETS atom and checking
1596  * if it contains any of the supported text targets. This function 
1597  * waits for the data to be received using the main loop, so events, 
1598  * timeouts, etc, may be dispatched during the wait.
1599  *
1600  * This function is a little faster than calling
1601  * gtk_clipboard_wait_for_text() since it doesn't need to retrieve
1602  * the actual text.
1603  * 
1604  * Return value: %TRUE is there is text available, %FALSE otherwise.
1605  **/
1606 gboolean
1607 gtk_clipboard_wait_is_text_available (GtkClipboard *clipboard)
1608 {
1609   GtkSelectionData *data;
1610   gboolean result = FALSE;
1611
1612   data = gtk_clipboard_wait_for_contents (clipboard, gdk_atom_intern_static_string ("TARGETS"));
1613   if (data)
1614     {
1615       result = gtk_selection_data_targets_include_text (data);
1616       gtk_selection_data_free (data);
1617     }
1618
1619   return result;
1620 }
1621
1622 /**
1623  * gtk_clipboard_wait_is_rich_text_available:
1624  * @clipboard: a #GtkClipboard
1625  * @buffer: a #GtkTextBuffer
1626  *
1627  * Test to see if there is rich text available to be pasted
1628  * This is done by requesting the TARGETS atom and checking
1629  * if it contains any of the supported rich text targets. This function
1630  * waits for the data to be received using the main loop, so events,
1631  * timeouts, etc, may be dispatched during the wait.
1632  *
1633  * This function is a little faster than calling
1634  * gtk_clipboard_wait_for_rich_text() since it doesn't need to retrieve
1635  * the actual text.
1636  *
1637  * Return value: %TRUE is there is rich text available, %FALSE otherwise.
1638  *
1639  * Since: 2.10
1640  **/
1641 gboolean
1642 gtk_clipboard_wait_is_rich_text_available (GtkClipboard  *clipboard,
1643                                            GtkTextBuffer *buffer)
1644 {
1645   GtkSelectionData *data;
1646   gboolean result = FALSE;
1647
1648   g_return_val_if_fail (GTK_IS_CLIPBOARD (clipboard), FALSE);
1649   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
1650
1651   data = gtk_clipboard_wait_for_contents (clipboard, gdk_atom_intern_static_string ("TARGETS"));
1652   if (data)
1653     {
1654       result = gtk_selection_data_targets_include_rich_text (data, buffer);
1655       gtk_selection_data_free (data);
1656     }
1657
1658   return result;
1659 }
1660
1661 /**
1662  * gtk_clipboard_wait_is_image_available:
1663  * @clipboard: a #GtkClipboard
1664  * 
1665  * Test to see if there is an image available to be pasted
1666  * This is done by requesting the TARGETS atom and checking
1667  * if it contains any of the supported image targets. This function 
1668  * waits for the data to be received using the main loop, so events, 
1669  * timeouts, etc, may be dispatched during the wait.
1670  *
1671  * This function is a little faster than calling
1672  * gtk_clipboard_wait_for_image() since it doesn't need to retrieve
1673  * the actual image data.
1674  * 
1675  * Return value: %TRUE is there is an image available, %FALSE otherwise.
1676  *
1677  * Since: 2.6
1678  **/
1679 gboolean
1680 gtk_clipboard_wait_is_image_available (GtkClipboard *clipboard)
1681 {
1682   GtkSelectionData *data;
1683   gboolean result = FALSE;
1684
1685   data = gtk_clipboard_wait_for_contents (clipboard, 
1686                                           gdk_atom_intern_static_string ("TARGETS"));
1687   if (data)
1688     {
1689       result = gtk_selection_data_targets_include_image (data, FALSE);
1690       gtk_selection_data_free (data);
1691     }
1692
1693   return result;
1694 }
1695
1696 /**
1697  * gtk_clipboard_wait_is_uris_available:
1698  * @clipboard: a #GtkClipboard
1699  * 
1700  * Test to see if there is a list of URIs available to be pasted
1701  * This is done by requesting the TARGETS atom and checking
1702  * if it contains the URI targets. This function
1703  * waits for the data to be received using the main loop, so events, 
1704  * timeouts, etc, may be dispatched during the wait.
1705  *
1706  * This function is a little faster than calling
1707  * gtk_clipboard_wait_for_uris() since it doesn't need to retrieve
1708  * the actual URI data.
1709  * 
1710  * Return value: %TRUE is there is an URI list available, %FALSE otherwise.
1711  *
1712  * Since: 2.14
1713  **/
1714 gboolean
1715 gtk_clipboard_wait_is_uris_available (GtkClipboard *clipboard)
1716 {
1717   GtkSelectionData *data;
1718   gboolean result = FALSE;
1719
1720   data = gtk_clipboard_wait_for_contents (clipboard, 
1721                                           gdk_atom_intern_static_string ("TARGETS"));
1722   if (data)
1723     {
1724       result = gtk_selection_data_targets_include_uri (data);
1725       gtk_selection_data_free (data);
1726     }
1727
1728   return result;
1729 }
1730
1731 /**
1732  * gtk_clipboard_wait_for_targets
1733  * @clipboard: a #GtkClipboard
1734  * @targets: (out) (array length=n_targets) (transfer container): location
1735  *           to store an array of targets. The result stored here must
1736  *           be freed with g_free().
1737  * @n_targets: location to store number of items in @targets.
1738  *
1739  * Returns a list of targets that are present on the clipboard, or %NULL
1740  * if there aren't any targets available. The returned list must be 
1741  * freed with g_free().
1742  * This function waits for the data to be received using the main 
1743  * loop, so events, timeouts, etc, may be dispatched during the wait.
1744  *
1745  * Return value: %TRUE if any targets are present on the clipboard,
1746  *               otherwise %FALSE.
1747  *
1748  * Since: 2.4
1749  */
1750 gboolean
1751 gtk_clipboard_wait_for_targets (GtkClipboard  *clipboard, 
1752                                 GdkAtom      **targets,
1753                                 gint          *n_targets)
1754 {
1755   GtkSelectionData *data;
1756   gboolean result = FALSE;
1757   
1758   g_return_val_if_fail (clipboard != NULL, FALSE);
1759
1760   /* If the display supports change notification we cache targets */
1761   if (gdk_display_supports_selection_notification (gtk_clipboard_get_display (clipboard)) &&
1762       clipboard->n_cached_targets != -1)
1763     {
1764       if (n_targets)
1765         *n_targets = clipboard->n_cached_targets;
1766  
1767       if (targets)
1768         *targets = g_memdup (clipboard->cached_targets,
1769                              clipboard->n_cached_targets * sizeof (GdkAtom));
1770
1771        return TRUE;
1772     }
1773   
1774   if (n_targets)
1775     *n_targets = 0;
1776       
1777   if (targets)
1778     *targets = NULL;      
1779
1780   data = gtk_clipboard_wait_for_contents (clipboard, gdk_atom_intern_static_string ("TARGETS"));
1781
1782   if (data)
1783     {
1784       GdkAtom *tmp_targets;
1785       gint tmp_n_targets;
1786        
1787       result = gtk_selection_data_get_targets (data, &tmp_targets, &tmp_n_targets);
1788  
1789       if (gdk_display_supports_selection_notification (gtk_clipboard_get_display (clipboard)))
1790         {
1791           clipboard->n_cached_targets = tmp_n_targets;
1792           clipboard->cached_targets = g_memdup (tmp_targets,
1793                                                 tmp_n_targets * sizeof (GdkAtom));
1794         }
1795  
1796       if (n_targets)
1797         *n_targets = tmp_n_targets;
1798  
1799       if (targets)
1800         *targets = tmp_targets;
1801       else
1802         g_free (tmp_targets);
1803       
1804       gtk_selection_data_free (data);
1805     }
1806
1807   return result;
1808 }
1809
1810 static GtkClipboard *
1811 clipboard_peek (GdkDisplay *display, 
1812                 GdkAtom     selection,
1813                 gboolean    only_if_exists)
1814 {
1815   GtkClipboard *clipboard = NULL;
1816   GSList *clipboards;
1817   GSList *tmp_list;
1818
1819   if (selection == GDK_NONE)
1820     selection = GDK_SELECTION_CLIPBOARD;
1821
1822   clipboards = g_object_get_data (G_OBJECT (display), "gtk-clipboard-list");
1823
1824   tmp_list = clipboards;
1825   while (tmp_list)
1826     {
1827       clipboard = tmp_list->data;
1828       if (clipboard->selection == selection)
1829         break;
1830
1831       tmp_list = tmp_list->next;
1832     }
1833
1834   if (!tmp_list && !only_if_exists)
1835     {
1836       clipboard = g_object_new (GTK_TYPE_CLIPBOARD, NULL);
1837       clipboard->selection = selection;
1838       clipboard->display = display;
1839       clipboard->n_cached_targets = -1;
1840       clipboard->n_storable_targets = -1;
1841       clipboards = g_slist_prepend (clipboards, clipboard);
1842       g_object_set_data (G_OBJECT (display), I_("gtk-clipboard-list"), clipboards);
1843       g_signal_connect (display, "closed",
1844                         G_CALLBACK (clipboard_display_closed), clipboard);
1845       gdk_display_request_selection_notification (display, selection);
1846     }
1847   
1848   return clipboard;
1849 }
1850
1851 static void
1852 gtk_clipboard_owner_change (GtkClipboard        *clipboard,
1853                             GdkEventOwnerChange *event)
1854 {
1855   if (clipboard->n_cached_targets != -1)
1856     {
1857       g_free (clipboard->cached_targets);
1858       clipboard->cached_targets = NULL;
1859       clipboard->n_cached_targets = -1;
1860     }
1861 }
1862
1863 /**
1864  * gtk_clipboard_wait_is_target_available:
1865  * @clipboard: a #GtkClipboard
1866  * @target:    A #GdkAtom indicating which target to look for.
1867  *
1868  * Checks if a clipboard supports pasting data of a given type. This
1869  * function can be used to determine if a "Paste" menu item should be
1870  * insensitive or not.
1871  *
1872  * If you want to see if there's text available on the clipboard, use
1873  * gtk_clipboard_wait_is_text_available () instead.
1874  *
1875  * Return value: %TRUE if the target is available, %FALSE otherwise.
1876  *
1877  * Since: 2.6
1878  */
1879 gboolean
1880 gtk_clipboard_wait_is_target_available (GtkClipboard *clipboard,
1881                                         GdkAtom       target)
1882 {
1883   GdkAtom *targets;
1884   gint i, n_targets;
1885   gboolean retval = FALSE;
1886     
1887   if (!gtk_clipboard_wait_for_targets (clipboard, &targets, &n_targets))
1888     return FALSE;
1889
1890   for (i = 0; i < n_targets; i++)
1891     {
1892       if (targets[i] == target)
1893         {
1894           retval = TRUE;
1895           break;
1896         }
1897     }
1898
1899   g_free (targets);
1900   
1901   return retval;
1902 }
1903
1904 /**
1905  * _gtk_clipboard_handle_event:
1906  * @event: a owner change event
1907  * 
1908  * Emits the #GtkClipboard::owner-change signal on the appropriate @clipboard.
1909  *
1910  * Since: 2.6
1911  **/
1912 void 
1913 _gtk_clipboard_handle_event (GdkEventOwnerChange *event)
1914 {
1915   GdkDisplay *display;
1916   GtkClipboard *clipboard;
1917   
1918   display = gdk_window_get_display (event->window);
1919   clipboard = clipboard_peek (display, event->selection, TRUE);
1920       
1921   if (clipboard)
1922     g_signal_emit (clipboard, 
1923                    clipboard_signals[OWNER_CHANGE], 0, event, NULL);
1924 }
1925
1926 static gboolean
1927 gtk_clipboard_store_timeout (GtkClipboard *clipboard)
1928 {
1929   g_main_loop_quit (clipboard->store_loop);
1930   
1931   return FALSE;
1932 }
1933
1934 /**
1935  * gtk_clipboard_set_can_store:
1936  * @clipboard: a #GtkClipboard
1937  * @targets: (allow-none) (array length=n_targets): array containing
1938  *           information about which forms should be stored or %NULL
1939  *           to indicate that all forms should be stored.
1940  * @n_targets: number of elements in @targets
1941  *
1942  * Hints that the clipboard data should be stored somewhere when the
1943  * application exits or when gtk_clipboard_store () is called.
1944  *
1945  * This value is reset when the clipboard owner changes.
1946  * Where the clipboard data is stored is platform dependent,
1947  * see gdk_display_store_clipboard () for more information.
1948  * 
1949  * Since: 2.6
1950  */
1951 void
1952 gtk_clipboard_set_can_store (GtkClipboard         *clipboard,
1953                              const GtkTargetEntry *targets,
1954                              gint                  n_targets)
1955 {
1956   GtkWidget *clipboard_widget;
1957   int i;
1958   static const GtkTargetEntry save_targets[] = {
1959     { "SAVE_TARGETS", 0, TARGET_SAVE_TARGETS }
1960   };
1961   
1962   g_return_if_fail (GTK_IS_CLIPBOARD (clipboard));
1963   g_return_if_fail (n_targets >= 0);
1964
1965   if (clipboard->selection != GDK_SELECTION_CLIPBOARD)
1966     return;
1967   
1968   g_free (clipboard->storable_targets);
1969   
1970   clipboard_widget = get_clipboard_widget (clipboard->display);
1971
1972   /* n_storable_targets being -1 means that
1973    * gtk_clipboard_set_can_store hasn't been called since the
1974    * clipboard owner changed. We only want to add SAVE_TARGETS and 
1975    * ref the owner once , so we do that here
1976    */  
1977   if (clipboard->n_storable_targets == -1)
1978     {
1979       gtk_selection_add_targets (clipboard_widget, clipboard->selection,
1980                                  save_targets, 1);
1981
1982       /* Ref the owner so it won't go away */
1983       if (clipboard->have_owner)
1984         g_object_ref (clipboard->user_data);
1985     }
1986   
1987   clipboard->n_storable_targets = n_targets;
1988   clipboard->storable_targets = g_new (GdkAtom, n_targets);
1989   for (i = 0; i < n_targets; i++)
1990     clipboard->storable_targets[i] = gdk_atom_intern (targets[i].target, FALSE);
1991 }
1992
1993 static gboolean
1994 gtk_clipboard_selection_notify (GtkWidget         *widget,
1995                                 GdkEventSelection *event,
1996                                 GtkClipboard      *clipboard)
1997 {
1998   if (event->selection == gdk_atom_intern_static_string ("CLIPBOARD_MANAGER") &&
1999       clipboard->storing_selection)
2000     g_main_loop_quit (clipboard->store_loop);
2001
2002   return FALSE;
2003 }
2004
2005 /**
2006  * gtk_clipboard_store:
2007  * @clipboard: a #GtkClipboard
2008  *
2009  * Stores the current clipboard data somewhere so that it will stay
2010  * around after the application has quit.
2011  *
2012  * Since: 2.6
2013  */
2014 void
2015 gtk_clipboard_store (GtkClipboard *clipboard)
2016 {
2017   GtkWidget *clipboard_widget;
2018
2019   g_return_if_fail (GTK_IS_CLIPBOARD (clipboard));
2020
2021   if (clipboard->n_storable_targets < 0)
2022     return;
2023   
2024   if (!gdk_display_supports_clipboard_persistence (clipboard->display))
2025     return;
2026
2027   g_object_ref (clipboard);
2028
2029   clipboard_widget = get_clipboard_widget (clipboard->display);
2030   clipboard->notify_signal_id = g_signal_connect (clipboard_widget,
2031                                                   "selection-notify-event",
2032                                                   G_CALLBACK (gtk_clipboard_selection_notify),
2033                                                   clipboard);
2034
2035   gdk_display_store_clipboard (clipboard->display,
2036                                gtk_widget_get_window (clipboard_widget),
2037                                clipboard_get_timestamp (clipboard),
2038                                clipboard->storable_targets,
2039                                clipboard->n_storable_targets);
2040
2041   clipboard->storing_selection = TRUE;
2042
2043   clipboard->store_loop = g_main_loop_new (NULL, TRUE);
2044   clipboard->store_timeout = g_timeout_add_seconds (10, (GSourceFunc) gtk_clipboard_store_timeout, clipboard);
2045
2046   if (g_main_loop_is_running (clipboard->store_loop))
2047     {
2048       GDK_THREADS_LEAVE ();
2049       g_main_loop_run (clipboard->store_loop);
2050       GDK_THREADS_ENTER ();
2051     }
2052   
2053   g_main_loop_unref (clipboard->store_loop);
2054   clipboard->store_loop = NULL;
2055   
2056   g_source_remove (clipboard->store_timeout);
2057   clipboard->store_timeout = 0;
2058   g_signal_handler_disconnect (clipboard_widget, clipboard->notify_signal_id);
2059   clipboard->notify_signal_id = 0;
2060   
2061   clipboard->storing_selection = FALSE;
2062
2063   g_object_unref (clipboard);
2064 }
2065
2066 /* Stores all clipboard selections on all displays, called from
2067  * gtk_main_quit ().
2068  */
2069 void
2070 _gtk_clipboard_store_all (void)
2071 {
2072   GtkClipboard *clipboard;
2073   GSList *displays, *list;
2074   
2075   displays = gdk_display_manager_list_displays (gdk_display_manager_get ());
2076
2077   list = displays;
2078   while (list)
2079     {
2080       GdkDisplay *display = list->data;
2081
2082       clipboard = clipboard_peek (display, GDK_SELECTION_CLIPBOARD, TRUE);
2083
2084       if (clipboard)
2085         gtk_clipboard_store (clipboard);
2086       
2087       list = list->next;
2088     }
2089   g_slist_free (displays);
2090   
2091 }