gdkdnd-x11.c 103 KB
Newer Older
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 7 8 9 10 11
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * 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 16 17 18
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */
19 20

/*
21
 * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
22 23 24 25 26
 * file for a list of people on the GTK+ Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
 * GTK+ at ftp://ftp.gtk.org/pub/gtk/. 
 */

27
#include <config.h>
28 29 30
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <string.h>
Owen Taylor's avatar
Owen Taylor committed
31 32

#include "gdk.h"          /* For gdk_flush() */
33
#include "gdkx.h"
34
#include "gdkasync.h"
Owen Taylor's avatar
Owen Taylor committed
35 36
#include "gdkdnd.h"
#include "gdkproperty.h"
37
#include "gdkprivate-x11.h"
38 39 40
#include "gdkinternals.h"
#include "gdkscreen-x11.h"
#include "gdkdisplay-x11.h"
41
#include "gdkalias.h"
42

43
typedef struct _GdkDragContextPrivateX11 GdkDragContextPrivateX11;
44

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
typedef enum {
  GDK_DRAG_STATUS_DRAG,
  GDK_DRAG_STATUS_MOTION_WAIT,
  GDK_DRAG_STATUS_ACTION_WAIT,
  GDK_DRAG_STATUS_DROP
} GtkDragStatus;

typedef struct {
  guint32 xid;
  gint x, y, width, height;
  gboolean mapped;
} GdkCacheChild;

typedef struct {
  GList *children;
  GHashTable *child_hash;
  guint old_event_mask;
62
  GdkScreen *screen;
63 64 65 66 67
} GdkWindowCache;

/* Structure that holds information about a drag in progress.
 * this is used on both source and destination sides.
 */
68
struct _GdkDragContextPrivateX11 {
69 70
  GdkDragContext context;

71
  Atom motif_selection;
72 73 74 75
  guint   ref_count;

  guint16 last_x;		/* Coordinates from last event */
  guint16 last_y;
76 77 78
  GdkDragAction old_action;	  /* The last action we sent to the source */
  GdkDragAction old_actions;	  /* The last actions we sent to the source */
  GdkDragAction xdnd_actions;     /* What is currently set in XdndActionList */
79

80 81
  Window dest_xid;              /* The last window we looked up */
  Window drop_xid;            /* The (non-proxied) window that is receiving drops */
82
  guint xdnd_targets_set : 1;   /* Whether we've already set XdndTypeList */
83
  guint xdnd_actions_set : 1;   /* Whether we've already set XdndActionList */
84
  guint xdnd_have_actions : 1;  /* Whether an XdndActionList was provided */
85 86
  guint motif_targets_set : 1;  /* Whether we've already set motif initiator info */
  guint drag_status : 4;	/* current status of drag */
87 88 89
  
  guint drop_failed : 1;        /* Whether the drop was unsuccessful */
  guint version;                /* Xdnd protocol version */
90

91
  GSList *window_caches;
92 93
};

94 95
#define PRIVATE_DATA(context) ((GdkDragContextPrivateX11 *) GDK_DRAG_CONTEXT (context)->windowing_data)

96 97 98 99
/* Forward declarations */

static void gdk_window_cache_destroy (GdkWindowCache *cache);

100 101
static void motif_read_target_table (GdkDisplay *display);

102 103 104 105
static GdkFilterReturn motif_dnd_filter (GdkXEvent *xev,
					 GdkEvent  *event,
					 gpointer   data);

106 107 108 109 110 111
static GdkFilterReturn xdnd_enter_filter    (GdkXEvent *xev,
					     GdkEvent  *event,
					     gpointer   data);
static GdkFilterReturn xdnd_leave_filter    (GdkXEvent *xev,
					     GdkEvent  *event,
					     gpointer   data);
112 113 114
static GdkFilterReturn xdnd_position_filter (GdkXEvent *xev,
					     GdkEvent  *event,
					     gpointer   data);
115 116 117
static GdkFilterReturn xdnd_status_filter   (GdkXEvent *xev,
					     GdkEvent  *event,
					     gpointer   data);
118
static GdkFilterReturn xdnd_finished_filter (GdkXEvent *xev,
119 120 121 122 123
					     GdkEvent  *event,
					     gpointer   data);
static GdkFilterReturn xdnd_drop_filter     (GdkXEvent *xev,
					     GdkEvent  *event,
					     gpointer   data);
124

125 126 127 128
static void   xdnd_manage_source_filter (GdkDragContext *context,
					 GdkWindow      *window,
					 gboolean        add_filter);

129 130 131
static void gdk_drag_context_init       (GdkDragContext      *dragcontext);
static void gdk_drag_context_class_init (GdkDragContextClass *klass);
static void gdk_drag_context_finalize   (GObject              *object);
132

133
static gpointer parent_class = NULL;
134 135
static GList *contexts;

136 137 138
const static struct {
  const char *atom_name;
  GdkFilterFunc func;
139
} const xdnd_filters[] = {
140 141 142 143 144 145 146 147
  { "XdndEnter",    xdnd_enter_filter },
  { "XdndLeave",    xdnd_leave_filter },
  { "XdndPosition", xdnd_position_filter },
  { "XdndStatus",   xdnd_status_filter },
  { "XdndFinished", xdnd_finished_filter },
  { "XdndDrop",     xdnd_drop_filter },
};
	      
148 149
GType
gdk_drag_context_get_type (void)
150
{
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
  static GType object_type = 0;

  if (!object_type)
    {
      static const GTypeInfo object_info =
      {
        sizeof (GdkDragContextClass),
        (GBaseInitFunc) NULL,
        (GBaseFinalizeFunc) NULL,
        (GClassInitFunc) gdk_drag_context_class_init,
        NULL,           /* class_finalize */
        NULL,           /* class_data */
        sizeof (GdkDragContext),
        0,              /* n_preallocs */
        (GInstanceInitFunc) gdk_drag_context_init,
      };
      
      object_type = g_type_register_static (G_TYPE_OBJECT,
169
                                            g_intern_static_string ("GdkDragContext"),
170
                                            &object_info, 0);
171 172 173 174
    }
  
  return object_type;
}
175

176 177 178 179
static void
gdk_drag_context_init (GdkDragContext *dragcontext)
{
  GdkDragContextPrivateX11 *private;
180

181
  private = g_new0 (GdkDragContextPrivateX11, 1);
182

183
  dragcontext->windowing_data = private;
184

185
  contexts = g_list_prepend (contexts, dragcontext);
186 187
}

188 189
static void
gdk_drag_context_class_init (GdkDragContextClass *klass)
190
{
191 192 193
  GObjectClass *object_class = G_OBJECT_CLASS (klass);

  parent_class = g_type_class_peek_parent (klass);
Jeff Garzik's avatar
Jeff Garzik committed
194

195
  object_class->finalize = gdk_drag_context_finalize;
196 197
}

198 199
static void
gdk_drag_context_finalize (GObject *object)
200
{
201 202
  GdkDragContext *context = GDK_DRAG_CONTEXT (object);
  GdkDragContextPrivateX11 *private = PRIVATE_DATA (context);
203
  GSList *tmp_list;
204
  
205 206 207
  g_list_free (context->targets);

  if (context->source_window)
208
    {
209 210 211
      if ((context->protocol == GDK_DRAG_PROTO_XDND) &&
          !context->is_source)
        xdnd_manage_source_filter (context, context->source_window, FALSE);
212
      
213
      g_object_unref (context->source_window);
214 215 216
    }
  
  if (context->dest_window)
217
    g_object_unref (context->dest_window);
218 219 220 221

  for (tmp_list = private->window_caches; tmp_list; tmp_list = tmp_list->next)
    gdk_window_cache_destroy (tmp_list->data);
  g_slist_free (private->window_caches);
222 223
  
  contexts = g_list_remove (contexts, context);
224

225 226 227 228
  g_free (private);
  
  G_OBJECT_CLASS (parent_class)->finalize (object);
}
229

230 231
/* Drag Contexts */

232 233 234 235 236 237 238
/**
 * gdk_drag_context_new:
 * 
 * Creates a new #GdkDragContext.
 * 
 * Return value: the newly created #GdkDragContext.
 **/
239 240 241
GdkDragContext *
gdk_drag_context_new        (void)
{
242
  return g_object_new (gdk_drag_context_get_type (), NULL);
243 244
}

245 246 247 248 249 250
/**
 * gdk_drag_context_ref:
 * @context: a #GdkDragContext.
 * 
 * Deprecated function; use g_object_ref() instead.
 **/
251 252 253 254
void            
gdk_drag_context_ref (GdkDragContext *context)
{
  g_return_if_fail (GDK_IS_DRAG_CONTEXT (context));
255

256
  g_object_ref (context);
257
}
258

259 260 261 262 263 264
/**
 * gdk_drag_context_unref:
 * @context: a #GdkDragContext.
 * 
 * Deprecated function; use g_object_unref() instead.
 **/
265 266 267 268
void            
gdk_drag_context_unref (GdkDragContext *context)
{
  g_return_if_fail (GDK_IS_DRAG_CONTEXT (context));
269

270
  g_object_unref (context);
271 272 273
}

static GdkDragContext *
274 275 276 277
gdk_drag_context_find (GdkDisplay *display,
		       gboolean    is_source,
		       Window      source_xid,
		       Window      dest_xid)
278 279
{
  GList *tmp_list = contexts;
Jeff Garzik's avatar
Jeff Garzik committed
280
  GdkDragContext *context;
281
  GdkDragContextPrivateX11 *private;
282
  Window context_dest_xid;
283 284 285

  while (tmp_list)
    {
Jeff Garzik's avatar
Jeff Garzik committed
286
      context = (GdkDragContext *)tmp_list->data;
287
      private = PRIVATE_DATA (context);
288

289 290 291 292
      if ((context->source_window && gdk_drawable_get_display (context->source_window) != display) ||
	  (context->dest_window && gdk_drawable_get_display (context->dest_window) != display))
	continue;

293
      context_dest_xid = context->dest_window ? 
294 295 296 297
                            (private->drop_xid ?
                              private->drop_xid :
                              GDK_DRAWABLE_XID (context->dest_window)) :
	                     None;
298 299 300

      if ((!context->is_source == !is_source) &&
	  ((source_xid == None) || (context->source_window &&
301
	    (GDK_DRAWABLE_XID (context->source_window) == source_xid))) &&
302
	  ((dest_xid == None) || (context_dest_xid == dest_xid)))
303 304 305 306 307 308 309 310
	return context;
      
      tmp_list = tmp_list->next;
    }
  
  return NULL;
}

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
static void
precache_target_list (GdkDragContext *context)
{
  if (context->targets)
    {
      GPtrArray *targets = g_ptr_array_new ();
      GList *tmp_list;
      int i;

      for (tmp_list = context->targets; tmp_list; tmp_list = tmp_list->next)
	g_ptr_array_add (targets, gdk_atom_name (GDK_POINTER_TO_ATOM (tmp_list->data)));

      _gdk_x11_precache_atoms (GDK_WINDOW_DISPLAY (context->source_window),
			       (const gchar **)targets->pdata,
			       targets->len);

      for (i =0; i < targets->len; i++)
	g_free (targets->pdata[i]);

      g_ptr_array_free (targets, TRUE);
    }
}

334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
/* Utility functions */

static void
gdk_window_cache_add (GdkWindowCache *cache,
		      guint32 xid,
		      gint x, gint y, gint width, gint height, 
		      gboolean mapped)
{
  GdkCacheChild *child = g_new (GdkCacheChild, 1);

  child->xid = xid;
  child->x = x;
  child->y = y;
  child->width = width;
  child->height = height;
  child->mapped = mapped;

  cache->children = g_list_prepend (cache->children, child);
  g_hash_table_insert (cache->child_hash, GUINT_TO_POINTER (xid), 
		       cache->children);
}

static GdkFilterReturn
gdk_window_cache_filter (GdkXEvent *xev,
			 GdkEvent  *event,
			 gpointer   data)
{
  XEvent *xevent = (XEvent *)xev;
  GdkWindowCache *cache = data;

  switch (xevent->type)
    {
    case CirculateNotify:
      break;
    case ConfigureNotify:
      {
	XConfigureEvent *xce = &xevent->xconfigure;
	GList *node;

	node = g_hash_table_lookup (cache->child_hash, 
				    GUINT_TO_POINTER (xce->window));
	if (node) 
	  {
	    GdkCacheChild *child = node->data;
	    child->x = xce->x; 
	    child->y = xce->y;
	    child->width = xce->width; 
	    child->height = xce->height;
	    if (xce->above == None && (node->next))
	      {
		GList *last = g_list_last (cache->children);
		cache->children = g_list_remove_link (cache->children, node);
		last->next = node;
		node->next = NULL;
		node->prev = last;
	      }
	    else
	      {
		GList *above_node = g_hash_table_lookup (cache->child_hash, 
							 GUINT_TO_POINTER (xce->above));
394
		if (above_node && node->next != above_node)
395
		  {
396 397
		    /* Put the window above (before in the list) above_node
		     */
398
		    cache->children = g_list_remove_link (cache->children, node);
399 400 401
		    node->prev = above_node->prev;
		    if (node->prev)
		      node->prev->next = node;
402 403
		    else
		      cache->children = node;
404 405
		    node->next = above_node;
		    above_node->prev = node;
406 407 408 409 410 411 412 413
		  }
	      }
	  }
	break;
      }
    case CreateNotify:
      {
	XCreateWindowEvent *xcwe = &xevent->xcreatewindow;
414

415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
	if (!g_hash_table_lookup (cache->child_hash, 
				  GUINT_TO_POINTER (xcwe->window))) 
	  gdk_window_cache_add (cache, xcwe->window, 
				xcwe->x, xcwe->y, xcwe->width, xcwe->height,
				FALSE);
	break;
      }
    case DestroyNotify:
      {
	XDestroyWindowEvent *xdwe = &xevent->xdestroywindow;
	GList *node;

	node = g_hash_table_lookup (cache->child_hash, 
				    GUINT_TO_POINTER (xdwe->window));
	if (node) 
	  {
	    g_hash_table_remove (cache->child_hash,
				 GUINT_TO_POINTER (xdwe->window));
	    cache->children = g_list_remove_link (cache->children, node);
	    g_free (node->data);
	    g_list_free_1 (node);
	  }
	break;
      }
    case MapNotify:
      {
	XMapEvent *xme = &xevent->xmap;
	GList *node;

	node = g_hash_table_lookup (cache->child_hash, 
				    GUINT_TO_POINTER (xme->window));
	if (node) 
	  {
	    GdkCacheChild *child = node->data;
	    child->mapped = TRUE;
	  }
	break;
      }
    case ReparentNotify:
      break;
    case UnmapNotify:
      {
	XMapEvent *xume = &xevent->xmap;
	GList *node;

	node = g_hash_table_lookup (cache->child_hash, 
				    GUINT_TO_POINTER (xume->window));
	if (node) 
	  {
	    GdkCacheChild *child = node->data;
	    child->mapped = FALSE;
	  }
	break;
      }
    default:
      return GDK_FILTER_CONTINUE;
    }
  return GDK_FILTER_REMOVE;
}

static GdkWindowCache *
476
gdk_window_cache_new (GdkScreen *screen)
477 478
{
  XWindowAttributes xwa;
479 480
  Display *xdisplay = GDK_SCREEN_XDISPLAY (screen);
  GdkWindow *root_window = gdk_screen_get_root_window (screen);
481 482
  GdkChildInfoX11 *children;
  guint nchildren, i;
483 484 485 486 487
  
  GdkWindowCache *result = g_new (GdkWindowCache, 1);

  result->children = NULL;
  result->child_hash = g_hash_table_new (g_direct_hash, NULL);
488
  result->screen = screen;
489

490
  XGetWindowAttributes (xdisplay, GDK_WINDOW_XWINDOW (root_window), &xwa);
491
  result->old_event_mask = xwa.your_event_mask;
492
  XSelectInput (xdisplay, GDK_WINDOW_XWINDOW (root_window),
493
		result->old_event_mask | SubstructureNotifyMask);
494
  gdk_window_add_filter (root_window, gdk_window_cache_filter, result);
495

496 497
  if (!_gdk_x11_get_window_child_info (gdk_screen_get_display (screen),
				       GDK_WINDOW_XWINDOW (root_window),
498 499
				       FALSE, NULL,
				       &children, &nchildren))
500
    return result;
501

502 503
  for (i = 0; i < nchildren ; i++)
    {
504 505 506
      gdk_window_cache_add (result, children[i].window,
			    children[i].x, children[i].y, children[i].width, children[i].height,
			    children[i].is_mapped);
507 508
    }

509
  g_free (children);
510 511 512 513 514 515 516

  return result;
}

static void
gdk_window_cache_destroy (GdkWindowCache *cache)
{
517 518 519 520 521 522
  GdkWindow *root_window = gdk_screen_get_root_window (cache->screen);
  
  XSelectInput (GDK_WINDOW_XDISPLAY (root_window), 
		GDK_WINDOW_XWINDOW (root_window),
		cache->old_event_mask);
  gdk_window_remove_filter (root_window, gdk_window_cache_filter, cache);
523 524 525 526

  g_list_foreach (cache->children, (GFunc)g_free, NULL);
  g_list_free (cache->children);
  g_hash_table_destroy (cache->child_hash);
527 528

  g_free (cache);
529 530
}

531 532 533
static Window
get_client_window_at_coords_recurse (GdkDisplay *display,
				     Window      win,
534
				     gboolean    is_toplevel,
535 536 537 538 539 540 541
				     gint        x,
				     gint        y)
{
  GdkChildInfoX11 *children;
  unsigned int nchildren;
  int i;
  gboolean found_child = FALSE;
542
  GdkChildInfoX11 child = { 0, };
543
  gboolean has_wm_state = FALSE;
544 545

  if (!_gdk_x11_get_window_child_info (display, win, TRUE,
546
				       is_toplevel? &has_wm_state : NULL,
547
				       &children, &nchildren))
548
    return None;
549

550
  if (has_wm_state)
551 552 553 554 555
    {
      g_free (children);

      return win;
    }
556

557
  for (i = nchildren - 1; (i >= 0) && !found_child; i--)
558
    {
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
      GdkChildInfoX11 *cur_child = &children[i];
       
      if ((cur_child->is_mapped) && (cur_child->window_class == InputOutput) &&
	  (x >= cur_child->x) && (x < cur_child->x + cur_child->width) &&
	  (y >= cur_child->y) && (y < cur_child->y + cur_child->height))
 	{
	  x -= cur_child->x;
	  y -= cur_child->y;
	  child = *cur_child;
	  found_child = TRUE;
 	}
    }
   
  g_free (children);
 
  if (found_child)
    {
      if (child.has_wm_state)
	return child.window;
      else
579
	return get_client_window_at_coords_recurse (display, child.window, FALSE, x, y);
580
    }
581 582 583 584
  else
    return None;
}

Jeff Garzik's avatar
Jeff Garzik committed
585
static Window 
586
get_client_window_at_coords (GdkWindowCache *cache,
587 588 589
			     Window          ignore,
			     gint            x_root,
			     gint            y_root)
590 591 592 593
{
  GList *tmp_list;
  Window retval = None;

594
  gdk_error_trap_push ();
595 596 597 598 599 600 601 602 603 604 605 606
  
  tmp_list = cache->children;

  while (tmp_list && !retval)
    {
      GdkCacheChild *child = tmp_list->data;

      if ((child->xid != ignore) && (child->mapped))
	{
	  if ((x_root >= child->x) && (x_root < child->x + child->width) &&
	      (y_root >= child->y) && (y_root < child->y + child->height))
	    {
607 608 609 610
	      retval = get_client_window_at_coords_recurse (gdk_screen_get_display (cache->screen),
							    child->xid, TRUE,
							    x_root - child->x,
							    y_root - child->y);
611 612 613 614 615 616 617 618
	      if (!retval)
		retval = child->xid;
	    }
	  
	}
      tmp_list = tmp_list->next;
    }

619
  gdk_error_trap_pop ();
620 621 622 623
  
  if (retval)
    return retval;
  else
624
    return GDK_WINDOW_XWINDOW (gdk_screen_get_root_window (cache->screen));
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
}

/*************************************************************
 ***************************** MOTIF *************************
 *************************************************************/

/* values used in the message type for Motif DND */
enum {
    XmTOP_LEVEL_ENTER,
    XmTOP_LEVEL_LEAVE,
    XmDRAG_MOTION,
    XmDROP_SITE_ENTER,
    XmDROP_SITE_LEAVE,
    XmDROP_START,
    XmDROP_FINISH,
    XmDRAG_DROP_FINISH,
    XmOPERATION_CHANGED
};

/* Values used to specify type of protocol to use */
enum {
    XmDRAG_NONE,
    XmDRAG_DROP_ONLY,
    XmDRAG_PREFER_PREREGISTER,
    XmDRAG_PREREGISTER,
    XmDRAG_PREFER_DYNAMIC,
    XmDRAG_DYNAMIC,
    XmDRAG_PREFER_RECEIVER
};

/* Operation codes */
enum {
  XmDROP_NOOP,
  XmDROP_MOVE = 0x01,
  XmDROP_COPY = 0x02,
  XmDROP_LINK = 0x04
};

/* Drop site status */
enum {
  XmNO_DROP_SITE = 0x01,
  XmDROP_SITE_INVALID = 0x02,
  XmDROP_SITE_VALID = 0x03
};

/* completion status */
enum {
  XmDROP,
  XmDROP_HELP,
  XmDROP_CANCEL,
  XmDROP_INTERRUPT
};

/* Byte swapping routines. The motif specification leaves it
 * up to us to save a few bytes in the client messages
 */
static gchar local_byte_order = '\0';

#ifdef G_ENABLE_DEBUG
static void
print_target_list (GList *targets)
{
  while (targets)
    {
689
      gchar *name = gdk_atom_name (GDK_POINTER_TO_ATOM (targets->data));
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
      g_message ("\t%s", name);
      g_free (name);
      targets = targets->next;
    }
}
#endif /* G_ENABLE_DEBUG */

static void
init_byte_order (void)
{
  guint32 myint = 0x01020304;
  local_byte_order = (*(gchar *)&myint == 1) ? 'B' : 'l';
}

static guint16
card16_to_host (guint16 x, gchar byte_order) {
  if (byte_order == local_byte_order)
    return x;
  else
    return (x << 8) | (x >> 8);
}

static guint32
card32_to_host (guint32 x, gchar byte_order) {
  if (byte_order == local_byte_order)
    return x;
  else
    return (x << 24) | ((x & 0xff00) << 8) | ((x & 0xff0000) >> 8) | (x >> 24);
}

720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
/* Motif packs together fields of varying length into the
 * client message. We can't rely on accessing these
 * through data.s[], data.l[], etc, because on some architectures
 * (i.e., Alpha) these won't be valid for format == 8. 
 */

#define MOTIF_XCLIENT_BYTE(xevent,i) \
  (xevent)->xclient.data.b[i]
#define MOTIF_XCLIENT_SHORT(xevent,i) \
  ((gint16 *)&((xevent)->xclient.data.b[0]))[i]
#define MOTIF_XCLIENT_LONG(xevent,i) \
  ((gint32 *)&((xevent)->xclient.data.b[0]))[i]

#define MOTIF_UNPACK_BYTE(xevent,i) MOTIF_XCLIENT_BYTE(xevent,i)
#define MOTIF_UNPACK_SHORT(xevent,i) \
  card16_to_host (MOTIF_XCLIENT_SHORT(xevent,i), MOTIF_XCLIENT_BYTE(xevent, 1))
#define MOTIF_UNPACK_LONG(xevent,i) \
  card32_to_host (MOTIF_XCLIENT_LONG(xevent,i), MOTIF_XCLIENT_BYTE(xevent, 1))
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770

/***** Dest side ***********/

/* Property placed on source windows */
typedef struct _MotifDragInitiatorInfo {
  guint8 byte_order;
  guint8 protocol_version;
  guint16 targets_index;
  guint32 selection_atom;
} MotifDragInitiatorInfo;

/* Header for target table on the drag window */
typedef struct _MotifTargetTableHeader {
  guchar byte_order;
  guchar protocol_version;
  guint16 n_lists;
  guint32 total_size;
} MotifTargetTableHeader;

/* Property placed on target windows */
typedef struct _MotifDragReceiverInfo {
  guint8 byte_order;
  guint8 protocol_version;
  guint8 protocol_style;
  guint8 pad;
  guint32 proxy_window;
  guint16 num_drop_sites;
  guint16 padding;
  guint32 total_size;
} MotifDragReceiverInfo;

/* Target table handling */

771
static GdkFilterReturn
772 773 774 775 776
motif_drag_window_filter (GdkXEvent *xevent,
			  GdkEvent  *event,
			  gpointer data)
{
  XEvent *xev = (XEvent *)xevent;
777 778
  GdkDisplay *display = GDK_WINDOW_DISPLAY (event->any.window); 
  GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (display);
779 780 781 782

  switch (xev->xany.type)
    {
    case DestroyNotify:
783 784
      display_x11->motif_drag_window = None;
      display_x11->motif_drag_gdk_window = NULL;
785 786
      break;
    case PropertyNotify:
787 788 789
      if (display_x11->motif_target_lists &&
	  (xev->xproperty.atom == gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_TARGETS")))
	motif_read_target_table (display);
790 791 792 793 794 795
      break;
    }
  return GDK_FILTER_REMOVE;
}

static Window
796 797
motif_lookup_drag_window (GdkDisplay *display,
			  Display    *lookup_xdisplay)
798 799 800
{
  Window retval = None;
  gulong bytes_after, nitems;
801
  Atom type;
802 803 804
  gint format;
  guchar *data;

805
  XGetWindowProperty (lookup_xdisplay, RootWindow (lookup_xdisplay, 0),
806
		      gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_WINDOW"),
807
		      0, 1, FALSE,
808 809 810
		      XA_WINDOW, &type, &format, &nitems, &bytes_after,
		      &data);
  
811
  if ((format == 32) && (nitems == 1) && (bytes_after == 0))
812 813
    {
      retval = *(Window *)data;
814 815
      GDK_NOTE (DND, 
		g_message ("Found drag window %#lx\n", GDK_DISPLAY_X11 (display)->motif_drag_window));
816 817 818 819 820 821 822 823 824 825 826
    }

  if (type != None)
    XFree (data);

  return retval;
}

/* Finds the window where global Motif drag information is stored.
 * If it doesn't exist and 'create' is TRUE, create one.
 */
827
static Window 
828 829
motif_find_drag_window (GdkDisplay *display,
			gboolean    create)
830
{
831 832 833
  GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (display);
  
  if (!display_x11->motif_drag_window)
834
    {
835 836
      Atom motif_drag_window_atom = gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_WINDOW");
      display_x11->motif_drag_window = motif_lookup_drag_window (display, display_x11->xdisplay);
837
      
838
      if (!display_x11->motif_drag_window && create)
839 840 841
	{
	  /* Create a persistant window. (Copied from LessTif) */
	  
842
	  Display *persistant_xdisplay;
843
	  XSetWindowAttributes attr;
844 845
	  persistant_xdisplay = XOpenDisplay (gdk_display_get_name (display));
	  XSetCloseDownMode (persistant_xdisplay, RetainPermanent);
846

847
	  XGrabServer (persistant_xdisplay);
848
	  
849
	  display_x11->motif_drag_window = motif_lookup_drag_window (display, persistant_xdisplay);
850

851
	  if (!display_x11->motif_drag_window)
852 853 854 855
	    {
	      attr.override_redirect = True;
	      attr.event_mask = PropertyChangeMask;
	      
856 857
	       display_x11->motif_drag_window = 
		XCreateWindow (persistant_xdisplay, 
858
			       RootWindow (persistant_xdisplay, 0),
859
			      -100, -100, 10, 10, 0, 0,
Matthias Clasen's avatar
Matthias Clasen committed
860
			      InputOnly, (Visual *)CopyFromParent,
861 862 863
			      (CWOverrideRedirect | CWEventMask), &attr);
	      
	      GDK_NOTE (DND,
864
			g_message ("Created drag window %#lx\n", display_x11->motif_drag_window));
865
	      
866
	      XChangeProperty (persistant_xdisplay, 
867
			       RootWindow (persistant_xdisplay, 0),
868 869 870 871 872
			       motif_drag_window_atom, XA_WINDOW,
			       32, PropModeReplace,
			       (guchar *)&motif_drag_window_atom, 1);

	    }
873 874
	  XUngrabServer (persistant_xdisplay);
	  XCloseDisplay (persistant_xdisplay);
875 876 877 878 879
	}

      /* There is a miniscule race condition here if the drag window
       * gets destroyed exactly now.
       */
880
      if (display_x11->motif_drag_window)
881
	{
882 883 884
	  display_x11->motif_drag_gdk_window = 
	    gdk_window_foreign_new_for_display (display, display_x11->motif_drag_window);
	  gdk_window_add_filter (display_x11->motif_drag_gdk_window,
885 886 887 888 889
				 motif_drag_window_filter,
				 NULL);
	}
    }

890
  return display_x11->motif_drag_window;
891 892 893
}

static void 
894
motif_read_target_table (GdkDisplay *display)
895
{
896
  GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (display);
897
  gulong bytes_after, nitems;
898
  Atom type;
899 900
  gint format;
  gint i, j;
901 902
  
  Atom motif_drag_targets_atom = gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_TARGETS");
903

904
  if (display_x11->motif_target_lists)
905
    {
906 907
      for (i=0; i<display_x11->motif_n_target_lists; i++)
	g_list_free (display_x11->motif_target_lists[i]);
908
      
909 910 911
      g_free (display_x11->motif_target_lists);
      display_x11->motif_target_lists = NULL;
      display_x11->motif_n_target_lists = 0;
912 913
    }

914
  if (motif_find_drag_window (display, FALSE))
915
    {
916
      guchar *data;
917 918 919 920 921
      MotifTargetTableHeader *header = NULL;
      guchar *target_bytes = NULL;
      guchar *p;
      gboolean success = FALSE;

Owen Taylor's avatar
Owen Taylor committed
922
      gdk_error_trap_push ();
923 924
      XGetWindowProperty (display_x11->xdisplay, 
			  display_x11->motif_drag_window, 
925 926 927 928
			  motif_drag_targets_atom,
			  0, (sizeof(MotifTargetTableHeader)+3)/4, FALSE,
			  motif_drag_targets_atom, 
			  &type, &format, &nitems, &bytes_after,
929
			  &data);
930

Owen Taylor's avatar
Owen Taylor committed
931
      if (gdk_error_trap_pop () || (format != 8) || (nitems < sizeof (MotifTargetTableHeader)))
932 933
	goto error;

934 935
      header = (MotifTargetTableHeader *)data;

936 937 938
      header->n_lists = card16_to_host (header->n_lists, header->byte_order);
      header->total_size = card32_to_host (header->total_size, header->byte_order);

Owen Taylor's avatar
Owen Taylor committed
939
      gdk_error_trap_push ();
940 941 942
      XGetWindowProperty (display_x11->xdisplay, 
			  display_x11->motif_drag_window, 
		          motif_drag_targets_atom,
943
			  (sizeof(MotifTargetTableHeader)+3)/4, 
944
			  (header->total_size + 3)/4 - (sizeof(MotifTargetTableHeader) + 3)/4,
945 946 947 948
			  FALSE,
			  motif_drag_targets_atom, &type, &format, &nitems, 
			  &bytes_after, &target_bytes);
      
Owen Taylor's avatar
Owen Taylor committed
949
      if (gdk_error_trap_pop () || (format != 8) || (bytes_after != 0) || 
950 951 952
	  (nitems != header->total_size - sizeof(MotifTargetTableHeader)))
	  goto error;

953 954
      display_x11->motif_n_target_lists = header->n_lists;
      display_x11->motif_target_lists = g_new0 (GList *, display_x11->motif_n_target_lists);
955 956 957 958 959 960 961 962 963 964 965

      p = target_bytes;
      for (i=0; i<header->n_lists; i++)
	{
	  gint n_targets;
	  guint32 *targets;
	  
	  if (p + sizeof(guint16) - target_bytes > nitems)
	    goto error;

	  n_targets = card16_to_host (*(gushort *)p, header->byte_order);
966 967 968 969 970 971

	  /* We need to make a copy of the targets, since it may
	   * be unaligned
	   */
	  targets = g_new (guint32, n_targets);
	  memcpy (targets, p + sizeof(guint16), sizeof(guint32) * n_targets);
972 973 974 975 976 977

	  p +=  sizeof(guint16) + n_targets * sizeof(guint32);
	  if (p - target_bytes > nitems)
	    goto error;

	  for (j=0; j<n_targets; j++)
978 979 980
	    display_x11->motif_target_lists[i] = 
	      g_list_prepend (display_x11->motif_target_lists[i],
			      GUINT_TO_POINTER (card32_to_host (targets[j],
981
								header->byte_order)));
982
	  g_free (targets);
983
	  display_x11->motif_target_lists[i] = g_list_reverse (display_x11->motif_target_lists[i]);
984 985 986 987 988 989 990 991 992 993 994 995 996
	}

      success = TRUE;
      
    error:
      if (header)
	XFree (header);
      
      if (target_bytes)
	XFree (target_bytes);

      if (!success)
	{
997
	  if (display_x11->motif_target_lists)
998
	    {
999 1000 1001
	      g_free (display_x11->motif_target_lists);
	      display_x11->motif_target_lists = NULL;
	      display_x11->motif_n_target_lists = 0;
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
	    }
	  g_warning ("Error reading Motif target table\n");
	}
    }
}

static gint
targets_sort_func (gconstpointer a, gconstpointer b)
{
  return (GPOINTER_TO_UINT (a) < GPOINTER_TO_UINT (b)) ?
    -1 : ((GPOINTER_TO_UINT (a) > GPOINTER_TO_UINT (b)) ? 1 : 0);
}

/* Check if given (sorted) list is in the targets table */
1016
static gint
1017 1018
motif_target_table_check (GdkDisplay *display,
			  GList      *sorted)
1019
{
1020
  GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (display);
1021 1022 1023
  GList *tmp_list1, *tmp_list2;
  gint i;

1024
  for (i=0; i<display_x11->motif_n_target_lists; i++)
1025
    {
1026
      tmp_list1 = display_x11->motif_target_lists[i];
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
      tmp_list2 = sorted;
      
      while (tmp_list1 && tmp_list2)
	{
	  if (tmp_list1->data != tmp_list2->data)
	    break;

	  tmp_list1 = tmp_list1->next;
	  tmp_list2 = tmp_list2->next;
	}
      if (!tmp_list1 && !tmp_list2)	/* Found it */
	return i;
    }

  return -1;
}

static gint
1045 1046
motif_add_to_target_table (GdkDisplay *display,
			   GList      *targets) /* targets is list of GdkAtom */
1047
{
1048
  GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (display);
1049 1050 1051 1052 1053 1054 1055 1056 1057
  GList *sorted = NULL;
  gint index = -1;
  gint i;
  GList *tmp_list;
  
  /* make a sorted copy of the list */
  
  while (targets)
    {
1058
      Atom xatom = gdk_x11_atom_to_xatom_for_display (display, GDK_POINTER_TO_ATOM (targets->data));
1059
      sorted = g_list_insert_sorted (sorted, GUINT_TO_POINTER (xatom), targets_sort_func);
1060 1061 1062
      targets = targets->next;
    }

1063
  /* First check if it is there already */
1064

1065 1066
  if (display_x11->motif_target_lists)
    index = motif_target_table_check (display, sorted);
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077

  /* We need to grab the server while doing this, to ensure
   * atomiticity. Ugh
   */

  if (index < 0)
    {
      /* We need to make sure that it exists _before_ we grab the
       * server, since we can't open a new connection after we
       * grab the server. 
       */
1078
      motif_find_drag_window (display, TRUE);
1079

1080 1081
      gdk_x11_display_grab (display);
      motif_read_target_table (display);
1082 1083 1084
    
      /* Check again, in case it was added in the meantime */
      
1085
      if (display_x11->motif_target_lists)
1086
	index = motif_target_table_check (display, sorted);
1087 1088 1089 1090 1091 1092 1093 1094 1095

      if (index < 0)
	{
	  guint32 total_size = 0;
	  guchar *data;
	  guchar *p;
	  guint16 *p16;
	  MotifTargetTableHeader *header;
	  
1096
	  if (!display_x11->motif_target_lists)
1097
	    {
1098 1099
	      display_x11->motif_target_lists = g_new (GList *, 1);
	      display_x11->motif_n_target_lists = 1;
1100 1101 1102
	    }
	  else
	    {
1103 1104 1105
	      display_x11->motif_n_target_lists++;
	      display_x11->motif_target_lists = g_realloc (display_x11->motif_target_lists,
							   sizeof(GList *) * display_x11->motif_n_target_lists);
1106
	    }
1107
	  display_x11->motif_target_lists[display_x11->motif_n_target_lists - 1] = sorted;
1108
	  sorted = NULL;
1109
	  index = display_x11->motif_n_target_lists - 1;
1110 1111

	  total_size = sizeof (MotifTargetTableHeader);
1112 1113
	  for (i = 0; i < display_x11->motif_n_target_lists ; i++)
	    total_size += sizeof(guint16) + sizeof(guint32) * g_list_length (display_x11->motif_target_lists[i]);
1114 1115 1116 1117 1118 1119 1120 1121

	  data = g_malloc (total_size);

	  header = (MotifTargetTableHeader *)data;
	  p = data + sizeof(MotifTargetTableHeader);

	  header->byte_order = local_byte_order;
	  header->protocol_version = 0;
1122
	  header->n_lists = display_x11->motif_n_target_lists;
1123 1124
	  header->total_size = total_size;

1125
	  for (i = 0; i < display_x11->motif_n_target_lists ; i++)
1126
	    {
1127
	      guint16 n_targets = g_list_length (display_x11->motif_target_lists[i]);
1128 1129
	      guint32 *targets = g_new (guint32, n_targets);
	      guint32 *p32 = targets;
1130
	      
1131
	      tmp_list = display_x11->motif_target_lists[i];
1132 1133
	      while (tmp_list)
		{
1134 1135
		  *p32 = GPOINTER_TO_UINT (tmp_list->data);
		  
1136
		  tmp_list = tmp_list->next;
1137
		  p32++;
1138
		}
1139 1140 1141 1142 1143 1144 1145 1146 1147

	      p16 = (guint16 *)p;
	      p += sizeof(guint16);

	      memcpy (p, targets, n_targets * sizeof(guint32));

	      *p16 = n_targets;
	      p += sizeof(guint32) * n_targets;
	      g_free (targets);
1148 1149
	    }

1150 1151 1152 1153
	  XChangeProperty (display_x11->xdisplay,
			   display_x11->motif_drag_window,
			   gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_TARGETS"),
			   gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_TARGETS"),
1154 1155 1156
			   8, PropModeReplace,
			   data, total_size);
	}
1157
      gdk_x11_display_ungrab (display);
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
    }

  g_list_free (sorted);
  return index;
}

/* Translate flags */

static void
motif_dnd_translate_flags (GdkDragContext *context, guint16 flags)
{
  guint recommended_op = flags & 0x000f;
  guint possible_ops = (flags & 0x0f0) >> 4;
  
  switch (recommended_op)
    {
    case XmDROP_MOVE:
      context->suggested_action = GDK_ACTION_MOVE;
      break;
    case XmDROP_COPY:
      context->suggested_action = GDK_ACTION_COPY;
      break;
    case XmDROP_LINK:
      context->suggested_action = GDK_ACTION_LINK;
      break;
    default:
      context->suggested_action = GDK_ACTION_COPY;
      break;
    }

  context->actions = 0;
  if (possible_ops & XmDROP_MOVE)
    context->actions |= GDK_ACTION_MOVE;
  if (possible_ops & XmDROP_COPY)
    context->actions |= GDK_ACTION_COPY;
  if (possible_ops & XmDROP_LINK)
    context->actions |= GDK_ACTION_LINK;
}

static guint16
motif_dnd_get_flags (GdkDragContext *context)
{
  guint16 flags = 0;
  
  switch (context->suggested_action)
    {
    case GDK_ACTION_MOVE:
      flags = XmDROP_MOVE;
      break;
    case GDK_ACTION_COPY:
      flags = XmDROP_COPY;
      break;
    case GDK_ACTION_LINK:
      flags = XmDROP_LINK;
      break;
    default:
      flags = XmDROP_NOOP;
      break;
    }
  
  if (context->actions & GDK_ACTION_MOVE)
    flags |= XmDROP_MOVE << 8;
  if (context->actions & GDK_ACTION_COPY)
    flags |= XmDROP_COPY << 8;
  if (context->actions & GDK_ACTION_LINK)
    flags |= XmDROP_LINK << 8;

  return flags;
}

/* Source Side */

static void
motif_set_targets (GdkDragContext *context)
{
1233
  GdkDragContextPrivateX11 *private = PRIVATE_DATA (context);
1234 1235
  MotifDragInitiatorInfo info;
  gint i;
1236 1237
  GdkDisplay *display = GDK_DRAWABLE_DISPLAY (context->source_window);
  
1238 1239 1240
  info.byte_order = local_byte_order;
  info.protocol_version = 0;
  
1241
  info.targets_index = motif_add_to_target_table (display, context->targets);
1242 1243 1244 1245 1246 1247

  for (i=0; ; i++)
    {
      gchar buf[20];
      g_snprintf(buf, 20, "_GDK_SELECTION_%d", i);
      
1248 1249
      private->motif_selection = gdk_x11_get_xatom_by_name_for_display (display, buf);
      if (!XGetSelectionOwner (GDK_DISPLAY_XDISPLAY (display), private->motif_selection))
1250 1251 1252 1253 1254
	break;
    }

  info.selection_atom = private->motif_selection;

1255 1256
  XChangeProperty (GDK_DRAWABLE_XDISPLAY (context->source_window),
		   GDK_DRAWABLE_XID (context->source_window),
1257
		   private->motif_selection,
1258 1259
		   gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_INITIATOR_INFO"),
		   8, PropModeReplace,
1260 1261 1262 1263 1264
		   (guchar *)&info, sizeof (info));

  private->motif_targets_set = 1;
}

1265
static guint32
1266 1267
motif_check_dest (GdkDisplay *display,
		  Window      win)
1268 1269
{
  gboolean retval = FALSE;
1270
  guchar *data;
1271 1272 1273 1274
  MotifDragReceiverInfo *info;
  Atom type = None;
  int format;
  unsigned long nitems, after;
1275
  Atom motif_drag_receiver_info_atom = gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_RECEIVER_INFO");
1276

Owen Taylor's avatar
Owen Taylor committed
1277
  gdk_error_trap_push ();
1278
  XGetWindowProperty (GDK_DISPLAY_XDISPLAY (display), win, 
1279 1280 1281
		      motif_drag_receiver_info_atom, 
		      0, (sizeof(*info)+3)/4, False, AnyPropertyType,
		      &type, &format, &nitems, &after, 
1282
		      &data);
Owen Taylor's avatar
Owen Taylor committed
1283 1284

  if (gdk_error_trap_pop() == 0)
1285
    {
Owen Taylor's avatar
Owen Taylor committed
1286
      if (type != None)
1287
	{
1288 1289
	  info = (MotifDragReceiverInfo *)data;
	  
Owen Taylor's avatar
Owen Taylor committed
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
	  if ((format == 8) && (nitems == sizeof(*info)))
	    {
	      if ((info->protocol_version == 0) &&
		  ((info->protocol_style == XmDRAG_PREFER_PREREGISTER) ||
		   (info->protocol_style == XmDRAG_PREFER_DYNAMIC) ||
		   (info->protocol_style == XmDRAG_DYNAMIC)))
		retval = TRUE;
	    }
	  else
	    {
	      GDK_NOTE (DND, 
			g_warning ("Invalid Motif drag receiver property on window %ld\n", win));
	    }
	  
	  XFree (info);
1305 1306 1307
	}
    }

1308
  return retval ? win : None;
1309 1310 1311 1312 1313 1314
}

static void
motif_send_enter (GdkDragContext  *context,
		  guint32          time)
{
1315
  GdkDragContextPrivateX11 *private = PRIVATE_DATA (context);
1316 1317
  GdkDisplay *display = GDK_DRAWABLE_DISPLAY (context->source_window);
  XEvent xev;
1318 1319

  xev.xclient.type = ClientMessage;
1320
  xev.xclient.message_type = gdk_x11_get_xatom_by_name_for_display (display, "_MOTIF_DRAG_AND_DROP_MESSAGE");
1321
  xev.xclient.format = 8;
1322
  xev.xclient.window = GDK_DRAWABLE_XID (context->dest_window);