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