]> Pileus Git - ~andy/gtk/blob - gdk/x11/gdkdnd-x11.c
Use G_DEFINE_TYPE.
[~andy/gtk] / gdk / x11 / gdkdnd-x11.c
1 /* GDK - The GIMP Drawing Kit
2  * Copyright (C) 1995-1999 Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GTK+ Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GTK+ at ftp://ftp.gtk.org/pub/gtk/. 
25  */
26
27 #include <config.h>
28 #include <X11/Xlib.h>
29 #include <X11/Xatom.h>
30 #include <string.h>
31
32 #include "gdk.h"          /* For gdk_flush() */
33 #include "gdkx.h"
34 #include "gdkasync.h"
35 #include "gdkdnd.h"
36 #include "gdkproperty.h"
37 #include "gdkprivate-x11.h"
38 #include "gdkinternals.h"
39 #include "gdkscreen-x11.h"
40 #include "gdkdisplay-x11.h"
41 #include "gdkalias.h"
42
43 typedef struct _GdkDragContextPrivateX11 GdkDragContextPrivateX11;
44
45 typedef enum {
46   GDK_DRAG_STATUS_DRAG,
47   GDK_DRAG_STATUS_MOTION_WAIT,
48   GDK_DRAG_STATUS_ACTION_WAIT,
49   GDK_DRAG_STATUS_DROP
50 } GtkDragStatus;
51
52 typedef struct {
53   guint32 xid;
54   gint x, y, width, height;
55   gboolean mapped;
56 } GdkCacheChild;
57
58 typedef struct {
59   GList *children;
60   GHashTable *child_hash;
61   guint old_event_mask;
62   GdkScreen *screen;
63 } GdkWindowCache;
64
65 /* Structure that holds information about a drag in progress.
66  * this is used on both source and destination sides.
67  */
68 struct _GdkDragContextPrivateX11 {
69   GdkDragContext context;
70
71   Atom motif_selection;
72   guint   ref_count;
73
74   guint16 last_x;               /* Coordinates from last event */
75   guint16 last_y;
76   GdkDragAction old_action;       /* The last action we sent to the source */
77   GdkDragAction old_actions;      /* The last actions we sent to the source */
78   GdkDragAction xdnd_actions;     /* What is currently set in XdndActionList */
79
80   Window dest_xid;              /* The last window we looked up */
81   Window drop_xid;            /* The (non-proxied) window that is receiving drops */
82   guint xdnd_targets_set : 1;   /* Whether we've already set XdndTypeList */
83   guint xdnd_actions_set : 1;   /* Whether we've already set XdndActionList */
84   guint xdnd_have_actions : 1;  /* Whether an XdndActionList was provided */
85   guint motif_targets_set : 1;  /* Whether we've already set motif initiator info */
86   guint drag_status : 4;        /* current status of drag */
87   
88   guint drop_failed : 1;        /* Whether the drop was unsuccessful */
89   guint version;                /* Xdnd protocol version */
90
91   GSList *window_caches;
92 };
93
94 #define PRIVATE_DATA(context) ((GdkDragContextPrivateX11 *) GDK_DRAG_CONTEXT (context)->windowing_data)
95
96 /* Forward declarations */
97
98 static void gdk_window_cache_destroy (GdkWindowCache *cache);
99
100 static void motif_read_target_table (GdkDisplay *display);
101
102 static GdkFilterReturn motif_dnd_filter (GdkXEvent *xev,
103                                          GdkEvent  *event,
104                                          gpointer   data);
105
106 static GdkFilterReturn xdnd_enter_filter    (GdkXEvent *xev,
107                                              GdkEvent  *event,
108                                              gpointer   data);
109 static GdkFilterReturn xdnd_leave_filter    (GdkXEvent *xev,
110                                              GdkEvent  *event,
111                                              gpointer   data);
112 static GdkFilterReturn xdnd_position_filter (GdkXEvent *xev,
113                                              GdkEvent  *event,
114                                              gpointer   data);
115 static GdkFilterReturn xdnd_status_filter   (GdkXEvent *xev,
116                                              GdkEvent  *event,
117                                              gpointer   data);
118 static GdkFilterReturn xdnd_finished_filter (GdkXEvent *xev,
119                                              GdkEvent  *event,
120                                              gpointer   data);
121 static GdkFilterReturn xdnd_drop_filter     (GdkXEvent *xev,
122                                              GdkEvent  *event,
123                                              gpointer   data);
124
125 static void   xdnd_manage_source_filter (GdkDragContext *context,
126                                          GdkWindow      *window,
127                                          gboolean        add_filter);
128
129 static void gdk_drag_context_finalize   (GObject              *object);
130
131 static GList *contexts;
132
133 const static struct {
134   const char *atom_name;
135   GdkFilterFunc func;
136 } xdnd_filters[] = {
137   { "XdndEnter",    xdnd_enter_filter },
138   { "XdndLeave",    xdnd_leave_filter },
139   { "XdndPosition", xdnd_position_filter },
140   { "XdndStatus",   xdnd_status_filter },
141   { "XdndFinished", xdnd_finished_filter },
142   { "XdndDrop",     xdnd_drop_filter },
143 };
144               
145 G_DEFINE_TYPE (GdkDragContext, gdk_drag_context, G_TYPE_OBJECT);
146
147 static void
148 gdk_drag_context_init (GdkDragContext *dragcontext)
149 {
150   GdkDragContextPrivateX11 *private;
151
152   private = G_TYPE_INSTANCE_GET_PRIVATE (dragcontext, 
153                                          GDK_TYPE_DRAG_CONTEXT, 
154                                          GdkDragContextPrivateX11);
155   
156   dragcontext->windowing_data = private;
157
158   contexts = g_list_prepend (contexts, dragcontext);
159 }
160
161 static void
162 gdk_drag_context_class_init (GdkDragContextClass *klass)
163 {
164   GObjectClass *object_class = G_OBJECT_CLASS (klass);
165
166   object_class->finalize = gdk_drag_context_finalize;
167
168   g_type_class_add_private (object_class, sizeof (GdkDragContextPrivateX11));
169 }
170
171 static void
172 gdk_drag_context_finalize (GObject *object)
173 {
174   GdkDragContext *context = GDK_DRAG_CONTEXT (object);
175   GdkDragContextPrivateX11 *private = PRIVATE_DATA (context);
176   GSList *tmp_list;
177   
178   g_list_free (context->targets);
179
180   if (context->source_window)
181     {
182       if ((context->protocol == GDK_DRAG_PROTO_XDND) &&
183           !context->is_source)
184         xdnd_manage_source_filter (context, context->source_window, FALSE);
185       
186       g_object_unref (context->source_window);
187     }
188   
189   if (context->dest_window)
190     g_object_unref (context->dest_window);
191
192   for (tmp_list = private->window_caches; tmp_list; tmp_list = tmp_list->next)
193     gdk_window_cache_destroy (tmp_list->data);
194   g_slist_free (private->window_caches);
195   
196   contexts = g_list_remove (contexts, context);
197
198   G_OBJECT_CLASS (gdk_drag_context_parent_class)->finalize (object);
199 }
200
201 /* Drag Contexts */
202
203 /**
204  * gdk_drag_context_new:
205  * 
206  * Creates a new #GdkDragContext.
207  * 
208  * Return value: the newly created #GdkDragContext.
209  **/
210 GdkDragContext *
211 gdk_drag_context_new (void)
212 {
213   return g_object_new (GDK_TYPE_DRAG_CONTEXT, NULL);
214 }
215
216 /**
217  * gdk_drag_context_ref:
218  * @context: a #GdkDragContext.
219  * 
220  * Deprecated function; use g_object_ref() instead.
221  **/
222 void            
223 gdk_drag_context_ref (GdkDragContext *context)
224 {
225   g_return_if_fail (GDK_IS_DRAG_CONTEXT (context));
226
227   g_object_ref (context);
228 }
229
230 /**
231  * gdk_drag_context_unref:
232  * @context: a #GdkDragContext.
233  * 
234  * Deprecated function; use g_object_unref() instead.
235  **/
236 void            
237 gdk_drag_context_unref (GdkDragContext *context)
238 {
239   g_return_if_fail (GDK_IS_DRAG_CONTEXT (context));
240
241   g_object_unref (context);
242 }
243
244 static GdkDragContext *
245 gdk_drag_context_find (GdkDisplay *display,
246                        gboolean    is_source,
247                        Window      source_xid,
248                        Window      dest_xid)
249 {
250   GList *tmp_list = contexts;
251   GdkDragContext *context;
252   GdkDragContextPrivateX11 *private;
253   Window context_dest_xid;
254
255   while (tmp_list)
256     {
257       context = (GdkDragContext *)tmp_list->data;
258       private = PRIVATE_DATA (context);
259
260       if ((context->source_window && gdk_drawable_get_display (context->source_window) != display) ||
261           (context->dest_window && gdk_drawable_get_display (context->dest_window) != display))
262         continue;
263
264       context_dest_xid = context->dest_window ? 
265                             (private->drop_xid ?
266                               private->drop_xid :
267                               GDK_DRAWABLE_XID (context->dest_window)) :
268                              None;
269
270       if ((!context->is_source == !is_source) &&
271           ((source_xid == None) || (context->source_window &&
272             (GDK_DRAWABLE_XID (context->source_window) == source_xid))) &&
273           ((dest_xid == None) || (context_dest_xid == dest_xid)))
274         return context;
275       
276       tmp_list = tmp_list->next;
277     }
278   
279   return NULL;
280 }
281
282 static void
283 precache_target_list (GdkDragContext *context)
284 {
285   if (context->targets)
286     {
287       GPtrArray *targets = g_ptr_array_new ();
288       GList *tmp_list;
289       int i;
290
291       for (tmp_list = context->targets; tmp_list; tmp_list = tmp_list->next)
292         g_ptr_array_add (targets, gdk_atom_name (GDK_POINTER_TO_ATOM (tmp_list->data)));
293
294       _gdk_x11_precache_atoms (GDK_WINDOW_DISPLAY (context->source_window),
295                                (const gchar **)targets->pdata,
296                                targets->len);
297
298       for (i =0; i < targets->len; i++)
299         g_free (targets->pdata[i]);
300
301       g_ptr_array_free (targets, TRUE);
302     }
303 }
304
305 /* Utility functions */
306
307 static void
308 gdk_window_cache_add (GdkWindowCache *cache,
309                       guint32 xid,
310                       gint x, gint y, gint width, gint height, 
311                       gboolean mapped)
312 {
313   GdkCacheChild *child = g_new (GdkCacheChild, 1);
314
315   child->xid = xid;
316   child->x = x;
317   child->y = y;
318   child->width = width;
319   child->height = height;
320   child->mapped = mapped;
321
322   cache->children = g_list_prepend (cache->children, child);
323   g_hash_table_insert (cache->child_hash, GUINT_TO_POINTER (xid), 
324                        cache->children);
325 }
326
327 static GdkFilterReturn
328 gdk_window_cache_filter (GdkXEvent *xev,
329                          GdkEvent  *event,
330                          gpointer   data)
331 {
332   XEvent *xevent = (XEvent *)xev;
333   GdkWindowCache *cache = data;
334
335   switch (xevent->type)
336     {
337     case CirculateNotify:
338       break;
339     case ConfigureNotify:
340       {
341         XConfigureEvent *xce = &xevent->xconfigure;
342         GList *node;
343
344         node = g_hash_table_lookup (cache->child_hash, 
345                                     GUINT_TO_POINTER (xce->window));
346         if (node) 
347           {
348             GdkCacheChild *child = node->data;
349             child->x = xce->x; 
350             child->y = xce->y;
351             child->width = xce->width; 
352             child->height = xce->height;
353             if (xce->above == None && (node->next))
354               {
355                 GList *last = g_list_last (cache->children);
356                 cache->children = g_list_remove_link (cache->children, node);
357                 last->next = node;
358                 node->next = NULL;
359                 node->prev = last;
360               }
361             else
362               {
363                 GList *above_node = g_hash_table_lookup (cache->child_hash, 
364                                                          GUINT_TO_POINTER (xce->above));
365                 if (above_node && node->next != above_node)
366                   {
367                     /* Put the window above (before in the list) above_node
368                      */
369                     cache->children = g_list_remove_link (cache->children, node);
370                     node->prev = above_node->prev;
371                     if (node->prev)
372                       node->prev->next = node;
373                     else
374                       cache->children = node;
375                     node->next = above_node;
376                     above_node->prev = node;
377                   }
378               }
379           }
380         break;
381       }
382     case CreateNotify:
383       {
384         XCreateWindowEvent *xcwe = &xevent->xcreatewindow;
385
386         if (!g_hash_table_lookup (cache->child_hash, 
387                                   GUINT_TO_POINTER (xcwe->window))) 
388           gdk_window_cache_add (cache, xcwe->window, 
389                                 xcwe->x, xcwe->y, xcwe->width, xcwe->height,
390                                 FALSE);
391         break;
392       }
393     case DestroyNotify:
394       {
395         XDestroyWindowEvent *xdwe = &xevent->xdestroywindow;
396         GList *node;
397
398         node = g_hash_table_lookup (cache->child_hash, 
399                                     GUINT_TO_POINTER (xdwe->window));
400         if (node) 
401           {
402             g_hash_table_remove (cache->child_hash,
403                                  GUINT_TO_POINTER (xdwe->window));
404             cache->children = g_list_remove_link (cache->children, node);
405             g_free (node->data);
406             g_list_free_1 (node);
407           }
408         break;
409       }
410     case MapNotify:
411       {
412         XMapEvent *xme = &xevent->xmap;
413         GList *node;
414
415         node = g_hash_table_lookup (cache->child_hash, 
416                                     GUINT_TO_POINTER (xme->window));
417         if (node) 
418           {
419             GdkCacheChild *child = node->data;
420             child->mapped = TRUE;
421           }
422         break;
423       }
424     case ReparentNotify:
425       break;
426     case UnmapNotify:
427       {
428         XMapEvent *xume = &xevent->xmap;
429         GList *node;
430
431         node = g_hash_table_lookup (cache->child_hash, 
432                                     GUINT_TO_POINTER (xume->window));
433         if (node) 
434           {
435             GdkCacheChild *child = node->data;
436             child->mapped = FALSE;
437           }
438         break;
439       }
440     default:
441       return GDK_FILTER_CONTINUE;
442     }
443   return GDK_FILTER_REMOVE;
444 }
445
446 static GdkWindowCache *
447 gdk_window_cache_new (GdkScreen *screen)
448 {
449   XWindowAttributes xwa;
450   Display *xdisplay = GDK_SCREEN_XDISPLAY (screen);
451   GdkWindow *root_window = gdk_screen_get_root_window (screen);
452   GdkChildInfoX11 *children;
453   guint nchildren, i;
454   
455   GdkWindowCache *result = g_new (GdkWindowCache, 1);
456
457   result->children = NULL;
458   result->child_hash = g_hash_table_new (g_direct_hash, NULL);
459   result->screen = screen;
460
461   XGetWindowAttributes (xdisplay, GDK_WINDOW_XWINDOW (root_window), &xwa);
462   result->old_event_mask = xwa.your_event_mask;
463   XSelectInput (xdisplay, GDK_WINDOW_XWINDOW (root_window),
464                 result->old_event_mask | SubstructureNotifyMask);
465   gdk_window_add_filter (root_window, gdk_window_cache_filter, result);
466
467   if (!_gdk_x11_get_window_child_info (gdk_screen_get_display (screen),
468                                        GDK_WINDOW_XWINDOW (root_window),
469                                        FALSE, NULL,
470                                        &children, &nchildren))
471     return result;
472
473   for (i = 0; i < nchildren ; i++)
474     {
475       gdk_window_cache_add (result, children[i].window,
476                             children[i].x, children[i].y, children[i].width, children[i].height,
477                             children[i].is_mapped);
478     }
479
480   g_free (children);
481
482   return result;
483 }
484
485 static void
486 gdk_window_cache_destroy (GdkWindowCache *cache)
487 {
488   GdkWindow *root_window = gdk_screen_get_root_window (cache->screen);
489   
490   XSelectInput (GDK_WINDOW_XDISPLAY (root_window), 
491                 GDK_WINDOW_XWINDOW (root_window),
492                 cache->old_event_mask);
493   gdk_window_remove_filter (root_window, gdk_window_cache_filter, cache);
494
495   g_list_foreach (cache->children, (GFunc)g_free, NULL);
496   g_list_free (cache->children);
497   g_hash_table_destroy (cache->child_hash);
498
499   g_free (cache);
500 }
501
502 static Window
503 get_client_window_at_coords_recurse (GdkDisplay *display,
504                                      Window      win,
505                                      gboolean    is_toplevel,
506                                      gint        x,
507                                      gint        y)
508 {
509   GdkChildInfoX11 *children;
510   unsigned int nchildren;
511   int i;
512   gboolean found_child = FALSE;
513   GdkChildInfoX11 child = { 0, };
514   gboolean has_wm_state = FALSE;
515
516   if (!_gdk_x11_get_window_child_info (display, win, TRUE,
517                                        is_toplevel? &has_wm_state : NULL,
518                                        &children, &nchildren))
519     return None;
520
521   if (has_wm_state)
522     {
523       g_free (children);
524
525       return win;
526     }
527
528   for (i = nchildren - 1; (i >= 0) && !found_child; i--)
529     {
530       GdkChildInfoX11 *cur_child = &children[i];
531        
532       if ((cur_child->is_mapped) && (cur_child->window_class == InputOutput) &&
533           (x >= cur_child->x) && (x < cur_child->x + cur_child->width) &&
534           (y >= cur_child->y) && (y < cur_child->y + cur_child->height))
535         {
536           x -= cur_child->x;
537           y -= cur_child->y;
538           child = *cur_child;
539           found_child = TRUE;
540         }
541     }
542    
543   g_free (children);
544  
545   if (found_child)
546     {
547       if (child.has_wm_state)
548         return child.window;
549       else
550         return get_client_window_at_coords_recurse (display, child.window, FALSE, x, y);
551     }
552   else
553     return None;
554 }
555
556 static Window 
557 get_client_window_at_coords (GdkWindowCache *cache,
558                              Window          ignore,
559                              gint            x_root,
560                              gint            y_root)
561 {
562   GList *tmp_list;
563   Window retval = None;
564
565   gdk_error_trap_push ();
566   
567   tmp_list = cache->children;
568
569   while (tmp_list && !retval)
570     {
571       GdkCacheChild *child = tmp_list->data;
572
573       if ((child->xid != ignore) && (child->mapped))
574         {
575           if ((x_root >= child->x) && (x_root < child->x + child->width) &&
576               (y_root >= child->y) && (y_root < child->y + child->height))
577             {
578               retval = get_client_window_at_coords_recurse (gdk_screen_get_display (cache->screen),
579                                                             child->xid, TRUE,
580                                                             x_root - child->x,
581                                                             y_root - child->y);
582               if (!retval)
583                 retval = child->xid;
584             }
585           
586         }
587       tmp_list = tmp_list->next;
588     }
589
590   gdk_error_trap_pop ();
591   
592   if (retval)
593     return retval;
594   else
595     return GDK_WINDOW_XWINDOW (gdk_screen_get_root_window (cache->screen));
596 }
597
598 /*************************************************************
599  ***************************** MOTIF *************************
600  *************************************************************/
601
602 /* values used in the message type for Motif DND */
603 enum {
604     XmTOP_LEVEL_ENTER,
605     XmTOP_LEVEL_LEAVE,
606     XmDRAG_MOTION,
607     XmDROP_SITE_ENTER,
608     XmDROP_SITE_LEAVE,
609     XmDROP_START,
610     XmDROP_FINISH,
611     XmDRAG_DROP_FINISH,
612     XmOPERATION_CHANGED
613 };
614
615 /* Values used to specify type of protocol to use */
616 enum {
617     XmDRAG_NONE,
618     XmDRAG_DROP_ONLY,
619     XmDRAG_PREFER_PREREGISTER,
620     XmDRAG_PREREGISTER,
621     XmDRAG_PREFER_DYNAMIC,
622     XmDRAG_DYNAMIC,
623     XmDRAG_PREFER_RECEIVER
624 };
625
626 /* Operation codes */
627 enum {
628   XmDROP_NOOP,
629   XmDROP_MOVE = 0x01,
630   XmDROP_COPY = 0x02,
631   XmDROP_LINK = 0x04
632 };
633
634 /* Drop site status */
635 enum {
636   XmNO_DROP_SITE = 0x01,
637   XmDROP_SITE_INVALID = 0x02,
638   XmDROP_SITE_VALID = 0x03
639 };
640
641 /* completion status */
642 enum {
643   XmDROP,
644   XmDROP_HELP,
645   XmDROP_CANCEL,
646   XmDROP_INTERRUPT
647 };
648
649 /* Byte swapping routines. The motif specification leaves it
650  * up to us to save a few bytes in the client messages
651  */
652 static gchar local_byte_order = '\0';
653
654 #ifdef G_ENABLE_DEBUG
655 static void
656 print_target_list (GList *targets)
657 {
658   while (targets)
659     {
660       gchar *name = gdk_atom_name (GDK_POINTER_TO_ATOM (targets->data));
661       g_message ("\t%s", name);
662       g_free (name);
663       targets = targets->next;
664     }
665 }
666 #endif /* G_ENABLE_DEBUG */
667
668 static void
669 init_byte_order (void)
670 {
671   guint32 myint = 0x01020304;
672   local_byte_order = (*(gchar *)&myint == 1) ? 'B' : 'l';
673 }
674
675 static guint16
676 card16_to_host (guint16 x, gchar byte_order) {
677   if (byte_order == local_byte_order)
678     return x;
679   else
680     return (x << 8) | (x >> 8);
681 }
682
683 static guint32
684 card32_to_host (guint32 x, gchar byte_order) {
685   if (byte_order == local_byte_order)
686     return x;
687   else
688     return (x << 24) | ((x & 0xff00) << 8) | ((x & 0xff0000) >> 8) | (x >> 24);
689 }
690
691 /* Motif packs together fields of varying length into the
692  * client message. We can't rely on accessing these
693  * through data.s[], data.l[], etc, because on some architectures
694  * (i.e., Alpha) these won't be valid for format == 8. 
695  */
696
697 #define MOTIF_XCLIENT_BYTE(xevent,i) \
698   (xevent)->xclient.data.b[i]
699 #define MOTIF_XCLIENT_SHORT(xevent,i) \
700   ((gint16 *)&((xevent)->xclient.data.b[0]))[i]
701 #define MOTIF_XCLIENT_LONG(xevent,i) \
702   ((gint32 *)&((xevent)->xclient.data.b[0]))[i]
703
704 #define MOTIF_UNPACK_BYTE(xevent,i) MOTIF_XCLIENT_BYTE(xevent,i)
705 #define MOTIF_UNPACK_SHORT(xevent,i) \
706   card16_to_host (MOTIF_XCLIENT_SHORT(xevent,i), MOTIF_XCLIENT_BYTE(xevent, 1))
707 #define MOTIF_UNPACK_LONG(xevent,i) \
708   card32_to_host (MOTIF_XCLIENT_LONG(xevent,i), MOTIF_XCLIENT_BYTE(xevent, 1))
709
710 /***** Dest side ***********/
711
712 /* Property placed on source windows */
713 typedef struct _MotifDragInitiatorInfo {
714   guint8 byte_order;
715   guint8 protocol_version;
716   guint16 targets_index;
717   guint32 selection_atom;
718 } MotifDragInitiatorInfo;
719
720 /* Header for target table on the drag window */
721 typedef struct _MotifTargetTableHeader {
722   guchar byte_order;
723   guchar protocol_version;
724   guint16 n_lists;
725   guint32 total_size;
726 } MotifTargetTableHeader;
727
728 /* Property placed on target windows */
729 typedef struct _MotifDragReceiverInfo {
730   guint8 byte_order;
731   guint8 protocol_version;
732   guint8 protocol_style;
733   guint8 pad;
734   guint32 proxy_window;
735   guint16 num_drop_sites;
736   guint16 padding;
737   guint32 total_size;
738 } MotifDragReceiverInfo;
739
740 /* Target table handling */
741
742 static GdkFilterReturn
743 motif_drag_window_filter (GdkXEvent *xevent,
744                           GdkEvent  *event,
745                           gpointer data)
746 {
747   XEvent *xev = (XEvent *)xevent;
748   GdkDisplay *display = GDK_WINDOW_DISPLAY (event->any.window); 
749   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (display);
750
751   switch (xev->xany.type)
752     {
753     case DestroyNotify:
754       display_x11->motif_drag_window = None;
755       display_x11->motif_drag_gdk_window = NULL;
756       break;
757     case PropertyNotify:
758       if (display_x11->motif_target_lists &&
759           (xev->xproperty.atom == gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_TARGETS")))
760         motif_read_target_table (display);
761       break;
762     }
763   return GDK_FILTER_REMOVE;
764 }
765
766 static Window
767 motif_lookup_drag_window (GdkDisplay *display,
768                           Display    *lookup_xdisplay)
769 {
770   Window retval = None;
771   gulong bytes_after, nitems;
772   Atom type;
773   gint format;
774   guchar *data;
775
776   XGetWindowProperty (lookup_xdisplay, RootWindow (lookup_xdisplay, 0),
777                       gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_WINDOW"),
778                       0, 1, FALSE,
779                       XA_WINDOW, &type, &format, &nitems, &bytes_after,
780                       &data);
781   
782   if ((format == 32) && (nitems == 1) && (bytes_after == 0))
783     {
784       retval = *(Window *)data;
785       GDK_NOTE (DND, 
786                 g_message ("Found drag window %#lx\n", GDK_DISPLAY_X11 (display)->motif_drag_window));
787     }
788
789   if (type != None)
790     XFree (data);
791
792   return retval;
793 }
794
795 /* Finds the window where global Motif drag information is stored.
796  * If it doesn't exist and 'create' is TRUE, create one.
797  */
798 static Window 
799 motif_find_drag_window (GdkDisplay *display,
800                         gboolean    create)
801 {
802   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (display);
803   
804   if (!display_x11->motif_drag_window)
805     {
806       Atom motif_drag_window_atom = gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_WINDOW");
807       display_x11->motif_drag_window = motif_lookup_drag_window (display, display_x11->xdisplay);
808       
809       if (!display_x11->motif_drag_window && create)
810         {
811           /* Create a persistant window. (Copied from LessTif) */
812           
813           Display *persistant_xdisplay;
814           XSetWindowAttributes attr;
815           persistant_xdisplay = XOpenDisplay (gdk_display_get_name (display));
816           XSetCloseDownMode (persistant_xdisplay, RetainPermanent);
817
818           XGrabServer (persistant_xdisplay);
819           
820           display_x11->motif_drag_window = motif_lookup_drag_window (display, persistant_xdisplay);
821
822           if (!display_x11->motif_drag_window)
823             {
824               attr.override_redirect = True;
825               attr.event_mask = PropertyChangeMask;
826               
827                display_x11->motif_drag_window = 
828                 XCreateWindow (persistant_xdisplay, 
829                                RootWindow (persistant_xdisplay, 0),
830                               -100, -100, 10, 10, 0, 0,
831                               InputOnly, (Visual *)CopyFromParent,
832                               (CWOverrideRedirect | CWEventMask), &attr);
833               
834               GDK_NOTE (DND,
835                         g_message ("Created drag window %#lx\n", display_x11->motif_drag_window));
836               
837               XChangeProperty (persistant_xdisplay, 
838                                RootWindow (persistant_xdisplay, 0),
839                                motif_drag_window_atom, XA_WINDOW,
840                                32, PropModeReplace,
841                                (guchar *)&motif_drag_window_atom, 1);
842
843             }
844           XUngrabServer (persistant_xdisplay);
845           XCloseDisplay (persistant_xdisplay);
846         }
847
848       /* There is a miniscule race condition here if the drag window
849        * gets destroyed exactly now.
850        */
851       if (display_x11->motif_drag_window)
852         {
853           display_x11->motif_drag_gdk_window = 
854             gdk_window_foreign_new_for_display (display, display_x11->motif_drag_window);
855           gdk_window_add_filter (display_x11->motif_drag_gdk_window,
856                                  motif_drag_window_filter,
857                                  NULL);
858         }
859     }
860
861   return display_x11->motif_drag_window;
862 }
863
864 static void 
865 motif_read_target_table (GdkDisplay *display)
866 {
867   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (display);
868   gulong bytes_after, nitems;
869   Atom type;
870   gint format;
871   gint i, j;
872   
873   Atom motif_drag_targets_atom = gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_TARGETS");
874
875   if (display_x11->motif_target_lists)
876     {
877       for (i=0; i<display_x11->motif_n_target_lists; i++)
878         g_list_free (display_x11->motif_target_lists[i]);
879       
880       g_free (display_x11->motif_target_lists);
881       display_x11->motif_target_lists = NULL;
882       display_x11->motif_n_target_lists = 0;
883     }
884
885   if (motif_find_drag_window (display, FALSE))
886     {
887       guchar *data;
888       MotifTargetTableHeader *header = NULL;
889       guchar *target_bytes = NULL;
890       guchar *p;
891       gboolean success = FALSE;
892
893       gdk_error_trap_push ();
894       XGetWindowProperty (display_x11->xdisplay, 
895                           display_x11->motif_drag_window, 
896                           motif_drag_targets_atom,
897                           0, (sizeof(MotifTargetTableHeader)+3)/4, FALSE,
898                           motif_drag_targets_atom, 
899                           &type, &format, &nitems, &bytes_after,
900                           &data);
901
902       if (gdk_error_trap_pop () || (format != 8) || (nitems < sizeof (MotifTargetTableHeader)))
903         goto error;
904
905       header = (MotifTargetTableHeader *)data;
906
907       header->n_lists = card16_to_host (header->n_lists, header->byte_order);
908       header->total_size = card32_to_host (header->total_size, header->byte_order);
909
910       gdk_error_trap_push ();
911       XGetWindowProperty (display_x11->xdisplay, 
912                           display_x11->motif_drag_window, 
913                           motif_drag_targets_atom,
914                           (sizeof(MotifTargetTableHeader)+3)/4, 
915                           (header->total_size + 3)/4 - (sizeof(MotifTargetTableHeader) + 3)/4,
916                           FALSE,
917                           motif_drag_targets_atom, &type, &format, &nitems, 
918                           &bytes_after, &target_bytes);
919       
920       if (gdk_error_trap_pop () || (format != 8) || (bytes_after != 0) || 
921           (nitems != header->total_size - sizeof(MotifTargetTableHeader)))
922           goto error;
923
924       display_x11->motif_n_target_lists = header->n_lists;
925       display_x11->motif_target_lists = g_new0 (GList *, display_x11->motif_n_target_lists);
926
927       p = target_bytes;
928       for (i=0; i<header->n_lists; i++)
929         {
930           gint n_targets;
931           guint32 *targets;
932           
933           if (p + sizeof(guint16) - target_bytes > nitems)
934             goto error;
935
936           n_targets = card16_to_host (*(gushort *)p, header->byte_order);
937
938           /* We need to make a copy of the targets, since it may
939            * be unaligned
940            */
941           targets = g_new (guint32, n_targets);
942           memcpy (targets, p + sizeof(guint16), sizeof(guint32) * n_targets);
943
944           p +=  sizeof(guint16) + n_targets * sizeof(guint32);
945           if (p - target_bytes > nitems)
946             goto error;
947
948           for (j=0; j<n_targets; j++)
949             display_x11->motif_target_lists[i] = 
950               g_list_prepend (display_x11->motif_target_lists[i],
951                               GUINT_TO_POINTER (card32_to_host (targets[j],
952                                                                 header->byte_order)));
953           g_free (targets);
954           display_x11->motif_target_lists[i] = g_list_reverse (display_x11->motif_target_lists[i]);
955         }
956
957       success = TRUE;
958       
959     error:
960       if (header)
961         XFree (header);
962       
963       if (target_bytes)
964         XFree (target_bytes);
965
966       if (!success)
967         {
968           if (display_x11->motif_target_lists)
969             {
970               g_free (display_x11->motif_target_lists);
971               display_x11->motif_target_lists = NULL;
972               display_x11->motif_n_target_lists = 0;
973             }
974           g_warning ("Error reading Motif target table\n");
975         }
976     }
977 }
978
979 static gint
980 targets_sort_func (gconstpointer a, gconstpointer b)
981 {
982   return (GPOINTER_TO_UINT (a) < GPOINTER_TO_UINT (b)) ?
983     -1 : ((GPOINTER_TO_UINT (a) > GPOINTER_TO_UINT (b)) ? 1 : 0);
984 }
985
986 /* Check if given (sorted) list is in the targets table */
987 static gint
988 motif_target_table_check (GdkDisplay *display,
989                           GList      *sorted)
990 {
991   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (display);
992   GList *tmp_list1, *tmp_list2;
993   gint i;
994
995   for (i=0; i<display_x11->motif_n_target_lists; i++)
996     {
997       tmp_list1 = display_x11->motif_target_lists[i];
998       tmp_list2 = sorted;
999       
1000       while (tmp_list1 && tmp_list2)
1001         {
1002           if (tmp_list1->data != tmp_list2->data)
1003             break;
1004
1005           tmp_list1 = tmp_list1->next;
1006           tmp_list2 = tmp_list2->next;
1007         }
1008       if (!tmp_list1 && !tmp_list2)     /* Found it */
1009         return i;
1010     }
1011
1012   return -1;
1013 }
1014
1015 static gint
1016 motif_add_to_target_table (GdkDisplay *display,
1017                            GList      *targets) /* targets is list of GdkAtom */
1018 {
1019   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (display);
1020   GList *sorted = NULL;
1021   gint index = -1;
1022   gint i;
1023   GList *tmp_list;
1024   
1025   /* make a sorted copy of the list */
1026   
1027   while (targets)
1028     {
1029       Atom xatom = gdk_x11_atom_to_xatom_for_display (display, GDK_POINTER_TO_ATOM (targets->data));
1030       sorted = g_list_insert_sorted (sorted, GUINT_TO_POINTER (xatom), targets_sort_func);
1031       targets = targets->next;
1032     }
1033
1034   /* First check if it is there already */
1035
1036   if (display_x11->motif_target_lists)
1037     index = motif_target_table_check (display, sorted);
1038
1039   /* We need to grab the server while doing this, to ensure
1040    * atomiticity. Ugh
1041    */
1042
1043   if (index < 0)
1044     {
1045       /* We need to make sure that it exists _before_ we grab the
1046        * server, since we can't open a new connection after we
1047        * grab the server. 
1048        */
1049       motif_find_drag_window (display, TRUE);
1050
1051       gdk_x11_display_grab (display);
1052       motif_read_target_table (display);
1053     
1054       /* Check again, in case it was added in the meantime */
1055       
1056       if (display_x11->motif_target_lists)
1057         index = motif_target_table_check (display, sorted);
1058
1059       if (index < 0)
1060         {
1061           guint32 total_size = 0;
1062           guchar *data;
1063           guchar *p;
1064           guint16 *p16;
1065           MotifTargetTableHeader *header;
1066           
1067           if (!display_x11->motif_target_lists)
1068             {
1069               display_x11->motif_target_lists = g_new (GList *, 1);
1070               display_x11->motif_n_target_lists = 1;
1071             }
1072           else
1073             {
1074               display_x11->motif_n_target_lists++;
1075               display_x11->motif_target_lists = g_realloc (display_x11->motif_target_lists,
1076                                                            sizeof(GList *) * display_x11->motif_n_target_lists);
1077             }
1078           display_x11->motif_target_lists[display_x11->motif_n_target_lists - 1] = sorted;
1079           sorted = NULL;
1080           index = display_x11->motif_n_target_lists - 1;
1081
1082           total_size = sizeof (MotifTargetTableHeader);
1083           for (i = 0; i < display_x11->motif_n_target_lists ; i++)
1084             total_size += sizeof(guint16) + sizeof(guint32) * g_list_length (display_x11->motif_target_lists[i]);
1085
1086           data = g_malloc (total_size);
1087
1088           header = (MotifTargetTableHeader *)data;
1089           p = data + sizeof(MotifTargetTableHeader);
1090
1091           header->byte_order = local_byte_order;
1092           header->protocol_version = 0;
1093           header->n_lists = display_x11->motif_n_target_lists;
1094           header->total_size = total_size;
1095
1096           for (i = 0; i < display_x11->motif_n_target_lists ; i++)
1097             {
1098               guint16 n_targets = g_list_length (display_x11->motif_target_lists[i]);
1099               guint32 *targets = g_new (guint32, n_targets);
1100               guint32 *p32 = targets;
1101               
1102               tmp_list = display_x11->motif_target_lists[i];
1103               while (tmp_list)
1104                 {
1105                   *p32 = GPOINTER_TO_UINT (tmp_list->data);
1106                   
1107                   tmp_list = tmp_list->next;
1108                   p32++;
1109                 }
1110
1111               p16 = (guint16 *)p;
1112               p += sizeof(guint16);
1113
1114               memcpy (p, targets, n_targets * sizeof(guint32));
1115
1116               *p16 = n_targets;
1117               p += sizeof(guint32) * n_targets;
1118               g_free (targets);
1119             }
1120
1121           XChangeProperty (display_x11->xdisplay,
1122                            display_x11->motif_drag_window,
1123                            gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_TARGETS"),
1124                            gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_TARGETS"),
1125                            8, PropModeReplace,
1126                            data, total_size);
1127         }
1128       gdk_x11_display_ungrab (display);
1129     }
1130
1131   g_list_free (sorted);
1132   return index;
1133 }
1134
1135 /* Translate flags */
1136
1137 static void
1138 motif_dnd_translate_flags (GdkDragContext *context, guint16 flags)
1139 {
1140   guint recommended_op = flags & 0x000f;
1141   guint possible_ops = (flags & 0x0f0) >> 4;
1142   
1143   switch (recommended_op)
1144     {
1145     case XmDROP_MOVE:
1146       context->suggested_action = GDK_ACTION_MOVE;
1147       break;
1148     case XmDROP_COPY:
1149       context->suggested_action = GDK_ACTION_COPY;
1150       break;
1151     case XmDROP_LINK:
1152       context->suggested_action = GDK_ACTION_LINK;
1153       break;
1154     default:
1155       context->suggested_action = GDK_ACTION_COPY;
1156       break;
1157     }
1158
1159   context->actions = 0;
1160   if (possible_ops & XmDROP_MOVE)
1161     context->actions |= GDK_ACTION_MOVE;
1162   if (possible_ops & XmDROP_COPY)
1163     context->actions |= GDK_ACTION_COPY;
1164   if (possible_ops & XmDROP_LINK)
1165     context->actions |= GDK_ACTION_LINK;
1166 }
1167
1168 static guint16
1169 motif_dnd_get_flags (GdkDragContext *context)
1170 {
1171   guint16 flags = 0;
1172   
1173   switch (context->suggested_action)
1174     {
1175     case GDK_ACTION_MOVE:
1176       flags = XmDROP_MOVE;
1177       break;
1178     case GDK_ACTION_COPY:
1179       flags = XmDROP_COPY;
1180       break;
1181     case GDK_ACTION_LINK:
1182       flags = XmDROP_LINK;
1183       break;
1184     default:
1185       flags = XmDROP_NOOP;
1186       break;
1187     }
1188   
1189   if (context->actions & GDK_ACTION_MOVE)
1190     flags |= XmDROP_MOVE << 8;
1191   if (context->actions & GDK_ACTION_COPY)
1192     flags |= XmDROP_COPY << 8;
1193   if (context->actions & GDK_ACTION_LINK)
1194     flags |= XmDROP_LINK << 8;
1195
1196   return flags;
1197 }
1198
1199 /* Source Side */
1200
1201 static void
1202 motif_set_targets (GdkDragContext *context)
1203 {
1204   GdkDragContextPrivateX11 *private = PRIVATE_DATA (context);
1205   MotifDragInitiatorInfo info;
1206   gint i;
1207   GdkDisplay *display = GDK_DRAWABLE_DISPLAY (context->source_window);
1208   
1209   info.byte_order = local_byte_order;
1210   info.protocol_version = 0;
1211   
1212   info.targets_index = motif_add_to_target_table (display, context->targets);
1213
1214   for (i=0; ; i++)
1215     {
1216       gchar buf[20];
1217       g_snprintf(buf, 20, "_GDK_SELECTION_%d", i);
1218       
1219       private->motif_selection = gdk_x11_get_xatom_by_name_for_display (display, buf);
1220       if (!XGetSelectionOwner (GDK_DISPLAY_XDISPLAY (display), private->motif_selection))
1221         break;
1222     }
1223
1224   info.selection_atom = private->motif_selection;
1225
1226   XChangeProperty (GDK_DRAWABLE_XDISPLAY (context->source_window),
1227                    GDK_DRAWABLE_XID (context->source_window),
1228                    private->motif_selection,
1229                    gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_INITIATOR_INFO"),
1230                    8, PropModeReplace,
1231                    (guchar *)&info, sizeof (info));
1232
1233   private->motif_targets_set = 1;
1234 }
1235
1236 static guint32
1237 motif_check_dest (GdkDisplay *display,
1238                   Window      win)
1239 {
1240   gboolean retval = FALSE;
1241   guchar *data;
1242   MotifDragReceiverInfo *info;
1243   Atom type = None;
1244   int format;
1245   unsigned long nitems, after;
1246   Atom motif_drag_receiver_info_atom = gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_RECEIVER_INFO");
1247
1248   gdk_error_trap_push ();
1249   XGetWindowProperty (GDK_DISPLAY_XDISPLAY (display), win, 
1250                       motif_drag_receiver_info_atom, 
1251                       0, (sizeof(*info)+3)/4, False, AnyPropertyType,
1252                       &type, &format, &nitems, &after, 
1253                       &data);
1254
1255   if (gdk_error_trap_pop() == 0)
1256     {
1257       if (type != None)
1258         {
1259           info = (MotifDragReceiverInfo *)data;
1260           
1261           if ((format == 8) && (nitems == sizeof(*info)))
1262             {
1263               if ((info->protocol_version == 0) &&
1264                   ((info->protocol_style == XmDRAG_PREFER_PREREGISTER) ||
1265                    (info->protocol_style == XmDRAG_PREFER_DYNAMIC) ||
1266                    (info->protocol_style == XmDRAG_DYNAMIC)))
1267                 retval = TRUE;
1268             }
1269           else
1270             {
1271               GDK_NOTE (DND, 
1272                         g_warning ("Invalid Motif drag receiver property on window %ld\n", win));
1273             }
1274           
1275           XFree (info);
1276         }
1277     }
1278
1279   return retval ? win : None;
1280 }
1281
1282 static void
1283 motif_send_enter (GdkDragContext  *context,
1284                   guint32          time)
1285 {
1286   GdkDragContextPrivateX11 *private = PRIVATE_DATA (context);
1287   GdkDisplay *display = GDK_DRAWABLE_DISPLAY (context->source_window);
1288   XEvent xev;
1289
1290   xev.xclient.type = ClientMessage;
1291   xev.xclient.message_type = gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_AND_DROP_MESSAGE");
1292   xev.xclient.format = 8;
1293   xev.xclient.window = GDK_DRAWABLE_XID (context->dest_window);
1294
1295   MOTIF_XCLIENT_BYTE (&xev, 0) = XmTOP_LEVEL_ENTER;
1296   MOTIF_XCLIENT_BYTE (&xev, 1) = local_byte_order;
1297   MOTIF_XCLIENT_SHORT (&xev, 1) = 0;
1298   MOTIF_XCLIENT_LONG (&xev, 1) = time;
1299   MOTIF_XCLIENT_LONG (&xev, 2) = GDK_DRAWABLE_XID (context->source_window);
1300
1301   if (!private->motif_targets_set)
1302     motif_set_targets (context);
1303
1304   MOTIF_XCLIENT_LONG (&xev, 3) = private->motif_selection;
1305   MOTIF_XCLIENT_LONG (&xev, 4) = 0;
1306
1307   if (!_gdk_send_xevent (display,
1308                          GDK_DRAWABLE_XID (context->dest_window),
1309                          FALSE, 0, &xev))
1310     GDK_NOTE (DND, 
1311               g_message ("Send event to %lx failed",
1312                          GDK_DRAWABLE_XID (context->dest_window)));
1313 }
1314
1315 static void
1316 motif_send_leave (GdkDragContext  *context,
1317                   guint32          time)
1318 {
1319   GdkDisplay *display = GDK_DRAWABLE_DISPLAY (context->source_window);
1320   XEvent xev;
1321
1322   xev.xclient.type = ClientMessage;
1323   xev.xclient.message_type = gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_AND_DROP_MESSAGE");
1324   xev.xclient.format = 8;
1325   xev.xclient.window = GDK_DRAWABLE_XID (context->dest_window);
1326
1327   MOTIF_XCLIENT_BYTE (&xev, 0) = XmTOP_LEVEL_LEAVE;
1328   MOTIF_XCLIENT_BYTE (&xev, 1) = local_byte_order;
1329   MOTIF_XCLIENT_SHORT (&xev, 1) = 0;
1330   MOTIF_XCLIENT_LONG (&xev, 1) = time;
1331   MOTIF_XCLIENT_LONG (&xev, 2) = 0;
1332   MOTIF_XCLIENT_LONG (&xev, 3) = 0;
1333   MOTIF_XCLIENT_LONG (&xev, 4) = 0;
1334
1335   if (!_gdk_send_xevent (display,
1336                          GDK_DRAWABLE_XID (context->dest_window),
1337                          FALSE, 0, &xev))
1338     GDK_NOTE (DND, 
1339               g_message ("Send event to %lx failed",
1340                          GDK_DRAWABLE_XID (context->dest_window)));
1341 }
1342
1343 static gboolean
1344 motif_send_motion (GdkDragContext  *context,
1345                     gint            x_root, 
1346                     gint            y_root,
1347                     GdkDragAction   action,
1348                     guint32         time)
1349 {
1350   GdkDragContextPrivateX11 *private = PRIVATE_DATA (context);
1351   GdkDisplay *display = GDK_DRAWABLE_DISPLAY (context->source_window);
1352   gboolean retval;
1353   XEvent xev;
1354
1355   xev.xclient.type = ClientMessage;
1356   xev.xclient.message_type = gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_AND_DROP_MESSAGE");
1357   xev.xclient.format = 8;
1358   xev.xclient.window = GDK_DRAWABLE_XID (context->dest_window);
1359
1360   MOTIF_XCLIENT_BYTE (&xev, 1) = local_byte_order;
1361   MOTIF_XCLIENT_SHORT (&xev, 1) = motif_dnd_get_flags (context);
1362   MOTIF_XCLIENT_LONG (&xev, 1) = time;
1363   MOTIF_XCLIENT_LONG (&xev, 3) = 0;
1364   MOTIF_XCLIENT_LONG (&xev, 4) = 0;
1365
1366   if ((context->suggested_action != private->old_action) ||
1367       (context->actions != private->old_actions))
1368     {
1369       MOTIF_XCLIENT_BYTE (&xev, 0) = XmOPERATION_CHANGED;
1370
1371       /* private->drag_status = GDK_DRAG_STATUS_ACTION_WAIT; */
1372       retval = TRUE;
1373     }
1374   else
1375     {
1376       MOTIF_XCLIENT_BYTE (&xev, 0) = XmDRAG_MOTION;
1377
1378       MOTIF_XCLIENT_SHORT (&xev, 4) = x_root;
1379       MOTIF_XCLIENT_SHORT (&xev, 5) = y_root;
1380       
1381       private->drag_status = GDK_DRAG_STATUS_MOTION_WAIT;
1382       retval = FALSE;
1383     }
1384
1385   if (!_gdk_send_xevent (display,
1386                          GDK_DRAWABLE_XID (context->dest_window),
1387                          FALSE, 0, &xev))
1388     GDK_NOTE (DND, 
1389               g_message ("Send event to %lx failed",
1390                          GDK_DRAWABLE_XID (context->dest_window)));
1391
1392   return retval;
1393 }
1394
1395 static void
1396 motif_send_drop (GdkDragContext *context, guint32 time)
1397 {
1398   GdkDragContextPrivateX11 *private = PRIVATE_DATA (context);
1399   GdkDisplay *display = GDK_DRAWABLE_DISPLAY (context->source_window);
1400   XEvent xev;
1401
1402   xev.xclient.type = ClientMessage;
1403   xev.xclient.message_type = gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_AND_DROP_MESSAGE");
1404   xev.xclient.format = 8;
1405   xev.xclient.window = GDK_DRAWABLE_XID (context->dest_window);
1406
1407   MOTIF_XCLIENT_BYTE (&xev, 0) = XmDROP_START;
1408   MOTIF_XCLIENT_BYTE (&xev, 1) = local_byte_order;
1409   MOTIF_XCLIENT_SHORT (&xev, 1) = motif_dnd_get_flags (context);
1410   MOTIF_XCLIENT_LONG (&xev, 1)  = time;
1411
1412   MOTIF_XCLIENT_SHORT (&xev, 4) = private->last_x;
1413   MOTIF_XCLIENT_SHORT (&xev, 5) = private->last_y;
1414
1415   MOTIF_XCLIENT_LONG (&xev, 3)  = private->motif_selection;
1416   MOTIF_XCLIENT_LONG (&xev, 4)  = GDK_DRAWABLE_XID (context->source_window);
1417
1418   if (!_gdk_send_xevent (display,
1419                          GDK_DRAWABLE_XID (context->dest_window),
1420                          FALSE, 0, &xev))
1421     GDK_NOTE (DND, 
1422               g_message ("Send event to %lx failed",
1423                          GDK_DRAWABLE_XID (context->dest_window)));
1424 }
1425
1426 /* Target Side */
1427
1428 static gboolean
1429 motif_read_initiator_info (GdkDisplay *display,
1430                            Window      source_window, 
1431                            Atom        atom,
1432                            GList     **targets,
1433                            Atom       *selection)
1434 {
1435   GList *tmp_list;
1436   Atom type;
1437   gint format;
1438   gulong nitems;
1439   gulong bytes_after;
1440   guchar *data;
1441   MotifDragInitiatorInfo *initiator_info;
1442   
1443   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (display);
1444   
1445   gdk_error_trap_push ();
1446   XGetWindowProperty (GDK_DISPLAY_XDISPLAY (display), source_window, atom,
1447                       0, sizeof(*initiator_info), FALSE,
1448                       gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_INITIATOR_INFO"),
1449                       &type, &format, &nitems, &bytes_after,
1450                       &data);
1451
1452   if (gdk_error_trap_pop () || (format != 8) || (nitems != sizeof (MotifDragInitiatorInfo)) || (bytes_after != 0))
1453     {
1454       g_warning ("Error reading initiator info\n");
1455       return FALSE;
1456     }
1457
1458   initiator_info = (MotifDragInitiatorInfo *)data;
1459
1460   motif_read_target_table (display);
1461
1462   initiator_info->targets_index = 
1463     card16_to_host (initiator_info->targets_index, initiator_info->byte_order);
1464   initiator_info->selection_atom = 
1465     card32_to_host (initiator_info->selection_atom, initiator_info->byte_order);
1466   
1467   if (initiator_info->targets_index >= display_x11->motif_n_target_lists)
1468     {
1469       g_warning ("Invalid target index in TOP_LEVEL_ENTER MESSAGE");
1470       XFree (initiator_info);
1471       return FALSE;
1472     }
1473
1474   tmp_list = g_list_last (display_x11->motif_target_lists[initiator_info->targets_index]);
1475
1476   *targets = NULL;
1477   while (tmp_list)
1478     {
1479       GdkAtom atom = gdk_x11_xatom_to_atom_for_display (display, GPOINTER_TO_UINT (tmp_list->data));
1480       *targets = g_list_prepend (*targets, GDK_ATOM_TO_POINTER (atom));
1481       tmp_list = tmp_list->prev;
1482     }
1483
1484 #ifdef G_ENABLE_DEBUG
1485   if (_gdk_debug_flags & GDK_DEBUG_DND)
1486     print_target_list (*targets);
1487 #endif /* G_ENABLE_DEBUG */
1488
1489   *selection = initiator_info->selection_atom;
1490
1491   XFree (initiator_info);
1492
1493   return TRUE;
1494 }
1495
1496 static GdkDragContext *
1497 motif_drag_context_new (GdkWindow *dest_window,
1498                         guint32    timestamp,
1499                         guint32    source_window,
1500                         guint32    atom)
1501 {
1502   GdkDragContext *new_context;
1503   GdkDragContextPrivateX11 *private;
1504   GdkDisplay *display = GDK_DRAWABLE_DISPLAY (dest_window);
1505   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (display);
1506
1507   /* FIXME, current_dest_drag really shouldn't be NULL'd
1508    * if we error below.
1509    */
1510   if (display_x11->current_dest_drag != NULL)
1511     {
1512       if (timestamp >= display_x11->current_dest_drag->start_time)
1513         {
1514           g_object_unref (display_x11->current_dest_drag);
1515           display_x11->current_dest_drag = NULL;
1516         }
1517       else
1518         return NULL;
1519     }
1520
1521   new_context = gdk_drag_context_new ();
1522   private = PRIVATE_DATA (new_context);
1523
1524   new_context->protocol = GDK_DRAG_PROTO_MOTIF;
1525   new_context->is_source = FALSE;
1526
1527   new_context->source_window = gdk_window_lookup_for_display (display, source_window);
1528   if (new_context->source_window)
1529     g_object_ref (new_context->source_window);
1530   else
1531     {
1532       new_context->source_window = gdk_window_foreign_new_for_display (display, source_window);
1533       if (!new_context->source_window)
1534         {
1535           g_object_unref (new_context);
1536           return NULL;
1537         }
1538     }
1539
1540   new_context->dest_window = dest_window;
1541   g_object_ref (dest_window);
1542   new_context->start_time = timestamp;
1543
1544   if (!motif_read_initiator_info (GDK_WINDOW_DISPLAY (dest_window),
1545                                   source_window,
1546                                   atom,
1547                                   &new_context->targets,
1548                                   &private->motif_selection))
1549     {
1550       g_object_unref (new_context);
1551       return NULL;
1552     }
1553
1554   return new_context;
1555 }
1556
1557 /*
1558  * The MOTIF drag protocol has no real provisions for distinguishing
1559  * multiple simultaneous drops. If the sources grab the pointer
1560  * when doing drags, that shouldn't happen, in any case. If it
1561  * does, we can't do much except hope for the best.
1562  */
1563
1564 static GdkFilterReturn
1565 motif_top_level_enter (GdkEvent *event,
1566                        guint16   flags, 
1567                        guint32   timestamp, 
1568                        guint32   source_window, 
1569                        guint32   atom)
1570 {
1571   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (GDK_DRAWABLE_DISPLAY (event->any.window));
1572   GdkDragContext *new_context;
1573
1574   GDK_NOTE(DND, g_message ("Motif DND top level enter: flags: %#4x time: %d source_widow: %#4x atom: %d",
1575                            flags, timestamp, source_window, atom));
1576
1577   new_context = motif_drag_context_new (event->any.window, timestamp, source_window, atom);
1578   if (!new_context)
1579     return GDK_FILTER_REMOVE;
1580
1581   event->dnd.type = GDK_DRAG_ENTER;
1582   event->dnd.context = new_context;
1583   g_object_ref (new_context);
1584
1585   display_x11->current_dest_drag = new_context;
1586
1587   return GDK_FILTER_TRANSLATE;
1588 }
1589
1590 static GdkFilterReturn
1591 motif_top_level_leave (GdkEvent *event,
1592                        guint16   flags, 
1593                        guint32   timestamp)
1594 {
1595   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (GDK_DRAWABLE_DISPLAY (event->any.window));
1596
1597   GDK_NOTE(DND, g_message ("Motif DND top level leave: flags: %#4x time: %d",
1598                            flags, timestamp));
1599
1600   if ((display_x11->current_dest_drag != NULL) &&
1601       (display_x11->current_dest_drag->protocol == GDK_DRAG_PROTO_MOTIF) &&
1602       (timestamp >= display_x11->current_dest_drag->start_time))
1603     {
1604       event->dnd.type = GDK_DRAG_LEAVE;
1605       /* Pass ownership of context to the event */
1606       event->dnd.context = display_x11->current_dest_drag;
1607
1608       display_x11->current_dest_drag = NULL;
1609
1610       return GDK_FILTER_TRANSLATE;
1611     }
1612   else
1613     return GDK_FILTER_REMOVE;
1614 }
1615
1616 static GdkFilterReturn
1617 motif_motion (GdkEvent *event,
1618               guint16   flags, 
1619               guint32   timestamp,
1620               gint16    x_root,
1621               gint16    y_root)
1622 {
1623   GdkDragContextPrivateX11 *private;
1624   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (GDK_DRAWABLE_DISPLAY (event->any.window));
1625   
1626   GDK_NOTE(DND, g_message ("Motif DND motion: flags: %#4x time: %d (%d, %d)",
1627                            flags, timestamp, x_root, y_root));
1628
1629   if ((display_x11->current_dest_drag != NULL) &&
1630       (display_x11->current_dest_drag->protocol == GDK_DRAG_PROTO_MOTIF) &&
1631       (timestamp >= display_x11->current_dest_drag->start_time))
1632     {
1633       private = PRIVATE_DATA (display_x11->current_dest_drag);
1634
1635       event->dnd.type = GDK_DRAG_MOTION;
1636       event->dnd.context = display_x11->current_dest_drag;
1637       g_object_ref (display_x11->current_dest_drag);
1638
1639       event->dnd.time = timestamp;
1640
1641       motif_dnd_translate_flags (display_x11->current_dest_drag, flags);
1642
1643       event->dnd.x_root = x_root;
1644       event->dnd.y_root = y_root;
1645
1646       private->last_x = x_root;
1647       private->last_y = y_root;
1648
1649       private->drag_status = GDK_DRAG_STATUS_MOTION_WAIT;
1650
1651       return GDK_FILTER_TRANSLATE;
1652     }
1653
1654   return GDK_FILTER_REMOVE;
1655 }
1656
1657 static GdkFilterReturn
1658 motif_operation_changed (GdkEvent *event,
1659                          guint16   flags, 
1660                          guint32   timestamp)
1661 {
1662   GdkDragContextPrivateX11 *private;
1663   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (GDK_DRAWABLE_DISPLAY (event->any.window));
1664   GDK_NOTE(DND, g_message ("Motif DND operation changed: flags: %#4x time: %d",
1665                            flags, timestamp));
1666
1667   if ((display_x11->current_dest_drag != NULL) &&
1668       (display_x11->current_dest_drag->protocol == GDK_DRAG_PROTO_MOTIF) &&
1669       (timestamp >= display_x11->current_dest_drag->start_time))
1670     {
1671       event->dnd.type = GDK_DRAG_MOTION;
1672       event->dnd.send_event = FALSE;
1673       event->dnd.context = display_x11->current_dest_drag;
1674       g_object_ref (display_x11->current_dest_drag);
1675
1676       event->dnd.time = timestamp;
1677       private = PRIVATE_DATA (display_x11->current_dest_drag);
1678
1679       motif_dnd_translate_flags (display_x11->current_dest_drag, flags);
1680
1681       event->dnd.x_root = private->last_x;
1682       event->dnd.y_root = private->last_y;
1683
1684       private->drag_status = GDK_DRAG_STATUS_ACTION_WAIT;
1685
1686       return GDK_FILTER_TRANSLATE;
1687     }
1688
1689   return GDK_FILTER_REMOVE;
1690 }
1691
1692 static GdkFilterReturn
1693 motif_drop_start (GdkEvent *event,
1694                   guint16   flags,
1695                   guint32   timestamp,
1696                   guint32   source_window,
1697                   guint32   atom,
1698                   gint16    x_root,
1699                   gint16    y_root)
1700 {
1701   GdkDragContext *new_context;
1702   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (GDK_DRAWABLE_DISPLAY (event->any.window));
1703
1704   GDK_NOTE(DND, g_message ("Motif DND drop start: flags: %#4x time: %d (%d, %d) source_widow: %#4x atom: %d",
1705                            flags, timestamp, x_root, y_root, source_window, atom));
1706
1707   new_context = motif_drag_context_new (event->any.window, timestamp, source_window, atom);
1708   if (!new_context)
1709     return GDK_FILTER_REMOVE;
1710
1711   motif_dnd_translate_flags (new_context, flags);
1712
1713   event->dnd.type = GDK_DROP_START;
1714   event->dnd.context = new_context;
1715   event->dnd.time = timestamp;
1716   event->dnd.x_root = x_root;
1717   event->dnd.y_root = y_root;
1718
1719   gdk_x11_window_set_user_time (event->any.window, timestamp);
1720
1721   g_object_ref (new_context);
1722   display_x11->current_dest_drag = new_context;
1723
1724   return GDK_FILTER_TRANSLATE;
1725 }  
1726
1727 static GdkFilterReturn
1728 motif_drag_status (GdkEvent *event,
1729                    guint16   flags,
1730                    guint32   timestamp)
1731 {
1732   GdkDragContext *context;
1733   GdkDisplay *display;
1734   
1735   GDK_NOTE (DND, 
1736             g_message ("Motif status message: flags %x", flags));
1737
1738   display = gdk_drawable_get_display (event->any.window);
1739   if (!display)
1740     return GDK_FILTER_REMOVE;
1741   
1742   context = gdk_drag_context_find (display, TRUE, GDK_DRAWABLE_XID (event->any.window), None);
1743
1744   if (context)
1745     {
1746       GdkDragContextPrivateX11 *private = PRIVATE_DATA (context);
1747       if ((private->drag_status == GDK_DRAG_STATUS_MOTION_WAIT) ||
1748           (private->drag_status == GDK_DRAG_STATUS_ACTION_WAIT))
1749         private->drag_status = GDK_DRAG_STATUS_DRAG;
1750       
1751       event->dnd.type = GDK_DRAG_STATUS;
1752       event->dnd.send_event = FALSE;
1753       event->dnd.context = context;
1754       g_object_ref (context);
1755
1756       event->dnd.time = timestamp;
1757
1758       if ((flags & 0x00f0) >> 4 == XmDROP_SITE_VALID)
1759         {
1760           switch (flags & 0x000f)
1761             {
1762             case XmDROP_NOOP:
1763               context->action = 0;
1764               break;
1765             case XmDROP_MOVE:
1766                 context->action = GDK_ACTION_MOVE;
1767                 break;
1768             case XmDROP_COPY:
1769               context->action = GDK_ACTION_COPY;
1770               break;
1771             case XmDROP_LINK:
1772               context->action = GDK_ACTION_LINK;
1773               break;
1774             }
1775         }
1776       else
1777         context->action = 0;
1778
1779       return GDK_FILTER_TRANSLATE;
1780     }
1781   return GDK_FILTER_REMOVE;
1782 }
1783
1784 static GdkFilterReturn
1785 motif_dnd_filter (GdkXEvent *xev,
1786                   GdkEvent  *event,
1787                   gpointer data)
1788 {
1789   XEvent *xevent = (XEvent *)xev;
1790
1791   guint8 reason;
1792   guint16 flags;
1793   guint32 timestamp;
1794   guint32 source_window;
1795   Atom atom;
1796   gint16 x_root, y_root;
1797   gboolean is_reply;
1798
1799   if (!event->any.window ||
1800       gdk_window_get_window_type (event->any.window) == GDK_WINDOW_FOREIGN)
1801     return GDK_FILTER_CONTINUE;                 /* Not for us */
1802   
1803   /* First read some fields common to all Motif DND messages */
1804
1805   reason = MOTIF_UNPACK_BYTE (xevent, 0);
1806   flags = MOTIF_UNPACK_SHORT (xevent, 1);
1807   timestamp = MOTIF_UNPACK_LONG (xevent, 1);
1808
1809   is_reply = ((reason & 0x80) != 0);
1810
1811   switch (reason & 0x7f)
1812     {
1813     case XmTOP_LEVEL_ENTER:
1814       source_window = MOTIF_UNPACK_LONG (xevent, 2);
1815       atom = MOTIF_UNPACK_LONG (xevent, 3);
1816       return motif_top_level_enter (event, flags, timestamp, source_window, atom);
1817     case XmTOP_LEVEL_LEAVE:
1818       return motif_top_level_leave (event, flags, timestamp);
1819
1820     case XmDRAG_MOTION:
1821       x_root = MOTIF_UNPACK_SHORT (xevent, 4);
1822       y_root = MOTIF_UNPACK_SHORT (xevent, 5);
1823       
1824       if (!is_reply)
1825         return motif_motion (event, flags, timestamp, x_root, y_root);
1826       else
1827         return motif_drag_status (event, flags, timestamp);
1828
1829     case XmDROP_SITE_ENTER:
1830       return motif_drag_status (event, flags, timestamp);
1831
1832     case XmDROP_SITE_LEAVE:
1833       return motif_drag_status (event,
1834                                 XmNO_DROP_SITE << 8 | XmDROP_NOOP, 
1835                                 timestamp);
1836     case XmDROP_START:
1837       x_root = MOTIF_UNPACK_SHORT (xevent, 4);
1838       y_root = MOTIF_UNPACK_SHORT (xevent, 5);
1839       atom = MOTIF_UNPACK_LONG (xevent, 3);
1840       source_window = MOTIF_UNPACK_LONG (xevent, 4);
1841
1842       if (!is_reply)
1843         return motif_drop_start (event, flags, timestamp, source_window, atom, x_root, y_root);
1844       
1845      break;
1846     case XmOPERATION_CHANGED:
1847       if (!is_reply)
1848         return motif_operation_changed (event, flags, timestamp);
1849       else
1850         return motif_drag_status (event, flags, timestamp);
1851
1852       break;
1853       /* To the best of my knowledge, these next two messages are 
1854        * not part of the protocol, though they are defined in
1855        * the header files.
1856        */
1857     case XmDROP_FINISH:
1858     case XmDRAG_DROP_FINISH:
1859       break;
1860     }
1861
1862   return GDK_FILTER_REMOVE;
1863 }
1864
1865 /*************************************************************
1866  ***************************** XDND **************************
1867  *************************************************************/
1868
1869 /* Utility functions */
1870
1871 static struct {
1872   const gchar *name;
1873   GdkAtom atom;
1874   GdkDragAction action;
1875 } xdnd_actions_table[] = {
1876     { "XdndActionCopy",    None, GDK_ACTION_COPY },
1877     { "XdndActionMove",    None, GDK_ACTION_MOVE },
1878     { "XdndActionLink",    None, GDK_ACTION_LINK },
1879     { "XdndActionAsk",     None, GDK_ACTION_ASK  },
1880     { "XdndActionPrivate", None, GDK_ACTION_COPY },
1881   };
1882
1883 static const gint xdnd_n_actions = sizeof(xdnd_actions_table) / sizeof(xdnd_actions_table[0]);
1884 static gboolean xdnd_actions_initialized = FALSE;
1885
1886 static void
1887 xdnd_initialize_actions (void)
1888 {
1889   gint i;
1890   
1891   xdnd_actions_initialized = TRUE;
1892   for (i=0; i < xdnd_n_actions; i++)
1893     xdnd_actions_table[i].atom = gdk_atom_intern_static_string (xdnd_actions_table[i].name);
1894 }
1895
1896 static GdkDragAction
1897 xdnd_action_from_atom (GdkDisplay *display,
1898                        Atom        xatom)
1899 {
1900   GdkAtom atom = gdk_x11_xatom_to_atom_for_display (display, xatom);
1901   gint i;
1902
1903   if (!xdnd_actions_initialized)
1904     xdnd_initialize_actions();
1905
1906   for (i=0; i<xdnd_n_actions; i++)
1907     if (atom == xdnd_actions_table[i].atom)
1908       return xdnd_actions_table[i].action;
1909
1910   return 0;
1911 }
1912
1913 static Atom
1914 xdnd_action_to_atom (GdkDisplay    *display,
1915                      GdkDragAction  action)
1916 {
1917   gint i;
1918
1919   if (!xdnd_actions_initialized)
1920     xdnd_initialize_actions();
1921
1922   for (i=0; i<xdnd_n_actions; i++)
1923     if (action == xdnd_actions_table[i].action)
1924       return gdk_x11_atom_to_xatom_for_display (display, xdnd_actions_table[i].atom);
1925
1926   return None;
1927 }
1928
1929 /* Source side */
1930
1931 static GdkFilterReturn 
1932 xdnd_status_filter (GdkXEvent *xev,
1933                     GdkEvent  *event,
1934                     gpointer   data)
1935 {
1936   GdkDisplay *display;
1937   XEvent *xevent = (XEvent *)xev;
1938   guint32 dest_window = xevent->xclient.data.l[0];
1939   guint32 flags = xevent->xclient.data.l[1];
1940   Atom action = xevent->xclient.data.l[4];
1941   GdkDragContext *context;
1942
1943   if (!event->any.window ||
1944       gdk_window_get_window_type (event->any.window) == GDK_WINDOW_FOREIGN)
1945     return GDK_FILTER_CONTINUE;                 /* Not for us */
1946   
1947   GDK_NOTE (DND, 
1948             g_message ("XdndStatus: dest_window: %#x  action: %ld",
1949                        dest_window, action));
1950
1951   display = gdk_drawable_get_display (event->any.window);
1952   context = gdk_drag_context_find (display, TRUE, xevent->xclient.window, dest_window);
1953   
1954   if (context)
1955     {
1956       GdkDragContextPrivateX11 *private = PRIVATE_DATA (context);
1957       if (private->drag_status == GDK_DRAG_STATUS_MOTION_WAIT)
1958         private->drag_status = GDK_DRAG_STATUS_DRAG;
1959       
1960       event->dnd.send_event = FALSE;
1961       event->dnd.type = GDK_DRAG_STATUS;
1962       event->dnd.context = context;
1963       g_object_ref (context);
1964
1965       event->dnd.time = GDK_CURRENT_TIME; /* FIXME? */
1966       if (!(action != 0) != !(flags & 1))
1967         {
1968           GDK_NOTE (DND,
1969                     g_warning ("Received status event with flags not corresponding to action!\n"));
1970           action = 0;
1971         }
1972
1973       context->action = xdnd_action_from_atom (display, action);
1974
1975       return GDK_FILTER_TRANSLATE;
1976     }
1977
1978   return GDK_FILTER_REMOVE;
1979 }
1980
1981 static GdkFilterReturn 
1982 xdnd_finished_filter (GdkXEvent *xev,
1983                       GdkEvent  *event,
1984                       gpointer   data)
1985 {
1986   GdkDisplay *display;
1987   XEvent *xevent = (XEvent *)xev;
1988   guint32 dest_window = xevent->xclient.data.l[0];
1989   GdkDragContext *context;
1990   GdkDragContextPrivateX11 *private;
1991
1992   if (!event->any.window ||
1993       gdk_window_get_window_type (event->any.window) == GDK_WINDOW_FOREIGN)
1994     return GDK_FILTER_CONTINUE;                 /* Not for us */
1995   
1996   GDK_NOTE (DND, 
1997             g_message ("XdndFinished: dest_window: %#x", dest_window));
1998
1999   display = gdk_drawable_get_display (event->any.window);
2000   context = gdk_drag_context_find (display, TRUE, xevent->xclient.window, dest_window);
2001   
2002   if (context)
2003     {
2004       private = PRIVATE_DATA (context);
2005       if (private->version == 5)
2006         private->drop_failed = xevent->xclient.data.l[1] == 0;
2007       
2008       event->dnd.type = GDK_DROP_FINISHED;
2009       event->dnd.context = context;
2010       g_object_ref (context);
2011
2012       event->dnd.time = GDK_CURRENT_TIME; /* FIXME? */
2013
2014       return GDK_FILTER_TRANSLATE;
2015     }
2016
2017   return GDK_FILTER_REMOVE;
2018 }
2019
2020 static void
2021 xdnd_set_targets (GdkDragContext *context)
2022 {
2023   GdkDragContextPrivateX11 *private = PRIVATE_DATA (context);
2024   Atom *atomlist;
2025   GList *tmp_list = context->targets;
2026   gint i;
2027   gint n_atoms = g_list_length (context->targets);
2028   GdkDisplay *display = GDK_DRAWABLE_DISPLAY (context->source_window);
2029
2030   atomlist = g_new (Atom, n_atoms);
2031   i = 0;
2032   while (tmp_list)
2033     {
2034       atomlist[i] = gdk_x11_atom_to_xatom_for_display (display, GDK_POINTER_TO_ATOM (tmp_list->data));
2035       tmp_list = tmp_list->next;
2036       i++;
2037     }
2038
2039   XChangeProperty (GDK_DRAWABLE_XDISPLAY (context->source_window),
2040                    GDK_DRAWABLE_XID (context->source_window),
2041                    gdk_x11_get_xatom_by_name_for_display (display, "XdndTypeList"),
2042                    XA_ATOM, 32, PropModeReplace,
2043                    (guchar *)atomlist, n_atoms);
2044
2045   g_free (atomlist);
2046
2047   private->xdnd_targets_set = 1;
2048 }
2049
2050 static void
2051 xdnd_set_actions (GdkDragContext *context)
2052 {
2053   GdkDragContextPrivateX11 *private = PRIVATE_DATA (context);
2054   Atom *atomlist;
2055   gint i;
2056   gint n_atoms;
2057   guint actions;
2058   GdkDisplay *display = GDK_DRAWABLE_DISPLAY (context->source_window);
2059
2060   if (!xdnd_actions_initialized)
2061     xdnd_initialize_actions();
2062   
2063   actions = context->actions;
2064   n_atoms = 0;
2065   for (i=0; i<xdnd_n_actions; i++)
2066     {
2067       if (actions & xdnd_actions_table[i].action)
2068         {
2069           actions &= ~xdnd_actions_table[i].action;
2070           n_atoms++;
2071         }
2072     }
2073
2074   atomlist = g_new (Atom, n_atoms);
2075
2076   actions = context->actions;
2077   n_atoms = 0;
2078   for (i=0; i<xdnd_n_actions; i++)
2079     {
2080       if (actions & xdnd_actions_table[i].action)
2081         {
2082           actions &= ~xdnd_actions_table[i].action;
2083           atomlist[n_atoms] = gdk_x11_atom_to_xatom_for_display (display, xdnd_actions_table[i].atom);
2084           n_atoms++;
2085         }
2086     }
2087
2088   XChangeProperty (GDK_DRAWABLE_XDISPLAY (context->source_window),
2089                    GDK_DRAWABLE_XID (context->source_window),
2090                    gdk_x11_get_xatom_by_name_for_display (display, "XdndActionList"),
2091                    XA_ATOM, 32, PropModeReplace,
2092                    (guchar *)atomlist, n_atoms);
2093
2094   g_free (atomlist);
2095
2096   private->xdnd_actions_set = TRUE;
2097   private->xdnd_actions = context->actions;
2098 }
2099
2100 static void
2101 send_client_message_async_cb (Window   window,
2102                               gboolean success,
2103                               gpointer data)
2104 {
2105   GdkDragContext *context = data;
2106   GDK_NOTE (DND,
2107             g_message ("Got async callback for #%lx, success = %d",
2108                        window, success));
2109
2110   /* On failure, we immediately continue with the protocol
2111    * so we don't end up blocking for a timeout
2112    */
2113   if (!success &&
2114       context->dest_window &&
2115       window == GDK_WINDOW_XID (context->dest_window))
2116     {
2117       GdkEvent temp_event;
2118       GdkDragContextPrivateX11 *private = PRIVATE_DATA (context);
2119
2120       g_object_unref (context->dest_window);
2121       context->dest_window = NULL;
2122       context->action = 0;
2123
2124       private->drag_status = GDK_DRAG_STATUS_DRAG;
2125
2126       temp_event.dnd.type = GDK_DRAG_STATUS;
2127       temp_event.dnd.window = context->source_window;
2128       temp_event.dnd.send_event = TRUE;
2129       temp_event.dnd.context = context;
2130       temp_event.dnd.time = GDK_CURRENT_TIME;
2131
2132       gdk_event_put (&temp_event);
2133     }
2134
2135   g_object_unref (context);
2136 }
2137
2138
2139 static GdkDisplay *
2140 gdk_drag_context_get_display (GdkDragContext *context)
2141 {
2142   if (context->source_window)
2143     return GDK_DRAWABLE_DISPLAY (context->source_window);
2144   else if (context->dest_window)
2145     return GDK_DRAWABLE_DISPLAY (context->dest_window);
2146
2147   g_assert_not_reached ();
2148   return NULL;
2149 }
2150
2151 static void
2152 send_client_message_async (GdkDragContext      *context,
2153                            Window               window, 
2154                            gboolean             propagate,
2155                            glong                event_mask,
2156                            XClientMessageEvent *event_send)
2157 {
2158   GdkDisplay *display = gdk_drag_context_get_display (context);
2159   
2160   g_object_ref (context);
2161
2162   _gdk_x11_send_client_message_async (display, window,
2163                                       propagate, event_mask, event_send,
2164                                       send_client_message_async_cb, context);
2165 }
2166
2167 static gboolean
2168 xdnd_send_xevent (GdkDragContext *context,
2169                   GdkWindow      *window, 
2170                   gboolean        propagate,
2171                   XEvent         *event_send)
2172 {
2173   GdkDisplay *display = gdk_drag_context_get_display (context);
2174   Window xwindow;
2175   glong event_mask;
2176
2177   g_assert (event_send->xany.type == ClientMessage);
2178
2179   /* We short-circuit messages to ourselves */
2180   if (gdk_window_get_window_type (window) != GDK_WINDOW_FOREIGN)
2181     {
2182       gint i;
2183       
2184       for (i = 0; i < G_N_ELEMENTS (xdnd_filters); i++)
2185         {
2186           if (gdk_x11_get_xatom_by_name_for_display (display, xdnd_filters[i].atom_name) ==
2187               event_send->xclient.message_type)
2188             {
2189               GdkEvent temp_event;
2190               temp_event.any.window = window;
2191
2192               if  ((*xdnd_filters[i].func) (event_send, &temp_event, NULL) == GDK_FILTER_TRANSLATE)
2193                 {
2194                   gdk_event_put (&temp_event);
2195                   g_object_unref (temp_event.dnd.context);
2196                 }
2197               
2198               return TRUE;
2199             }
2200         }
2201     }
2202
2203   xwindow = GDK_WINDOW_XWINDOW (window);
2204   
2205   if (_gdk_x11_display_is_root_window (display, xwindow))
2206     event_mask = ButtonPressMask;
2207   else
2208     event_mask = 0;
2209   
2210   send_client_message_async (context, xwindow, propagate, event_mask,
2211                              &event_send->xclient);
2212
2213   return TRUE;
2214 }
2215  
2216 static void
2217 xdnd_send_enter (GdkDragContext *context)
2218 {
2219   XEvent xev;
2220   GdkDragContextPrivateX11 *private = PRIVATE_DATA (context);
2221   GdkDisplay *display = GDK_DRAWABLE_DISPLAY (context->dest_window);
2222
2223   xev.xclient.type = ClientMessage;
2224   xev.xclient.message_type = gdk_x11_get_xatom_by_name_for_display (display, "XdndEnter");
2225   xev.xclient.format = 32;
2226   xev.xclient.window = private->drop_xid ? 
2227                            private->drop_xid : 
2228                            GDK_DRAWABLE_XID (context->dest_window);
2229   xev.xclient.data.l[0] = GDK_DRAWABLE_XID (context->source_window);
2230   xev.xclient.data.l[1] = (private->version << 24); /* version */
2231   xev.xclient.data.l[2] = 0;
2232   xev.xclient.data.l[3] = 0;
2233   xev.xclient.data.l[4] = 0;
2234
2235   GDK_NOTE(DND,
2236            g_message ("Sending enter source window %#lx XDND protocol version %d\n",
2237                       GDK_DRAWABLE_XID (context->source_window), private->version));
2238   if (g_list_length (context->targets) > 3)
2239     {
2240       if (!private->xdnd_targets_set)
2241         xdnd_set_targets (context);
2242       xev.xclient.data.l[1] |= 1;
2243     }
2244   else
2245     {
2246       GList *tmp_list = context->targets;
2247       gint i = 2;
2248
2249       while (tmp_list)
2250         {
2251           xev.xclient.data.l[i] = gdk_x11_atom_to_xatom_for_display (display,
2252                                                                      GDK_POINTER_TO_ATOM (tmp_list->data));
2253           tmp_list = tmp_list->next;
2254           i++;
2255         }
2256     }
2257
2258   if (!xdnd_send_xevent (context, context->dest_window,
2259                          FALSE, &xev))
2260     {
2261       GDK_NOTE (DND, 
2262                 g_message ("Send event to %lx failed",
2263                            GDK_DRAWABLE_XID (context->dest_window)));
2264       g_object_unref (context->dest_window);
2265       context->dest_window = NULL;
2266     }
2267 }
2268
2269 static void
2270 xdnd_send_leave (GdkDragContext *context)
2271 {
2272   GdkDisplay *display = GDK_DRAWABLE_DISPLAY (context->source_window);
2273   XEvent xev;
2274
2275   GdkDragContextPrivateX11 *private = PRIVATE_DATA (context);
2276
2277   xev.xclient.type = ClientMessage;
2278   xev.xclient.message_type = gdk_x11_get_xatom_by_name_for_display (display, "XdndLeave");
2279   xev.xclient.format = 32;
2280   xev.xclient.window = private->drop_xid ? 
2281                            private->drop_xid : 
2282                            GDK_DRAWABLE_XID (context->dest_window);
2283   xev.xclient.data.l[0] = GDK_DRAWABLE_XID (context->source_window);
2284   xev.xclient.data.l[1] = 0;
2285   xev.xclient.data.l[2] = 0;
2286   xev.xclient.data.l[3] = 0;
2287   xev.xclient.data.l[4] = 0;
2288
2289   if (!xdnd_send_xevent (context, context->dest_window,
2290                          FALSE, &xev))
2291     {
2292       GDK_NOTE (DND, 
2293                 g_message ("Send event to %lx failed",
2294                            GDK_DRAWABLE_XID (context->dest_window)));
2295       g_object_unref (context->dest_window);
2296       context->dest_window = NULL;
2297     }
2298 }
2299
2300 static void
2301 xdnd_send_drop (GdkDragContext *context, guint32 time)
2302 {
2303   GdkDragContextPrivateX11 *private = PRIVATE_DATA (context);
2304   GdkDisplay *display = GDK_DRAWABLE_DISPLAY (context->source_window);
2305   XEvent xev;
2306
2307   xev.xclient.type = ClientMessage;
2308   xev.xclient.message_type = gdk_x11_get_xatom_by_name_for_display (display, "XdndDrop");
2309   xev.xclient.format = 32;
2310   xev.xclient.window = private->drop_xid ? 
2311                            private->drop_xid : 
2312                            GDK_DRAWABLE_XID (context->dest_window);
2313   xev.xclient.data.l[0] = GDK_DRAWABLE_XID (context->source_window);
2314   xev.xclient.data.l[1] = 0;
2315   xev.xclient.data.l[2] = time;
2316   xev.xclient.data.l[3] = 0;
2317   xev.xclient.data.l[4] = 0;
2318
2319   if (!xdnd_send_xevent (context, context->dest_window,
2320                          FALSE, &xev))
2321     {
2322       GDK_NOTE (DND, 
2323                 g_message ("Send event to %lx failed",
2324                            GDK_DRAWABLE_XID (context->dest_window)));
2325       g_object_unref (context->dest_window);
2326       context->dest_window = NULL;
2327     }
2328 }
2329
2330 static void
2331 xdnd_send_motion (GdkDragContext *context,
2332                   gint            x_root, 
2333                   gint            y_root,
2334                   GdkDragAction   action,
2335                   guint32         time)
2336 {
2337   GdkDragContextPrivateX11 *private = PRIVATE_DATA (context);
2338   GdkDisplay *display = GDK_DRAWABLE_DISPLAY (context->source_window);
2339   XEvent xev;
2340
2341   xev.xclient.type = ClientMessage;
2342   xev.xclient.message_type = gdk_x11_get_xatom_by_name_for_display (display, "XdndPosition");
2343   xev.xclient.format = 32;
2344   xev.xclient.window = private->drop_xid ? 
2345                            private->drop_xid : 
2346                            GDK_DRAWABLE_XID (context->dest_window);
2347   xev.xclient.data.l[0] = GDK_DRAWABLE_XID (context->source_window);
2348   xev.xclient.data.l[1] = 0;
2349   xev.xclient.data.l[2] = (x_root << 16) | y_root;
2350   xev.xclient.data.l[3] = time;
2351   xev.xclient.data.l[4] = xdnd_action_to_atom (display, action);
2352
2353   if (!xdnd_send_xevent (context, context->dest_window,
2354                          FALSE, &xev))
2355     {
2356       GDK_NOTE (DND, 
2357                 g_message ("Send event to %lx failed",
2358                            GDK_DRAWABLE_XID (context->dest_window)));
2359       g_object_unref (context->dest_window);
2360       context->dest_window = NULL;
2361     }
2362   private->drag_status = GDK_DRAG_STATUS_MOTION_WAIT;
2363 }
2364
2365 static guint32
2366 xdnd_check_dest (GdkDisplay *display,
2367                  Window      win,
2368                  guint      *xdnd_version)
2369 {
2370   gboolean retval = FALSE;
2371   Atom type = None;
2372   int format;
2373   unsigned long nitems, after;
2374   guchar *data;
2375   Atom *version;
2376   Window *proxy_data;
2377   Window proxy;
2378   Atom xdnd_proxy_atom = gdk_x11_get_xatom_by_name_for_display (display, "XdndProxy");
2379   Atom xdnd_aware_atom = gdk_x11_get_xatom_by_name_for_display (display, "XdndAware");
2380
2381   proxy = None;
2382
2383   gdk_error_trap_push ();
2384   
2385   if (XGetWindowProperty (GDK_DISPLAY_XDISPLAY (display), win, 
2386                           xdnd_proxy_atom, 0, 
2387                           1, False, AnyPropertyType,
2388                           &type, &format, &nitems, &after, 
2389                           &data) == Success)
2390     {
2391       if (type != None)
2392         {
2393           proxy_data = (Window *)data;
2394           
2395           if ((format == 32) && (nitems == 1))
2396             {
2397               proxy = *proxy_data;
2398             }
2399           else
2400             GDK_NOTE (DND, 
2401                       g_warning ("Invalid XdndProxy "
2402                                  "property on window %ld\n", win));
2403           
2404           XFree (proxy_data);
2405         }
2406       
2407       if ((XGetWindowProperty (GDK_DISPLAY_XDISPLAY (display), proxy ? proxy : win,
2408                                xdnd_aware_atom, 0, 
2409                                1, False, AnyPropertyType,
2410                                &type, &format, &nitems, &after, 
2411                                &data) == Success) &&
2412           type != None)
2413         {
2414           version = (Atom *)data;
2415           
2416           if ((format == 32) && (nitems == 1))
2417             {
2418               if (*version >= 3)
2419                 retval = TRUE;
2420               if (xdnd_version)
2421                 *xdnd_version = *version;
2422             }
2423           else
2424             GDK_NOTE (DND, 
2425                       g_warning ("Invalid XdndAware "
2426                                  "property on window %ld\n", win));
2427           
2428           XFree (version);
2429         }
2430     }
2431
2432   gdk_error_trap_pop ();
2433   
2434   return retval ? (proxy ? proxy : win) : None;
2435 }
2436
2437 /* Target side */
2438
2439 static void
2440 xdnd_read_actions (GdkDragContext *context)
2441 {
2442   GdkDisplay *display = GDK_WINDOW_DISPLAY (context->source_window);
2443   Atom type;
2444   int format;
2445   gulong nitems, after;
2446   guchar *data;
2447   Atom *atoms;
2448
2449   gint i;
2450   
2451   PRIVATE_DATA (context)->xdnd_have_actions = FALSE;
2452
2453   if (gdk_window_get_window_type (context->source_window) == GDK_WINDOW_FOREIGN)
2454     {
2455       /* Get the XdndActionList, if set */
2456       
2457       gdk_error_trap_push ();
2458       
2459       if (XGetWindowProperty (GDK_DISPLAY_XDISPLAY (display),
2460                               GDK_DRAWABLE_XID (context->source_window),
2461                               gdk_x11_get_xatom_by_name_for_display (display, "XdndActionList"),
2462                               0, 65536,
2463                               False, XA_ATOM, &type, &format, &nitems,
2464                               &after, &data) == Success &&
2465           type == XA_ATOM)
2466         {
2467           atoms = (Atom *)data;
2468           
2469           context->actions = 0;
2470           
2471           for (i=0; i<nitems; i++)
2472             context->actions |= xdnd_action_from_atom (display, atoms[i]);
2473           
2474           PRIVATE_DATA (context)->xdnd_have_actions = TRUE;
2475           
2476 #ifdef G_ENABLE_DEBUG
2477           if (_gdk_debug_flags & GDK_DEBUG_DND)
2478             {
2479               GString *action_str = g_string_new (NULL);
2480               if (context->actions & GDK_ACTION_MOVE)
2481                 g_string_append(action_str, "MOVE ");
2482               if (context->actions & GDK_ACTION_COPY)
2483                 g_string_append(action_str, "COPY ");
2484               if (context->actions & GDK_ACTION_LINK)
2485                 g_string_append(action_str, "LINK ");
2486               if (context->actions & GDK_ACTION_ASK)
2487                 g_string_append(action_str, "ASK ");
2488               
2489               g_message("Xdnd actions = %s", action_str->str);
2490               g_string_free (action_str, TRUE);
2491             }
2492 #endif /* G_ENABLE_DEBUG */
2493           
2494         }
2495
2496       if (data)
2497         XFree (data);
2498       
2499       gdk_error_trap_pop ();
2500     }
2501   else
2502     {
2503       /* Local drag
2504        */
2505       GdkDragContext *source_context;
2506
2507       source_context = gdk_drag_context_find (display, TRUE,
2508                                               GDK_DRAWABLE_XID (context->source_window),
2509                                               GDK_DRAWABLE_XID (context->dest_window));
2510
2511       if (source_context)
2512         {
2513           context->actions = source_context->actions;
2514           PRIVATE_DATA (context)->xdnd_have_actions = TRUE;
2515         }
2516     }
2517 }
2518
2519 /* We have to make sure that the XdndActionList we keep internally
2520  * is up to date with the XdndActionList on the source window
2521  * because we get no notification, because Xdnd wasn't meant
2522  * to continually send actions. So we select on PropertyChangeMask
2523  * and add this filter.
2524  */
2525 static GdkFilterReturn 
2526 xdnd_source_window_filter (GdkXEvent *xev,
2527                            GdkEvent  *event,
2528                            gpointer   cb_data)
2529 {
2530   XEvent *xevent = (XEvent *)xev;
2531   GdkDragContext *context = cb_data;
2532   GdkDisplay *display = GDK_WINDOW_DISPLAY(event->any.window);
2533
2534   if ((xevent->xany.type == PropertyNotify) &&
2535       (xevent->xproperty.atom == gdk_x11_get_xatom_by_name_for_display (display, "XdndActionList")))
2536     {
2537       xdnd_read_actions (context);
2538
2539       return GDK_FILTER_REMOVE;
2540     }
2541
2542   return GDK_FILTER_CONTINUE;
2543 }
2544
2545 static void
2546 xdnd_manage_source_filter (GdkDragContext *context,
2547                            GdkWindow      *window,
2548                            gboolean        add_filter)
2549 {
2550   if (!GDK_WINDOW_DESTROYED (window) &&
2551       gdk_window_get_window_type (window) == GDK_WINDOW_FOREIGN)
2552     {
2553       gdk_error_trap_push ();
2554
2555       if (add_filter)
2556         {
2557           gdk_window_set_events (window,
2558                                  gdk_window_get_events (window) |
2559                                  GDK_PROPERTY_CHANGE_MASK);
2560           gdk_window_add_filter (window, xdnd_source_window_filter, context);
2561         }
2562       else
2563         {
2564           gdk_window_remove_filter (window,
2565                                     xdnd_source_window_filter,
2566                                     context);
2567           /* Should we remove the GDK_PROPERTY_NOTIFY mask?
2568            * but we might want it for other reasons. (Like
2569            * INCR selection transactions).
2570            */
2571         }
2572       
2573       gdk_display_sync (gdk_drawable_get_display (window));
2574       gdk_error_trap_pop ();  
2575     }
2576 }
2577
2578 static void
2579 base_precache_atoms (GdkDisplay *display)
2580 {
2581   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (display);
2582
2583   if (!display_x11->base_dnd_atoms_precached)
2584     {
2585       static const char *const precache_atoms[] = {
2586         "ENLIGHTENMENT_DESKTOP",
2587         "WM_STATE",
2588         "XdndAware",
2589         "XdndProxy",
2590         "_MOTIF_DRAG_RECEIVER_INFO"
2591       };
2592
2593       _gdk_x11_precache_atoms (display,
2594                                precache_atoms, G_N_ELEMENTS (precache_atoms));
2595
2596       display_x11->base_dnd_atoms_precached = TRUE;
2597     }
2598 }
2599
2600 static void
2601 xdnd_precache_atoms (GdkDisplay *display)
2602 {
2603   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (display);
2604
2605   if (!display_x11->xdnd_atoms_precached)
2606     {
2607       static const char *const precache_atoms[] = {
2608         "XdndActionAsk",
2609         "XdndActionCopy",
2610         "XdndActionLink",
2611         "XdndActionList",
2612         "XdndActionMove",
2613         "XdndActionPrivate",
2614         "XdndDrop",
2615         "XdndEnter",
2616         "XdndFinished",
2617         "XdndLeave",
2618         "XdndPosition",
2619         "XdndSelection",
2620         "XdndStatus",
2621         "XdndTypeList"
2622       };
2623
2624       _gdk_x11_precache_atoms (display,
2625                                precache_atoms, G_N_ELEMENTS (precache_atoms));
2626
2627       display_x11->xdnd_atoms_precached = TRUE;
2628     }
2629 }
2630
2631 static GdkFilterReturn 
2632 xdnd_enter_filter (GdkXEvent *xev,
2633                    GdkEvent  *event,
2634                    gpointer   cb_data)
2635 {
2636   GdkDisplay *display;
2637   GdkDisplayX11 *display_x11;
2638   XEvent *xevent = (XEvent *)xev;
2639   GdkDragContext *new_context;
2640   gint i;
2641   
2642   Atom type;
2643   int format;
2644   gulong nitems, after;
2645   guchar *data;
2646   Atom *atoms;
2647
2648   guint32 source_window;
2649   gboolean get_types;
2650   gint version;
2651
2652   if (!event->any.window ||
2653       gdk_window_get_window_type (event->any.window) == GDK_WINDOW_FOREIGN)
2654     return GDK_FILTER_CONTINUE;                 /* Not for us */
2655
2656   source_window = xevent->xclient.data.l[0];
2657   get_types = ((xevent->xclient.data.l[1] & 1) != 0);
2658   version = (xevent->xclient.data.l[1] & 0xff000000) >> 24;
2659   
2660   display = GDK_DRAWABLE_DISPLAY (event->any.window);
2661   display_x11 = GDK_DISPLAY_X11 (display);
2662
2663   xdnd_precache_atoms (display);
2664
2665   GDK_NOTE (DND, 
2666             g_message ("XdndEnter: source_window: %#x, version: %#x",
2667                        source_window, version));
2668
2669   if (version < 3)
2670     {
2671       /* Old source ignore */
2672       GDK_NOTE (DND, g_message ("Ignored old XdndEnter message"));
2673       return GDK_FILTER_REMOVE;
2674     }
2675   
2676   if (display_x11->current_dest_drag != NULL)
2677     {
2678       g_object_unref (display_x11->current_dest_drag);
2679       display_x11->current_dest_drag = NULL;
2680     }
2681
2682   new_context = gdk_drag_context_new ();
2683   new_context->protocol = GDK_DRAG_PROTO_XDND;
2684   PRIVATE_DATA(new_context)->version = version;
2685
2686   new_context->source_window = gdk_window_lookup_for_display (display, source_window);
2687   if (new_context->source_window)
2688     g_object_ref (new_context->source_window);
2689   else
2690     {
2691       new_context->source_window = gdk_window_foreign_new_for_display (display, source_window);
2692       if (!new_context->source_window)
2693         {
2694           g_object_unref (new_context);
2695           return GDK_FILTER_REMOVE;
2696         }
2697     }
2698   new_context->dest_window = event->any.window;
2699   g_object_ref (new_context->dest_window);
2700
2701   new_context->targets = NULL;
2702   if (get_types)
2703     {
2704       gdk_error_trap_push ();
2705       XGetWindowProperty (GDK_DRAWABLE_XDISPLAY (event->any.window), 
2706                           source_window, 
2707                           gdk_x11_get_xatom_by_name_for_display (display, "XdndTypeList"),
2708                           0, 65536,
2709                           False, XA_ATOM, &type, &format, &nitems,
2710                           &after, &data);
2711
2712       if (gdk_error_trap_pop () || (format != 32) || (type != XA_ATOM))
2713         {
2714           g_object_unref (new_context);
2715
2716           if (data)
2717             XFree (data);
2718
2719           return GDK_FILTER_REMOVE;
2720         }
2721
2722       atoms = (Atom *)data;
2723
2724       for (i=0; i<nitems; i++)
2725         new_context->targets = 
2726           g_list_append (new_context->targets,
2727                          GDK_ATOM_TO_POINTER (gdk_x11_xatom_to_atom_for_display (display,
2728                                                                                  atoms[i])));
2729
2730       XFree(atoms);
2731     }
2732   else
2733     {
2734       for (i=0; i<3; i++)
2735         if (xevent->xclient.data.l[2+i])
2736           new_context->targets =
2737             g_list_append (new_context->targets,
2738                            GDK_ATOM_TO_POINTER (gdk_x11_xatom_to_atom_for_display (display, 
2739                                                                                    xevent->xclient.data.l[2+i])));
2740     }
2741
2742 #ifdef G_ENABLE_DEBUG
2743   if (_gdk_debug_flags & GDK_DEBUG_DND)
2744     print_target_list (new_context->targets);
2745 #endif /* G_ENABLE_DEBUG */
2746
2747   xdnd_manage_source_filter (new_context, new_context->source_window, TRUE);
2748   xdnd_read_actions (new_context);
2749
2750   event->dnd.type = GDK_DRAG_ENTER;
2751   event->dnd.context = new_context;
2752   g_object_ref (new_context);
2753
2754   display_x11->current_dest_drag = new_context;
2755
2756   return GDK_FILTER_TRANSLATE;
2757 }
2758
2759 static GdkFilterReturn 
2760 xdnd_leave_filter (GdkXEvent *xev,
2761                    GdkEvent  *event,
2762                    gpointer   data)
2763 {
2764   XEvent *xevent = (XEvent *)xev;
2765   guint32 source_window = xevent->xclient.data.l[0];
2766   GdkDisplay *display;
2767   GdkDisplayX11 *display_x11;
2768
2769   if (!event->any.window ||
2770       gdk_window_get_window_type (event->any.window) == GDK_WINDOW_FOREIGN)
2771     return GDK_FILTER_CONTINUE;                 /* Not for us */
2772  
2773   GDK_NOTE (DND, 
2774             g_message ("XdndLeave: source_window: %#x",
2775                        source_window));
2776
2777   display = GDK_DRAWABLE_DISPLAY (event->any.window);
2778   display_x11 = GDK_DISPLAY_X11 (display);
2779
2780   xdnd_precache_atoms (display);
2781
2782   if ((display_x11->current_dest_drag != NULL) &&
2783       (display_x11->current_dest_drag->protocol == GDK_DRAG_PROTO_XDND) &&
2784       (GDK_DRAWABLE_XID (display_x11->current_dest_drag->source_window) == source_window))
2785     {
2786       event->dnd.type = GDK_DRAG_LEAVE;
2787       /* Pass ownership of context to the event */
2788       event->dnd.context = display_x11->current_dest_drag;
2789
2790       display_x11->current_dest_drag = NULL;
2791
2792       return GDK_FILTER_TRANSLATE;
2793     }
2794   else
2795     return GDK_FILTER_REMOVE;
2796 }
2797
2798 static GdkFilterReturn 
2799 xdnd_position_filter (GdkXEvent *xev,
2800                       GdkEvent  *event,
2801                       gpointer   data)
2802 {
2803   XEvent *xevent = (XEvent *)xev;
2804   guint32 source_window = xevent->xclient.data.l[0];
2805   gint16 x_root = xevent->xclient.data.l[2] >> 16;
2806   gint16 y_root = xevent->xclient.data.l[2] & 0xffff;
2807   guint32 time = xevent->xclient.data.l[3];
2808   Atom action = xevent->xclient.data.l[4];
2809
2810   GdkDisplay *display;
2811   GdkDisplayX11 *display_x11;
2812
2813    if (!event->any.window ||
2814        gdk_window_get_window_type (event->any.window) == GDK_WINDOW_FOREIGN)
2815      return GDK_FILTER_CONTINUE;                        /* Not for us */
2816    
2817   GDK_NOTE (DND, 
2818             g_message ("XdndPosition: source_window: %#x position: (%d, %d)  time: %d  action: %ld",
2819                        source_window, x_root, y_root, time, action));
2820
2821   display = GDK_DRAWABLE_DISPLAY (event->any.window);
2822   display_x11 = GDK_DISPLAY_X11 (display);
2823   
2824   xdnd_precache_atoms (display);
2825
2826   if ((display_x11->current_dest_drag != NULL) &&
2827       (display_x11->current_dest_drag->protocol == GDK_DRAG_PROTO_XDND) &&
2828       (GDK_DRAWABLE_XID (display_x11->current_dest_drag->source_window) == source_window))
2829     {
2830       event->dnd.type = GDK_DRAG_MOTION;
2831       event->dnd.context = display_x11->current_dest_drag;
2832       g_object_ref (display_x11->current_dest_drag);
2833
2834       event->dnd.time = time;
2835
2836       display_x11->current_dest_drag->suggested_action = xdnd_action_from_atom (display, action);
2837       
2838       if (!(PRIVATE_DATA (display_x11->current_dest_drag))->xdnd_have_actions)
2839         display_x11->current_dest_drag->actions = display_x11->current_dest_drag->suggested_action;
2840
2841       event->dnd.x_root = x_root;
2842       event->dnd.y_root = y_root;
2843
2844       (PRIVATE_DATA (display_x11->current_dest_drag))->last_x = x_root;
2845       (PRIVATE_DATA (display_x11->current_dest_drag))->last_y = y_root;
2846       
2847       return GDK_FILTER_TRANSLATE;
2848     }
2849
2850   return GDK_FILTER_REMOVE;
2851 }
2852
2853 static GdkFilterReturn 
2854 xdnd_drop_filter (GdkXEvent *xev,
2855                   GdkEvent  *event,
2856                   gpointer   data)
2857 {
2858   XEvent *xevent = (XEvent *)xev;
2859   guint32 source_window = xevent->xclient.data.l[0];
2860   guint32 time = xevent->xclient.data.l[2];
2861   GdkDisplay *display;
2862   GdkDisplayX11 *display_x11;
2863   
2864   if (!event->any.window ||
2865       gdk_window_get_window_type (event->any.window) == GDK_WINDOW_FOREIGN)
2866     return GDK_FILTER_CONTINUE;                 /* Not for us */
2867   
2868   GDK_NOTE (DND, 
2869             g_message ("XdndDrop: source_window: %#x  time: %d",
2870                        source_window, time));
2871
2872   display = GDK_DRAWABLE_DISPLAY (event->any.window);
2873   display_x11 = GDK_DISPLAY_X11 (display);
2874
2875   xdnd_precache_atoms (display);
2876
2877   if ((display_x11->current_dest_drag != NULL) &&
2878       (display_x11->current_dest_drag->protocol == GDK_DRAG_PROTO_XDND) &&
2879       (GDK_DRAWABLE_XID (display_x11->current_dest_drag->source_window) == source_window))
2880     {
2881       GdkDragContextPrivateX11 *private;
2882       private = PRIVATE_DATA (display_x11->current_dest_drag);
2883
2884       event->dnd.type = GDK_DROP_START;
2885
2886       event->dnd.context = display_x11->current_dest_drag;
2887       g_object_ref (display_x11->current_dest_drag);
2888
2889       event->dnd.time = time;
2890       event->dnd.x_root = private->last_x;
2891       event->dnd.y_root = private->last_y;
2892
2893       gdk_x11_window_set_user_time (event->any.window, time);
2894       
2895       return GDK_FILTER_TRANSLATE;
2896     }
2897
2898   return GDK_FILTER_REMOVE;
2899 }
2900
2901 /*************************************************************
2902  ************************** Public API ***********************
2903  *************************************************************/
2904 void
2905 _gdk_dnd_init (GdkDisplay *display)
2906 {
2907   int i;
2908   init_byte_order ();
2909
2910   gdk_display_add_client_message_filter (
2911         display,
2912         gdk_atom_intern_static_string ("_MOTIF_DRAG_AND_DROP_MESSAGE"),
2913         motif_dnd_filter, NULL);
2914   
2915   for (i = 0; i < G_N_ELEMENTS (xdnd_filters); i++)
2916     {
2917       gdk_display_add_client_message_filter (
2918         display,
2919         gdk_atom_intern_static_string (xdnd_filters[i].atom_name),
2920         xdnd_filters[i].func, NULL);
2921     }
2922 }                     
2923
2924 /* Source side */
2925
2926 static void
2927 gdk_drag_do_leave (GdkDragContext *context, guint32 time)
2928 {
2929   if (context->dest_window)
2930     {
2931       switch (context->protocol)
2932         {
2933         case GDK_DRAG_PROTO_MOTIF:
2934           motif_send_leave (context, time);
2935           break;
2936         case GDK_DRAG_PROTO_XDND:
2937           xdnd_send_leave (context);
2938           break;
2939         case GDK_DRAG_PROTO_ROOTWIN:
2940         case GDK_DRAG_PROTO_NONE:
2941         default:
2942           break;
2943         }
2944
2945       g_object_unref (context->dest_window);
2946       context->dest_window = NULL;
2947     }
2948 }
2949
2950 /**
2951  * gdk_drag_begin:
2952  * @window: the source window for this drag.
2953  * @targets: the list of offered targets.
2954  * 
2955  * Starts a drag and creates a new drag context for it.
2956  *
2957  * This function is called by the drag source.
2958  * 
2959  * Return value: a newly created #GdkDragContext.
2960  **/
2961 GdkDragContext * 
2962 gdk_drag_begin (GdkWindow     *window,
2963                 GList         *targets)
2964 {
2965   GdkDragContext *new_context;
2966   
2967   g_return_val_if_fail (window != NULL, NULL);
2968
2969   new_context = gdk_drag_context_new ();
2970   new_context->is_source = TRUE;
2971   new_context->source_window = window;
2972   g_object_ref (window);
2973
2974   new_context->targets = g_list_copy (targets);
2975   precache_target_list (new_context);
2976   
2977   new_context->actions = 0;
2978
2979   return new_context;
2980 }
2981
2982 static guint32
2983 _gdk_drag_get_protocol_for_display (GdkDisplay      *display,
2984                                     guint32          xid,
2985                                     GdkDragProtocol *protocol,
2986                                     guint           *version)
2987
2988 {
2989   GdkWindow *window;
2990   guint32 retval;
2991   g_return_val_if_fail (GDK_IS_DISPLAY (display), None);
2992
2993   base_precache_atoms (display);
2994
2995   /* Check for a local drag
2996    */
2997   window = gdk_window_lookup_for_display (display, xid);
2998   if (window &&
2999       gdk_window_get_window_type (window) != GDK_WINDOW_FOREIGN)
3000     {
3001       if (g_object_get_data (G_OBJECT (window), "gdk-dnd-registered") != NULL)
3002         {
3003           *protocol = GDK_DRAG_PROTO_XDND;
3004           *version = 5;
3005           xdnd_precache_atoms (display);
3006           GDK_NOTE (DND, g_message ("Entering local Xdnd window %#x\n", xid));
3007           return xid;
3008         }
3009       else if (_gdk_x11_display_is_root_window (display, (Window) xid))
3010         {
3011           *protocol = GDK_DRAG_PROTO_ROOTWIN;
3012           GDK_NOTE (DND, g_message ("Entering root window\n"));
3013           return xid;
3014         }
3015                
3016         return None;
3017     }
3018   
3019   if ((retval = xdnd_check_dest (display, xid, version)))
3020     {
3021       *protocol = GDK_DRAG_PROTO_XDND;
3022       xdnd_precache_atoms (display);
3023       GDK_NOTE (DND, g_message ("Entering Xdnd window %#x\n", xid));
3024       return retval;
3025     }
3026   else if ((retval = motif_check_dest (display, xid)))
3027     {
3028       *protocol = GDK_DRAG_PROTO_MOTIF;
3029       GDK_NOTE (DND, g_message ("Entering motif window %#x\n", xid));
3030       return retval;
3031     }
3032   else
3033     {
3034       /* Check if this is a root window */
3035
3036       gboolean rootwin = FALSE;
3037       Atom type = None;
3038       int format;
3039       unsigned long nitems, after;
3040       unsigned char *data;
3041
3042       if (_gdk_x11_display_is_root_window (display, (Window) xid))
3043         rootwin = TRUE;
3044
3045       gdk_error_trap_push ();
3046       
3047       if (!rootwin)
3048         {
3049           if (XGetWindowProperty (GDK_DISPLAY_XDISPLAY (display), xid,
3050                                   gdk_x11_get_xatom_by_name_for_display (display, "ENLIGHTENMENT_DESKTOP"),
3051                                   0, 0, False, AnyPropertyType,
3052                                   &type, &format, &nitems, &after, &data) == Success &&
3053               type != None)
3054             {
3055               XFree (data);
3056               rootwin = TRUE;
3057             }
3058         }
3059
3060       /* Until I find out what window manager the next one is for,
3061        * I'm leaving it commented out. It's supported in the
3062        * xscreensaver sources, though.
3063        */
3064 #if 0
3065       if (!rootwin)
3066         {
3067           if (XGetWindowProperty (gdk_display, win,
3068                                   gdk_x11_get_xatom_by_name ("__SWM_VROOT"),
3069                                   0, 0, False, AnyPropertyType,
3070                                   &type, &format, &nitems, &data) &&
3071               type != None)
3072             {
3073               XFree (data);
3074               rootwin = TRUE;
3075             }
3076         }
3077 #endif      
3078
3079       gdk_error_trap_pop ();
3080
3081       if (rootwin)
3082         {
3083           GDK_NOTE (DND, g_message ("Entering root window\n"));
3084           *protocol = GDK_DRAG_PROTO_ROOTWIN;
3085           return xid;
3086         }
3087     }
3088
3089   *protocol = GDK_DRAG_PROTO_NONE;
3090   return None;
3091 }
3092
3093 /**
3094  * gdk_drag_get_protocol_for_display:
3095  * @display: the #GdkDisplay where the destination window resides
3096  * @xid: the X id of the destination window.
3097  * @protocol: location where the supported DND protocol is returned.
3098  * @returns: the X id of the window where the drop should happen. This 
3099  *     may be @xid or the X id of a proxy window, or None if @xid doesn't
3100  *     support Drag and Drop.
3101  *
3102  * Finds out the DND protocol supported by a window.
3103  *
3104  * Since: 2.2
3105  */ 
3106 guint32
3107 gdk_drag_get_protocol_for_display (GdkDisplay      *display,
3108                                    guint32          xid,
3109                                    GdkDragProtocol *protocol)
3110 {
3111   return _gdk_drag_get_protocol_for_display (display, xid, protocol, NULL);
3112 }
3113
3114 static GdkWindowCache *
3115 drag_context_find_window_cache (GdkDragContext  *context,
3116                                 GdkScreen       *screen)
3117 {
3118   GdkDragContextPrivateX11 *private = PRIVATE_DATA (context);
3119   GSList *tmp_list;
3120   GdkWindowCache *cache;
3121
3122   for (tmp_list = private->window_caches; tmp_list; tmp_list = tmp_list->next)
3123     {
3124       cache = tmp_list->data;
3125       if (cache->screen == screen)
3126         return cache;
3127     }
3128
3129   cache = gdk_window_cache_new (screen);
3130   private->window_caches = g_slist_prepend (private->window_caches, cache);
3131   
3132   return cache;
3133 }
3134
3135 /**
3136  * gdk_drag_find_window_for_screen:
3137  * @context: a #GdkDragContext
3138  * @drag_window: a window which may be at the pointer position, but
3139  * should be ignored, since it is put up by the drag source as an icon.
3140  * @screen: the screen where the destination window is sought. 
3141  * @x_root: the x position of the pointer in root coordinates.
3142  * @y_root: the y position of the pointer in root coordinates.
3143  * @dest_window: location to store the destination window in.
3144  * @protocol: location to store the DND protocol in.
3145  * 
3146  * Finds the destination window and DND protocol to use at the
3147  * given pointer position. 
3148  *
3149  * This function is called by the drag source to obtain the 
3150  * @dest_window and @protocol parameters for gdk_drag_motion().
3151  *
3152  * Since: 2.2
3153  **/
3154 void
3155 gdk_drag_find_window_for_screen (GdkDragContext  *context,
3156                                  GdkWindow       *drag_window,
3157                                  GdkScreen       *screen,
3158                                  gint             x_root,
3159                                  gint             y_root,
3160                                  GdkWindow      **dest_window,
3161                                  GdkDragProtocol *protocol)
3162 {
3163   GdkDragContextPrivateX11 *private = PRIVATE_DATA (context);
3164   GdkWindowCache *window_cache;
3165   GdkDisplay *display;
3166   Window dest;
3167
3168   g_return_if_fail (context != NULL);
3169
3170   display = GDK_WINDOW_DISPLAY (context->source_window);
3171
3172   window_cache = drag_context_find_window_cache (context, screen);
3173
3174   dest = get_client_window_at_coords (window_cache,
3175                                       drag_window ? 
3176                                       GDK_DRAWABLE_XID (drag_window) : None,
3177                                       x_root, y_root);
3178
3179   if (private->dest_xid != dest)
3180     {
3181       Window recipient;
3182       private->dest_xid = dest;
3183
3184       /* Check if new destination accepts drags, and which protocol */
3185
3186       /* There is some ugliness here. We actually need to pass
3187        * _three_ pieces of information to drag_motion - dest_window,
3188        * protocol, and the XID of the unproxied window. The first
3189        * two are passed explicitely, the third implicitly through
3190        * protocol->dest_xid.
3191        */
3192       if ((recipient = _gdk_drag_get_protocol_for_display (display, dest, 
3193                                                            protocol, &private->version)))
3194         {
3195           *dest_window = gdk_window_lookup_for_display (display, recipient);
3196           if (*dest_window)
3197             g_object_ref (*dest_window);
3198           else
3199             *dest_window = gdk_window_foreign_new_for_display (display, recipient);
3200         }
3201       else
3202         *dest_window = NULL;
3203     }
3204   else
3205     {
3206       *dest_window = context->dest_window;
3207       if (*dest_window)
3208         g_object_ref (*dest_window);
3209       *protocol = context->protocol;
3210     }
3211 }
3212
3213 /**
3214  * gdk_drag_motion:
3215  * @context: a #GdkDragContext.
3216  * @dest_window: the new destination window, obtained by 
3217  *     gdk_drag_find_window().
3218  * @protocol: the DND protocol in use, obtained by gdk_drag_find_window().
3219  * @x_root: the x position of the pointer in root coordinates.
3220  * @y_root: the y position of the pointer in root coordinates.
3221  * @suggested_action: the suggested action.
3222  * @possible_actions: the possible actions.
3223  * @time_: the timestamp for this operation.
3224  * 
3225  * Updates the drag context when the pointer moves or the 
3226  * set of actions changes.
3227  *
3228  * This function is called by the drag source.
3229  * 
3230  * Return value: FIXME
3231  **/
3232 gboolean        
3233 gdk_drag_motion (GdkDragContext *context,
3234                  GdkWindow      *dest_window,
3235                  GdkDragProtocol protocol,
3236                  gint            x_root, 
3237                  gint            y_root,
3238                  GdkDragAction   suggested_action,
3239                  GdkDragAction   possible_actions,
3240                  guint32         time)
3241 {
3242   GdkDragContextPrivateX11 *private = PRIVATE_DATA (context);
3243
3244   g_return_val_if_fail (context != NULL, FALSE);
3245
3246   private->old_actions = context->actions;
3247   context->actions = possible_actions;
3248   
3249   if (private->old_actions != possible_actions)
3250     private->xdnd_actions_set = FALSE;
3251   
3252   if (protocol == GDK_DRAG_PROTO_XDND && private->version == 0)
3253     {
3254       /* This ugly hack is necessary since GTK+ doesn't know about
3255        * the XDND protocol version, and in particular doesn't know 
3256        * that gdk_drag_find_window_for_screen() has the side-effect 
3257        * of setting private->version, and therefore sometimes call
3258        * gdk_drag_motion() without a prior call to 
3259        * gdk_drag_find_window_for_screen(). This happens, e.g.
3260        * when GTK+ is proxying DND events to embedded windows.
3261        */ 
3262       if (dest_window)
3263         {
3264           GdkDisplay *display = GDK_WINDOW_DISPLAY (dest_window);
3265           
3266           xdnd_check_dest (display, 
3267                            GDK_DRAWABLE_XID (dest_window), 
3268                            &private->version);
3269         }
3270     }
3271
3272   /* When we have a Xdnd target, make sure our XdndActionList
3273    * matches the current actions;
3274    */
3275   if (protocol == GDK_DRAG_PROTO_XDND && !private->xdnd_actions_set)
3276     {
3277       if (dest_window)
3278         {
3279           if (gdk_window_get_window_type (dest_window) == GDK_WINDOW_FOREIGN)
3280             xdnd_set_actions (context);
3281           else if (context->dest_window == dest_window)
3282             {
3283               GdkDisplay *display = GDK_WINDOW_DISPLAY (dest_window);
3284               GdkDragContext *dest_context;
3285                     
3286               dest_context = gdk_drag_context_find (display, FALSE,
3287                                                     GDK_DRAWABLE_XID (context->source_window),
3288                                                     GDK_DRAWABLE_XID (dest_window));
3289
3290               if (dest_context)
3291                 {
3292                   dest_context->actions = context->actions;
3293                   PRIVATE_DATA (dest_context)->xdnd_have_actions = TRUE;
3294                 }
3295             }
3296         }
3297     }
3298
3299   if (context->dest_window != dest_window)
3300     {
3301       GdkEvent temp_event;
3302
3303       /* Send a leave to the last destination */
3304       gdk_drag_do_leave (context, time);
3305       private->drag_status = GDK_DRAG_STATUS_DRAG;
3306
3307       /* Check if new destination accepts drags, and which protocol */
3308
3309       if (dest_window)
3310         {
3311           context->dest_window = dest_window;
3312           private->drop_xid = private->dest_xid;
3313           g_object_ref (context->dest_window);
3314           context->protocol = protocol;
3315
3316           switch (protocol)
3317             {
3318             case GDK_DRAG_PROTO_MOTIF:
3319               motif_send_enter (context, time);
3320               break;
3321
3322             case GDK_DRAG_PROTO_XDND:
3323               xdnd_send_enter (context);
3324               break;
3325
3326             case GDK_DRAG_PROTO_ROOTWIN:
3327             case GDK_DRAG_PROTO_NONE:
3328             default:
3329               break;
3330             }
3331           private->old_action = suggested_action;
3332           context->suggested_action = suggested_action;
3333           private->old_actions = possible_actions;
3334         }
3335       else
3336         {
3337           context->dest_window = NULL;
3338           private->drop_xid = None;
3339           context->action = 0;
3340         }
3341
3342       /* Push a status event, to let the client know that
3343        * the drag changed 
3344        */
3345
3346       temp_event.dnd.type = GDK_DRAG_STATUS;
3347       temp_event.dnd.window = context->source_window;
3348       /* We use this to signal a synthetic status. Perhaps
3349        * we should use an extra field...
3350        */
3351       temp_event.dnd.send_event = TRUE;
3352
3353       temp_event.dnd.context = context;
3354       temp_event.dnd.time = time;
3355
3356       gdk_event_put (&temp_event);
3357     }
3358   else
3359     {
3360       private->old_action = context->suggested_action;
3361       context->suggested_action = suggested_action;
3362     }
3363
3364   /* Send a drag-motion event */
3365
3366   private->last_x = x_root;
3367   private->last_y = y_root;
3368       
3369   if (context->dest_window)
3370     {
3371       if (private->drag_status == GDK_DRAG_STATUS_DRAG)
3372         {
3373           switch (context->protocol)
3374             {
3375             case GDK_DRAG_PROTO_MOTIF:
3376               motif_send_motion (context, x_root, y_root, suggested_action, time);
3377               break;
3378               
3379             case GDK_DRAG_PROTO_XDND:
3380               xdnd_send_motion (context, x_root, y_root, suggested_action, time);
3381               break;
3382
3383             case GDK_DRAG_PROTO_ROOTWIN:
3384               {
3385                 GdkEvent temp_event;
3386                 /* GTK+ traditionally has used application/x-rootwin-drop,
3387                  * but the XDND spec specifies x-rootwindow-drop.
3388                  */
3389                 GdkAtom target1 = gdk_atom_intern_static_string ("application/x-rootwindow-drop");
3390                 GdkAtom target2 = gdk_atom_intern_static_string ("application/x-rootwin-drop");
3391
3392                 if (g_list_find (context->targets,
3393                                  GDK_ATOM_TO_POINTER (target1)) ||
3394                     g_list_find (context->targets,
3395                                  GDK_ATOM_TO_POINTER (target2)))
3396                   context->action = context->suggested_action;
3397                 else
3398                   context->action = 0;
3399
3400                 temp_event.dnd.type = GDK_DRAG_STATUS;
3401                 temp_event.dnd.window = context->source_window;
3402                 temp_event.dnd.send_event = FALSE;
3403                 temp_event.dnd.context = context;
3404                 temp_event.dnd.time = time;
3405
3406                 gdk_event_put (&temp_event);
3407               }
3408               break;
3409             case GDK_DRAG_PROTO_NONE:
3410               g_warning ("GDK_DRAG_PROTO_NONE is not valid in gdk_drag_motion()");
3411               break;
3412             default:
3413               break;
3414             }
3415         }
3416       else
3417         return TRUE;
3418     }
3419
3420   return FALSE;
3421 }
3422
3423 /**
3424  * gdk_drag_drop:
3425  * @context: a #GdkDragContext.
3426  * @time_: the timestamp for this operation.
3427  * 
3428  * Drops on the current destination.
3429  * 
3430  * This function is called by the drag source.
3431  **/
3432 void
3433 gdk_drag_drop (GdkDragContext *context,
3434                guint32         time)
3435 {
3436   g_return_if_fail (context != NULL);
3437
3438   if (context->dest_window)
3439     {
3440       switch (context->protocol)
3441         {
3442         case GDK_DRAG_PROTO_MOTIF:
3443           motif_send_leave (context, time);
3444           motif_send_drop (context, time);
3445           break;
3446           
3447         case GDK_DRAG_PROTO_XDND:
3448           xdnd_send_drop (context, time);
3449           break;
3450
3451         case GDK_DRAG_PROTO_ROOTWIN:
3452           g_warning ("Drops for GDK_DRAG_PROTO_ROOTWIN must be handled internally");
3453           break;
3454         case GDK_DRAG_PROTO_NONE:
3455           g_warning ("GDK_DRAG_PROTO_NONE is not valid in gdk_drag_drop()");
3456           break;
3457         default:
3458           break;
3459         }
3460     }
3461 }
3462
3463 /**
3464  * gdk_drag_abort:
3465  * @context: a #GdkDragContext.
3466  * @time_: the timestamp for this operation.
3467  * 
3468  * Aborts a drag without dropping. 
3469  *
3470  * This function is called by the drag source.
3471  **/
3472 void
3473 gdk_drag_abort (GdkDragContext *context,
3474                 guint32         time)
3475 {
3476   g_return_if_fail (context != NULL);
3477
3478   gdk_drag_do_leave (context, time);
3479 }
3480
3481 /* Destination side */
3482
3483 /**
3484  * gdk_drag_status:
3485  * @context: a #GdkDragContext.
3486  * @action: the selected action which will be taken when a drop happens, 
3487  *    or 0 to indicate that a drop will not be accepted.
3488  * @time_: the timestamp for this operation.
3489  * 
3490  * Selects one of the actions offered by the drag source.
3491  *
3492  * This function is called by the drag destination in response to
3493  * gdk_drag_motion() called by the drag source.
3494  **/
3495 void             
3496 gdk_drag_status (GdkDragContext   *context,
3497                  GdkDragAction     action,
3498                  guint32           time)
3499 {
3500   GdkDragContextPrivateX11 *private;
3501   XEvent xev;
3502   GdkDisplay *display;
3503
3504   g_return_if_fail (context != NULL);
3505
3506   private = PRIVATE_DATA (context);
3507   display = GDK_DRAWABLE_DISPLAY (context->source_window);
3508   
3509   context->action = action;
3510
3511   if (context->protocol == GDK_DRAG_PROTO_MOTIF)
3512     {
3513       gboolean need_coords = FALSE;
3514       
3515       xev.xclient.type = ClientMessage;
3516       xev.xclient.message_type = gdk_x11_get_xatom_by_name_for_display (display,
3517                                                                         "_MOTIF_DRAG_AND_DROP_MESSAGE");
3518       xev.xclient.format = 8;
3519       xev.xclient.window = GDK_DRAWABLE_XID (context->source_window);
3520
3521       if (private->drag_status == GDK_DRAG_STATUS_ACTION_WAIT)
3522         {
3523           MOTIF_XCLIENT_BYTE (&xev, 0) = XmOPERATION_CHANGED | 0x80;
3524         }
3525       else
3526         {
3527           if ((action != 0) != (private->old_action != 0))
3528             {
3529               if (action != 0)
3530                 {
3531                   MOTIF_XCLIENT_BYTE (&xev, 0) = XmDROP_SITE_ENTER | 0x80;
3532                   need_coords = TRUE;
3533                 }
3534               else
3535                 MOTIF_XCLIENT_BYTE (&xev, 0) = XmDROP_SITE_LEAVE | 0x80;
3536             }
3537           else
3538             {
3539               MOTIF_XCLIENT_BYTE (&xev, 0) = XmDRAG_MOTION | 0x80;
3540               need_coords = TRUE;
3541             }
3542         }
3543
3544       MOTIF_XCLIENT_BYTE (&xev, 1) = local_byte_order;
3545
3546       switch (action)
3547         {
3548         case GDK_ACTION_MOVE:
3549           MOTIF_XCLIENT_SHORT (&xev, 1) = XmDROP_MOVE;
3550           break;
3551         case GDK_ACTION_COPY:
3552           MOTIF_XCLIENT_SHORT (&xev, 1) = XmDROP_COPY;
3553           break;
3554         case GDK_ACTION_LINK:
3555           MOTIF_XCLIENT_SHORT (&xev, 1) = XmDROP_LINK;
3556           break;
3557         default:
3558           MOTIF_XCLIENT_SHORT (&xev, 1) = XmDROP_NOOP;
3559           break;
3560         }
3561
3562       if (action)
3563         MOTIF_XCLIENT_SHORT (&xev, 1) |= (XmDROP_SITE_VALID << 4);
3564       else
3565         MOTIF_XCLIENT_SHORT (&xev, 1) |= (XmNO_DROP_SITE << 4);
3566
3567       MOTIF_XCLIENT_LONG (&xev, 1) = time;
3568       
3569       if (need_coords)
3570         {
3571           MOTIF_XCLIENT_SHORT (&xev, 4) = private->last_x;
3572           MOTIF_XCLIENT_SHORT (&xev, 5) = private->last_y;
3573         }
3574       else
3575         MOTIF_XCLIENT_LONG (&xev, 2) = 0;
3576       
3577       MOTIF_XCLIENT_LONG (&xev, 3) = 0;
3578       MOTIF_XCLIENT_LONG (&xev, 4) = 0;
3579
3580       if (!_gdk_send_xevent (display,
3581                              GDK_DRAWABLE_XID (context->source_window),
3582                              FALSE, 0, &xev))
3583         GDK_NOTE (DND, 
3584                   g_message ("Send event to %lx failed",
3585                              GDK_DRAWABLE_XID (context->source_window)));
3586     }
3587   else if (context->protocol == GDK_DRAG_PROTO_XDND)
3588     {
3589       xev.xclient.type = ClientMessage;
3590       xev.xclient.message_type = gdk_x11_get_xatom_by_name_for_display (display, "XdndStatus");
3591       xev.xclient.format = 32;
3592       xev.xclient.window = GDK_DRAWABLE_XID (context->source_window);
3593
3594       xev.xclient.data.l[0] = GDK_DRAWABLE_XID (context->dest_window);
3595       xev.xclient.data.l[1] = (action != 0) ? (2 | 1) : 0;
3596       xev.xclient.data.l[2] = 0;
3597       xev.xclient.data.l[3] = 0;
3598       xev.xclient.data.l[4] = xdnd_action_to_atom (display, action);
3599       
3600       if (!xdnd_send_xevent (context, context->source_window,
3601                              FALSE, &xev))
3602         GDK_NOTE (DND, 
3603                   g_message ("Send event to %lx failed",
3604                              GDK_DRAWABLE_XID (context->source_window)));
3605     }
3606
3607   private->old_action = action;
3608 }
3609
3610 /**
3611  * gdk_drop_reply:
3612  * @context: a #GdkDragContext.
3613  * @ok: %TRUE if the drop is accepted.
3614  * @time_: the timestamp for this operation.
3615  * 
3616  * Accepts or rejects a drop. 
3617  *
3618  * This function is called by the drag destination in response
3619  * to a drop initiated by the drag source.
3620  **/
3621 void 
3622 gdk_drop_reply (GdkDragContext   *context,
3623                 gboolean          ok,
3624                 guint32           time)
3625 {
3626   GdkDragContextPrivateX11 *private;
3627
3628   g_return_if_fail (context != NULL);
3629
3630   private = PRIVATE_DATA (context);
3631   
3632   if (context->protocol == GDK_DRAG_PROTO_MOTIF)
3633     {
3634       GdkDisplay *display = GDK_DRAWABLE_DISPLAY (context->source_window);
3635       XEvent xev;
3636
3637       xev.xclient.type = ClientMessage;
3638       xev.xclient.message_type = gdk_x11_get_xatom_by_name_for_display (display,
3639                                                                         "_MOTIF_DRAG_AND_DROP_MESSAGE");
3640       xev.xclient.format = 8;
3641
3642       MOTIF_XCLIENT_BYTE (&xev, 0) = XmDROP_START | 0x80;
3643       MOTIF_XCLIENT_BYTE (&xev, 1) = local_byte_order;
3644       if (ok)
3645         MOTIF_XCLIENT_SHORT (&xev, 1) = XmDROP_COPY | 
3646                                        (XmDROP_SITE_VALID << 4) |
3647                                        (XmDROP_NOOP << 8) |
3648                                        (XmDROP << 12);
3649       else
3650         MOTIF_XCLIENT_SHORT (&xev, 1) = XmDROP_NOOP | 
3651                                        (XmNO_DROP_SITE << 4) |
3652                                        (XmDROP_NOOP << 8) |
3653                                        (XmDROP_CANCEL << 12);
3654       MOTIF_XCLIENT_SHORT (&xev, 2) = private->last_x;
3655       MOTIF_XCLIENT_SHORT (&xev, 3) = private->last_y;
3656       MOTIF_XCLIENT_LONG (&xev, 2) = 0;
3657       MOTIF_XCLIENT_LONG (&xev, 3) = 0;
3658       MOTIF_XCLIENT_LONG (&xev, 4) = 0;
3659       
3660       _gdk_send_xevent (display,
3661                         GDK_DRAWABLE_XID (context->source_window),
3662                         FALSE, 0, &xev);
3663     }
3664 }
3665
3666 /**
3667  * gdk_drop_finish:
3668  * @context: a #GtkDragContext.
3669  * @success: %TRUE if the data was successfully received.
3670  * @time_: the timestamp for this operation.
3671  * 
3672  * Ends the drag operation after a drop.
3673  *
3674  * This function is called by the drag destination.
3675  **/
3676 void             
3677 gdk_drop_finish (GdkDragContext   *context,
3678                  gboolean          success,
3679                  guint32           time)
3680 {
3681   g_return_if_fail (context != NULL);
3682
3683   if (context->protocol == GDK_DRAG_PROTO_XDND)
3684     {
3685       GdkDisplay *display = GDK_DRAWABLE_DISPLAY (context->source_window);
3686       XEvent xev;
3687
3688       xev.xclient.type = ClientMessage;
3689       xev.xclient.message_type = gdk_x11_get_xatom_by_name_for_display (display, "XdndFinished");
3690       xev.xclient.format = 32;
3691       xev.xclient.window = GDK_DRAWABLE_XID (context->source_window);
3692       
3693       xev.xclient.data.l[0] = GDK_DRAWABLE_XID (context->dest_window);
3694       if (success)
3695         {
3696           xev.xclient.data.l[1] = 1;
3697           xev.xclient.data.l[2] = xdnd_action_to_atom (display, 
3698                                                        context->action);
3699         }
3700       else
3701         {
3702           xev.xclient.data.l[1] = 0;
3703           xev.xclient.data.l[2] = None;
3704         }
3705       xev.xclient.data.l[3] = 0;
3706       xev.xclient.data.l[4] = 0;
3707
3708       if (!xdnd_send_xevent (context, context->source_window,
3709                              FALSE, &xev))
3710         GDK_NOTE (DND, 
3711                   g_message ("Send event to %lx failed",
3712                              GDK_DRAWABLE_XID (context->source_window)));
3713     }
3714 }
3715
3716
3717 void            
3718 gdk_window_register_dnd (GdkWindow      *window)
3719 {
3720   static const gulong xdnd_version = 5;
3721   MotifDragReceiverInfo info;
3722   Atom motif_drag_receiver_info_atom;
3723   GdkDisplay *display = gdk_drawable_get_display (window);
3724
3725   g_return_if_fail (window != NULL);
3726
3727   base_precache_atoms (display);
3728
3729   if (g_object_get_data (G_OBJECT (window), "gdk-dnd-registered") != NULL)
3730     return;
3731   else
3732     g_object_set_data (G_OBJECT (window), "gdk-dnd-registered", GINT_TO_POINTER (TRUE));
3733   
3734   /* Set Motif drag receiver information property */
3735
3736   motif_drag_receiver_info_atom = gdk_x11_get_xatom_by_name_for_display (display,
3737                                                                          "_MOTIF_DRAG_RECEIVER_INFO");
3738   info.byte_order = local_byte_order;
3739   info.protocol_version = 0;
3740   info.protocol_style = XmDRAG_DYNAMIC;
3741   info.proxy_window = None;
3742   info.num_drop_sites = 0;
3743   info.total_size = sizeof(info);
3744
3745   XChangeProperty (GDK_DISPLAY_XDISPLAY (display), GDK_DRAWABLE_XID (window),
3746                    motif_drag_receiver_info_atom,
3747                    motif_drag_receiver_info_atom,
3748                    8, PropModeReplace,
3749                    (guchar *)&info,
3750                    sizeof (info));
3751
3752   /* Set XdndAware */
3753
3754   /* The property needs to be of type XA_ATOM, not XA_INTEGER. Blech */
3755   XChangeProperty (GDK_DISPLAY_XDISPLAY (display),
3756                    GDK_DRAWABLE_XID (window),
3757                    gdk_x11_get_xatom_by_name_for_display (display, "XdndAware"),
3758                    XA_ATOM, 32, PropModeReplace,
3759                    (guchar *)&xdnd_version, 1);
3760 }
3761
3762 /**
3763  * gdk_drag_get_selection:
3764  * @context: a #GdkDragContext.
3765  * 
3766  * Returns the selection atom for the current source window.
3767  * 
3768  * Return value: the selection atom.
3769  **/
3770 GdkAtom
3771 gdk_drag_get_selection (GdkDragContext *context)
3772 {
3773   g_return_val_if_fail (context != NULL, GDK_NONE);
3774
3775   if (context->protocol == GDK_DRAG_PROTO_MOTIF)
3776     return gdk_x11_xatom_to_atom_for_display (GDK_DRAWABLE_DISPLAY (context->source_window),
3777                                               (PRIVATE_DATA (context))->motif_selection);
3778   else if (context->protocol == GDK_DRAG_PROTO_XDND)
3779     return gdk_atom_intern_static_string ("XdndSelection");
3780   else
3781     return GDK_NONE;
3782 }
3783
3784 /**
3785  * gdk_drag_drop_succeeded:
3786  * @context: a #GdkDragContext
3787  * 
3788  * Returns wether the dropped data has been successfully 
3789  * transferred. This function is intended to be used while 
3790  * handling a %GDK_DROP_FINISHED event, its return value is
3791  * meaningless at other times.
3792  * 
3793  * Return value: %TRUE if the drop was successful.
3794  *
3795  * Since: 2.6
3796  **/
3797 gboolean 
3798 gdk_drag_drop_succeeded (GdkDragContext *context)
3799 {
3800   GdkDragContextPrivateX11 *private;
3801
3802   g_return_val_if_fail (context != NULL, FALSE);
3803
3804   private = PRIVATE_DATA (context);
3805
3806   return !private->drop_failed;
3807 }
3808
3809 #define __GDK_DND_X11_C__
3810 #include "gdkaliasdef.c"