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