gdkdrag-win32.c 76.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* GDK - The GIMP Drawing Kit
 * Copyright (C) 1995-1999 Peter Mattis, Spencer Kimball and Josh MacDonald
 * Copyright (C) 2001 Archaeopteryx Software Inc.
 * Copyright (C) 1998-2002 Tor Lillqvist
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
 * 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/.
 */

#include "config.h"
#include <string.h>

#include <io.h>
#include <fcntl.h>
32
#include <math.h>
33
34
35
36
37
38
39
40

/*
 * Support for OLE-2 drag and drop added at Archaeopteryx Software, 2001
 * For more information, do not contact Stephan R.A. Deibel (sdeibel@archaeopteryx.com),
 * because the code went through multiple modifications since then.
 *
 * Notes on the implementation:
 *
41
 * Source drag context, IDropSource and IDataObject for it are created
42
43
44
45
46
47
48
49
50
51
52
 * (almost) simultaneously, whereas target drag context and IDropTarget
 * are separated in time - IDropTarget is created when a window is made
 * to accept drops, while target drag context is created when a dragging
 * cursor enters the window and is destroyed when that cursor leaves
 * the window.
 *
 * There's a mismatch between data types supported by W32 (W32 formats)
 * and by GTK+ (GDK contentformats).
 * To account for it the data is transmuted back and forth. There are two
 * main points of transmutation:
 * * GdkWin32HDATAOutputStream: transmutes GTK+ data to W32 data
53
 * * GdkWin32Drop: transmutes W32 data to GTK+ data
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
 *
 * There are also two points where data formats are considered:
 * * When source drag context is created, it gets a list of GDK contentformats
 *   that it supports, these are matched to the W32 formats they
 *   correspond to (possibly with transmutation). New W32 formats for
 *   GTK+-specific contentformats are also created here (see below).
 * * When target drop context is created, it queries the IDataObject
 *   for the list of W32 formats it supports and matches these to
 *   corresponding GDK contentformats that it will be able to provide
 *   (possibly with transmutation) later. Missing GDK contentformats for
 *   W32-specific formats are also created here (see below).
 *
 * W32 formats are integers (CLIPFORMAT), while GTK+ contentformats
 * are mime/type strings, and cannot be used interchangeably.
 *
 * To accommodate advanced GTK+ applications the code allows them to
 * register drop targets that accept W32 data formats, and to register
 * drag sources that provide W32 data formats. To do that they must
 * register with the mime/type "application/x.windows.ZZZ", where
 * ZZZ is the string name of the format in question
 * (for example, "Shell IDList Array") or, for unnamed pre-defined
 * formats, register with the stringified constant name of the format
 * in question (for example, "CF_UNICODETEXT").
 * If such contentformat is accepted/provided, GDK will not try to
 * transmute it to/from something else. Otherwise GDK will do the following
 * transmutation:
 * * If GTK+ application provides image/png, image/gif or image/jpeg,
 *   GDK will claim to also provide "PNG", "GIF" or "JFIF" respectively,
 *   and will pass these along verbatim.
 * * If GTK+ application provides any GdkPixbuf-compatible contentformat,
 *   GDK will also offer "PNG" and CF_DIB W32 formats.
 * * If GTK+ application provides text/plain;charset=utf8, GDK will also offer
 *   CF_UNICODETEXT (UTF-16-encoded) and CF_TEXT (encoded with thread-
 *   and locale-depenant codepage), and will do the conversion when such
 *   data is requested.
 * * If GTK+ application accepts image/png, image/gif or image/jpeg,
 *   GDK will claim to also accept "PNG", "GIF" or "JFIF" respectively,
 *   and will pass these along verbatim.
 * * If GTK+ application accepts image/bmp, GDK will
 *   claim to accept CF_DIB W32 format, and will convert
 *   it, changing the header, when such data is provided.
 * * If GTK+ application accepts text/plain;charset=utf8, GDK will
 *   claim to accept CF_UNICODETEXT and CF_TEXT, and will do
 *   the conversion when such data is provided.
 * * If GTK+ application accepts text/uri-list, GDK will
 *   claim to accept "Shell IDList Array", and will do the
 *   conversion when such data is provided.
 *
 * Currently the conversion from text/uri-list to "Shell IDList Array" is not
 * implemented, so it's not possible to drag & drop files from GTK+
 * applications to non-GTK+ applications the same way one can drag files
 * from Windows Explorer.
 *
 * To increase inter-GTK compatibility, GDK will register GTK+-specific
 * formats by their mime/types, as-is (i.e "text/plain;charset=utf-8", for example).
 * That way two GTK+ applications can exchange data in their native formats
 * (both well-known ones, such as text/plain;charset=utf8, and special,
 * known only to specific applications). This will work just
 * fine as long as both applications agree on what kind of data is stored
 * under such format exactly.
 *
 * Note that clipboard format space is limited, there can only be 16384
 * of them for a particular user session. Therefore it is highly inadvisable
 * to create and register such formats out of the whole cloth, dynamically.
 * If more flexibility is needed, register one format that has some
 * internal indicators of the kind of data it contains, then write the application
 * in such a way that it requests the data and inspects its header before deciding
 * whether to accept it or not. For details see GTK+ drag & drop documentation
 * on the "drag-motion" and "drag-data-received" signals.
 *
 * How managed DnD works:
 * GTK widget detects a drag gesture and calls
 * S: gdk_drag_begin_from_point() -> backend:drag_begin()
 * which creates the source drag context and the drag window,
 * and grabs the pointing device. GDK layer adds the context
 * to a list of currently-active contexts.
 *
 * From that point forward the context gets any events emitted
 * by GDK, and can prevent these events from going anywhere else.
 * They are all handled in
134
 * S: gdk_drag_handle_source_event() -> backend:handle_event()
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
 * (except for wayland backend - it doesn't have that function).
 *
 * That function catches the following events:
 * GDK_MOTION_NOTIFY
 * GDK_BUTTON_RELEASE
 * GDK_KEY_PRESS
 * GDK_KEY_RELEASE
 * GDK_GRAB_BROKEN
 *
 * GDK_MOTION_NOTIFY is emitted by the backend in response to
 * mouse movement.
 * Drag context handles it by calling a bunch of functions to
 * determine the state of the drag actions from the keys being
 * pressed, finding the drag window (another backend function
 * routed through GDK layer) and finally calls
 * S: gdk_drag_motion -> backend:drag_motion()
 * to notify the backend (i.e. itself) that the drag cursor
 * moved.
 * The response to that is to move the drag window and
 * do various bookkeeping.
 * W32: OLE2 protocol does nothing (other than moving the
 * drag window) in response to this, as all the functions
 * that GDK could perform here are already handled by the
 * OS driving the DnD process via DoDragDrop() call.
 * The LOCAL protocol, on the other hande, does a lot,
 * similar to what X11 backend does with XDND - it sends
 * GDK_DRAG_LEAVE and GDK_DRAG_ENTER, emits GDK_DRAG_MOTION.
 *
 * GDK_BUTTON_RELEASE checks the
 * released button - if it's the button that was used to
 * initiate the drag, the "drop-performed" signal is emitted,
 * otherwise the drag is cancelled.
 *
 * GDK_KEY_PRESS and GDK_KEY_RELEASE handler does exactly the same thing as
 * GDK_MOTION_NOTIFY handler, but only after it checks the pressed
 * keys to emit "drop-performed" signal (on Space, Enter etc),
 * cancel the drag (on Escape) or move the drag cursor (arrow keys).
 *
 * GDK_GRAB_BROKEN handler cancels the drag for most broken grabs
 * (except for some special cases where the backend itself does
 *  temporary grabs as part of DnD, such as changing the cursor).
 *
 * GDK_DRAG_ENTER, GDK_DRAG_LEAVE, GDK_DRAG_MOTION and GDK_DROP_START
 * events are emitted when
 * the OS notifies the process about these things happening.
 * For X11 backend that is done in Xdnd event filters,
 * for W32 backend this is done in IDropSource/IDropTarget
 * object methods for the OLE2 protocol, whereas for the
 * LOCAL protocol these events are emitted only by GDK itself
 * (with the exception of WM_DROPFILES message, which causes
 *  GDK to create a drop context and then immediately finish
 *  the drag, providing the list of files it got from the message).
 * 
 */

/* The mingw.org compiler does not export GUIDS in it's import library. To work
 * around that, define INITGUID to have the GUIDS declared. */
#if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
#define INITGUID
#endif

/* For C-style COM wrapper macros */
#define COBJMACROS

199
#include "gdkdrag.h"
200
201
202
203
204
205
#include "gdkproperty.h"
#include "gdkinternals.h"
#include "gdkprivate-win32.h"
#include "gdkwin32.h"
#include "gdkwin32dnd.h"
#include "gdkdisplayprivate.h"
206
#include "gdk/gdkdragprivate.h"
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
#include "gdkwin32dnd-private.h"
#include "gdkdisplay-win32.h"
#include "gdkdeviceprivate.h"
#include "gdkhdataoutputstream-win32.h"

#include <ole2.h>

#include <shlobj.h>
#include <shlguid.h>
#include <objidl.h>
#include "gdkintl.h"

#include <gdk/gdk.h>
#include <glib/gstdio.h>

/* Just to avoid calling RegisterWindowMessage() every time */
static UINT thread_wakeup_message;

typedef struct
{
  IDropSource                     ids;
  IDropSourceNotify               idsn;
  gint                            ref_count;
230
  GdkDrag                        *drag;
231
232

  /* These are thread-local
233
   * copies of the similar fields from GdkWin32Drag
234
   */
235
  GdkWin32DragUtilityData  util_data;
236
237
238
239
240
241
242
243
244

  /* Cached here, so that we don't have to look in
   * the context every time.
   */
  HWND                            source_window_handle;
  guint                           scale;

  /* We get this from the OS via IDropSourceNotify and pass it to the
   * main thread.
245
   * Will be INVALID_HANDLE_VALUE (not NULL!) when unset.
246
247
248
249
250
251
252
   */
  HWND                            dest_window_handle;
} source_drag_context;

typedef struct {
  IDataObject                     ido;
  int                             ref_count;
253
  GdkDrag                        *drag;
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
  GArray                         *formats;
} data_object;

typedef struct {
  IEnumFORMATETC                  ief;
  int                             ref_count;
  int                             ix;
  GArray                         *formats;
} enum_formats;

typedef enum _GdkWin32DnDThreadQueueItemType GdkWin32DnDThreadQueueItemType;

enum _GdkWin32DnDThreadQueueItemType
{
  GDK_WIN32_DND_THREAD_QUEUE_ITEM_GIVE_FEEDBACK = 1,
  GDK_WIN32_DND_THREAD_QUEUE_ITEM_DRAG_INFO = 2,
  GDK_WIN32_DND_THREAD_QUEUE_ITEM_DO_DRAG_DROP = 3,
  GDK_WIN32_DND_THREAD_QUEUE_ITEM_GET_DATA = 4,
  GDK_WIN32_DND_THREAD_QUEUE_ITEM_UPDATE_DRAG_STATE = 5,
};

typedef struct _GdkWin32DnDThreadQueueItem GdkWin32DnDThreadQueueItem;

struct _GdkWin32DnDThreadQueueItem
{
  GdkWin32DnDThreadQueueItemType  item_type;

  /* This is used by the DnD thread to communicate the identity
   * of the drag context to the main thread. This is thread-safe
   * because DnD thread holds a reference to the context.
   */
  gpointer                        opaque_context;
};

typedef struct _GdkWin32DnDThreadDoDragDrop GdkWin32DnDThreadDoDragDrop;

/* This is used both to signal the DnD thread that it needs
 * to call DoDragDrop(), *and* to signal the main thread
 * that the DoDragDrop() call returned.
 */
struct _GdkWin32DnDThreadDoDragDrop
{
  GdkWin32DnDThreadQueueItem  base;

  source_drag_context        *src_context;
  data_object                *src_object;
  DWORD                       allowed_drop_effects;

  DWORD                       received_drop_effect;
  HRESULT                     received_result;
};

typedef struct _GdkWin32DnDThreadGetData GdkWin32DnDThreadGetData;

/* This is used both to signal the main thread that the DnD thread
 * needs DnD data, and to give that data to the DnD thread.
 */
struct _GdkWin32DnDThreadGetData
{
  GdkWin32DnDThreadQueueItem  base;

  GdkWin32ContentFormatPair   pair;
  GdkWin32HDataOutputStream  *stream;

  STGMEDIUM                   produced_data_medium;
};

typedef struct _GdkWin32DnDThreadGiveFeedback GdkWin32DnDThreadGiveFeedback;

struct _GdkWin32DnDThreadGiveFeedback
{
  GdkWin32DnDThreadQueueItem base;

  DWORD                      received_drop_effect;
};

typedef struct _GdkWin32DnDThreadDragInfo GdkWin32DnDThreadDragInfo;

struct _GdkWin32DnDThreadDragInfo
{
  GdkWin32DnDThreadQueueItem base;

  BOOL                       received_escape_pressed;
  DWORD                      received_keyboard_mods;
};

typedef struct _GdkWin32DnDThreadUpdateDragState GdkWin32DnDThreadUpdateDragState;

struct _GdkWin32DnDThreadUpdateDragState
{
  GdkWin32DnDThreadQueueItem base;

346
347
  gpointer                opaque_ddd;
  GdkWin32DragUtilityData produced_util_data;
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
394
395
396
397
398
399
400
401
402
403
404
};

typedef struct _GdkWin32DnDThread GdkWin32DnDThread;

struct _GdkWin32DnDThread
{
  /* We receive instructions from the main thread in this queue */
  GAsyncQueue *input_queue;

  /* We can't peek the queue or "unpop" queue items,
   * so the items that we can't act upon (yet) got
   * to be stored *somewhere*.
   */
  GList       *dequeued_items;

  source_drag_context *src_context;
  data_object         *src_object;
};

/* The code is much more secure if we don't rely on the OS to keep
 * this around for us.
 */
static GdkWin32DnDThread *dnd_thread_data = NULL;

static gboolean
dnd_queue_is_empty ()
{
  return g_atomic_int_get (&_win32_clipdrop->dnd_queue_counter) == 0;
}

static void
decrement_dnd_queue_counter ()
{
  g_atomic_int_dec_and_test (&_win32_clipdrop->dnd_queue_counter);
}

static void
increment_dnd_queue_counter ()
{
  g_atomic_int_inc (&_win32_clipdrop->dnd_queue_counter);
}

static void
free_queue_item (GdkWin32DnDThreadQueueItem *item)
{
  GdkWin32DnDThreadGetData *getdata;

  switch (item->item_type)
    {
    case GDK_WIN32_DND_THREAD_QUEUE_ITEM_DO_DRAG_DROP:
      /* Don't unref anything, it's all done in the main thread,
       * when it receives a DoDragDrop reply.
       */
      break;
    case GDK_WIN32_DND_THREAD_QUEUE_ITEM_UPDATE_DRAG_STATE:
    case GDK_WIN32_DND_THREAD_QUEUE_ITEM_GIVE_FEEDBACK:
    case GDK_WIN32_DND_THREAD_QUEUE_ITEM_DRAG_INFO:
405
      /* These have no data to clean up */
406
407
408
409
410
411
412
413
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
476
477
478
479
480
481
482
483
484
485
486
487
      break;
    case GDK_WIN32_DND_THREAD_QUEUE_ITEM_GET_DATA:
      getdata = (GdkWin32DnDThreadGetData *) item;

      switch (getdata->produced_data_medium.tymed)
        {
        case TYMED_FILE:
        case TYMED_ISTREAM:
        case TYMED_ISTORAGE:
        case TYMED_GDI:
        case TYMED_MFPICT:
        case TYMED_ENHMF:
          g_critical ("Unsupported STGMEDIUM type");
          break;
        case TYMED_NULL:
          break;
        case TYMED_HGLOBAL:
          GlobalFree (getdata->produced_data_medium.hGlobal);
          break;
        }
    }

  g_free (item);
}

static gboolean
process_dnd_queue (gboolean                   timed,
                   guint64                    end_time,
                   GdkWin32DnDThreadGetData  *getdata_check)
{
  GdkWin32DnDThreadQueueItem *item;
  GdkWin32DnDThreadUpdateDragState *updatestate;
  GdkWin32DnDThreadDoDragDrop *ddd;

  while (TRUE)
    {
      if (timed)
        {
          guint64 current_time = g_get_monotonic_time ();

          if (current_time >= end_time)
            break;

          item = g_async_queue_timeout_pop (dnd_thread_data->input_queue, end_time - current_time);
        }
      else
        {
          item = g_async_queue_try_pop (dnd_thread_data->input_queue);
        }

      if (item == NULL)
        break;

      decrement_dnd_queue_counter ();

      switch (item->item_type)
        {
        case GDK_WIN32_DND_THREAD_QUEUE_ITEM_DO_DRAG_DROP:
          /* We don't support more than one DnD at a time */
          free_queue_item (item);
          break;
        case GDK_WIN32_DND_THREAD_QUEUE_ITEM_UPDATE_DRAG_STATE:
          updatestate = (GdkWin32DnDThreadUpdateDragState *) item;
          ddd = (GdkWin32DnDThreadDoDragDrop *) updatestate->opaque_ddd;
          ddd->src_context->util_data = updatestate->produced_util_data;
          free_queue_item (item);
          break;
        case GDK_WIN32_DND_THREAD_QUEUE_ITEM_GET_DATA:
          if (item == (GdkWin32DnDThreadQueueItem *) getdata_check)
            return TRUE;

          free_queue_item (item);
          break;
        case GDK_WIN32_DND_THREAD_QUEUE_ITEM_GIVE_FEEDBACK:
        case GDK_WIN32_DND_THREAD_QUEUE_ITEM_DRAG_INFO:
          g_assert_not_reached ();
        }
    }

  return FALSE;
}

488
void
489
490
_gdk_win32_local_drag_drop_response (GdkDrag        *drag,
                                     GdkDragAction   action)
491
{
492
  GDK_NOTE (DND, g_print ("_gdk_win32_local_drag_drop_response: 0x%p\n",
493
494
495
496
497
498
                          drag));

  g_signal_emit_by_name (drag, "dnd-finished");
  gdk_drag_drop_done (drag, action != 0);
}

499
500
501
502
503
static gboolean
do_drag_drop_response (gpointer user_data)
{
  GdkWin32DnDThreadDoDragDrop *ddd = (GdkWin32DnDThreadDoDragDrop *) user_data;
  HRESULT hr = ddd->received_result;
504
505
  GdkDrag *drag = GDK_DRAG (ddd->base.opaque_context);
  GdkWin32Drag *drag_win32 = GDK_WIN32_DRAG (drag);
506
  GdkWin32Clipdrop *clipdrop = _gdk_win32_clipdrop_get ();
507
  gpointer table_value = g_hash_table_lookup (clipdrop->active_source_drags, drag);
508
509
510
511
512
513
514
515
516

  if (ddd == table_value)
    {
      GDK_NOTE (DND, g_print ("DoDragDrop returned %s with effect %lu\n",
                              (hr == DRAGDROP_S_DROP ? "DRAGDROP_S_DROP" :
                               (hr == DRAGDROP_S_CANCEL ? "DRAGDROP_S_CANCEL" :
                                (hr == E_UNEXPECTED ? "E_UNEXPECTED" :
                                 g_strdup_printf ("%#.8lx", hr)))), ddd->received_drop_effect));

517
      drag_win32->drop_failed = !(SUCCEEDED (hr) || hr == DRAGDROP_S_DROP);
518
519
520
521
522
523

      /* We used to delete the selection here,
       * now GTK does that automatically in response to 
       * the "dnd-finished" signal,
       * if the operation was successful and was a move.
       */
524
525
      GDK_NOTE (DND, g_print ("gdk_dnd_handle_drop_finished: 0x%p\n",
                              drag));
526

527
528
      g_signal_emit_by_name (drag, "dnd-finished");
      gdk_drag_drop_done (drag, !drag_win32->drop_failed);
529
530
531
532
    }
  else
    {
      if (!table_value)
533
        g_critical ("Did not find drag 0x%p in the active drags table", drag);
534
      else
535
        g_critical ("Found drag 0x%p in the active drags table, but the record doesn't match (0x%p != 0x%p)", drag, ddd, table_value);
536
537
538
    }

  /* 3rd parties could keep a reference to this object,
539
   * but we won't keep the drag alive that long.
540
   * Neutralize it (attempts to get its data will fail)
541
   * by nullifying the drag pointer (it doesn't hold
542
543
   * a reference, so no unreffing).
   */
544
  g_clear_object (&ddd->src_object->drag);
545
546
547
548

  IDropSource_Release (&ddd->src_context->ids);
  IDataObject_Release (&ddd->src_object->ido);

549
  g_hash_table_remove (clipdrop->active_source_drags, drag);
550
551
552
553
554
555
  free_queue_item (&ddd->base);

  return G_SOURCE_REMOVE;
}

static void
556
received_drag_context_data (GObject      *drag,
557
558
559
560
561
562
563
                            GAsyncResult *result,
                            gpointer      user_data)
{
  GError *error = NULL;
  GdkWin32DnDThreadGetData *getdata = (GdkWin32DnDThreadGetData *) user_data;
  GdkWin32Clipdrop *clipdrop = _gdk_win32_clipdrop_get ();

564
  if (!gdk_drag_write_finish (GDK_DRAG (drag), result, &error))
565
566
567
568
    {
      HANDLE handle;
      gboolean is_hdata;

569
      GDK_NOTE (DND, g_printerr ("%p: failed to write HData-backed stream: %s\n", drag, error->message));
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
      g_error_free (error);
      g_output_stream_close (G_OUTPUT_STREAM (getdata->stream), NULL, NULL);
      handle = gdk_win32_hdata_output_stream_get_handle (getdata->stream, &is_hdata);

      if (is_hdata)
        API_CALL (GlobalFree, (handle));
      else
        API_CALL (CloseHandle, (handle));
    }
  else
    {
      g_output_stream_close (G_OUTPUT_STREAM (getdata->stream), NULL, NULL);
      getdata->produced_data_medium.tymed = TYMED_HGLOBAL;
      getdata->produced_data_medium.hGlobal = gdk_win32_hdata_output_stream_get_handle (getdata->stream, NULL);
    }

  g_clear_object (&getdata->stream);
  increment_dnd_queue_counter ();
  g_async_queue_push (clipdrop->dnd_queue, getdata);
  API_CALL (PostThreadMessage, (clipdrop->dnd_thread_id, thread_wakeup_message, 0, 0));
}

static gboolean
get_data_response (gpointer user_data)
{
  GdkWin32DnDThreadGetData *getdata = (GdkWin32DnDThreadGetData *) user_data;
  GdkWin32Clipdrop *clipdrop = _gdk_win32_clipdrop_get ();
597
  GdkDrag *drag = GDK_DRAG (getdata->base.opaque_context);
598
  gpointer ddd = g_hash_table_lookup (clipdrop->active_source_drags, drag);
599
600
601
602

  GDK_NOTE (DND, g_print ("idataobject_getdata will request target 0x%p (%s)",
                          getdata->pair.contentformat, getdata->pair.contentformat));

603
  /* This just verifies that we got the right drag,
604
605
606
607
608
609
610
611
612
613
   * we don't need the ddd struct itself.
   */
  if (ddd)
    {
      GError *error = NULL;
      GOutputStream *stream = gdk_win32_hdata_output_stream_new (&getdata->pair, &error);

      if (stream)
        {
          getdata->stream = GDK_WIN32_HDATA_OUTPUT_STREAM (stream);
614
          gdk_drag_write_async (drag,
615
616
617
618
619
620
621
622
623
624
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
689
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
720
721
722
723
724
                                        getdata->pair.contentformat,
                                        stream,
                                        G_PRIORITY_DEFAULT,
                                        NULL,
                                        received_drag_context_data,
                                        getdata);

          return G_SOURCE_REMOVE;
        }
    }

  increment_dnd_queue_counter ();
  g_async_queue_push (clipdrop->dnd_queue, getdata);
  API_CALL (PostThreadMessage, (clipdrop->dnd_thread_id, thread_wakeup_message, 0, 0));

  return G_SOURCE_REMOVE;
}

static void
do_drag_drop (GdkWin32DnDThreadDoDragDrop *ddd)
{
  HRESULT hr;

  dnd_thread_data->src_object = ddd->src_object;
  dnd_thread_data->src_context = ddd->src_context;

  hr = DoDragDrop (&dnd_thread_data->src_object->ido,
                   &dnd_thread_data->src_context->ids,
                   ddd->allowed_drop_effects,
                   &ddd->received_drop_effect);

  ddd->received_result = hr;

  g_idle_add_full (G_PRIORITY_DEFAULT, do_drag_drop_response, ddd, NULL);
}

gpointer
_gdk_win32_dnd_thread_main (gpointer data)
{
  GAsyncQueue *queue = (GAsyncQueue *) data;
  GdkWin32DnDThreadQueueItem *item;
  MSG msg;
  HRESULT hr;

  g_assert (dnd_thread_data == NULL);

  dnd_thread_data = g_new0 (GdkWin32DnDThread, 1);
  dnd_thread_data->input_queue = queue;

  CoInitializeEx (NULL, COINIT_APARTMENTTHREADED);

  hr = OleInitialize (NULL);

  if (!SUCCEEDED (hr))
    g_error ("OleInitialize failed");

  /* Create a message queue */
  PeekMessage (&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);

  thread_wakeup_message = RegisterWindowMessage ("GDK_WORKER_THREAD_WEAKEUP");

  /* Signal the main thread that we're ready.
   * This is the only time the queue works in reverse.
   */
  g_async_queue_push (queue, GUINT_TO_POINTER (GetCurrentThreadId ()));

  while (GetMessage (&msg, NULL, 0, 0))
    {
      if (!dnd_queue_is_empty ())
        {
          while ((item = g_async_queue_try_pop (queue)) != NULL)
            {
              decrement_dnd_queue_counter ();

              if (item->item_type != GDK_WIN32_DND_THREAD_QUEUE_ITEM_DO_DRAG_DROP)
                {
                  free_queue_item (item);
                  continue;
                }

              do_drag_drop ((GdkWin32DnDThreadDoDragDrop *) item);
              API_CALL (PostThreadMessage, (GetCurrentThreadId (), thread_wakeup_message, 0, 0));
              break;
            }
        }

      /* Just to be safe, although this mostly does nothing */
      TranslateMessage (&msg); 
      DispatchMessage (&msg); 
    }

  g_async_queue_unref (queue);
  g_clear_pointer (&dnd_thread_data, g_free);

  OleUninitialize ();
  CoUninitialize ();

  return NULL;
}

/* For the LOCAL protocol */
typedef enum {
  GDK_DRAG_STATUS_DRAG,
  GDK_DRAG_STATUS_MOTION_WAIT,
  GDK_DRAG_STATUS_ACTION_WAIT,
  GDK_DRAG_STATUS_DROP
} GdkDragStatus;

static gboolean use_ole2_dnd = TRUE;

725
static gboolean drag_context_grab (GdkDrag *drag);
726

727
G_DEFINE_TYPE (GdkWin32Drag, gdk_win32_drag, GDK_TYPE_DRAG)
728
729

static void
730
731
732
move_drag_surface (GdkDrag *drag,
                   guint    x_root,
                   guint    y_root)
733
{
734
  GdkWin32Drag *drag_win32 = GDK_WIN32_DRAG (drag);
735
736
737
738

  g_assert (_win32_main_thread == NULL ||
            _win32_main_thread == g_thread_self ());

739
740
741
742
  gdk_surface_move (drag_win32->drag_surface,
                    x_root - drag_win32->hot_x,
                    y_root - drag_win32->hot_y);
  gdk_surface_raise (drag_win32->drag_surface);
743
744
745
}

static void
746
gdk_win32_drag_init (GdkWin32Drag *drag)
747
748
749
750
{
  g_assert (_win32_main_thread == NULL ||
            _win32_main_thread == g_thread_self ());

751
  drag->handle_events = TRUE;
752
  drag->dest_window = INVALID_HANDLE_VALUE;
753

754
  GDK_NOTE (DND, g_print ("gdk_win32_drag_init %p\n", drag));
755
756
757
}

static void
758
gdk_win32_drag_finalize (GObject *object)
759
{
760
761
  GdkDrag *drag;
  GdkWin32Drag *drag_win32;
762
763
764
765
766
  GdkSurface *drag_surface;

  g_assert (_win32_main_thread == NULL ||
            _win32_main_thread == g_thread_self ());

767
  GDK_NOTE (DND, g_print ("gdk_win32_drag_finalize %p\n", object));
768

769
  g_return_if_fail (GDK_IS_WIN32_DRAG (object));
770

771
772
  drag = GDK_DRAG (object);
  drag_win32 = GDK_WIN32_DRAG (drag);
773

774
  gdk_drag_set_cursor (drag, NULL);
775

776
  g_set_object (&drag_win32->grab_surface, NULL);
777
  drag_surface = drag_win32->drag_surface;
778

779
  G_OBJECT_CLASS (gdk_win32_drag_parent_class)->finalize (object);
780
781
782
783
784
785
786

  if (drag_surface)
    gdk_surface_destroy (drag_surface);
}

/* Drag Contexts */

787
788
static GdkDrag *
gdk_drag_new (GdkDisplay         *display,
789
              GdkSurface         *surface,
790
791
792
793
              GdkContentProvider *content,
              GdkDragAction       actions,
              GdkDevice          *device,
              GdkDragProtocol     protocol)
794
{
795
  GdkWin32Drag *drag_win32;
796
  GdkWin32Display *win32_display = GDK_WIN32_DISPLAY (display);
797
  GdkDrag *drag;
798

799
800
801
  drag_win32 = g_object_new (GDK_TYPE_WIN32_DRAG,
                             "device", device,
                             "content", content,
802
803
                             "surface", surface,
                             "actions", actions,
804
                             NULL);
805

806
  drag = GDK_DRAG (drag_win32);
807
808

  if (win32_display->has_fixed_scale)
809
    drag_win32->scale = win32_display->surface_scale;
810
  else
811
    drag_win32->scale = _gdk_win32_display_get_monitor_scale_factor (win32_display, NULL, NULL, NULL);
812

813
  drag_win32->protocol = protocol;
814

815
  return drag;
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
}

#define PRINT_GUID(guid) \
  g_print ("%.08lx-%.04x-%.04x-%.02x%.02x-%.02x%.02x%.02x%.02x%.02x%.02x", \
           ((gulong *)  guid)[0], \
           ((gushort *) guid)[2], \
           ((gushort *) guid)[3], \
           ((guchar *)  guid)[8], \
           ((guchar *)  guid)[9], \
           ((guchar *)  guid)[10], \
           ((guchar *)  guid)[11], \
           ((guchar *)  guid)[12], \
           ((guchar *)  guid)[13], \
           ((guchar *)  guid)[14], \
           ((guchar *)  guid)[15]);

static enum_formats *enum_formats_new (GArray *formats);

834
/* Finds a GdkDrag object that corresponds to a DnD operation
835
 * which is currently targetting the dest_window
836
837
 * Does not give a reference.
 */
838
GdkDrag *
839
_gdk_win32_find_drag_for_dest_window (HWND dest_window)
840
841
{
  GHashTableIter               iter;
842
  GdkWin32Drag                *drag_win32;
843
844
845
846
847
  GdkWin32DnDThreadDoDragDrop *ddd;
  GdkWin32Clipdrop            *clipdrop = _gdk_win32_clipdrop_get ();

  g_hash_table_iter_init (&iter, clipdrop->active_source_drags);

848
  while (g_hash_table_iter_next (&iter, (gpointer *) &drag_win32, (gpointer *) &ddd))
849
    if (ddd->src_context->dest_window_handle == dest_window)
850
      return GDK_DRAG (drag_win32);
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893

  return NULL;
}

static GdkDragAction
action_for_drop_effect (DWORD effect)
{
  GdkDragAction action = 0;

  if (effect & DROPEFFECT_MOVE)
    action |= GDK_ACTION_MOVE;
  if (effect & DROPEFFECT_LINK)
    action |= GDK_ACTION_LINK;
  if (effect & DROPEFFECT_COPY)
    action |= GDK_ACTION_COPY;

  return action;
}

static ULONG STDMETHODCALLTYPE
idropsource_addref (LPDROPSOURCE This)
{
  source_drag_context *ctx = (source_drag_context *) This;

  int ref_count = ++ctx->ref_count;

  GDK_NOTE (DND, g_print ("idropsource_addref %p %d\n", This, ref_count));

  return ref_count;
}

typedef struct _GdkWin32DnDEnterLeaveNotify GdkWin32DnDEnterLeaveNotify;

struct _GdkWin32DnDEnterLeaveNotify
{
  gpointer opaque_context;
  HWND     target_window_handle;
};

static gboolean
notify_dnd_enter (gpointer user_data)
{
  GdkWin32DnDEnterLeaveNotify *notify = (GdkWin32DnDEnterLeaveNotify *) user_data;
894
  GdkWin32Drag *drag_win32 = GDK_WIN32_DRAG (notify->opaque_context);
895

896
  drag_win32->dest_window = notify->target_window_handle;
897
898
899
900
901
902
903
904
905
906

  g_free (notify);

  return G_SOURCE_REMOVE;
}

static gboolean
notify_dnd_leave (gpointer user_data)
{
  GdkWin32DnDEnterLeaveNotify *notify = (GdkWin32DnDEnterLeaveNotify *) user_data;
907
  GdkWin32Drag *drag_win32 = GDK_WIN32_DRAG (notify->opaque_context);
908

909
910
  if (notify->target_window_handle != drag_win32->dest_window)
    g_warning ("DnD leave says that the window handle is 0x%p, but drag has 0x%p", notify->target_window_handle, drag_win32->dest_window);
911

912
  drag_win32->dest_window = INVALID_HANDLE_VALUE;
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934

  g_free (notify);

  return G_SOURCE_REMOVE;
}

static HRESULT STDMETHODCALLTYPE
idropsourcenotify_dragentertarget (IDropSourceNotify *This,
                                   HWND               hwndTarget)
{
  source_drag_context *ctx = (source_drag_context *) (((char *) This) - G_STRUCT_OFFSET (source_drag_context, idsn));
  GdkWin32DnDEnterLeaveNotify *notify;

  if (!dnd_queue_is_empty ())
    process_dnd_queue (FALSE, 0, NULL);

  GDK_NOTE (DND, g_print ("idropsourcenotify_dragentertarget %p (SDC %p) 0x%p\n", This, ctx, hwndTarget));

  ctx->dest_window_handle = hwndTarget;

  notify = g_new0 (GdkWin32DnDEnterLeaveNotify, 1);
  notify->target_window_handle = hwndTarget;
935
  notify->opaque_context = ctx->drag;
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
  g_idle_add_full (G_PRIORITY_DEFAULT, notify_dnd_enter, notify, NULL);

  return S_OK;
}

static HRESULT STDMETHODCALLTYPE
idropsourcenotify_dragleavetarget (IDropSourceNotify *This)
{
  source_drag_context *ctx = (source_drag_context *) (((char *) This) - G_STRUCT_OFFSET (source_drag_context, idsn));
  GdkWin32DnDEnterLeaveNotify *notify;

  if (!dnd_queue_is_empty ())
    process_dnd_queue (FALSE, 0, NULL);

  GDK_NOTE (DND, g_print ("idropsourcenotify_dragleavetarget %p (SDC %p) 0x%p\n", This, ctx, ctx->dest_window_handle));

  notify = g_new0 (GdkWin32DnDEnterLeaveNotify, 1);
  notify->target_window_handle = ctx->dest_window_handle;
954
  ctx->dest_window_handle = INVALID_HANDLE_VALUE;
955
  notify->opaque_context = ctx->drag;
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
  g_idle_add_full (G_PRIORITY_DEFAULT, notify_dnd_leave, notify, NULL);

  return S_OK;
}

static HRESULT STDMETHODCALLTYPE
idropsource_queryinterface (LPDROPSOURCE This,
                            REFIID       riid,
                            LPVOID      *ppvObject)
{
  GDK_NOTE (DND, {
      g_print ("idropsource_queryinterface %p ", This);
      PRINT_GUID (riid);
    });

  *ppvObject = NULL;

  if (IsEqualGUID (riid, &IID_IUnknown))
    {
      GDK_NOTE (DND, g_print ("...IUnknown S_OK\n"));
      idropsource_addref (This);
      *ppvObject = This;
      return S_OK;
    }
  else if (IsEqualGUID (riid, &IID_IDropSource))
    {
      GDK_NOTE (DND, g_print ("...IDropSource S_OK\n"));
      idropsource_addref (This);
      *ppvObject = This;
      return S_OK;
    }
  else if (IsEqualGUID (riid, &IID_IDropSourceNotify))
    {
      GDK_NOTE (DND, g_print ("...IDropSourceNotify S_OK\n"));
      idropsource_addref (This);
      *ppvObject = &((source_drag_context *) This)->idsn;
      return S_OK;
    }
  else
    {
      GDK_NOTE (DND, g_print ("...E_NOINTERFACE\n"));
      return E_NOINTERFACE;
    }
}

static gboolean
unref_context_in_main_thread (gpointer opaque_context)
{
1004
  GdkDrag *drag = GDK_DRAG (opaque_context);
1005

1006
  g_clear_object (&drag);
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021

  return G_SOURCE_REMOVE;
}

static ULONG STDMETHODCALLTYPE
idropsource_release (LPDROPSOURCE This)
{
  source_drag_context *ctx = (source_drag_context *) This;

  int ref_count = --ctx->ref_count;

  GDK_NOTE (DND, g_print ("idropsource_release %p %d\n", This, ref_count));

  if (ref_count == 0)
  {
1022
    g_idle_add (unref_context_in_main_thread, ctx->drag);
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
    g_free (This);
  }

  return ref_count;
}

/* NOTE: This method is called continuously, even if nothing is
 * happening, as long as the drag operation is in progress.
 * It is OK to return a "safe" value (S_OK, to keep the drag
 * operation going) even if something notable happens, because
 * we will have another opportunity to return the "right" value
 * (once we know what it is, after GTK processes the events we
 *  send out) very soon.
 * Note that keyboard-related state in this function is nonsense,
 * as DoDragDrop doesn't get precise information about the keyboard,
 * especially the fEscapePressed argument.
 */
static HRESULT STDMETHODCALLTYPE
idropsource_querycontinuedrag (LPDROPSOURCE This,
                               BOOL         fEscapePressed,
                               DWORD        grfKeyState)
{
  source_drag_context *ctx = (source_drag_context *) This;

1047
  GDK_NOTE (DND, g_print ("idropsource_querycontinuedrag %p esc=%d keystate=0x%lx with state %d\n", This, fEscapePressed, grfKeyState, ctx->util_data.state));
1048
1049
1050
1051

  if (!dnd_queue_is_empty ())
    process_dnd_queue (FALSE, 0, NULL);

1052
1053
  GDK_NOTE (DND, g_print ("idropsource_querycontinuedrag state %d\n", ctx->util_data.state));

1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
  if (ctx->util_data.state == GDK_WIN32_DND_DROPPED)
    {
      GDK_NOTE (DND, g_print ("DRAGDROP_S_DROP\n"));
      return DRAGDROP_S_DROP;
    }
  else if (ctx->util_data.state == GDK_WIN32_DND_NONE)
    {
      GDK_NOTE (DND, g_print ("DRAGDROP_S_CANCEL\n"));
      return DRAGDROP_S_CANCEL;
    }
  else
    {
      GDK_NOTE (DND, g_print ("S_OK\n"));
      return S_OK;
    }
}

1071
static void
1072
maybe_emit_action_changed (GdkWin32Drag        *drag_win32,
1073
1074
1075
1076
1077
                           GdkDragAction        actions)
{
  if (actions != drag_win32->current_action)
    {
      drag_win32->current_action = actions;
Matthias Clasen's avatar
Matthias Clasen committed
1078
      gdk_drag_set_selected_action (GDK_DRAG (drag_win32), actions);
1079
1080
1081
1082
    }
}

void
1083
_gdk_win32_local_drag_give_feedback (GdkDrag        *drag,
1084
1085
                                     GdkDragAction   actions)
{
1086
  GdkWin32Drag *drag_win32 = GDK_WIN32_DRAG (drag);
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096

  if (drag_win32->drag_status == GDK_DRAG_STATUS_MOTION_WAIT)
    drag_win32->drag_status = GDK_DRAG_STATUS_DRAG;

  GDK_NOTE (DND, g_print ("_gdk_win32_local_drag_give_feedback: 0x%p\n",
                          drag));

  maybe_emit_action_changed (drag_win32, actions);
}

1097
1098
1099
1100
1101
1102
1103
1104
1105
static gboolean
give_feedback (gpointer user_data)
{
  GdkWin32DnDThreadGiveFeedback *feedback = (GdkWin32DnDThreadGiveFeedback *) user_data;
  GdkWin32Clipdrop *clipdrop = _gdk_win32_clipdrop_get ();
  gpointer ddd = g_hash_table_lookup (clipdrop->active_source_drags, feedback->base.opaque_context);

  if (ddd)
    {
1106
1107
      GdkDrag *drag = GDK_DRAG (feedback->base.opaque_context);
      GdkWin32Drag *drag_win32 = GDK_WIN32_DRAG (drag);
1108
1109

      GDK_NOTE (DND, g_print ("gdk_dnd_handle_drag_status: 0x%p\n",
1110
                              drag));
1111

Matthias Clasen's avatar
Matthias Clasen committed
1112
      maybe_emit_action_changed (drag_win32, action_for_drop_effect (feedback->received_drop_effect));
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
    }

  free_queue_item (&feedback->base);

  return G_SOURCE_REMOVE;
}

static HRESULT STDMETHODCALLTYPE
idropsource_givefeedback (LPDROPSOURCE This,
                          DWORD        dwEffect)
{
  source_drag_context *ctx = (source_drag_context *) This;
  GdkWin32DnDThreadGiveFeedback *feedback;

  GDK_NOTE (DND, g_print ("idropsource_givefeedback %p with drop effect %lu S_OK\n", This, dwEffect));

  if (!dnd_queue_is_empty ())
    process_dnd_queue (FALSE, 0, NULL);

  feedback = g_new0 (GdkWin32DnDThreadGiveFeedback, 1);
1133
1134
  feedback->base.item_type = GDK_WIN32_DND_THREAD_QUEUE_ITEM_GIVE_FEEDBACK;
  feedback->base.opaque_context = ctx->drag;
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
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
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
  feedback->received_drop_effect = dwEffect;

  g_idle_add_full (G_PRIORITY_DEFAULT, give_feedback, feedback, NULL);

  GDK_NOTE (DND, g_print ("idropsource_givefeedback %p returns\n", This));

  return S_OK;
}

static ULONG STDMETHODCALLTYPE
idataobject_addref (LPDATAOBJECT This)
{
  data_object *dobj = (data_object *) This;
  int ref_count = ++dobj->ref_count;

  GDK_NOTE (DND, g_print ("idataobject_addref %p %d\n", This, ref_count));

  return ref_count;
}

static HRESULT STDMETHODCALLTYPE
idataobject_queryinterface (LPDATAOBJECT This,
                            REFIID       riid,
                            LPVOID      *ppvObject)
{
  GDK_NOTE (DND, {
      g_print ("idataobject_queryinterface %p ", This);
      PRINT_GUID (riid);
    });

  *ppvObject = NULL;

  if (IsEqualGUID (riid, &IID_IUnknown))
    {
      GDK_NOTE (DND, g_print ("...IUnknown S_OK\n"));
      idataobject_addref (This);
      *ppvObject = This;
      return S_OK;
    }
  else if (IsEqualGUID (riid, &IID_IDataObject))
    {
      GDK_NOTE (DND, g_print ("...IDataObject S_OK\n"));
      idataobject_addref (This);
      *ppvObject = This;
      return S_OK;
    }
  else
    {
      GDK_NOTE (DND, g_print ("...E_NOINTERFACE\n"));
      return E_NOINTERFACE;
    }
}

static ULONG STDMETHODCALLTYPE
idataobject_release (LPDATAOBJECT This)
{
  data_object *dobj = (data_object *) This;
  int ref_count = --dobj->ref_count;

  GDK_NOTE (DND, g_print ("idataobject_release %p %d\n", This, ref_count));

  if (ref_count == 0)
    {
      g_array_free (dobj->formats, TRUE);
      g_free (This);
    }

  return ref_count;
}

static HRESULT
query (LPDATAOBJECT                This,
       LPFORMATETC                 pFormatEtc,
       GdkWin32ContentFormatPair **pair)
{
  data_object *ctx = (data_object *) This;
  gint i;

  if (pair)
    *pair = NULL;

  if (!pFormatEtc)
    return DV_E_FORMATETC;

  if (pFormatEtc->lindex != -1)
    return DV_E_LINDEX;

  if ((pFormatEtc->tymed & TYMED_HGLOBAL) == 0)
    return DV_E_TYMED;

  if ((pFormatEtc->dwAspect & DVASPECT_CONTENT) == 0)
    return DV_E_DVASPECT;

  for (i = 0; i < ctx->formats->len; i++)
    {
      GdkWin32ContentFormatPair *p = &g_array_index (ctx->formats, GdkWin32ContentFormatPair, i);
      if (pFormatEtc->cfFormat == p->w32format)
        {
          if (pair)
            *pair = p;

          return S_OK;
        }
    }

  return DV_E_FORMATETC;
}

static HRESULT STDMETHODCALLTYPE
idataobject_getdata (LPDATAOBJECT This,
                     LPFORMATETC  pFormatEtc,
                     LPSTGMEDIUM  pMedium)
{
  data_object *ctx = (data_object *) This;
  HRESULT hr;
  GdkWin32DnDThreadGetData *getdata;
  GdkWin32ContentFormatPair *pair;

1253
  if (ctx->drag == NULL)
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
    return E_FAIL;

  GDK_NOTE (DND, g_print ("idataobject_getdata %p %s ",
                          This, _gdk_win32_cf_to_string (pFormatEtc->cfFormat)));

  /* Check whether we can provide requested format */
  hr = query (This, pFormatEtc, &pair);

  if (hr != S_OK)
    {
      GDK_NOTE (DND, g_print ("Unsupported format, returning 0x%lx\n", hr));
      return hr;
    }

  if (!dnd_queue_is_empty ())
    process_dnd_queue (FALSE, 0, NULL);

  getdata = g_new0 (GdkWin32DnDThreadGetData, 1);
  getdata->base.item_type = GDK_WIN32_DND_THREAD_QUEUE_ITEM_GET_DATA;
1273
  getdata->base.opaque_context = (gpointer) ctx->drag;
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
  getdata->pair = *pair;
  g_idle_add_full (G_PRIORITY_DEFAULT, get_data_response, getdata, NULL);

  if (!process_dnd_queue (TRUE, g_get_monotonic_time () + G_USEC_PER_SEC * 30, getdata))
    return E_FAIL;

  if (getdata->produced_data_medium.tymed == TYMED_NULL)
    {
      free_queue_item (&getdata->base);

      return E_FAIL;
    }

  memcpy (pMedium, &getdata->produced_data_medium, sizeof (*pMedium));

  /* To ensure that the data isn't freed */
  getdata->produced_data_medium.tymed = TYMED_NULL;

  free_queue_item (&getdata->base);

  return S_OK;
}

static HRESULT STDMETHODCALLTYPE
idataobject_getdatahere (LPDATAOBJECT This,
                         LPFORMATETC  pFormatEtc,
                         LPSTGMEDIUM  pMedium)
{
  GDK_NOTE (DND, g_print ("idataobject_getdatahere %p E_NOTIMPL\n", This));

  return E_NOTIMPL;
}

static HRESULT STDMETHODCALLTYPE
idataobject_querygetdata (LPDATAOBJECT This,
                          LPFORMATETC  pFormatEtc)
{
  HRESULT hr;

  g_assert (_win32_main_thread == NULL ||
            _win32_main_thread != g_thread_self ());

  hr = query (This, pFormatEtc, NULL);

  GDK_NOTE (DND,
      g_print ("idataobject_querygetdata %p 0x%08x fmt, %p ptd, %lu aspect, %ld lindex, %0lx tymed - %s, return %#lx (%s)\n",
               This, pFormatEtc->cfFormat, pFormatEtc->ptd, pFormatEtc->dwAspect, pFormatEtc->lindex, pFormatEtc->tymed, _gdk_win32_cf_to_string (pFormatEtc->cfFormat),
               hr, (hr == S_OK) ? "S_OK" : (hr == DV_E_FORMATETC) ? "DV_E_FORMATETC" : (hr == DV_E_LINDEX) ? "DV_E_LINDEX" : (hr == DV_E_TYMED) ? "DV_E_TYMED" : (hr == DV_E_DVASPECT) ? "DV_E_DVASPECT" : "uknown meaning"));

  return hr;
}

static HRESULT STDMETHODCALLTYPE
idataobject_getcanonicalformatetc (LPDATAOBJECT This,
                                   LPFORMATETC  pFormatEtcIn,
                                   LPFORMATETC  pFormatEtcOut)
{
  GDK_NOTE (DND, g_print ("idataobject_getcanonicalformatetc %p E_NOTIMPL\n", This));

  return E_NOTIMPL;
}

static HRESULT STDMETHODCALLTYPE
idataobject_setdata (LPDATAOBJECT This,
                     LPFORMATETC  pFormatEtc,
                     LPSTGMEDIUM  pMedium,
                     BOOL         fRelease)
{
  GDK_NOTE (DND, g_print ("idataobject_setdata %p %s E_NOTIMPL\n",
                          This, _gdk_win32_cf_to_string (pFormatEtc->cfFormat)));

  return E_NOTIMPL;
}

static HRESULT STDMETHODCALLTYPE
idataobject_enumformatetc (LPDATAOBJECT     This,
                           DWORD            dwDirection,
                           LPENUMFORMATETC *ppEnumFormatEtc)
{
  g_assert (_win32_main_thread == NULL ||
            _win32_main_thread != g_thread_self ());

  if (dwDirection != DATADIR_GET)
    {
      GDK_NOTE (DND, g_print ("idataobject_enumformatetc %p E_NOTIMPL", This));

      return E_NOTIMPL;
    }

  *ppEnumFormatEtc = &enum_formats_new (((data_object *) This)->formats)->ief;

  GDK_NOTE (DND, g_print ("idataobject_enumformatetc %p -> %p S_OK", This, *ppEnumFormatEtc));

  return S_OK;
}

static HRESULT STDMETHODCALLTYPE
idataobject_dadvise (LPDATAOBJECT This,
                     LPFORMATETC  pFormatetc,
                     DWORD        advf,
                     LPADVISESINK pAdvSink,
                     DWORD       *pdwConnection)
{
  GDK_NOTE (DND, g_print ("idataobject_dadvise %p E_NOTIMPL\n", This));

  return E_NOTIMPL;
}

static HRESULT STDMETHODCALLTYPE
idataobject_dunadvise (LPDATAOBJECT This,
                       DWORD         dwConnection)
{
  GDK_NOTE (DND, g_print ("idataobject_dunadvise %p E_NOTIMPL\n", This));

  return E_NOTIMPL;
}

static HRESULT STDMETHODCALLTYPE
idataobject_enumdadvise (LPDATAOBJECT    This,
                         LPENUMSTATDATA *ppenumAdvise)
{
  GDK_NOTE (DND, g_print ("idataobject_enumdadvise %p OLE_E_ADVISENOTSUPPORTED\n", This));

  return OLE_E_ADVISENOTSUPPORTED;
}

static ULONG STDMETHODCALLTYPE
ienumformatetc_addref (LPENUMFORMATETC This)
{
  enum_formats *en = (enum_formats *) This;
  int ref_count = ++en->ref_count;

  GDK_NOTE (DND, g_print ("ienumformatetc_addref %p %d\n", This, ref_count));

  return ref_count;
}

static HRESULT STDMETHODCALLTYPE
ienumformatetc_queryinterface (LPENUMFORMATETC This,
                               REFIID          riid,
                               LPVOID         *ppvObject)
{
  GDK_NOTE (DND, {
      g_print ("ienumformatetc_queryinterface %p", This);
      PRINT_GUID (riid);
    });

  *ppvObject = NULL;

  if (IsEqualGUID (riid, &IID_IUnknown))
    {
      GDK_NOTE (DND, g_print ("...IUnknown S_OK\n"));
      ienumformatetc_addref (This);
      *ppvObject = This;
      return S_OK;
    }
  else if (IsEqualGUID (riid, &IID_IEnumFORMATETC))
    {
      GDK_NOTE (DND, g_print ("...IEnumFORMATETC S_OK\n"));
      ienumformatetc_addref (This);
      *ppvObject = This;
      return S_OK;
    }
  else
    {
      GDK_NOTE (DND, g_print ("...E_NOINTERFACE\n"));
      return E_NOINTERFACE;
    }
}

static ULONG STDMETHODCALLTYPE
ienumformatetc_release (LPENUMFORMATETC This)
{
  enum_formats *en = (enum_formats *) This;
  int ref_count = --en->ref_count;

  GDK_NOTE (DND, g_print ("ienumformatetc_release %p %d\n", This, ref_count));

  if (ref_count == 0)
    {
      g_array_unref (en->formats);
      g_free (This);
    }

  return ref_count;
}

static HRESULT STDMETHODCALLTYPE
ienumformatetc_next (LPENUMFORMATETC This,
                     ULONG             celt,
                     LPFORMATETC     elts,
                     ULONG            *nelt)
{
  enum_formats *en = (enum_formats *) This;
  ULONG i, n;
  ULONG formats_to_get = celt;

  GDK_NOTE (DND, g_print ("ienumformatetc_next %p %d %ld ", This, en->ix, celt));

  n = 0;
  for (i = 0; i < formats_to_get; i++)
    {
      UINT fmt;
      if (en->ix >= en->formats->len)
        break;
      fmt = g_array_index (en->formats, GdkWin32ContentFormatPair, en->ix++).w32format;
      /* skip internals */
      if (fmt == 0 || fmt > 0xFFFF)
        {
          formats_to_get += 1;
          continue;
        }
      elts[n].cfFormat = fmt;
      elts[n].ptd = NULL;
      elts[n].dwAspect = DVASPECT_CONTENT;
      elts[n].lindex = -1;
      elts[n].tymed = TYMED_HGLOBAL;

      n++;
    }

  if (nelt != NULL)
    *nelt = n;

  GDK_NOTE (DND, g_print ("%s\n", (n == celt) ? "S_OK" : "S_FALSE"));

  if (n == celt)
    return S_OK;
  else
    return S_FALSE;
}

static HRESULT STDMETHODCALLTYPE
ienumformatetc_skip (LPENUMFORMATETC This,
                     ULONG             celt)
{
  enum_formats *en = (enum_formats *) This;

  GDK_NOTE (DND, g_print ("ienumformatetc_skip %p %d %ld S_OK\n", This, en->ix, celt));

  en->ix += celt;

  return S_OK;
}

static HRESULT STDMETHODCALLTYPE
ienumformatetc_reset (LPENUMFORMATETC This)
{
  enum_formats *en = (enum_formats *) This;

  GDK_NOTE (DND, g_print ("ienumformatetc_reset %p S_OK\n", This));

  en->ix = 0;

  return S_OK;
}

static HRESULT STDMETHODCALLTYPE
ienumformatetc_clone (LPENUMFORMATETC  This,
                      LPENUMFORMATETC *ppEnumFormatEtc)
{
  enum_formats *en = (enum_formats *) This;
  enum_formats *new;

  GDK_NOTE (DND, g_print ("ienumformatetc_clone %p S_OK\n", This));

  new = enum_formats_new (en->formats);

  new->ix = en->ix;

  *ppEnumFormatEtc = &new->ief;

  return S_OK;
}

static IDropSourceVtbl ids_vtbl = {
  idropsource_queryinterface,
  idropsource_addref,
  idropsource_release,
  idropsource_querycontinuedrag,
  idropsource_givefeedback
};

static IDropSourceNotifyVtbl idsn_vtbl = {
  (HRESULT (STDMETHODCALLTYPE *) (IDropSourceNotify *, REFIID , LPVOID *)) idropsource_queryinterface,
  (ULONG (STDMETHODCALLTYPE *) (IDropSourceNotify *)) idropsource_addref,
  (ULONG (STDMETHODCALLTYPE *) (IDropSourceNotify *)) idropsource_release,
  idropsourcenotify_dragentertarget,
  idropsourcenotify_dragleavetarget
};

static IDataObjectVtbl ido_vtbl = {
  idataobject_queryinterface,
  idataobject_addref,
  idataobject_release,
  idataobject_getdata,
  idataobject_getdatahere,
  idataobject_querygetdata,
  idataobject_getcanonicalformatetc,
  idataobject_setdata,
  idataobject_enumformatetc,
  idataobject_dadvise,
  idataobject_dunadvise,
  idataobject_enumdadvise
};

static IEnumFORMATETCVtbl ief_vtbl = {
  ienumformatetc_queryinterface,
  ienumformatetc_addref,
  ienumformatetc_release,
  ienumformatetc_next,
  ienumformatetc_skip,
  ienumformatetc_reset,
  ienumformatetc_clone
};

static source_drag_context *
1591
source_context_new (GdkDrag           *drag,
1592
1593
                    GdkContentFormats *formats)
{
1594
  GdkWin32Drag *drag_win32;
1595
  source_drag_context *result;
1596
  GdkSurface *surface;
1597

1598
  drag_win32 = GDK_WIN32_DRAG (drag);
1599

1600
1601
  g_object_get (drag, "surface", &surface, NULL);

1602
  result = g_new0 (source_drag_context, 1);
1603
  result->drag = g_object_ref (drag);
1604
1605
1606
  result->ids.lpVtbl = &ids_vtbl;
  result->idsn.lpVtbl = &idsn_vtbl;
  result->ref_count = 1;
1607
  result->source_window_handle = GDK_SURFACE_HWND (surface);
1608
  result->scale = drag_win32->scale;
1609
  result->util_data.state = GDK_WIN32_DND_PENDING; /* Implicit */
1610
  result->dest_window_handle = INVALID_HANDLE_VALUE;
1611

1612
1613
  g_object_unref (surface);

1614
  GDK_NOTE (DND, g_print ("source_context_new: %p (drag %p)\n", result, result->drag));
1615
1616
1617
1618
1619

  return result;
}

static data_object *
1620
data_object_new (GdkDrag *drag)
1621
1622
1623
1624
1625
1626
1627
1628
1629
{
  data_object *result;
  const char * const *mime_types;
  gsize n_mime_types, i;

  result = g_new0 (data_object, 1);

  result->ido.lpVtbl = &ido_vtbl;
  result->ref_count = 1;
1630
  result->drag = drag;
1631
1632
  result->formats = g_array_new (FALSE, FALSE, sizeof (GdkWin32ContentFormatPair));

1633
  mime_types = gdk_content_formats_get_mime_types (gdk_drag_get_formats (drag), &n_mime_types);
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672

  for (i = 0; i < n_mime_types; i++)
    {
      gint added_count = 0;
      gint j;

      GDK_NOTE (DND, g_print ("DataObject supports contentformat 0x%p (%s)\n", mime_types[i], mime_types[i]));

      added_count = _gdk_win32_add_contentformat_to_pairs (mime_types[i], result->formats);

      for (j = 0; j < added_count && result->formats->len - 1 - j >= 0; j++)
        GDK_NOTE (DND, g_print ("DataObject will support w32format 0x%x\n", g_array_index (result->formats, GdkWin32ContentFormatPair, j).w32format));
    }

  GDK_NOTE (DND, g_print ("data_object_new: %p\n", result));

  return result;
}

static enum_formats *
enum_formats_new (GArray *formats)
{
  enum_formats *result;

  result = g_new0 (enum_formats, 1);

  result->ief.lpVtbl = &ief_vtbl;
  result->ref_count = 1;
  result->ix = 0;
  result->formats = g_array_ref (formats);

  return result;
}

void
_gdk_drag_init (void)
{
  CoInitializeEx (NULL, COINIT_APARTMENTTHREADED);

1673
1674
  if (g_strcmp0 (getenv ("GDK_WIN32_OLE2_DND"), "0") == 0)
    use_ole2_dnd = FALSE;
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700

  if (use_ole2_dnd)
    {
      HRESULT hr;

      hr = OleInitialize (NULL);

      if (! SUCCEEDED (hr))
        g_error ("OleInitialize failed");
    }
}

void
_gdk_win32_dnd_exit (void)
{
  if (use_ole2_dnd)
    {
      OleUninitialize ();
    }

  CoUninitialize ();
}

static GdkSurface *
create_drag_surface (GdkDisplay *display)
{
1701
  GdkSurface *surface;
1702

1703
  surface = gdk_surface_new_popup (display, &(GdkRectangle) { 0, 0, 100, 100 });
1704

1705
  gdk_surface_set_type_hint (surface, GDK_SURFACE_TYPE_HINT_DND);
1706

1707
  return surface;
1708
1709
}

1710
GdkDrag *
1711
_gdk_win32_surface_drag_begin (GdkSurface         *surface,
1712
1713
1714
1715
1716
1717
                               GdkDevice          *device,
                               GdkContentProvider *content,
                               GdkDragAction       actions,
                               gint                dx,
                               gint                dy)
{
1718
1719
  GdkDrag *drag;
  GdkWin32Drag *drag_win32;
1720
  GdkWin32Clipdrop *clipdrop = _gdk_win32_clipdrop_get ();
1721
  double px, py;
1722
1723
  int x_root, y_root;

1724
  g_return_val_if_fail (surface != NULL, NULL);
1725

1726
  drag = gdk_drag_new (gdk_surface_get_display (surface),
1727
                       surface,
1728
1729
1730
1731
1732
                       content,
                       actions,
                       device,
                       use_ole2_dnd ? GDK_DRAG_PROTO_OLE2 : GDK_DRAG_PROTO_LOCAL);
  drag_win32 = GDK_WIN32_DRAG (drag);
1733

1734
  GDK_NOTE (DND, g_print ("_gdk_win32_surface_drag_begin\n"));
1735

1736
  gdk_device_get_position (device, &px, &py);
1737
1738
  x_root = round (px) + dx;
  y_root = round (py) + dy;
1739

1740
1741
1742
1743
  drag_win32->start_x = x_root;
  drag_win32->start_y = y_root;
  drag_win32->util_data.last_x = drag_win32->start_x;
  drag_win32->util_data.last_y = drag_win32->start_y;
1744

1745
  g_set_object (&drag_win32->grab_surface, surface);
1746

1747
  drag_win32->drag_surface = create_drag_surface (gdk_surface_get_display (surface));
1748

1749
  if (!drag_context_grab (drag))
1750
    {
1751
      g_object_unref (drag);
1752
1753
1754
      return FALSE;
    }

1755
  if (drag_win32->protocol == GDK_DRAG_PROTO_OLE2)
1756
1757
1758
1759
1760
    {
      GdkWin32DnDThreadDoDragDrop *ddd = g_new0 (GdkWin32DnDThreadDoDragDrop, 1);
      source_drag_context *source_ctx;
      data_object         *data_obj;

1761
      source_ctx = source_context_new (drag, gdk_drag_get_formats (drag));
1762
      data_obj = data_object_new (drag);
1763
1764

      ddd->base.item_type = GDK_WIN32_DND_THREAD_QUEUE_ITEM_DO_DRAG_DROP;
1765
      ddd->base.opaque_context = drag_win32;
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
      ddd->src_context = source_ctx;
      ddd->src_object = data_obj;
      ddd->allowed_drop_effects = 0;
      if (actions & GDK_ACTION_COPY)
        ddd->allowed_drop_effects |= DROPEFFECT_COPY;
      if (actions & GDK_ACTION_MOVE)
        ddd->allowed_drop_effects |= DROPEFFECT_MOVE;
      if (actions & GDK_ACTION_LINK)
        ddd->allowed_drop_effects |= DROPEFFECT_LINK;

1776
      g_hash_table_replace (clipdrop->active_source_drags, g_object_ref (drag), ddd);
1777
1778
1779
1780
      increment_dnd_queue_counter ();
      g_async_queue_push (clipdrop->dnd_queue, ddd);
      API_CALL (PostThreadMessage, (clipdrop->dnd_thread_id, thread_wakeup_message, 0, 0));

1781
      drag_win32->util_data.state = GDK_WIN32_DND_PENDING;
1782
1783
    }

1784
  move_drag_surface (drag, x_root, y_root);
1785

1786
  return drag;
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
}

/* TODO: remove this?
 * window finder is only used by our gdk_drag_update() to
 * find the window at drag coordinates - which is
 * something IDropSourceNotify already gives us.
 * Unless, of course, we keep the LOCAL protocol around.
 */
typedef struct {
  gint x;
  gint y;
  HWND ignore;
  HWND result;
} find_window_enum_arg;

static BOOL CALLBACK
find_window_enum_proc (HWND   hwnd,
                       LPARAM lparam)
{
  RECT rect;
  POINT tl, br;
  find_window_enum_arg *a = (find_window_enum_arg *) lparam;

  if (hwnd == a->ignore)
    return TRUE;

  if (!IsWindowVisible (hwnd))
    return TRUE;

  tl.x = tl.y = 0;
  ClientToScreen (hwnd, &tl);
  GetClientRect (hwnd, &rect);
  br.x = rect.right;
  br.y = rect.bottom;
  ClientToScreen (hwnd, &br);

  if (a->x >= tl.x && a->y >= tl.y && a->x < br.x && a->y < br.y)
    {
      a->result = hwnd;
      return FALSE;
    }
  else
    return TRUE;
}

1832
/* Finds the HWND under cursor. Local DnD protcol
1833
1834
1835
1836
 * uses this function, since local protocol is implemented
 * entirely in GDK and cannot rely on the OS to notify
 * drop targets about drags that move over them.
 */
1837
static HWND
1838
1839
1840
1841
gdk_win32_drag_find_window (GdkDrag    *drag,
                            GdkSurface *drag_surface,
                            gint        x_root,
                            gint        y_root)
1842
{
1843
  GdkWin32Drag *drag_win32 = GDK_WIN32_DRAG (drag);
1844
1845
1846
1847
1848
  find_window_enum_arg a;

  g_assert (_win32_main_thread == NULL ||
            _win32_main_thread == g_thread_self ());

1849
1850
  a.x = x_root * drag_win32->scale - _gdk_offset_x;
  a.y = y_root * drag_win32->scale - _gdk_offset_y;
1851
  a.ignore = drag_surface ? GDK_SURFACE_HWND (drag_surface) : NULL;
1852
  a.result = INVALID_HANDLE_VALUE;
1853
1854

  GDK_NOTE (DND,
1855
            g_print ("gdk_win32_drag_find_window: %p %+d%+d\n",
1856
1857
1858
1859
1860
1861
                     (drag_surface ? GDK_SURFACE_HWND (drag_surface) : NULL),
                     a.x, a.y));

  EnumWindows (find_window_enum_proc, (LPARAM) &a);

  GDK_NOTE (DND,
1862
            g_print ("gdk_win32_drag_find_window: %p %+d%+d: %p\n",
1863
1864
                     (drag_surface ? GDK_SURFACE_HWND (drag_surface) : NULL),
                     x_root, y_root,
1865
                     a.result));
1866

1867
  return a.result;
1868
1869
}

1870
1871
static DWORD
manufacture_keystate_from_GMT (GdkModifierType state)
1872
{
1873
  DWORD key_state = 0;
1874

1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
  if (state & GDK_