gdkselection-win32.c 92.1 KB
Newer Older
1 2
/* GDK - The GIMP Drawing Kit
 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
3
 * Copyright (C) 1998-2002 Tor Lillqvist
4 5
 *
 * This library is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU Lesser General Public
7 8 9 10 11 12
 * 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
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public
Javier Jardon's avatar
Javier Jardon committed
16
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
17 18 19
 */

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

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 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 134 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 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
/*
GTK+ selection works like this:
There are three selections that matter - GDK_SELECTION_CLIPBOARD,
GDK_SELECTION_PRIMARY and DND. Primary selection is only handled
internally by GTK+ (it's not portable to Windows). DND is actually
represented by two selections - LOCAL and OLE2, one for each DnD protocol,
but they work the same way.

"Target" is a GdkAtom describing a clipboard format.

For Clipboard:
GTK+ calls gtk_clipboard_set_contents(), which first ensures the
clipboard is owned by the clipboard widget (which also indirectly
causes an SelectionRequest xevent to be sent to it), then clears the old
supported targets from the clipboard, then adds all the
targets it's given to the clipboard. No data is sent anywhere.

gtk_clipboard_set_contents() is also given a callback to invoke when
the actual data is needed. This callback is implemented by the widget
from which the data can be put into clipboard.

GTK+ might also call gtk_clipboard_set_can_store(), which sets the
targets for which the data can be put into system clipboard, so that
it remains usable even if the application is no longer around. Usually
all data formats are storable, except for the shortcut formats, which
refer to actual widgets directly, and are thus only working while
the application is alive.

("C:" means clipboard client (requestor), "S:" means clipboard server (provider))

When something needs to be obtained from clipboard, GTK+ calls
C: gtk_selection_convert().
That function has a shortcut where it directly gets the selection contents by calling
S: gtk_selection_invoke_handler(),
asking the widget to provide data, and then calling
C: gtk_selection_retrieval_report()
to report the data back to the caller.

If that shortcut isn't possible (selection is owned by another process),
gtk_selection_convert() calls
C:gdk_selection_convert() (_gdk_x11_display_convert_selection())

On X11 gdk_selection_convert() just calls
C:XConvertSelection(),
which sends SelectionRequest xevent to the window that owns the selection.
The client gives its clipboard window as the requestor for that event,
and gives the property as GDK_SELECTION.

Server-side GTK+ catches SelectionRequest in a
S:_gtk_selection_request()
event handler, which calls
S:gtk_selection_invoke_handler()
to get the data, and then calls
S:gdk_property_change() (_gdk_x11_window_change_property())
to submit the data, by setting the property given by the message sender
(GDK_SELECTION) on the requestor window (our client clipboard window).

On X11 data submission takes from of
S:XChangeProperty()
call, which causes SelectionNotify (and PropertyNotify for INCR)
xevent to be sent, which client-side GTK+ catches and handles in
C:_gtk_selection_notify()
(and
C:_gtk_selection_property_notify(),
for INCR)
event handler, which calls
C:gtk_selection_retrieval_report()
to report back to the caller. The caller gets the property
data from the window, and returns it up the stack.

On X11 the "TARGETS" target might be given in a SelectionRequest xmessage to request
all supported targets for a selection.

If data must be stored on the clipboard, because the application is quitting,
GTK+ will call
S:gdk_clipboard_store() -> gdk_display_store_clipboard() (gdk_x11_display_store_clipboard())
on all the clipboards it owns.
X11 gdk_display_store_clipboard() puts a list of storeable targets into GDK_SELECTION
property of the clipboard window, then calls
S:XConvertSelection()
on the clipboard manager window (retrieved from the CLIPBOARD_MANAGER atom),
and the clipboard manager responds by requesting all these formats and storing the data,
then responds with SelectionNotify xevent to allow the application to quit.

When clipboard owner changes, the old owner receives SelectionClear xevent,
GTK+ handles it by clearing the clipboard object on its own level, GDK
is not involved.

On Windows:
Clipboard is opened by OpenClipboard(), emptied by EmptyClipboard() (which also
makes the window the clipboard owner), data is put into it by SetClipboardData().
Clipboard is closed with CloseClipboard().
If SetClipboardData() is given a NULL data value, the owner will later
receive WM_RENDERFORMAT message, in response to which it must call
SetClipboardData() with the provided handle and the actual data this time.
This way applications can avoid storing everything in the clipboard
all the time, only putting the data there as it is requested by other applications.
At some undefined points of time an application might get WM_RENDERALLFORMATS
message, it should respond by opening the clipboard and rendering
into it all the data that it offers, as if responding to multiple WM_RENDERFORMAT
messages.

On GDK-Win32:
GTK+ calls gtk_clipboard_set_contents(), which first ensures the
clipboard is owned by the clipboard widget (calls OpenClipboard(),
then EmptyClipboard() to become the owner, then
sends a TARGETS GDK_SELECTION_REQUEST to itself, without closing the clipboard),
then clears the old supported targets from the clipboard, then adds all the
targets it's given to the clipboard. No data is sent anywhere.

gtk_clipboard_set_contents() is also given a callback to invoke when
the actual data is needed. This callback is implemented by the widget
from which the data can be put into clipboard.

GTK+ might also call gtk_clipboard_set_can_store(), which sets the
targets for which the data can be put into system clipboard, so that
it remains usable even if the application is no longer around. Usually
all data formats are storable, except for the shortcut formats, which
refer to actual widgets directly, and are thus only working while
the application is alive.

("C:" means clipboard client (requestor), "S:" means clipboard server (provider))
("transmute" here means "change the format of some data"; this term is used here
 instead of "convert" to avoid clashing with g(t|d)k_selection_convert(), which
 is completely unrelated)

When something needs to be obtained from clipboard, GTK+ calls
C: gtk_selection_convert().
That function has a shortcut where it directly gets the selection contents by calling
S: gtk_selection_invoke_handler(),
asking the widget to provide data, and then calling
C: gtk_selection_retrieval_report()
to report the data back to the caller.

If that shortcut isn't possible (selection is owned by another process),
gtk_selection_convert() calls
C:gdk_selection_convert() (_gdk_win32_display_convert_selection())

On GDK-Win32 gdk_selection_convert() just calls
C:OpenClipboard()
to open clipboard (if that fails, it shedules a timeout to regularly
try to open clipboard for the next 30 seconds, and do the actions
outlined below once the clipboard is opened, or notify about
conversion failure after 30 seconds),
C:EnumClipboardFormats() (2000+)
to get the list of supported formats, figures out the format it should
use to request the data (first it looks for supported formats with names
that match the target name, then looks through compatibility
formats for the target and checks whether these are supported).
Note that it has no list of supported targets at hand,
just the single requested target, and thus it might have
to do some transmutation between formats; the caller up the stack
either only supports just one format that it asks for,
or supports multiple formats and asks for them in sequence (from
the most preferred to the least preferred), until one call succeeds,
or supports multiple formats and asks for the TARGETS format first,
and then figures out what to ask for - GDK can't know that.
Either way, GDK has to call
C:GetClipboardData()
to get the data (this causes WM_RENDERFORMAT to be sent to the owner,
if the owner uses delayed rendering for the requested format, otherwise
it just picks the data right from the OS)

Server-side GDK catches WM_RENDERFORMAT, figures out a target
to request (this one is easier, as it has the list of supported
targets saved up), and posts a GDK_SELECTION_REQUEST event, then runs the main loop,
while GTK+ catches the event in a
S:_gtk_selection_request()
event handler, which calls
S:gtk_selection_invoke_handler()
to get the data, and then calls
S:gdk_property_change() (_gdk_win32_window_change_property())
to submit the data, by first transmuting it to the format actually requested
by the sender of WM_RENDERFORMAT, and then by returning thedata back up the stack,
to the WM_RENDERFORMAT handler, which then calls
S:SetClipboardData()
with the handle provided by the sender.

Meanwhile, the client code, still in
C:_gdk_win32_display_convert_selection(),
gets the data in response to GetClipboardData(),
transmutes it (if needed) to the target format, sets the requested
window property to that data (unlike change_property!),
calls
C:CloseClipboard() (if there are no more clipboard opeartions
scheduled)
and posts a GDK_SELECTION_NOTIFY event, which GTK+ catches in
C:_gtk_selection_notify()
event handler, which calls
C:gtk_selection_retrieval_report()
to report back to the caller. The caller gets the property
data from the window, and returns it up the stack.

On GDK-Win32 the "TARGETS" target might be given in a GDK_SELECTION_REQUEST to request
all supported targets for a selection.
Note that this server side -
client side should call gdk_selection_convert() -> gdk_selection_convert() with "TARGETS" target
to get the list of targets offered by the clipboard holder. It never causes GDK_SELECTION_REQUEST
to be generated, just queries the system clipboard.
On server side GDK_SELECTION_REQUEST is only generated internally:
in response to WM_RENDERFORMAT (it renders a target),
in response to idataobject_getdata() (it renders a target),
after DnD ends (with a DELETE target, this is caught by GTK to make it delete the selection),
and in response to owner change, with TARGETS target, which makes it register its formats by calling
S:SetClipboardData(..., NULL)

If data must be stored on the clipboard, because the application is quitting,
GTK+ will call
S:gdk_clipboard_store() -> gdk_display_store_clipboard() (gdk_win32_display_store_clipboard())
on all the clipboards it owns.
GDK-Win32 gdk_display_store_clipboard() sends WM_RENDERALLFORMATS to the window,
then posts a GDK_SELECTION_NOTIFY event allow the application to quit.

When clipboard owner changes, the old owner receives WM_DESTROYCLIPBOARD message,
GDK handles it by posting a GDK_SELECTION_CLEAR event, which
GTK+ handles by clearing the clipboard object on its own level.

Any operations that require OpenClipboard()/CloseClipboard() combo (i.e.
everything, except for WM_RENDERFORMAT handling) must be put into a queue,
and then a once-per-second-for-up-to-30-seconds timeout must be added.
The timeout function must call OpenClipboard(),
and then proceed to perform the queued actions on the clipboard, once it opened,
or return and try again a second later, as long as there are still items in the queue,
and remove the queue items that are older than 30 seconds.
Once the queue is empty, the clipboard is closed.

DND:
GDK-Win32:
S:idataobject_getdata()
sends a GDK_SELECTION_REQUEST event, which results in a call to
S:_gdk_win32_window_change_property()
which passes clipboard data back via the selection singleton.
GDK-Win32 uses delayed rendering for all formats, even text.

GTK+ will call
C:gtk_selection_convert() -> gdk_selection_convert() (_gdk_win32_display_convert_selection())
to get the data associated with the drag, when GTK+ apps want to inspect the data,
but with a OLE2_DND selection instead of CLIPBOARD selection.

_gdk_win32_display_convert_selection() queries the droptarget global variable,
which should already contain a matched list of supported formats and targets,
picks a format there, then queries it from the IDataObject that the droptarget kept around.
Then optionally transmutes the data, and sets the property. Then posts GDK_SELECTION_NOTIFY.

GTK+ catches that event and processes it, causeing "selection-received" signal to
be emitted on the selection widget, and its handler is
C:gtk_drag_selection_received(),
which emits the "drag-data-received" signal for the app.
*/

276
#include "config.h"
277
#include <string.h>
278
#include <stdlib.h>
279

280 281 282 283 284 285
/* For C-style COM wrapper macros */
#define COBJMACROS

/* for CIDA */
#include <shlobj.h>

286 287
#include "gdkproperty.h"
#include "gdkselection.h"
288
#include "gdkdisplay.h"
289
#include "gdkprivate-win32.h"
290 291 292
#include "gdkselection-win32.h"
#include "gdk/gdkdndprivate.h"
#include "gdkwin32dnd-private.h"
Hans Breuer's avatar
Hans Breuer committed
293
#include "gdkwin32.h"
294

295 296 297 298 299 300 301 302 303
typedef struct _GdkWin32ClipboardQueueInfo GdkWin32ClipboardQueueInfo;

typedef enum _GdkWin32ClipboardQueueAction GdkWin32ClipboardQueueAction;

enum _GdkWin32ClipboardQueueAction
{
  GDK_WIN32_CLIPBOARD_QUEUE_ACTION_CONVERT = 0,
  GDK_WIN32_CLIPBOARD_QUEUE_ACTION_TARGETS
};
304

305 306 307 308 309 310 311 312 313 314 315 316
struct _GdkWin32ClipboardQueueInfo
{
  GdkDisplay                   *display;
  GdkWindow                    *requestor;
  GdkAtom                       selection;
  GdkAtom                       target;
  guint32                       time;

  /* Number of seconds since we started our
   * attempts to open clipboard.
   */
  guint32                       idle_time;
317

318 319 320
  /* What to do once clipboard is opened */
  GdkWin32ClipboardQueueAction  action;
};
321

322 323
/* List of GdkWin32ClipboardQueueInfo slices */
static GList *clipboard_queue = NULL;
324

325 326
#define HIDA_GetPIDLFolder(pida) (LPCITEMIDLIST)(((LPBYTE)pida)+(pida)->aoffset[0])
#define HIDA_GetPIDLItem(pida, i) (LPCITEMIDLIST)(((LPBYTE)pida)+(pida)->aoffset[i+1])
327

328
G_DEFINE_TYPE (GdkWin32Selection, gdk_win32_selection, G_TYPE_OBJECT)
329

330 331 332 333
static void
gdk_win32_selection_class_init (GdkWin32SelectionClass *klass)
{
}
334

335
void
336
_gdk_win32_selection_init (void)
337
{
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
  _win32_selection = GDK_WIN32_SELECTION (g_object_new (GDK_TYPE_WIN32_SELECTION, NULL));
}

static void
gdk_win32_selection_init (GdkWin32Selection *win32_selection)
{
  GArray             *atoms;
  GArray             *cfs;
  GSList             *pixbuf_formats;
  GSList             *rover;
  int                 i;
  GArray             *comp;
  GdkSelTargetFormat  fmt;

  win32_selection->ignore_destroy_clipboard = FALSE;
  win32_selection->clipboard_opened_for = INVALID_HANDLE_VALUE;

  win32_selection->dnd_target_state = GDK_WIN32_DND_NONE;
  win32_selection->dnd_source_state = GDK_WIN32_DND_NONE;
  win32_selection->dnd_data_object_target = NULL;
  win32_selection->property_change_format = 0;
  win32_selection->property_change_data = NULL;
360
  win32_selection->property_change_target_atom = 0;
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 405 406 407 408 409 410

  atoms = g_array_sized_new (FALSE, TRUE, sizeof (GdkAtom), GDK_WIN32_ATOM_INDEX_LAST);
  g_array_set_size (atoms, GDK_WIN32_ATOM_INDEX_LAST);
  cfs = g_array_sized_new (FALSE, TRUE, sizeof (UINT), GDK_WIN32_CF_INDEX_LAST);
  g_array_set_size (cfs, GDK_WIN32_CF_INDEX_LAST);

  win32_selection->known_atoms = atoms;
  win32_selection->known_clipboard_formats = cfs;

  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_GDK_SELECTION) = gdk_atom_intern_static_string ("GDK_SELECTION");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_CLIPBOARD_MANAGER) = gdk_atom_intern_static_string ("CLIPBOARD_MANAGER");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_WM_TRANSIENT_FOR) = gdk_atom_intern_static_string ("WM_TRANSIENT_FOR");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_TARGETS) = gdk_atom_intern_static_string ("TARGETS");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_DELETE) = gdk_atom_intern_static_string ("DELETE");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_SAVE_TARGETS) = gdk_atom_intern_static_string ("SAVE_TARGETS");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_UTF8_STRING) = gdk_atom_intern_static_string ("UTF8_STRING");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_TEXT) = gdk_atom_intern_static_string ("TEXT");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_COMPOUND_TEXT) = gdk_atom_intern_static_string ("COMPOUND_TEXT");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_TEXT_URI_LIST) = gdk_atom_intern_static_string ("text/uri-list");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_TEXT_HTML) = gdk_atom_intern_static_string ("text/html");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_PNG) = gdk_atom_intern_static_string ("image/png");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_JPEG) = gdk_atom_intern_static_string ("image/jpeg");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_BMP) = gdk_atom_intern_static_string ("image/bmp");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_GIF) = gdk_atom_intern_static_string ("image/gif");

  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_LOCAL_DND_SELECTION) = gdk_atom_intern_static_string ("LocalDndSelection");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_DROPFILES_DND) = gdk_atom_intern_static_string ("DROPFILES_DND");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_OLE2_DND) = gdk_atom_intern_static_string ("OLE2_DND");

  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_PNG)= gdk_atom_intern_static_string ("PNG");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_JFIF) = gdk_atom_intern_static_string ("JFIF");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_GIF) = gdk_atom_intern_static_string ("GIF");

  /* These are a bit unusual. It's here to allow GTK+ applications
   * to actually support CF_DIB and Shell ID List clipboard formats on their own,
   * instead of allowing GDK to use them internally for interoperability.
   */
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_CF_DIB) = gdk_atom_intern_static_string ("CF_DIB");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_CFSTR_SHELLIDLIST) = gdk_atom_intern_static_string (CFSTR_SHELLIDLIST);
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_CF_UNICODETEXT) = gdk_atom_intern_static_string ("CF_UNICODETEXT");
  _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_CF_TEXT) = gdk_atom_intern_static_string ("CF_TEXT");

  /* MS Office 2007, at least, offers images in common file formats
   * using clipboard format names like "PNG" and "JFIF". So we follow
   * the lead and map the GDK target name "image/png" to the clipboard
   * format name "PNG" etc.
   */
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_PNG) = RegisterClipboardFormatA ("PNG");
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_JFIF) = RegisterClipboardFormatA ("JFIF");
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_GIF) = RegisterClipboardFormatA ("GIF");
411

412 413 414 415 416 417 418 419 420 421 422 423 424 425
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_UNIFORMRESOURCELOCATORW) = RegisterClipboardFormatA ("UniformResourceLocatorW");
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_CFSTR_SHELLIDLIST) = RegisterClipboardFormatA (CFSTR_SHELLIDLIST);
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_HTML_FORMAT) = RegisterClipboardFormatA ("HTML Format");
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_TEXT_HTML) = RegisterClipboardFormatA ("text/html");

  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_IMAGE_PNG) = RegisterClipboardFormatA ("image/png");
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_IMAGE_JPEG) = RegisterClipboardFormatA ("image/jpeg");
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_IMAGE_BMP) = RegisterClipboardFormatA ("image/bmp");
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_IMAGE_GIF) = RegisterClipboardFormatA ("image/gif");
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_TEXT_URI_LIST) = RegisterClipboardFormatA ("text/uri-list");
  _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_UTF8_STRING) = RegisterClipboardFormatA ("UTF8_STRING");

  win32_selection->sel_prop_table = g_hash_table_new (NULL, NULL);
  win32_selection->sel_owner_table = g_hash_table_new (NULL, NULL);
426 427 428

  pixbuf_formats = gdk_pixbuf_get_formats ();

429
  win32_selection->n_known_pixbuf_formats = 0;
430 431 432 433 434 435 436 437
  for (rover = pixbuf_formats; rover != NULL; rover = rover->next)
    {
      gchar **mime_types =
	gdk_pixbuf_format_get_mime_types ((GdkPixbufFormat *) rover->data);

      gchar **mime_type;

      for (mime_type = mime_types; *mime_type != NULL; mime_type++)
438
	win32_selection->n_known_pixbuf_formats++;
439 440
    }

441
  win32_selection->known_pixbuf_formats = g_new (GdkAtom, win32_selection->n_known_pixbuf_formats);
442

443
  i = 0;
444 445 446 447 448 449 450 451
  for (rover = pixbuf_formats; rover != NULL; rover = rover->next)
    {
      gchar **mime_types =
	gdk_pixbuf_format_get_mime_types ((GdkPixbufFormat *) rover->data);

      gchar **mime_type;

      for (mime_type = mime_types; *mime_type != NULL; mime_type++)
452
	win32_selection->known_pixbuf_formats[i++] = gdk_atom_intern (*mime_type, FALSE);
453 454 455
    }

  g_slist_free (pixbuf_formats);
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 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
  win32_selection->dnd_selection_targets = g_array_new (FALSE, FALSE, sizeof (GdkSelTargetFormat));
  win32_selection->clipboard_selection_targets = g_array_new (FALSE, FALSE, sizeof (GdkSelTargetFormat));
  win32_selection->compatibility_formats = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify) g_array_unref);

  /* GTK+ actually has more text formats, but it's unlikely that we'd
   * get anything other than UTF8_STRING these days.
   * GTKTEXTBUFFERCONTENTS format can potentially be converted to
   * W32-compatible rich text format, but that's too complex to address right now.
   */
  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkSelTargetFormat), 3);
  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_UTF8_STRING);

  fmt.format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_UTF8_STRING);
  fmt.transmute = FALSE;
  g_array_append_val (comp, fmt);

  fmt.format = CF_UNICODETEXT;
  fmt.transmute = TRUE;
  g_array_append_val (comp, fmt);

  fmt.format = CF_TEXT;
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_selection->compatibility_formats, fmt.target, comp);


  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkSelTargetFormat), 3);
  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_PNG);

  fmt.format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_IMAGE_PNG);
  fmt.transmute = FALSE;
  g_array_append_val (comp, fmt);

  fmt.format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_PNG);
  g_array_append_val (comp, fmt);

  fmt.format = CF_DIB;
  fmt.transmute = TRUE;
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_selection->compatibility_formats, fmt.target, comp);


  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkSelTargetFormat), 4);
  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_JPEG);

  fmt.format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_IMAGE_JPEG);
  fmt.transmute = FALSE;
  g_array_append_val (comp, fmt);

  fmt.format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_JFIF);
  g_array_append_val (comp, fmt);

  fmt.format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_PNG);
  fmt.transmute = TRUE;
  g_array_append_val (comp, fmt);

  fmt.format = CF_DIB;
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_selection->compatibility_formats, fmt.target, comp);


  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkSelTargetFormat), 4);
  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_GIF);

  fmt.format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_IMAGE_GIF);
  fmt.transmute = FALSE;
  g_array_append_val (comp, fmt);

  fmt.format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_GIF);
  g_array_append_val (comp, fmt);

  fmt.format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_PNG);
  fmt.transmute = TRUE;
  g_array_append_val (comp, fmt);

  fmt.format = CF_DIB;
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_selection->compatibility_formats, fmt.target, comp);


  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkSelTargetFormat), 2);
  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_BMP);

  fmt.format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_IMAGE_BMP);
  fmt.transmute = FALSE;
  g_array_append_val (comp, fmt);

  fmt.format = CF_DIB;
  fmt.transmute = TRUE;
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_selection->compatibility_formats, fmt.target, comp);


/* Not implemented, but definitely possible
  comp = g_array_sized_new (FALSE, FALSE, 2);
  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_TEXT_URI_LIST);

  fmt.format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_TEXT_URI_LIST);
  fmt.transmute = FALSE;
  g_array_append_val (comp, fmt);

  fmt.format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_CFSTR_SHELLIDLIST);
  fmt.transmute = TRUE;
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_selection->compatibility_formats, fmt.target, comp);
*/

  win32_selection->compatibility_targets = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify) g_array_unref);

  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkSelTargetFormat), 2);
  fmt.format = CF_TEXT;
  fmt.transmute = FALSE;

  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_CF_TEXT);
  g_array_append_val (comp, fmt);

  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_UTF8_STRING);
  fmt.transmute = TRUE;
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_selection->compatibility_targets, GINT_TO_POINTER (CF_TEXT), comp);

584

585 586 587
  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkSelTargetFormat), 2);
  fmt.format = CF_UNICODETEXT;
  fmt.transmute = FALSE;
588

589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 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
  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_CF_UNICODETEXT);
  g_array_append_val (comp, fmt);

  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_UTF8_STRING);
  fmt.transmute = TRUE;
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_selection->compatibility_targets, GINT_TO_POINTER (CF_UNICODETEXT), comp);


  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkSelTargetFormat), 3);
  fmt.format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_PNG);
  fmt.transmute = FALSE;

  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_PNG);
  g_array_append_val (comp, fmt);

  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_PNG);
  g_array_append_val (comp, fmt);

  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_BMP);
  fmt.transmute = TRUE;
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_selection->compatibility_targets, GINT_TO_POINTER (_gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_PNG)), comp);


  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkSelTargetFormat), 4);
  fmt.format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_JFIF);
  fmt.transmute = FALSE;

  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_JFIF);
  g_array_append_val (comp, fmt);

  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_JPEG);
  g_array_append_val (comp, fmt);

  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_PNG);
  fmt.transmute = TRUE;
  g_array_append_val (comp, fmt);

  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_BMP);
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_selection->compatibility_targets, GINT_TO_POINTER (_gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_JFIF)), comp);


  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkSelTargetFormat), 4);
  fmt.format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_GIF);
  fmt.transmute = FALSE;

  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_GIF);
  g_array_append_val (comp, fmt);

  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_GIF);
  g_array_append_val (comp, fmt);

  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_PNG);
  fmt.transmute = TRUE;
  g_array_append_val (comp, fmt);

  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_BMP);
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_selection->compatibility_targets, GINT_TO_POINTER (_gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_GIF)), comp);


  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkSelTargetFormat), 3);
  fmt.format = CF_DIB;
  fmt.transmute = FALSE;

  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_CF_DIB);
  g_array_append_val (comp, fmt);

  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_IMAGE_BMP);
  fmt.transmute = TRUE;
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_selection->compatibility_targets, GINT_TO_POINTER (CF_DIB), comp);


  comp = g_array_sized_new (FALSE, FALSE, sizeof (GdkSelTargetFormat), 3);
  fmt.format = _gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_CFSTR_SHELLIDLIST);
  fmt.transmute = FALSE;

  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_CFSTR_SHELLIDLIST);
  g_array_append_val (comp, fmt);

  fmt.target = _gdk_atom_array_index (atoms, GDK_WIN32_ATOM_INDEX_TEXT_URI_LIST);
  fmt.transmute = TRUE;
  g_array_append_val (comp, fmt);

  g_hash_table_replace (win32_selection->compatibility_targets, GINT_TO_POINTER (_gdk_cf_array_index (cfs, GDK_WIN32_CF_INDEX_CFSTR_SHELLIDLIST)), comp);
682 683
}

684 685 686 687 688 689 690
/* The specifications for COMPOUND_TEXT and STRING specify that C0 and
 * C1 are not allowed except for \n and \t, however the X conversions
 * routines for COMPOUND_TEXT only enforce this in one direction,
 * causing cut-and-paste of \r and \r\n separated text to fail.
 * This routine strips out all non-allowed C0 and C1 characters
 * from the input string and also canonicalizes \r, and \r\n to \n
 */
691
static gchar *
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
sanitize_utf8 (const gchar *src,
	       gint         length)
{
  GString *result = g_string_sized_new (length + 1);
  const gchar *p = src;
  const gchar *endp = src + length;

  while (p < endp)
    {
      if (*p == '\r')
	{
	  p++;
	  if (*p == '\n')
	    p++;

	  g_string_append_c (result, '\n');
	}
      else
	{
	  gunichar ch = g_utf8_get_char (p);
	  char buf[7];
	  gint buflen;
714

715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
	  if (!((ch < 0x20 && ch != '\t' && ch != '\n') || (ch >= 0x7f && ch < 0xa0)))
	    {
	      buflen = g_unichar_to_utf8 (ch, buf);
	      g_string_append_len (result, buf, buflen);
	    }

	  p = g_utf8_next_char (p);
	}
    }
  g_string_append_c (result, '\0');

  return g_string_free (result, FALSE);
}

static gchar *
_gdk_utf8_to_string_target_internal (const gchar *str,
				     gint         length)
{
  GError *error = NULL;
734

735 736 737 738 739 740 741 742 743 744
  gchar *tmp_str = sanitize_utf8 (str, length);
  gchar *result =  g_convert_with_fallback (tmp_str, -1,
					    "ISO-8859-1", "UTF-8",
					    NULL, NULL, NULL, &error);
  if (!result)
    {
      g_warning ("Error converting from UTF-8 to STRING: %s",
		 error->message);
      g_error_free (error);
    }
745

746 747 748 749 750
  g_free (tmp_str);
  return result;
}

static void
751 752 753 754 755
selection_property_store (GdkWindow *owner,
			  GdkAtom    type,
			  gint       format,
			  guchar    *data,
			  gint       length)
756 757
{
  GdkSelProp *prop;
758
  GdkWin32Selection *win32_sel = _gdk_win32_selection_get ();
759

760
  g_return_if_fail (type != GDK_TARGET_STRING);
761

762
  prop = g_hash_table_lookup (win32_sel->sel_prop_table, GDK_WINDOW_HWND (owner));
763

764
  if (prop != NULL)
765
    {
766 767
      g_free (prop->data);
      g_free (prop);
768
      g_hash_table_remove (win32_sel->sel_prop_table, GDK_WINDOW_HWND (owner));
769
    }
770 771 772 773 774

  prop = g_new (GdkSelProp, 1);

  prop->data = data;
  prop->length = length;
775 776
  prop->bitness = format;
  prop->target = type;
777

778
  g_hash_table_insert (win32_sel->sel_prop_table, GDK_WINDOW_HWND (owner), prop);
779 780 781 782 783
}

void
_gdk_dropfiles_store (gchar *data)
{
784 785
  GdkWin32Selection *win32_sel = _gdk_win32_selection_get ();

786 787
  if (data != NULL)
    {
788
      g_assert (win32_sel->dropfiles_prop == NULL);
789

790 791 792 793 794
      win32_sel->dropfiles_prop = g_new (GdkSelProp, 1);
      win32_sel->dropfiles_prop->data = (guchar *) data;
      win32_sel->dropfiles_prop->length = strlen (data) + 1;
      win32_sel->dropfiles_prop->bitness = 8;
      win32_sel->dropfiles_prop->target = _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_TEXT_URI_LIST);
795 796 797
    }
  else
    {
798
      if (win32_sel->dropfiles_prop != NULL)
799
	{
800 801
	  g_free (win32_sel->dropfiles_prop->data);
	  g_free (win32_sel->dropfiles_prop);
802
	}
803
      win32_sel->dropfiles_prop = NULL;
804
    }
805 806
}

807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
static void
generate_selection_notify (GdkWindow *requestor,
			   GdkAtom    selection,
			   GdkAtom    target,
			   GdkAtom    property,
			   guint32    time)
{
  GdkEvent tmp_event;

  memset (&tmp_event, 0, sizeof (tmp_event));
  tmp_event.selection.type = GDK_SELECTION_NOTIFY;
  tmp_event.selection.window = requestor;
  tmp_event.selection.send_event = FALSE;
  tmp_event.selection.selection = selection;
  tmp_event.selection.target = target;
  tmp_event.selection.property = property;
  tmp_event.selection.requestor = 0;
  tmp_event.selection.time = time;

  gdk_event_put (&tmp_event);
}

void
_gdk_win32_clear_clipboard_queue ()
831
{
832 833 834
  GList *tmp_list, *next;
  GdkWin32ClipboardQueueInfo *info;
  GdkWin32Selection *win32_sel = _gdk_win32_selection_get ();
835

836
  GDK_NOTE (DND, g_print ("Clear clipboard queue\n"));
837

838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
  for (tmp_list = clipboard_queue; tmp_list; tmp_list = next)
    {
      info = (GdkWin32ClipboardQueueInfo *) tmp_list->data;
      next = g_list_next (tmp_list);
      clipboard_queue = g_list_remove_link (clipboard_queue, tmp_list);
      g_list_free (tmp_list);
      switch (info->action)
        {
        case GDK_WIN32_CLIPBOARD_QUEUE_ACTION_TARGETS:
          break;
        case GDK_WIN32_CLIPBOARD_QUEUE_ACTION_CONVERT:
          generate_selection_notify (info->requestor, info->selection, info->target, GDK_NONE, info->time);
          break;
        }
      g_clear_object (&info->requestor);
      g_slice_free (GdkWin32ClipboardQueueInfo, info);
    }
855

856
  win32_sel->targets_request_pending = FALSE;
857 858
}

859 860 861 862 863 864
/* Send ourselves a selection request message with
 * the TARGETS target, we will do multiple SetClipboarData(...,NULL)
 * calls in response to announce the formats we support.
 */
static void
send_targets_request (guint time)
865
{
866
  GdkWindow *owner;
867
  GdkEvent tmp_event;
868
  GdkWin32Selection *win32_sel = _gdk_win32_selection_get ();
869

870 871
  if (win32_sel->targets_request_pending)
    return;
872

873 874
  owner = _gdk_win32_display_get_selection_owner (gdk_display_get_default (),
                                                  GDK_SELECTION_CLIPBOARD);
875

876 877
  if (owner == NULL)
    return;
878

879
  if (win32_sel->clipboard_opened_for == INVALID_HANDLE_VALUE)
Hans Breuer's avatar
Hans Breuer committed
880
    {
881 882 883 884 885
      if (OpenClipboard (GDK_WINDOW_HWND (owner)))
        {
          win32_sel->clipboard_opened_for = GDK_WINDOW_HWND (owner);
          GDK_NOTE (DND, g_print ("Opened clipboard for 0x%p @ %s:%d\n", win32_sel->clipboard_opened_for, __FILE__, __LINE__));
        }
Hans Breuer's avatar
Hans Breuer committed
886
    }
887

888 889 890 891 892 893 894 895 896 897
  GDK_NOTE (DND, g_print ("... sending GDK_SELECTION_REQUEST to ourselves\n"));
  memset (&tmp_event, 0, sizeof (tmp_event));
  tmp_event.selection.type = GDK_SELECTION_REQUEST;
  tmp_event.selection.window = owner;
  tmp_event.selection.send_event = FALSE;
  tmp_event.selection.selection = GDK_SELECTION_CLIPBOARD;
  tmp_event.selection.target = _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_TARGETS);
  tmp_event.selection.property = _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_GDK_SELECTION);
  tmp_event.selection.requestor = owner;
  tmp_event.selection.time = time;
898
  win32_sel->property_change_target_atom = _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_TARGETS);
899 900 901 902 903 904 905 906 907 908 909 910

  gdk_event_put (&tmp_event);
  win32_sel->targets_request_pending = TRUE;
}

#define CLIPBOARD_IDLE_ABORT_TIME 30

static const gchar *
predefined_name (UINT fmt)
{
#define CASE(fmt) case fmt: return #fmt
  switch (fmt)
911
    {
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
    CASE (CF_TEXT);
    CASE (CF_BITMAP);
    CASE (CF_METAFILEPICT);
    CASE (CF_SYLK);
    CASE (CF_DIF);
    CASE (CF_TIFF);
    CASE (CF_OEMTEXT);
    CASE (CF_DIB);
    CASE (CF_PALETTE);
    CASE (CF_PENDATA);
    CASE (CF_RIFF);
    CASE (CF_WAVE);
    CASE (CF_UNICODETEXT);
    CASE (CF_ENHMETAFILE);
    CASE (CF_HDROP);
    CASE (CF_LOCALE);
    CASE (CF_DIBV5);
    CASE (CF_MAX);

    CASE (CF_OWNERDISPLAY);
    CASE (CF_DSPTEXT);
    CASE (CF_DSPBITMAP);
    CASE (CF_DSPMETAFILEPICT);
    CASE (CF_DSPENHMETAFILE);
#undef CASE
    default:
      return NULL;
    }
}
941

942 943 944 945 946 947 948 949 950 951 952 953 954 955 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
gchar *
_gdk_win32_get_clipboard_format_name (UINT      fmt,
                                      gboolean *is_predefined)
{
  gint registered_name_w_len = 1024;
  wchar_t *registered_name_w = g_malloc (registered_name_w_len);
  gchar *registered_name = NULL;
  int gcfn_result;
  const gchar *predef = predefined_name (fmt);

  /* FIXME: cache the result in a hash table */

  do
    {
      gcfn_result = GetClipboardFormatNameW (fmt, registered_name_w, registered_name_w_len);

      if (gcfn_result > 0 && gcfn_result < registered_name_w_len)
        {
          registered_name = g_utf16_to_utf8 (registered_name_w, -1, NULL, NULL, NULL);
          g_clear_pointer (&registered_name_w, g_free);
          if (!registered_name)
            gcfn_result = 0;
          else
            *is_predefined = FALSE;
          break;
        }

      /* If GetClipboardFormatNameW() used up all the space, it means that
       * we probably need a bigger buffer, but cap this at 1 kilobyte.
       */
      if (gcfn_result == 0 || registered_name_w_len > 1024 * 1024)
        {
          gcfn_result = 0;
          g_clear_pointer (&registered_name_w, g_free);
          break;
        }

      registered_name_w_len *= 2;
      registered_name_w = g_realloc (registered_name_w, registered_name_w_len);
      gcfn_result = registered_name_w_len;
    } while (gcfn_result == registered_name_w_len);

  if (registered_name == NULL &&
      predef != NULL)
    {
      registered_name = g_strdup (predef);
      *is_predefined = TRUE;
989
    }
990

991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 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 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 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 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 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 1673 1674 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 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 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 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074
  return registered_name;
}

static GArray *
get_compatibility_formats_for_target (GdkAtom target)
{
  GArray *result = NULL;
  gint i;
  GdkWin32Selection *win32_sel = _gdk_win32_selection_get ();

  result = g_hash_table_lookup (win32_sel->compatibility_formats, target);

  if (result != NULL)
    return result;

  for (i = 0; i < win32_sel->n_known_pixbuf_formats; i++)
    {
      if (target != win32_sel->known_pixbuf_formats[i])
        continue;

      /* Any format known to gdk-pixbuf can be presented as PNG or BMP */
      result = g_hash_table_lookup (win32_sel->compatibility_formats,
                                    _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_IMAGE_PNG));
      break;
    }

  return result;
}

static GArray *
_gdk_win32_selection_get_compatibility_targets_for_format (UINT format)
{
  GArray *result = NULL;
  GdkWin32Selection *win32_sel = _gdk_win32_selection_get ();

  result = g_hash_table_lookup (win32_sel->compatibility_targets, GINT_TO_POINTER (format));

  if (result != NULL)
    return result;

  /* TODO: reverse gdk-pixbuf conversion? We have to somehow
   * match gdk-pixbuf format names to the corresponding clipboard
   * format names. The former are known only at runtime,
   * the latter are presently unknown...
   * Maybe try to get the data and then just feed it to gdk-pixbuf,
   * see if it knows what it is?
   */

  return result;
}

void
_gdk_win32_add_format_to_targets (UINT     format,
                                  GArray  *array,
                                  GList  **list)
{
  gboolean predef;
  gchar *format_name = _gdk_win32_get_clipboard_format_name (format, &predef);
  GdkAtom target_atom;
  GdkSelTargetFormat target_selformat;
  GArray *target_selformats;
  gint i,j;

  if (format_name != NULL)
    {
      target_atom = gdk_atom_intern (format_name, FALSE);
      GDK_NOTE (DND, g_print ("Maybe add as-is format %s (0x%p)\n", format_name, target_atom));
      g_free (format_name);
      if (array && target_atom != 0)
        {
          for (j = 0; j < array->len; j++)
            if (g_array_index (array, GdkSelTargetFormat, j).target == target_atom)
              break;
          if (j == array->len)
            {
              target_selformat.format = format;
              target_selformat.target = target_atom;
              target_selformat.transmute = FALSE;
              g_array_append_val (array, target_selformat);
            }
        }
      if (list && target_atom != 0 && g_list_find (*list, target_atom) == NULL)
        *list = g_list_prepend (*list, target_atom);
    }

 target_selformats = _gdk_win32_selection_get_compatibility_targets_for_format (format);

 if (array && target_selformats != NULL)
   for (i = 0; i < target_selformats->len; i++)
     {
       target_selformat = g_array_index (target_selformats, GdkSelTargetFormat, i);

       for (j = 0; j < array->len; j++)
         if (g_array_index (array, GdkSelTargetFormat, j).target == target_selformat.target &&
             g_array_index (array, GdkSelTargetFormat, j).format == target_selformat.format)
           break;

       if (j == array->len)
         g_array_append_val (array, target_selformat);
     }

 if (list && target_selformats != NULL)
   for (i = 0; i < target_selformats->len; i++)
     {
       target_selformat = g_array_index (target_selformats, GdkSelTargetFormat, i);

       if (g_list_find (*list, target_selformat.target) == NULL)
         *list = g_list_prepend (*list, target_selformat.target);
     }
}

static void
transmute_cf_unicodetext_to_utf8_string (const guchar    *data,
                                         gint             length,
                                         guchar         **set_data,
                                         gint            *set_data_length,
                                         GDestroyNotify  *set_data_destroy)
{
  wchar_t *ptr, *p, *q;
  gchar *result;
  glong wclen, u8_len;

  /* Strip out \r */
  ptr = (wchar_t *) data;
  p = ptr;
  q = ptr;
  wclen = 0;

  while (p < ptr + length / 2)
    {
      if (*p != L'\r')
        {
          *q++ = *p;
          wclen++;
        }
      p++;
    }

  result = g_utf16_to_utf8 (ptr, wclen, NULL, &u8_len, NULL);

  if (result)
    {
      *set_data = (guchar *) result;

      if (set_data_length)
        *set_data_length = u8_len + 1;
      if (set_data_destroy)
        *set_data_destroy = (GDestroyNotify) g_free;
    }
}

static void
transmute_utf8_string_to_cf_unicodetext (const guchar    *data,
                                         gint             length,
                                         guchar         **set_data,
                                         gint            *set_data_length,
                                         GDestroyNotify  *set_data_destroy)
{
  glong wclen;
  GError *err = NULL;
  glong size;
  gint i;
  wchar_t *wcptr, *p;

  wcptr = g_utf8_to_utf16 ((char *) data, length, NULL, &wclen, &err);
  if (err != NULL)
    {
      g_warning ("Failed to convert utf8: %s", err->message);
      g_clear_error (&err);
      return;
    }

  wclen++; /* Terminating 0 */
  size = wclen * 2;
  for (i = 0; i < wclen; i++)
    if (wcptr[i] == L'\n' && (i == 0 || wcptr[i - 1] != L'\r'))
      size += 2;

  *set_data = g_malloc0 (size);
  if (set_data_length)
    *set_data_length = size;
  if (set_data_destroy)
    *set_data_destroy = (GDestroyNotify) g_free;

  p = (wchar_t *) *set_data;

  for (i = 0; i < wclen; i++)
    {
      if (wcptr[i] == L'\n' && (i == 0 || wcptr[i - 1] != L'\r'))
	*p++ = L'\r';
      *p++ = wcptr[i];
    }

  g_free (wcptr);
}

static int
wchar_to_str (const wchar_t  *wstr,
              char         **retstr,
              UINT            cp)
{
  char *str;
  int   len;
  int   lenc;

  len = WideCharToMultiByte (cp, 0, wstr, -1, NULL, 0, NULL, NULL);

  if (len <= 0)
    return -1;

  str = g_malloc (sizeof (char) * len);

  lenc = WideCharToMultiByte (cp, 0, wstr, -1, str, len, NULL, NULL);

  if (lenc != len)
    {
      g_free (str);

      return -3;
    }

  *retstr = str;

  return 0;
}

static void
transmute_utf8_string_to_cf_text (const guchar    *data,
                                  gint             length,
                                  guchar         **set_data,
                                  gint            *set_data_length,
                                  GDestroyNotify  *set_data_destroy)
{
  glong rlen;
  GError *err = NULL;
  glong size;
  gint i;
  char *strptr, *p;
  wchar_t *wcptr;

  wcptr = g_utf8_to_utf16 ((char *) data, length, NULL, NULL, &err);
  if (err != NULL)
    {
      g_warning ("Failed to convert utf8: %s", err->message);
      g_clear_error (&err);
      return;
    }

  if (wchar_to_str (wcptr, &strptr, CP_ACP) != 0)
    {
      g_warning ("Failed to convert utf-16 %S to ACP", wcptr);
      g_free (wcptr);
      return;
    }

  rlen = strlen (strptr);
  g_free (wcptr);

  rlen++; /* Terminating 0 */
  size = rlen * sizeof (char);
  for (i = 0; i < rlen; i++)
    if (strptr[i] == '\n' && (i == 0 || strptr[i - 1] != '\r'))
      size += sizeof (char);

  *set_data = g_malloc0 (size);
  if (set_data_length)
    *set_data_length = size;
  if (set_data_destroy)
    *set_data_destroy = (GDestroyNotify) g_free;

  p = (char *) *set_data;

  for (i = 0; i < rlen; i++)
    {
      if (strptr[i] == '\n' && (i == 0 || strptr[i - 1] != '\r'))
	*p++ = '\r';
      *p++ = strptr[i];
    }

  g_free (strptr);
}

static int
str_to_wchar (const char  *str,
              wchar_t    **wretstr,
              UINT         cp)
{
  wchar_t *wstr;
  int      len;
  int      lenc;

  len = MultiByteToWideChar (cp, 0, str, -1, NULL, 0);

  if (len <= 0)
    return -1;

  wstr = g_malloc (sizeof (wchar_t) * len);

  lenc = MultiByteToWideChar (cp, 0, str, -1, wstr, len);

  if (lenc != len)
    {
      g_free (wstr);

      return -3;
    }

  *wretstr = wstr;

  return 0;
}

static void
transmute_cf_text_to_utf8_string (const guchar    *data,
                                  gint             length,
                                  guchar         **set_data,
                                  gint            *set_data_length,
                                  GDestroyNotify  *set_data_destroy)
{
  char *ptr, *p, *q;
  gchar *result;
  glong wclen, u8_len;
  wchar_t *wstr;

  /* Strip out \r */
  ptr = (gchar *) data;
  p = ptr;
  q = ptr;
  wclen = 0;

  while (p < ptr + length / 2)
    {
      if (*p != '\r')
        {
          *q++ = *p;
          wclen++;
        }
      p++;
    }

  if (str_to_wchar (ptr, &wstr, CP_ACP) < 0)
    return;

  result = g_utf16_to_utf8 (wstr, -1, NULL, &u8_len, NULL);

  if (result)
    {
      *set_data = (guchar *) result;

      if (set_data_length)
        *set_data_length = u8_len + 1;
      if (set_data_destroy)
        *set_data_destroy = (GDestroyNotify) g_free;
    }

  g_free (wstr);
}

static void
transmute_cf_dib_to_image_bmp (const guchar    *data,
                               gint             length,
                               guchar         **set_data,
                               gint            *set_data_length,
                               GDestroyNotify  *set_data_destroy)
{
  /* Need to add a BMP file header so gdk-pixbuf can load
   * it.
   *
   * If the data is from Mozilla Firefox or IE7, and
   * starts with an "old fashioned" BITMAPINFOHEADER,
   * i.e. with biSize==40, and biCompression == BI_RGB and
   * biBitCount==32, we assume that the "extra" byte in
   * each pixel in fact is alpha.
   *
   * The gdk-pixbuf bmp loader doesn't trust 32-bit BI_RGB
   * bitmaps to in fact have alpha, so we have to convince
   * it by changing the bitmap header to a version 5
   * BI_BITFIELDS one with explicit alpha mask indicated.
   *
   * The RGB bytes that are in bitmaps on the clipboard
   * originating from Firefox or IE7 seem to be
   * premultiplied with alpha. The gdk-pixbuf bmp loader
   * of course doesn't expect that, so we have to undo the
   * premultiplication before feeding the bitmap to the
   * bmp loader.
   *
   * Note that for some reason the bmp loader used to want
   * the alpha bytes in its input to actually be
   * 255-alpha, but here we assume that this has been
   * fixed before this is committed.
   */
  BITMAPINFOHEADER *bi = (BITMAPINFOHEADER *) data;
  BITMAPFILEHEADER *bf;
  gpointer result;
  gint data_length = length;
  gint new_length;
  gboolean make_dibv5 = FALSE;
  BITMAPV5HEADER *bV5;
  guchar *p;
  guint i;

  if (bi->biSize == sizeof (BITMAPINFOHEADER) &&
      bi->biPlanes == 1 &&
      bi->biBitCount == 32 &&
      bi->biCompression == BI_RGB &&
#if 0
      /* Maybe check explicitly for Mozilla or IE7?
       *
       * If the clipboard format
       * application/x-moz-nativeimage is present, that is
       * a reliable indicator that the data is offered by
       * Mozilla one would think. For IE7,
       * UniformResourceLocatorW is presumably not that
       * uniqie, so probably need to do some
       * GetClipboardOwner(), GetWindowThreadProcessId(),
       * OpenProcess(), GetModuleFileNameEx() dance to
       * check?
       */
      (IsClipboardFormatAvailable
       (RegisterClipboardFormatA ("application/x-moz-nativeimage")) ||
       IsClipboardFormatAvailable
       (RegisterClipboardFormatA ("UniformResourceLocatorW"))) &&
#endif
      TRUE)
    {
      /* We turn the BITMAPINFOHEADER into a
       * BITMAPV5HEADER before feeding it to gdk-pixbuf.
       */
      new_length = (data_length +
		    sizeof (BITMAPFILEHEADER) +
		    (sizeof (BITMAPV5HEADER) - sizeof (BITMAPINFOHEADER)));
      make_dibv5 = TRUE;
    }
  else
    {
      new_length = data_length + sizeof (BITMAPFILEHEADER);
    }

  result = g_try_malloc (new_length);

  if (result == NULL)
    return;

  bf = (BITMAPFILEHEADER *) result;
  bf->bfType = 0x4d42; /* "BM" */
  bf->bfSize = new_length;
  bf->bfReserved1 = 0;
  bf->bfReserved2 = 0;

  *set_data = result;

  if (set_data_length)
    *set_data_length = new_length;
  if (set_data_destroy)
    *set_data_destroy = g_free;

  if (!make_dibv5)
    {
      bf->bfOffBits = (sizeof (BITMAPFILEHEADER) +
		       bi->biSize +
		       bi->biClrUsed * sizeof (RGBQUAD));

      if (bi->biCompression == BI_BITFIELDS && bi->biBitCount >= 16)
        {
          /* Screenshots taken with PrintScreen or
           * Alt + PrintScreen are found on the clipboard in
           * this format. In this case the BITMAPINFOHEADER is
           * followed by three DWORD specifying the masks of the
           * red green and blue components, so adjust the offset
           * accordingly. */
          bf->bfOffBits += (3 * sizeof (DWORD));
        }

      memcpy ((char *) result + sizeof (BITMAPFILEHEADER),
	      bi,
	      data_length);

      return;
    }

  bV5 = (BITMAPV5HEADER *) ((char *) result + sizeof (BITMAPFILEHEADER));

  bV5->bV5Size = sizeof (BITMAPV5HEADER);
  bV5->bV5Width = bi->biWidth;
  bV5->bV5Height = bi->biHeight;
  bV5->bV5Planes = 1;
  bV5->bV5BitCount = 32;
  bV5->bV5Compression = BI_BITFIELDS;
  bV5->bV5SizeImage = 4 * bV5->bV5Width * ABS (bV5->bV5Height);
  bV5->bV5XPelsPerMeter = bi->biXPelsPerMeter;
  bV5->bV5YPelsPerMeter = bi->biYPelsPerMeter;
  bV5->bV5ClrUsed = 0;
  bV5->bV5ClrImportant = 0;
  /* Now the added mask fields */
  bV5->bV5RedMask   = 0x00ff0000;
  bV5->bV5GreenMask = 0x0000ff00;
  bV5->bV5BlueMask  = 0x000000ff;
  bV5->bV5AlphaMask = 0xff000000;
  ((char *) &bV5->bV5CSType)[3] = 's';
  ((char *) &bV5->bV5CSType)[2] = 'R';
  ((char *) &bV5->bV5CSType)[1] = 'G';
  ((char *) &bV5->bV5CSType)[0] = 'B';
  /* Ignore colorspace and profile fields */
  bV5->bV5Intent = LCS_GM_GRAPHICS;
  bV5->bV5Reserved = 0;

  bf->bfOffBits = (sizeof (BITMAPFILEHEADER) +
		   bV5->bV5Size);

  p = ((guchar *) result) + sizeof (BITMAPFILEHEADER) + sizeof (BITMAPV5HEADER);
  memcpy (p, ((char *) bi) + bi->biSize,
          data_length - sizeof (BITMAPINFOHEADER));

  for (i = 0; i < bV5->bV5SizeImage/4; i++)
    {
      if (p[3] != 0)
        {
          gdouble inverse_alpha = 255./p[3];

          p[0] = p[0] * inverse_alpha + 0.5;
          p[1] = p[1] * inverse_alpha + 0.5;
          p[2] = p[2] * inverse_alpha + 0.5;
        }

      p += 4;
    }
}

static void
transmute_cf_shell_id_list_to_text_uri_list (const guchar    *data,
                                             gint             length,
                                             guchar         **set_data,
                                             gint            *set_data_length,
                                             GDestroyNotify  *set_data_destroy)
{
  guint i;
  CIDA *cida = (CIDA *) data;
  guint number_of_ids = cida->cidl;
  GString *result = g_string_new (NULL);
  PCIDLIST_ABSOLUTE folder_id = HIDA_GetPIDLFolder (cida);
  wchar_t path_w[MAX_PATH + 1];

  for (i = 0; i < number_of_ids; i++)
    {
      PCUIDLIST_RELATIVE file_id = HIDA_GetPIDLItem (cida, i);
      PIDLIST_ABSOLUTE file_id_full = ILCombine (folder_id, file_id);

      if (SHGetPathFromIDListW (file_id_full, path_w))
        {
          gchar *filename = g_utf16_to_utf8 (path_w, -1, NULL, NULL, NULL);

          if (filename)
            {
              gchar *uri = g_filename_to_uri (filename, NULL, NULL);

              if (uri)
                {
                  g_string_append (result, uri);
                  g_string_append (result, "\r\n");
                  g_free (uri);
                }

              g_free (filename);
            }
        }

      ILFree (file_id_full);
    }

  *set_data = (guchar *) result->str;
  if (set_data_length)
    *set_data_length = result->len;
  if (set_data_destroy)
    *set_data_destroy = g_free;

  g_string_free (result, FALSE);
}

void
transmute_image_bmp_to_cf_dib (const guchar    *data,
                               gint             length,
                               guchar         **set_data,
                               gint            *set_data_length,
                               GDestroyNotify  *set_data_destroy)
{
  gint size;
  guchar *ptr;

  g_return_if_fail (length >= sizeof (BITMAPFILEHEADER));

  /* No conversion is needed, just strip the BITMAPFILEHEADER */
  size = length - sizeof (BITMAPFILEHEADER);
  ptr = g_malloc (size);

  memcpy (ptr, data + sizeof (BITMAPFILEHEADER), size);

  *set_data = ptr;

  if (set_data_length)
    *set_data_length = size;
  if (set_data_destroy)
    *set_data_destroy = g_free;
}

static void
transmute_selection_format (UINT          from_format,
                            GdkAtom       to_target,
                            const guchar *data,
                            gint          length,
                            guchar      **set_data,
                            gint         *set_data_length)
{
  if ((to_target == _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_IMAGE_PNG) &&
       from_format == _gdk_win32_selection_cf (GDK_WIN32_CF_INDEX_PNG)) ||
      (to_target == _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_IMAGE_JPEG) &&
       from_format == _gdk_win32_selection_cf (GDK_WIN32_CF_INDEX_JFIF)) ||
      (to_target == _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_GIF) &&
       from_format == _gdk_win32_selection_cf (GDK_WIN32_CF_INDEX_GIF)))
    {
      /* No transmutation needed */
      *set_data = g_memdup (data, length);
      *set_data_length = length;
    }
  else if (to_target == _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_UTF8_STRING) &&
           from_format == CF_UNICODETEXT)
    {
      transmute_cf_unicodetext_to_utf8_string (data, length, set_data, set_data_length, NULL);
    }
  else if (to_target == _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_UTF8_STRING) &&
           from_format == CF_TEXT)
    {
      transmute_cf_text_to_utf8_string (data, length, set_data, set_data_length, NULL);
    }
  else if (to_target == _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_IMAGE_BMP) &&
           (from_format == CF_DIB || from_format == CF_DIBV5))
    {
      transmute_cf_dib_to_image_bmp (data, length, set_data, set_data_length, NULL);
    }
  else if (to_target == _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_TEXT_URI_LIST) &&
           from_format == _gdk_win32_selection_cf (GDK_WIN32_CF_INDEX_CFSTR_SHELLIDLIST))
    {
      transmute_cf_shell_id_list_to_text_uri_list (data, length, set_data, set_data_length, NULL);
    }
  else
    {
      g_warning ("Don't know how to transmute format 0x%x to target 0x%p", from_format, to_target);
    }
}

void
transmute_selection_target (GdkAtom       from_target,
                            UINT          to_format,
                            const guchar *data,
                            gint          length,
                            guchar      **set_data,
                            gint         *set_data_length)
{
  if ((from_target == _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_IMAGE_PNG) &&
       to_format == _gdk_win32_selection_cf (GDK_WIN32_CF_INDEX_PNG)) ||
      (from_target == _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_IMAGE_JPEG) &&
       to_format == _gdk_win32_selection_cf (GDK_WIN32_CF_INDEX_JFIF)) ||
      (from_target == _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_GIF) &&
       to_format == _gdk_win32_selection_cf (GDK_WIN32_CF_INDEX_GIF)))
    {
      /* No conversion needed */
      *set_data = g_memdup (data, length);
      *set_data_length = length;
    }
  else if (from_target == _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_UTF8_STRING) &&
           to_format == CF_UNICODETEXT)
    {
      transmute_utf8_string_to_cf_unicodetext (data, length, set_data, set_data_length, NULL);
    }
  else if (from_target == _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_UTF8_STRING) &&
           to_format == CF_TEXT)
    {
      transmute_utf8_string_to_cf_text (data, length, set_data, set_data_length, NULL);
    }
  else if (from_target == _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_IMAGE_BMP) &&
           to_format == CF_DIB)
    {
      transmute_image_bmp_to_cf_dib (data, length, set_data, set_data_length, NULL);
    }
  else if (from_target == _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_IMAGE_BMP) &&
           to_format == CF_DIBV5)
    {
      transmute_image_bmp_to_cf_dib (data, length, set_data, set_data_length, NULL);
    }
/*
  else if (from_target == _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_TEXT_URI_LIST) &&
           to_format == _gdk_win32_selection_cf (GDK_WIN32_CF_INDEX_CFSTR_SHELLIDLIST))
    {
      transmute_text_uri_list_to_shell_id_list (data, length, set_data, set_data_length, NULL);
    }
*/
  else
    {
      g_warning ("Don't know how to transmute from target 0x%p to format 0x%x", from_target, to_format);
    }
}

static GdkAtom
convert_clipboard_selection_to_targets_target (GdkWindow *requestor)
{
  gint fmt;
  int i;
  int format_count = CountClipboardFormats ();
  GArray *targets = g_array_sized_new (FALSE, FALSE, sizeof (GdkSelTargetFormat), format_count);

  for (fmt = 0; 0 != (fmt = EnumClipboardFormats (fmt)); )
    _gdk_win32_add_format_to_targets (fmt, targets, NULL);

  GDK_NOTE (DND, {
      g_print ("... ");
      for (i = 0; i < targets->len; i++)
        {
          gchar *atom_name = gdk_atom_name (g_array_index (targets, GdkSelTargetFormat, i).target);

          g_print ("%s", atom_name);
          g_free (atom_name);
          if (i < targets->len - 1)
            g_print (", ");
        }
      g_print ("\n");
    });

  if (targets->len > 0)
    {
      gint len = targets->len;
      GdkAtom *targets_only = g_new0 (GdkAtom, len);

      for (i = 0; i < targets->len; i++)
        targets_only[i] = g_array_index (targets, GdkSelTargetFormat, i).target;

      g_array_free (targets, TRUE);
      selection_property_store (requestor, GDK_SELECTION_TYPE_ATOM,
                                32, (guchar *) targets_only,
                                len * sizeof (GdkAtom));
      return _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_GDK_SELECTION);
    }
  else
    {
      g_array_free (targets, TRUE);
      return GDK_NONE;
    }
}

static GdkAtom
convert_clipboard_selection_to_target (GdkWindow *requestor,
                                       GdkAtom    target)
{
  UINT format;
  HANDLE hdata;
  guchar *ptr;
  gint length;
  gboolean transmute = FALSE;
  GdkAtom result = _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_GDK_SELECTION);
  gboolean found;
  gchar *atom_name;

  atom_name = gdk_atom_name (target);

  for (format = 0, found = FALSE;
       !found && 0 != (format = EnumClipboardFormats (format));
      )
    {
      gboolean predef;
      gchar *format_name = _gdk_win32_get_clipboard_format_name (format, &predef);

      if (format_name == NULL)
        continue;

      found = g_strcmp0 (format_name, atom_name) == 0;
      g_free (format_name);
    }

  g_free (atom_name);

  if (format == 0)
    {
      gint i;
      GArray *compat_formats = get_compatibility_formats_for_target (target);

      for (i = 0; compat_formats != NULL && i < compat_formats->len; i++)
        {
          if (!IsClipboardFormatAvailable (g_array_index (compat_formats, GdkSelTargetFormat, i).format))
            continue;

          format = g_array_index (compat_formats, GdkSelTargetFormat, i).format;
          transmute = g_array_index (compat_formats, GdkSelTargetFormat, i).transmute;
          break;
        }
    }

  if (format == 0)
    return GDK_NONE;

  if ((hdata = GetClipboardData (format)) == NULL)
    return GDK_NONE;

  if ((ptr = GlobalLock (hdata)) != NULL)
    {
      guchar *data = NULL;
      gint data_len = 0;
      length = GlobalSize (hdata);

      GDK_NOTE (DND, g_print ("... format 0x%x: %d bytes\n", format, length));

      if (transmute)
        {
          transmute_selection_format (format, target, ptr, length, &data, &data_len);
        }
      else
        {
          data = g_memdup (ptr, length);
          data_len = length;
        }

      if (data)
        selection_property_store (requestor, target,
                                  8, data, data_len);
      else
        result = GDK_NONE;

      GlobalUnlock (hdata);
    }

  return result;
}

static GdkAtom
convert_selection_with_opened_clipboard (GdkDisplay *display,
                                          GdkWindow  *requestor,
                                          GdkAtom     target,
                                          guint32     time)
{
  GdkAtom property;

  if (target == _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_TARGETS))
    property = convert_clipboard_selection_to_targets_target (requestor);
  else
    property = convert_clipboard_selection_to_target (requestor, target);

  return property;
}

static void
announce_delayrendered_targets_with_opened_clipboard (GdkWin32Selection *win32_sel)
{
  gint i;
  /* Announce the formats we support, but don't actually put any data out there.
   * Other processes will send us WM_RENDERFORMAT to get the data.
   */
  for (i = 0; i < win32_sel->clipboard_selection_targets->len; i++)
    {
      GdkSelTargetFormat *fmt = &g_array_index (win32_sel->clipboard_selection_targets, GdkSelTargetFormat, i);

      /* Some calls here may be duplicates, but we don't really care */
      if (fmt->format != 0)
        SetClipboardData (fmt->format, NULL);
    }
}

static gboolean
open_clipboard_timeout (gpointer data)
{
  GList *tmp_list, *next;
  GdkWin32ClipboardQueueInfo *info;
  GdkWin32Selection *win32_sel = _gdk_win32_selection_get ();

  GDK_NOTE (DND, g_print ("Open clipboard timeout ticks\n"));

  /* Clear out old and invalid entries */
  for (tmp_list = clipboard_queue; tmp_list; tmp_list = next)
    {
      info = (GdkWin32ClipboardQueueInfo *) tmp_list->data;
      next = g_list_next (tmp_list);

      if (GDK_WINDOW_DESTROYED (info->requestor) ||
          info->idle_time >= CLIPBOARD_IDLE_ABORT_TIME)
        {
          clipboard_queue = g_list_remove_link (clipboard_queue, tmp_list);
          g_list_free (tmp_list);
          switch (info->action)
            {
            case GDK_WIN32_CLIPBOARD_QUEUE_ACTION_TARGETS:
              break;
            case GDK_WIN32_CLIPBOARD_QUEUE_ACTION_CONVERT:
              generate_selection_notify (info->requestor, info->selection, info->target, GDK_NONE, info->time);
              break;
            }
          g_clear_object (&info->requestor);
          g_slice_free (GdkWin32ClipboardQueueInfo, info);
        }
    }

  if (clipboard_queue == NULL)
    {
      GDK_NOTE (DND, g_print ("Stopping open clipboard timer\n"));

      if (win32_sel->clipboard_opened_for != INVALID_HANDLE_VALUE)
        {
          API_CALL (CloseClipboard, ());
          win32_sel->clipboard_opened_for = INVALID_HANDLE_VALUE;
          GDK_NOTE (DND, g_print ("Closed clipboard @ %s:%d\n", __FILE__, __LINE__));
        }

      return FALSE;
    }

  for (tmp_list = clipboard_queue; tmp_list; tmp_list = next)
    {
      GdkAtom property;

      info = (GdkWin32ClipboardQueueInfo *) tmp_list->data;
      next = g_list_next (tmp_list);

      /* CONVERT works with any opened clipboard,
       * but TARGETS needs to open the clipboard with the hande of the
       * owner window.
       */
      if (info->action == GDK_WIN32_CLIPBOARD_QUEUE_ACTION_TARGETS &&
          win32_sel->clipboard_opened_for == NULL)
        {
          GDK_NOTE (DND, g_print ("Need to re-open clipboard, closing\n"));
          API_CALL (CloseClipboard, ());
          win32_sel->clipboard_opened_for = INVALID_HANDLE_VALUE;
        }

      if (win32_sel->clipboard_opened_for == INVALID_HANDLE_VALUE)
        {
          if (!OpenClipboard (GDK_WINDOW_HWND (info->requestor)))
            {
              info->idle_time += 1;
              continue;
            }
          win32_sel->clipboard_opened_for = GDK_WINDOW_HWND (info->requestor);
          GDK_NOTE (DND, g_print ("Opened clipboard for 0x%p @ %s:%d\n", win32_sel->clipboard_opened_for, __FILE__, __LINE__));
        }

      clipboard_queue = g_list_remove_link (clipboard_queue, tmp_list);
      g_list_free (tmp_list);

      switch (info->action)
        {
        case GDK_WIN32_CLIPBOARD_QUEUE_ACTION_CONVERT:
          property = convert_selection_with_opened_clipboard (info->display,
                                                              info->requestor,
                                                              info->target,
                                                              info->time);
          generate_selection_notify (info->requestor,
                                     GDK_SELECTION_CLIPBOARD,
                                     info->target,
                                     property,
                                     info->time);
          break;
        case GDK_WIN32_CLIPBOARD_QUEUE_ACTION_TARGETS:
          announce_delayrendered_targets_with_opened_clipboard (win32_sel);
          break;
        default:
          g_assert_not_reached ();
        }

      g_clear_object (&info->requestor);
      g_slice_free (GdkWin32ClipboardQueueInfo, info);
    }

  if (clipboard_queue != NULL)
    return TRUE;

  if (win32_sel->clipboard_opened_for != INVALID_HANDLE_VALUE)
    {
      API_CALL (CloseClipboard, ());
      win32_sel->clipboard_opened_for = INVALID_HANDLE_VALUE;
      GDK_NOTE (DND, g_print ("Closed clipboard @ %s:%d\n", __FILE__, __LINE__));
    }

  GDK_NOTE (DND, g_print ("Stopping open clipboard timer\n"));

  return FALSE;
}

static void
queue_open_clipboard (GdkWin32ClipboardQueueAction  action,
                      GdkDisplay                   *display,
                      GdkWindow                    *requestor,
                      GdkAtom                       target,
                      guint32                       time)
{
  guint id;
  GList *tmp_list, *next;
  GdkWin32ClipboardQueueInfo *info;
  GdkWin32Selection *win32_sel = _gdk_win32_selection_get ();

  for (tmp_list = clipboard_queue; tmp_list; tmp_list = next)
    {
      info = (GdkWin32ClipboardQueueInfo *) tmp_list->data;
      next = g_list_next (tmp_list);

      if (info->action == action &&
          info->requestor == requestor)
	return;
    }

  info = g_slice_new (GdkWin32ClipboardQueueInfo);

  info->display = display;
  g_set_object (&info->requestor, requestor);
  info->selection = GDK_SELECTION_CLIPBOARD;
  info->target = target;
  info->idle_time = 0;
  info->time = time;
  info->action = action;

  GDK_NOTE (DND, g_print ("Queueing open clipboard\n"));

  if (win32_sel->clipboard_opened_for == INVALID_HANDLE_VALUE &&
      clipboard_queue == NULL)
    {
      id = gdk_threads_add_timeout_seconds (1, (GSourceFunc) open_clipboard_timeout, NULL);
      g_source_set_name_by_id (id, "[gdk-win32] open_clipboard_timeout");
      GDK_NOTE (DND, g_print ("Started open clipboard timer\n"));
    }

  clipboard_queue = g_list_append (clipboard_queue, info);
}

gboolean
_gdk_win32_display_set_selection_owner (GdkDisplay *display,
					GdkWindow  *owner,
					GdkAtom     selection,
					guint32     time,
					gboolean    send_event)
{
  HWND hwnd;
  GdkWin32Selection *win32_sel = _gdk_win32_selection_get ();

  g_return_val_if_fail (selection != GDK_NONE, FALSE);

  GDK_NOTE (DND, {
      gchar *sel_name = gdk_atom_name (selection);

      g_print ("gdk_selection_owner_set_for_display: %p %s\n",
	       (owner ? GDK_WINDOW_HWND (owner) : NULL),
	       sel_name);
      g_free (sel_name);
    });

  if (selection != GDK_SELECTION_CLIPBOARD)
    {
      if (owner != NULL)
        g_hash_table_insert (win32_sel->sel_owner_table, selection, GDK_WINDOW_HWND (owner));
      else
        g_hash_table_remove (win32_sel->sel_owner_table, selection);

      return TRUE;
    }

  /* Rest of this function handles the CLIPBOARD selection */
  if (owner != NULL)
    {
      if (GDK_WINDOW_DESTROYED (owner))
	return FALSE;

      hwnd = GDK_WINDOW_HWND (owner);
    }
  else
    hwnd = NULL;

  if (win32_sel->clipboard_opened_for != hwnd &&
      win32_sel->clipboard_opened_for != INVALID_HANDLE_VALUE)
    {
      API_CALL (CloseClipboard, ());
      win32_sel->clipboard_opened_for = INVALID_HANDLE_VALUE;
      GDK_NOTE (DND, g_print ("Closed clipboard @ %s:%d\n", __FILE__, __LINE__));
    }

  if (!OpenClipboard (hwnd))
    {
      if (GetLastError () != ERROR_ACCESS_DENIED)
        WIN32_API_FAILED ("OpenClipboard");

      return FALSE;
    }
2075

2076 2077 2078
  win32_sel->clipboard_opened_for = hwnd;
  GDK_NOTE (DND, g_print ("Opened clipboard for 0x%p @ %s:%d\n", win32_sel->clipboard_opened_for, __FILE__, __LINE__));
  win32_sel->ignore_destroy_clipboard = TRUE;
2079
  GDK_NOTE (DND, g_print ("... EmptyClipboard()\n"));
2080
  if (!API_CALL (EmptyClipboard, ()))
2081
    {
2082
      win32_sel->ignore_destroy_clipboard = FALSE;
2083
      API_CALL (CloseClipboard, ());
2084 2085
      win32_sel->clipboard_opened_for = INVALID_HANDLE_VALUE;
      GDK_NOTE (DND, g_print ("Closed clipboard @ %s:%d\n", __FILE__, __LINE__));
2086 2087
      return FALSE;
    }
2088
  win32_sel->ignore_destroy_clipboard = FALSE;
2089

2090 2091 2092 2093
  /* Any queued clipboard operations were just made pointless
   * by EmptyClipboard().
   */
  _gdk_win32_clear_clipboard_queue ();
2094

2095 2096 2097 2098 2099
  /* This is kind of risky, but we don't close the clipboard
   * to ensure that it's still open when GDK_SELECTION_REQUEST
   * is handled.
   */
  if (owner == NULL)
2100
    {
2101 2102 2103 2104
      if (!API_CALL (CloseClipboard, ()))
        return FALSE;
      GDK_NOTE (DND, g_print ("Closed clipboard @ %s:%d\n", __FILE__, __LINE__));
      win32_sel->clipboard_opened_for = INVALID_HANDLE_VALUE;
2105 2106
    }

2107 2108
  send_targets_request (time);

2109 2110 2111 2112
  return TRUE;
}

GdkWindow*
Hans Breuer's avatar
Hans Breuer committed
2113 2114
_gdk_win32_display_get_selection_owner (GdkDisplay *display,
                                        GdkAtom     selection)
2115 2116
{
  GdkWindow *window;
2117 2118
  HWND selection_owner;
  GdkWin32Selection *win32_sel = _gdk_win32_selection_get ();
2119

2120
  g_return_val_if_fail (selection != GDK_NONE, NULL);
2121

2122
  if (selection == GDK_SELECTION_CLIPBOARD)
2123 2124 2125
    selection_owner = GetClipboardOwner ();
  else
    selection_owner = g_hash_table_lookup (win32_sel->sel_owner_table, selection);
Hans Breuer's avatar
Hans Breuer committed
2126

2127 2128 2129 2130 2131
  if (selection_owner)
    window = gdk_win32_window_lookup_for_display (display,
                                                  selection_owner);
  else
    window = NULL;
2132

2133 2134
  GDK_NOTE (DND, {
      gchar *sel_name = gdk_atom_name (selection);
2135

2136 2137 2138 2139 2140
      g_print ("gdk_selection_owner_get: %s = %p\n",
	       sel_name,
	       (window ? GDK_WINDOW_HWND (window) : NULL));
      g_free (sel_name);
    });
2141 2142 2143 2144

  return window;
}

2145 2146 2147
static GdkAtom
convert_dnd_selection_to_target (GdkAtom    target,
                                 GdkWindow *requestor)
2148
{
2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177
  GdkWin32Selection *win32_sel = _gdk_win32_selection_get ();
  UINT format;
  gint i, with_transmute;
  guchar *ptr;
  gint length;
  gboolean transmute = FALSE;
  GdkWin32DragContext *context_win32;
  FORMATETC fmt;
  STGMEDIUM storage;
  HRESULT hr;
  GdkAtom result = _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_OLE2_DND);

  g_assert (win32_sel->target_drag_context != NULL);
  g_assert (win32_sel->dnd_data_object_target != NULL);

  context_win32 = GDK_WIN32_DRAG_CONTEXT (win32_sel->target_drag_context);

  fmt.ptd = NULL;
  fmt.dwAspect = DVASPECT_CONTENT;
  fmt.lindex = -1;
  fmt.tymed = TYMED_HGLOBAL;

  for (format = 0, with_transmute = 0; format == 0 && with_transmute < 2; with_transmute++)
    {
      for (i = 0;
           i < context_win32->droptarget_format_target_map->len;
           i++)
        {
          GdkSelTargetFormat selformat = g_array_index (context_win32->droptarget_format_target_map, GdkSelTargetFormat, i);
2178

2179 2180 2181
          if (selformat.target != target ||
              selformat.transmute != (with_transmute == 0 ? FALSE : TRUE))
            continue;
2182

2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
          fmt.cfFormat = selformat.format;

          hr = IDataObject_QueryGetData (win32_sel->dnd_data_object_target, &fmt);

          if (!SUCCEEDED (hr) || hr != S_OK)
            continue;

          format = selformat.format;
          transmute = selformat.transmute;
          break;
        }
    }

  if (format == 0)
    return GDK_NONE;

  hr = IDataObject_GetData (win32_sel->dnd_data_object_target, &fmt, &storage);

  if (!SUCCEEDED (hr) || hr != S_OK)
    return GDK_NONE;

  if ((ptr = GlobalLock (storage.hGlobal)) != NULL)
    {
      guchar *data = NULL;
      gint    data_len = 0;

      SetLastError (0);
      length = GlobalSize (storage.hGlobal);

      if (GetLastError () == NO_ERROR)
        {
          if (transmute)
            {
              transmute_selection_format (format, target, ptr, length, &data, &data_len);
            }
          else
            {
              data = g_memdup (ptr, length);
              data_len = length;
            }

          if (data)
            selection_property_store (requestor, target, 8,
                                      data, data_len);
          else
            result = GDK_NONE;
        }
      else
        result = GDK_NONE;

      GlobalUnlock (storage.hGlobal);
    }
  else
    result = GDK_NONE;

  ReleaseStgMedium (&storage);

  return result;
2241 2242
}

2243
void
Hans Breuer's avatar
Hans Breuer committed
2244 2245 2246 2247 2248
_gdk_win32_display_convert_selection (GdkDisplay *display,
				      GdkWindow *requestor,
				      GdkAtom    selection,
				      GdkAtom    target,
				      guint32    time)
2249
{
2250 2251
  GdkWin32Selection *win32_sel = _gdk_win32_selection_get ();
  GdkAtom property = _gdk_win32_selection_atom (GDK_WIN32_ATOM_INDEX_GDK_SELECTION);
2252

2253
  g_return_if_fail (selection != GDK_NONE);
2254
  g_return_if_fail (requestor != NULL);
2255

Tor Lillqvist's avatar
Tor Lillqvist committed
2256
  if (GDK_WINDOW_DESTROYED (requestor))
2257 2258
    return;

2259 2260 2261
  GDK_NOTE (DND, {
      gchar *sel_name = gdk_atom_name (selection);
      gchar *tgt_name = gdk_atom_name (target);
2262