msvcrt: Added _set_fmode and _get_fmode implementation.
[wine] / dlls / winex11.drv / clipboard.c
1 /*
2  * X11 clipboard windows driver
3  *
4  * Copyright 1994 Martin Ayotte
5  *           1996 Alex Korobka
6  *           1999 Noel Borthwick
7  *           2003 Ulrich Czekalla for CodeWeavers
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  *
23  * NOTES:
24  *    This file contains the X specific implementation for the windows
25  *    Clipboard API.
26  *
27  *    Wine's internal clipboard is exposed to external apps via the X
28  *    selection mechanism.
29  *    Currently the driver asserts ownership via two selection atoms:
30  *    1. PRIMARY(XA_PRIMARY)
31  *    2. CLIPBOARD
32  *
33  *    In our implementation, the CLIPBOARD selection takes precedence over PRIMARY,
34  *    i.e. if a CLIPBOARD selection is available, it is used instead of PRIMARY.
35  *    When Wine takes ownership of the clipboard, it takes ownership of BOTH selections.
36  *    While giving up selection ownership, if the CLIPBOARD selection is lost,
37  *    it will lose both PRIMARY and CLIPBOARD and empty the clipboard.
38  *    However if only PRIMARY is lost, it will continue to hold the CLIPBOARD selection
39  *    (leaving the clipboard cache content unaffected).
40  *
41  *      Every format exposed via a windows clipboard format is also exposed through
42  *    a corresponding X selection target. A selection target atom is synthesized
43  *    whenever a new Windows clipboard format is registered via RegisterClipboardFormat,
44  *    or when a built-in format is used for the first time.
45  *    Windows native format are exposed by prefixing the format name with "<WCF>"
46  *    This allows us to uniquely identify windows native formats exposed by other
47  *    running WINE apps.
48  *
49  *      In order to allow external applications to query WINE for supported formats,
50  *    we respond to the "TARGETS" selection target. (See EVENT_SelectionRequest
51  *    for implementation) We use the same mechanism to query external clients for
52  *    availability of a particular format, by caching the list of available targets
53  *    by using the clipboard cache's "delayed render" mechanism. If a selection client
54  *    does not support the "TARGETS" selection target, we actually attempt to retrieve
55  *    the format requested as a fallback mechanism.
56  *
57  *      Certain Windows native formats are automatically converted to X native formats
58  *    and vice versa. If a native format is available in the selection, it takes
59  *    precedence, in order to avoid unnecessary conversions.
60  *
61  * FIXME: global format list needs a critical section
62  */
63
64 #include "config.h"
65 #include "wine/port.h"
66
67 #include <string.h>
68 #include <stdarg.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #ifdef HAVE_UNISTD_H
72 # include <unistd.h>
73 #endif
74 #include <fcntl.h>
75 #include <limits.h>
76 #include <time.h>
77 #include <assert.h>
78
79 #include "windef.h"
80 #include "winbase.h"
81 #include "x11drv.h"
82 #include "wine/list.h"
83 #include "wine/debug.h"
84 #include "wine/unicode.h"
85 #include "wine/server.h"
86
87 WINE_DEFAULT_DEBUG_CHANNEL(clipboard);
88
89 /* Maximum wait time for selection notify */
90 #define SELECTION_RETRIES 500  /* wait for .5 seconds */
91 #define SELECTION_WAIT    1000 /* us */
92
93 /* Selection masks */
94 #define S_NOSELECTION    0
95 #define S_PRIMARY        1
96 #define S_CLIPBOARD      2
97
98 typedef struct
99 {
100     HWND hWndOpen;
101     HWND hWndOwner;
102     HWND hWndViewer;
103     UINT seqno;
104     UINT flags;
105 } CLIPBOARDINFO, *LPCLIPBOARDINFO;
106
107 struct tagWINE_CLIPDATA; /* Forward */
108
109 typedef HANDLE (*DRVEXPORTFUNC)(Display *display, Window requestor, Atom aTarget, Atom rprop,
110     struct tagWINE_CLIPDATA* lpData, LPDWORD lpBytes);
111 typedef HANDLE (*DRVIMPORTFUNC)(Display *d, Window w, Atom prop);
112
113 typedef struct tagWINE_CLIPFORMAT {
114     struct list entry;
115     UINT        wFormatID;
116     UINT        drvData;
117     DRVIMPORTFUNC  lpDrvImportFunc;
118     DRVEXPORTFUNC  lpDrvExportFunc;
119 } WINE_CLIPFORMAT, *LPWINE_CLIPFORMAT;
120
121 typedef struct tagWINE_CLIPDATA {
122     struct list entry;
123     UINT        wFormatID;
124     HANDLE      hData;
125     UINT        wFlags;
126     UINT        drvData;
127     LPWINE_CLIPFORMAT lpFormat;
128 } WINE_CLIPDATA, *LPWINE_CLIPDATA;
129
130 #define CF_FLAG_UNOWNED      0x0001 /* cached data is not owned */
131 #define CF_FLAG_SYNTHESIZED  0x0002 /* Implicitly converted data */
132
133 static int selectionAcquired = 0;              /* Contains the current selection masks */
134 static Window selectionWindow = None;          /* The top level X window which owns the selection */
135 static Atom selectionCacheSrc = XA_PRIMARY;    /* The selection source from which the clipboard cache was filled */
136
137 void CDECL X11DRV_EmptyClipboard(BOOL keepunowned);
138 void CDECL X11DRV_EndClipboardUpdate(void);
139 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *d, Window w, Atom prop);
140 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *d, Window w, Atom prop);
141 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *d, Window w, Atom prop);
142 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *d, Window w, Atom prop);
143 static HANDLE X11DRV_CLIPBOARD_ImportImageBmp(Display *d, Window w, Atom prop);
144 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *d, Window w, Atom prop);
145 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *d, Window w, Atom prop);
146 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *d, Window w, Atom prop);
147 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
148     Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
149 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget,
150     Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
151 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget,
152     Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
153 static HANDLE X11DRV_CLIPBOARD_ExportImageBmp(Display *display, Window requestor, Atom aTarget,
154     Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
155 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget,
156     Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
157 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget,
158     Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
159 static HANDLE X11DRV_CLIPBOARD_ExportTextHtml(Display *display, Window requestor, Atom aTarget,
160     Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
161 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(UINT id, Atom prop);
162 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID);
163 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData);
164 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void);
165 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo);
166 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData);
167 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
168     unsigned char** data, unsigned long* datasize);
169 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData);
170 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out);
171 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID);
172 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData);
173 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display);
174 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display);
175 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile(Display *display);
176 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple );
177
178 /* Clipboard formats */
179
180 static const struct
181 {
182     UINT          id;
183     UINT          data;
184     DRVIMPORTFUNC import;
185     DRVEXPORTFUNC export;
186 } builtin_formats[] =
187 {
188     { CF_TEXT, XA_STRING, X11DRV_CLIPBOARD_ImportXAString, X11DRV_CLIPBOARD_ExportString},
189     { CF_BITMAP, XATOM_WCF_BITMAP, X11DRV_CLIPBOARD_ImportClipboardData, NULL},
190     { CF_METAFILEPICT, XATOM_WCF_METAFILEPICT, X11DRV_CLIPBOARD_ImportMetaFilePict, X11DRV_CLIPBOARD_ExportMetaFilePict },
191     { CF_SYLK, XATOM_WCF_SYLK, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
192     { CF_DIF, XATOM_WCF_DIF, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
193     { CF_TIFF, XATOM_WCF_TIFF, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
194     { CF_OEMTEXT, XATOM_WCF_OEMTEXT, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
195     { CF_DIB, XA_PIXMAP, X11DRV_CLIPBOARD_ImportXAPIXMAP, X11DRV_CLIPBOARD_ExportXAPIXMAP },
196     { CF_PALETTE, XATOM_WCF_PALETTE, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
197     { CF_PENDATA, XATOM_WCF_PENDATA, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
198     { CF_RIFF, XATOM_WCF_RIFF, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
199     { CF_WAVE, XATOM_WCF_WAVE, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
200     { CF_UNICODETEXT, XATOM_UTF8_STRING, X11DRV_CLIPBOARD_ImportUTF8, X11DRV_CLIPBOARD_ExportString },
201     /* If UTF8_STRING is not available, attempt COMPOUND_TEXT */
202     { CF_UNICODETEXT, XATOM_COMPOUND_TEXT, X11DRV_CLIPBOARD_ImportCompoundText, X11DRV_CLIPBOARD_ExportString },
203     { CF_ENHMETAFILE, XATOM_WCF_ENHMETAFILE, X11DRV_CLIPBOARD_ImportEnhMetaFile, X11DRV_CLIPBOARD_ExportEnhMetaFile },
204     { CF_HDROP, XATOM_WCF_HDROP, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
205     { CF_LOCALE, XATOM_WCF_LOCALE, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
206     { CF_DIBV5, XATOM_WCF_DIBV5, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
207     { CF_OWNERDISPLAY, XATOM_WCF_OWNERDISPLAY, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
208     { CF_DSPTEXT, XATOM_WCF_DSPTEXT, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
209     { CF_DSPBITMAP, XATOM_WCF_DSPBITMAP, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
210     { CF_DSPMETAFILEPICT, XATOM_WCF_DSPMETAFILEPICT, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
211     { CF_DSPENHMETAFILE, XATOM_WCF_DSPENHMETAFILE, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
212     { CF_DIB, XATOM_image_bmp, X11DRV_CLIPBOARD_ImportImageBmp, X11DRV_CLIPBOARD_ExportImageBmp },
213 };
214
215 static struct list format_list = LIST_INIT( format_list );
216
217 #define GET_ATOM(prop)  (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
218
219 /* Maps X properties to Windows formats */
220 static const WCHAR wszRichTextFormat[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
221 static const WCHAR wszGIF[] = {'G','I','F',0};
222 static const WCHAR wszJFIF[] = {'J','F','I','F',0};
223 static const WCHAR wszPNG[] = {'P','N','G',0};
224 static const WCHAR wszHTMLFormat[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
225 static const struct
226 {
227     LPCWSTR lpszFormat;
228     UINT   prop;
229 } PropertyFormatMap[] =
230 {
231     { wszRichTextFormat, XATOM_text_rtf },
232     { wszRichTextFormat, XATOM_text_richtext },
233     { wszGIF, XATOM_image_gif },
234     { wszJFIF, XATOM_image_jpeg },
235     { wszPNG, XATOM_image_png },
236     { wszHTMLFormat, XATOM_HTML_Format }, /* prefer this to text/html */
237 };
238
239
240 /*
241  * Cached clipboard data.
242  */
243 static struct list data_list = LIST_INIT( data_list );
244 static UINT ClipDataCount = 0;
245
246 /*
247  * Clipboard sequence number
248  */
249 static UINT wSeqNo = 0;
250
251 /**************************************************************************
252  *                Internal Clipboard implementation methods
253  **************************************************************************/
254
255 static Window thread_selection_wnd(void)
256 {
257     struct x11drv_thread_data *thread_data = x11drv_init_thread_data();
258     Window w = thread_data->selection_wnd;
259
260     if (!w)
261     {
262         w = XCreateWindow(thread_data->display, root_window, 0, 0, 1, 1, 0, CopyFromParent,
263                           InputOnly, CopyFromParent, 0, NULL);
264         if (w)
265             thread_data->selection_wnd = w;
266         else
267             FIXME("Failed to create window. Fetching selection data will fail.\n");
268     }
269
270     return w;
271 }
272
273 static const char *debugstr_format( UINT id )
274 {
275     WCHAR buffer[256];
276
277     if (GetClipboardFormatNameW( id, buffer, 256 ))
278         return wine_dbg_sprintf( "%04x %s", id, debugstr_w(buffer) );
279
280     switch (id)
281     {
282 #define BUILTIN(id) case id: return #id;
283     BUILTIN(CF_TEXT)
284     BUILTIN(CF_BITMAP)
285     BUILTIN(CF_METAFILEPICT)
286     BUILTIN(CF_SYLK)
287     BUILTIN(CF_DIF)
288     BUILTIN(CF_TIFF)
289     BUILTIN(CF_OEMTEXT)
290     BUILTIN(CF_DIB)
291     BUILTIN(CF_PALETTE)
292     BUILTIN(CF_PENDATA)
293     BUILTIN(CF_RIFF)
294     BUILTIN(CF_WAVE)
295     BUILTIN(CF_UNICODETEXT)
296     BUILTIN(CF_ENHMETAFILE)
297     BUILTIN(CF_HDROP)
298     BUILTIN(CF_LOCALE)
299     BUILTIN(CF_DIBV5)
300     BUILTIN(CF_OWNERDISPLAY)
301     BUILTIN(CF_DSPTEXT)
302     BUILTIN(CF_DSPBITMAP)
303     BUILTIN(CF_DSPMETAFILEPICT)
304     BUILTIN(CF_DSPENHMETAFILE)
305 #undef BUILTIN
306     default: return wine_dbg_sprintf( "%04x", id );
307     }
308 }
309
310 /**************************************************************************
311  *              X11DRV_InitClipboard
312  */
313 void X11DRV_InitClipboard(void)
314 {
315     UINT i;
316     WINE_CLIPFORMAT *format;
317
318     /* Register built-in formats */
319     for (i = 0; i < sizeof(builtin_formats)/sizeof(builtin_formats[0]); i++)
320     {
321         if (!(format = HeapAlloc( GetProcessHeap(), 0, sizeof(*format )))) break;
322         format->wFormatID       = builtin_formats[i].id;
323         format->drvData         = GET_ATOM(builtin_formats[i].data);
324         format->lpDrvImportFunc = builtin_formats[i].import;
325         format->lpDrvExportFunc = builtin_formats[i].export;
326         list_add_tail( &format_list, &format->entry );
327     }
328
329     /* Register known mapping between window formats and X properties */
330     for (i = 0; i < sizeof(PropertyFormatMap)/sizeof(PropertyFormatMap[0]); i++)
331         X11DRV_CLIPBOARD_InsertClipboardFormat( RegisterClipboardFormatW(PropertyFormatMap[i].lpszFormat),
332                                                 GET_ATOM(PropertyFormatMap[i].prop));
333
334     /* Set up a conversion function from "HTML Format" to "text/html" */
335     format = X11DRV_CLIPBOARD_InsertClipboardFormat( RegisterClipboardFormatW(wszHTMLFormat),
336                                                      GET_ATOM(XATOM_text_html));
337     format->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportTextHtml;
338 }
339
340
341 /**************************************************************************
342  *                intern_atoms
343  *
344  * Intern atoms for formats that don't have one yet.
345  */
346 static void intern_atoms(void)
347 {
348     LPWINE_CLIPFORMAT format;
349     int i, count, len;
350     char **names;
351     Atom *atoms;
352     Display *display;
353     WCHAR buffer[256];
354
355     count = 0;
356     LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
357         if (!format->drvData) count++;
358     if (!count) return;
359
360     display = thread_init_display();
361
362     names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
363     atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
364
365     i = 0;
366     LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
367         if (!format->drvData) {
368             GetClipboardFormatNameW( format->wFormatID, buffer, 256 );
369             len = WideCharToMultiByte(CP_UNIXCP, 0, buffer, -1, NULL, 0, NULL, NULL);
370             names[i] = HeapAlloc(GetProcessHeap(), 0, len);
371             WideCharToMultiByte(CP_UNIXCP, 0, buffer, -1, names[i++], len, NULL, NULL);
372         }
373
374     XInternAtoms( display, names, count, False, atoms );
375
376     i = 0;
377     LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
378         if (!format->drvData) {
379             HeapFree(GetProcessHeap(), 0, names[i]);
380             format->drvData = atoms[i++];
381         }
382
383     HeapFree( GetProcessHeap(), 0, names );
384     HeapFree( GetProcessHeap(), 0, atoms );
385 }
386
387
388 /**************************************************************************
389  *              register_format
390  *
391  * Register a custom X clipboard format.
392  */
393 static WINE_CLIPFORMAT *register_format( UINT id, Atom prop )
394 {
395     LPWINE_CLIPFORMAT lpFormat;
396
397     /* walk format chain to see if it's already registered */
398     LIST_FOR_EACH_ENTRY( lpFormat, &format_list, WINE_CLIPFORMAT, entry )
399         if (lpFormat->wFormatID == id) return lpFormat;
400
401     return X11DRV_CLIPBOARD_InsertClipboardFormat(id, prop);
402 }
403
404
405 /**************************************************************************
406  *                X11DRV_CLIPBOARD_LookupProperty
407  */
408 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupProperty(LPWINE_CLIPFORMAT current, UINT drvData)
409 {
410     for (;;)
411     {
412         struct list *ptr = current ? &current->entry : &format_list;
413         BOOL need_intern = FALSE;
414
415         while ((ptr = list_next( &format_list, ptr )))
416         {
417             LPWINE_CLIPFORMAT lpFormat = LIST_ENTRY( ptr, WINE_CLIPFORMAT, entry );
418             if (lpFormat->drvData == drvData) return lpFormat;
419             if (!lpFormat->drvData) need_intern = TRUE;
420         }
421         if (!need_intern) return NULL;
422         intern_atoms();
423         /* restart the search for the new atoms */
424     }
425 }
426
427
428 /**************************************************************************
429  *               X11DRV_CLIPBOARD_LookupData
430  */
431 static LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
432 {
433     WINE_CLIPDATA *data;
434
435     LIST_FOR_EACH_ENTRY( data, &data_list, WINE_CLIPDATA, entry )
436         if (data->wFormatID == wID) return data;
437
438     return NULL;
439 }
440
441
442 /**************************************************************************
443  *              InsertClipboardFormat
444  */
445 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat( UINT id, Atom prop )
446 {
447     LPWINE_CLIPFORMAT lpNewFormat;
448
449     /* allocate storage for new format entry */
450     lpNewFormat = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPFORMAT));
451
452     if(lpNewFormat == NULL) 
453     {
454         WARN("No more memory for a new format!\n");
455         return NULL;
456     }
457     lpNewFormat->wFormatID = id;
458     lpNewFormat->drvData = prop;
459     lpNewFormat->lpDrvImportFunc = X11DRV_CLIPBOARD_ImportClipboardData;
460     lpNewFormat->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportClipboardData;
461
462     list_add_tail( &format_list, &lpNewFormat->entry );
463
464     TRACE("Registering format %s drvData %d\n",
465           debugstr_format(lpNewFormat->wFormatID), lpNewFormat->drvData);
466
467     return lpNewFormat;
468 }
469
470
471
472
473 /**************************************************************************
474  *                      X11DRV_CLIPBOARD_GetClipboardInfo
475  */
476 static BOOL X11DRV_CLIPBOARD_GetClipboardInfo(LPCLIPBOARDINFO cbInfo)
477 {
478     BOOL bRet = FALSE;
479
480     SERVER_START_REQ( set_clipboard_info )
481     {
482         req->flags = 0;
483
484         if (wine_server_call_err( req ))
485         {
486             ERR("Failed to get clipboard owner.\n");
487         }
488         else
489         {
490             cbInfo->hWndOpen = wine_server_ptr_handle( reply->old_clipboard );
491             cbInfo->hWndOwner = wine_server_ptr_handle( reply->old_owner );
492             cbInfo->hWndViewer = wine_server_ptr_handle( reply->old_viewer );
493             cbInfo->seqno = reply->seqno;
494             cbInfo->flags = reply->flags;
495
496             bRet = TRUE;
497         }
498     }
499     SERVER_END_REQ;
500
501     return bRet;
502 }
503
504
505 /**************************************************************************
506  *      X11DRV_CLIPBOARD_ReleaseOwnership
507  */
508 static BOOL X11DRV_CLIPBOARD_ReleaseOwnership(void)
509 {
510     BOOL bRet = FALSE;
511
512     SERVER_START_REQ( set_clipboard_info )
513     {
514         req->flags = SET_CB_RELOWNER | SET_CB_SEQNO;
515
516         if (wine_server_call_err( req ))
517         {
518             ERR("Failed to set clipboard.\n");
519         }
520         else
521         {
522             bRet = TRUE;
523         }
524     }
525     SERVER_END_REQ;
526
527     return bRet;
528 }
529
530
531
532 /**************************************************************************
533  *                      X11DRV_CLIPBOARD_InsertClipboardData
534  *
535  * Caller *must* have the clipboard open and be the owner.
536  */
537 static BOOL X11DRV_CLIPBOARD_InsertClipboardData(UINT wFormatID, HANDLE hData, DWORD flags,
538                                                  LPWINE_CLIPFORMAT lpFormat, BOOL override)
539 {
540     LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormatID);
541
542     TRACE("format=%04x lpData=%p hData=%p flags=0x%08x lpFormat=%p override=%d\n",
543         wFormatID, lpData, hData, flags, lpFormat, override);
544
545     /* make sure the format exists */
546     if (!lpFormat) register_format( wFormatID, 0 );
547
548     if (lpData && !override)
549         return TRUE;
550
551     if (lpData)
552     {
553         X11DRV_CLIPBOARD_FreeData(lpData);
554
555         lpData->hData = hData;
556     }
557     else
558     {
559         lpData = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPDATA));
560
561         lpData->wFormatID = wFormatID;
562         lpData->hData = hData;
563         lpData->lpFormat = lpFormat;
564         lpData->drvData = 0;
565
566         list_add_tail( &data_list, &lpData->entry );
567         ClipDataCount++;
568     }
569
570     lpData->wFlags = flags;
571
572     return TRUE;
573 }
574
575
576 /**************************************************************************
577  *                      X11DRV_CLIPBOARD_FreeData
578  *
579  * Free clipboard data handle.
580  */
581 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData)
582 {
583     TRACE("%04x\n", lpData->wFormatID);
584
585     if ((lpData->wFormatID >= CF_GDIOBJFIRST &&
586         lpData->wFormatID <= CF_GDIOBJLAST) || 
587         lpData->wFormatID == CF_BITMAP || 
588         lpData->wFormatID == CF_DIB || 
589         lpData->wFormatID == CF_PALETTE)
590     {
591       if (lpData->hData)
592         DeleteObject(lpData->hData);
593
594       if ((lpData->wFormatID == CF_DIB) && lpData->drvData)
595           XFreePixmap(gdi_display, lpData->drvData);
596     }
597     else if (lpData->wFormatID == CF_METAFILEPICT)
598     {
599       if (lpData->hData)
600       {
601         DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData ))->hMF );
602         GlobalFree(lpData->hData);
603       }
604     }
605     else if (lpData->wFormatID == CF_ENHMETAFILE)
606     {
607         if (lpData->hData)
608             DeleteEnhMetaFile(lpData->hData);
609     }
610     else if (lpData->wFormatID < CF_PRIVATEFIRST ||
611              lpData->wFormatID > CF_PRIVATELAST)
612     {
613       if (lpData->hData)
614         GlobalFree(lpData->hData);
615     }
616
617     lpData->hData = 0;
618     lpData->drvData = 0;
619 }
620
621
622 /**************************************************************************
623  *                      X11DRV_CLIPBOARD_UpdateCache
624  */
625 static BOOL X11DRV_CLIPBOARD_UpdateCache(LPCLIPBOARDINFO lpcbinfo)
626 {
627     BOOL bret = TRUE;
628
629     if (!X11DRV_CLIPBOARD_IsSelectionOwner())
630     {
631         if (!X11DRV_CLIPBOARD_GetClipboardInfo(lpcbinfo))
632         {
633             ERR("Failed to retrieve clipboard information.\n");
634             bret = FALSE;
635         }
636         else if (wSeqNo < lpcbinfo->seqno)
637         {
638             X11DRV_EmptyClipboard(TRUE);
639
640             if (X11DRV_CLIPBOARD_QueryAvailableData(thread_init_display(), lpcbinfo) < 0)
641             {
642                 ERR("Failed to cache clipboard data owned by another process.\n");
643                 bret = FALSE;
644             }
645             else
646             {
647                 X11DRV_EndClipboardUpdate();
648             }
649
650             wSeqNo = lpcbinfo->seqno;
651         }
652     }
653
654     return bret;
655 }
656
657
658 /**************************************************************************
659  *                      X11DRV_CLIPBOARD_RenderFormat
660  */
661 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData)
662 {
663     BOOL bret = TRUE;
664
665     TRACE(" 0x%04x hData(%p)\n", lpData->wFormatID, lpData->hData);
666
667     if (lpData->hData) return bret; /* Already rendered */
668
669     if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
670         bret = X11DRV_CLIPBOARD_RenderSynthesizedFormat(display, lpData);
671     else if (!X11DRV_CLIPBOARD_IsSelectionOwner())
672     {
673         if (!X11DRV_CLIPBOARD_ReadSelectionData(display, lpData))
674         {
675             ERR("Failed to cache clipboard data owned by another process. Format=%04x\n",
676                 lpData->wFormatID);
677             bret = FALSE;
678         }
679     }
680     else
681     {
682         CLIPBOARDINFO cbInfo;
683
684         if (X11DRV_CLIPBOARD_GetClipboardInfo(&cbInfo) && cbInfo.hWndOwner)
685         {
686             /* Send a WM_RENDERFORMAT message to notify the owner to render the
687              * data requested into the clipboard.
688              */
689             TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", cbInfo.hWndOwner);
690             SendMessageW(cbInfo.hWndOwner, WM_RENDERFORMAT, lpData->wFormatID, 0);
691
692             if (!lpData->hData) bret = FALSE;
693         }
694         else
695         {
696             ERR("hWndClipOwner is lost!\n");
697             bret = FALSE;
698         }
699     }
700
701     return bret;
702 }
703
704
705 /**************************************************************************
706  *                      CLIPBOARD_ConvertText
707  * Returns number of required/converted characters - not bytes!
708  */
709 static INT CLIPBOARD_ConvertText(WORD src_fmt, void const *src, INT src_size,
710                                  WORD dst_fmt, void *dst, INT dst_size)
711 {
712     UINT cp;
713
714     if(src_fmt == CF_UNICODETEXT)
715     {
716         switch(dst_fmt)
717         {
718         case CF_TEXT:
719             cp = CP_ACP;
720             break;
721         case CF_OEMTEXT:
722             cp = CP_OEMCP;
723             break;
724         default:
725             return 0;
726         }
727         return WideCharToMultiByte(cp, 0, src, src_size, dst, dst_size, NULL, NULL);
728     }
729
730     if(dst_fmt == CF_UNICODETEXT)
731     {
732         switch(src_fmt)
733         {
734         case CF_TEXT:
735             cp = CP_ACP;
736             break;
737         case CF_OEMTEXT:
738             cp = CP_OEMCP;
739             break;
740         default:
741             return 0;
742         }
743         return MultiByteToWideChar(cp, 0, src, src_size, dst, dst_size);
744     }
745
746     if(!dst_size) return src_size;
747
748     if(dst_size > src_size) dst_size = src_size;
749
750     if(src_fmt == CF_TEXT )
751         CharToOemBuffA(src, dst, dst_size);
752     else
753         OemToCharBuffA(src, dst, dst_size);
754
755     return dst_size;
756 }
757
758
759 /**************************************************************************
760  *                      X11DRV_CLIPBOARD_RenderSynthesizedFormat
761  */
762 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData)
763 {
764     BOOL bret = FALSE;
765
766     TRACE("\n");
767
768     if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
769     {
770         UINT wFormatID = lpData->wFormatID;
771
772         if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
773             bret = X11DRV_CLIPBOARD_RenderSynthesizedText(display, wFormatID);
774         else 
775         {
776             switch (wFormatID)
777             {
778                 case CF_DIB:
779                     bret = X11DRV_CLIPBOARD_RenderSynthesizedDIB( display );
780                     break;
781
782                 case CF_BITMAP:
783                     bret = X11DRV_CLIPBOARD_RenderSynthesizedBitmap( display );
784                     break;
785
786                 case CF_ENHMETAFILE:
787                     bret = X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile( display );
788                     break;
789
790                 case CF_METAFILEPICT:
791                     FIXME("Synthesizing CF_METAFILEPICT not implemented\n");
792                     break;
793
794                 default:
795                     FIXME("Called to synthesize unknown format 0x%08x\n", wFormatID);
796                     break;
797             }
798         }
799
800         lpData->wFlags &= ~CF_FLAG_SYNTHESIZED;
801     }
802
803     return bret;
804 }
805
806
807 /**************************************************************************
808  *                      X11DRV_CLIPBOARD_RenderSynthesizedText
809  *
810  * Renders synthesized text
811  */
812 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID)
813 {
814     LPCSTR lpstrS;
815     LPSTR  lpstrT;
816     HANDLE hData;
817     INT src_chars, dst_chars, alloc_size;
818     LPWINE_CLIPDATA lpSource = NULL;
819
820     TRACE("%04x\n", wFormatID);
821
822     if ((lpSource = X11DRV_CLIPBOARD_LookupData(wFormatID)) &&
823         lpSource->hData)
824         return TRUE;
825
826     /* Look for rendered source or non-synthesized source */
827     if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
828         (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
829     {
830         TRACE("UNICODETEXT -> %04x\n", wFormatID);
831     }
832     else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
833         (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
834     {
835         TRACE("TEXT -> %04x\n", wFormatID);
836     }
837     else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
838         (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
839     {
840         TRACE("OEMTEXT -> %04x\n", wFormatID);
841     }
842
843     if (!lpSource || (lpSource->wFlags & CF_FLAG_SYNTHESIZED &&
844         !lpSource->hData))
845         return FALSE;
846
847     /* Ask the clipboard owner to render the source text if necessary */
848     if (!lpSource->hData && !X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
849         return FALSE;
850
851     lpstrS = GlobalLock(lpSource->hData);
852     if (!lpstrS)
853         return FALSE;
854
855     /* Text always NULL terminated */
856     if(lpSource->wFormatID == CF_UNICODETEXT)
857         src_chars = strlenW((LPCWSTR)lpstrS) + 1;
858     else
859         src_chars = strlen(lpstrS) + 1;
860
861     /* Calculate number of characters in the destination buffer */
862     dst_chars = CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS, 
863         src_chars, wFormatID, NULL, 0);
864
865     if (!dst_chars)
866         return FALSE;
867
868     TRACE("Converting from '%04x' to '%04x', %i chars\n",
869         lpSource->wFormatID, wFormatID, src_chars);
870
871     /* Convert characters to bytes */
872     if(wFormatID == CF_UNICODETEXT)
873         alloc_size = dst_chars * sizeof(WCHAR);
874     else
875         alloc_size = dst_chars;
876
877     hData = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
878         GMEM_DDESHARE, alloc_size);
879
880     lpstrT = GlobalLock(hData);
881
882     if (lpstrT)
883     {
884         CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS, src_chars,
885             wFormatID, lpstrT, dst_chars);
886         GlobalUnlock(hData);
887     }
888
889     GlobalUnlock(lpSource->hData);
890
891     return X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, hData, 0, NULL, TRUE);
892 }
893
894
895 /***********************************************************************
896  *           bitmap_info_size
897  *
898  * Return the size of the bitmap info structure including color table.
899  */
900 static int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
901 {
902     unsigned int colors, size, masks = 0;
903
904     if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
905     {
906         const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
907         colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
908         return sizeof(BITMAPCOREHEADER) + colors *
909              ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
910     }
911     else  /* assume BITMAPINFOHEADER */
912     {
913         colors = info->bmiHeader.biClrUsed;
914         if (!colors && (info->bmiHeader.biBitCount <= 8))
915             colors = 1 << info->bmiHeader.biBitCount;
916         if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
917         size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
918         return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
919     }
920 }
921
922
923 /***********************************************************************
924  *           create_dib_from_bitmap
925  *
926  *  Allocates a packed DIB and copies the bitmap data into it.
927  */
928 static HGLOBAL create_dib_from_bitmap(HBITMAP hBmp)
929 {
930     BITMAP bmp;
931     HDC hdc;
932     HGLOBAL hPackedDIB;
933     LPBYTE pPackedDIB;
934     LPBITMAPINFOHEADER pbmiHeader;
935     unsigned int cDataSize, cPackedSize, OffsetBits;
936     int nLinesCopied;
937
938     if (!GetObjectW( hBmp, sizeof(bmp), &bmp )) return 0;
939
940     /*
941      * A packed DIB contains a BITMAPINFO structure followed immediately by
942      * an optional color palette and the pixel data.
943      */
944
945     /* Calculate the size of the packed DIB */
946     cDataSize = abs( bmp.bmHeight ) * (((bmp.bmWidth * bmp.bmBitsPixel + 31) / 8) & ~3);
947     cPackedSize = sizeof(BITMAPINFOHEADER)
948                   + ( (bmp.bmBitsPixel <= 8) ? (sizeof(RGBQUAD) * (1 << bmp.bmBitsPixel)) : 0 )
949                   + cDataSize;
950     /* Get the offset to the bits */
951     OffsetBits = cPackedSize - cDataSize;
952
953     /* Allocate the packed DIB */
954     TRACE("\tAllocating packed DIB of size %d\n", cPackedSize);
955     hPackedDIB = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE /*| GMEM_ZEROINIT*/,
956                              cPackedSize );
957     if ( !hPackedDIB )
958     {
959         WARN("Could not allocate packed DIB!\n");
960         return 0;
961     }
962
963     /* A packed DIB starts with a BITMAPINFOHEADER */
964     pPackedDIB = GlobalLock(hPackedDIB);
965     pbmiHeader = (LPBITMAPINFOHEADER)pPackedDIB;
966
967     /* Init the BITMAPINFOHEADER */
968     pbmiHeader->biSize = sizeof(BITMAPINFOHEADER);
969     pbmiHeader->biWidth = bmp.bmWidth;
970     pbmiHeader->biHeight = bmp.bmHeight;
971     pbmiHeader->biPlanes = 1;
972     pbmiHeader->biBitCount = bmp.bmBitsPixel;
973     pbmiHeader->biCompression = BI_RGB;
974     pbmiHeader->biSizeImage = 0;
975     pbmiHeader->biXPelsPerMeter = pbmiHeader->biYPelsPerMeter = 0;
976     pbmiHeader->biClrUsed = 0;
977     pbmiHeader->biClrImportant = 0;
978
979     /* Retrieve the DIB bits from the bitmap and fill in the
980      * DIB color table if present */
981     hdc = GetDC( 0 );
982     nLinesCopied = GetDIBits(hdc,                       /* Handle to device context */
983                              hBmp,                      /* Handle to bitmap */
984                              0,                         /* First scan line to set in dest bitmap */
985                              bmp.bmHeight,              /* Number of scan lines to copy */
986                              pPackedDIB + OffsetBits,   /* [out] Address of array for bitmap bits */
987                              (LPBITMAPINFO) pbmiHeader, /* [out] Address of BITMAPINFO structure */
988                              0);                        /* RGB or palette index */
989     GlobalUnlock(hPackedDIB);
990     ReleaseDC( 0, hdc );
991
992     /* Cleanup if GetDIBits failed */
993     if (nLinesCopied != bmp.bmHeight)
994     {
995         TRACE("\tGetDIBits returned %d. Actual lines=%d\n", nLinesCopied, bmp.bmHeight);
996         GlobalFree(hPackedDIB);
997         hPackedDIB = 0;
998     }
999     return hPackedDIB;
1000 }
1001
1002
1003 /**************************************************************************
1004  *                      X11DRV_CLIPBOARD_RenderSynthesizedDIB
1005  *
1006  * Renders synthesized DIB
1007  */
1008 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display)
1009 {
1010     BOOL bret = FALSE;
1011     LPWINE_CLIPDATA lpSource = NULL;
1012
1013     TRACE("\n");
1014
1015     if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) && lpSource->hData)
1016     {
1017         bret = TRUE;
1018     }
1019     /* If we have a bitmap and it's not synthesized or it has been rendered */
1020     else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
1021         (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1022     {
1023         /* Render source if required */
1024         if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1025         {
1026             HGLOBAL hData = create_dib_from_bitmap( lpSource->hData );
1027             if (hData)
1028             {
1029                 X11DRV_CLIPBOARD_InsertClipboardData(CF_DIB, hData, 0, NULL, TRUE);
1030                 bret = TRUE;
1031             }
1032         }
1033     }
1034
1035     return bret;
1036 }
1037
1038
1039 /**************************************************************************
1040  *                      X11DRV_CLIPBOARD_RenderSynthesizedBitmap
1041  *
1042  * Renders synthesized bitmap
1043  */
1044 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display)
1045 {
1046     BOOL bret = FALSE;
1047     LPWINE_CLIPDATA lpSource = NULL;
1048
1049     TRACE("\n");
1050
1051     if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) && lpSource->hData)
1052     {
1053         bret = TRUE;
1054     }
1055     /* If we have a dib and it's not synthesized or it has been rendered */
1056     else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
1057         (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1058     {
1059         /* Render source if required */
1060         if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1061         {
1062             HDC hdc;
1063             HBITMAP hData = NULL;
1064             unsigned int offset;
1065             LPBITMAPINFOHEADER lpbmih;
1066
1067             hdc = GetDC(NULL);
1068             lpbmih = GlobalLock(lpSource->hData);
1069             if (lpbmih)
1070             {
1071                 offset = sizeof(BITMAPINFOHEADER)
1072                       + ((lpbmih->biBitCount <= 8) ? (sizeof(RGBQUAD) *
1073                         (1 << lpbmih->biBitCount)) : 0);
1074
1075                 hData = CreateDIBitmap(hdc, lpbmih, CBM_INIT, (LPBYTE)lpbmih +
1076                     offset, (LPBITMAPINFO) lpbmih, DIB_RGB_COLORS);
1077
1078                 GlobalUnlock(lpSource->hData);
1079             }
1080             ReleaseDC(NULL, hdc);
1081
1082             if (hData)
1083             {
1084                 X11DRV_CLIPBOARD_InsertClipboardData(CF_BITMAP, hData, 0, NULL, TRUE);
1085                 bret = TRUE;
1086             }
1087         }
1088     }
1089
1090     return bret;
1091 }
1092
1093
1094 /**************************************************************************
1095  *                      X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile
1096  */
1097 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile(Display *display)
1098 {
1099     LPWINE_CLIPDATA lpSource = NULL;
1100
1101     TRACE("\n");
1102
1103     if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_ENHMETAFILE)) && lpSource->hData)
1104         return TRUE;
1105     /* If we have a MF pict and it's not synthesized or it has been rendered */
1106     else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
1107         (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1108     {
1109         /* Render source if required */
1110         if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1111         {
1112             METAFILEPICT *pmfp;
1113             HENHMETAFILE hData = NULL;
1114
1115             pmfp = GlobalLock(lpSource->hData);
1116             if (pmfp)
1117             {
1118                 UINT size_mf_bits = GetMetaFileBitsEx(pmfp->hMF, 0, NULL);
1119                 void *mf_bits = HeapAlloc(GetProcessHeap(), 0, size_mf_bits);
1120                 if (mf_bits)
1121                 {
1122                     GetMetaFileBitsEx(pmfp->hMF, size_mf_bits, mf_bits);
1123                     hData = SetWinMetaFileBits(size_mf_bits, mf_bits, NULL, pmfp);
1124                     HeapFree(GetProcessHeap(), 0, mf_bits);
1125                 }
1126                 GlobalUnlock(lpSource->hData);
1127             }
1128
1129             if (hData)
1130             {
1131                 X11DRV_CLIPBOARD_InsertClipboardData(CF_ENHMETAFILE, hData, 0, NULL, TRUE);
1132                 return TRUE;
1133             }
1134         }
1135     }
1136
1137     return FALSE;
1138 }
1139
1140
1141 /**************************************************************************
1142  *              X11DRV_CLIPBOARD_ImportXAString
1143  *
1144  *  Import XA_STRING, converting the string to CF_TEXT.
1145  */
1146 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *display, Window w, Atom prop)
1147 {
1148     LPBYTE lpdata;
1149     unsigned long cbytes;
1150     LPSTR lpstr;
1151     unsigned long i, inlcount = 0;
1152     HANDLE hText = 0;
1153
1154     if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1155         return 0;
1156
1157     for (i = 0; i <= cbytes; i++)
1158     {
1159         if (lpdata[i] == '\n')
1160             inlcount++;
1161     }
1162
1163     if ((hText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes + inlcount + 1)))
1164     {
1165         lpstr = GlobalLock(hText);
1166
1167         for (i = 0, inlcount = 0; i <= cbytes; i++)
1168         {
1169             if (lpdata[i] == '\n')
1170                 lpstr[inlcount++] = '\r';
1171
1172             lpstr[inlcount++] = lpdata[i];
1173         }
1174
1175         GlobalUnlock(hText);
1176     }
1177
1178     /* Free the retrieved property data */
1179     HeapFree(GetProcessHeap(), 0, lpdata);
1180
1181     return hText;
1182 }
1183
1184
1185 /**************************************************************************
1186  *              X11DRV_CLIPBOARD_ImportUTF8
1187  *
1188  *  Import XA_STRING, converting the string to CF_UNICODE.
1189  */
1190 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *display, Window w, Atom prop)
1191 {
1192     LPBYTE lpdata;
1193     unsigned long cbytes;
1194     LPSTR lpstr;
1195     unsigned long i, inlcount = 0;
1196     HANDLE hUnicodeText = 0;
1197
1198     if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1199         return 0;
1200
1201     for (i = 0; i <= cbytes; i++)
1202     {
1203         if (lpdata[i] == '\n')
1204             inlcount++;
1205     }
1206
1207     if ((lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbytes + inlcount + 1)))
1208     {
1209         UINT count;
1210
1211         for (i = 0, inlcount = 0; i <= cbytes; i++)
1212         {
1213             if (lpdata[i] == '\n')
1214                 lpstr[inlcount++] = '\r';
1215
1216             lpstr[inlcount++] = lpdata[i];
1217         }
1218
1219         count = MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, NULL, 0);
1220         hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
1221
1222         if (hUnicodeText)
1223         {
1224             WCHAR *textW = GlobalLock(hUnicodeText);
1225             MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, textW, count);
1226             GlobalUnlock(hUnicodeText);
1227         }
1228
1229         HeapFree(GetProcessHeap(), 0, lpstr);
1230     }
1231
1232     /* Free the retrieved property data */
1233     HeapFree(GetProcessHeap(), 0, lpdata);
1234
1235     return hUnicodeText;
1236 }
1237
1238
1239 /**************************************************************************
1240  *              X11DRV_CLIPBOARD_ImportCompoundText
1241  *
1242  *  Import COMPOUND_TEXT to CF_UNICODE
1243  */
1244 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *display, Window w, Atom prop)
1245 {
1246     int i, j, ret;
1247     char** srcstr;
1248     int count, lcount;
1249     int srclen, destlen;
1250     HANDLE hUnicodeText;
1251     XTextProperty txtprop;
1252
1253     if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &txtprop.value, &txtprop.nitems))
1254     {
1255         return 0;
1256     }
1257
1258     txtprop.encoding = x11drv_atom(COMPOUND_TEXT);
1259     txtprop.format = 8;
1260     ret = XmbTextPropertyToTextList(display, &txtprop, &srcstr, &count);
1261     HeapFree(GetProcessHeap(), 0, txtprop.value);
1262     if (ret != Success || !count) return 0;
1263
1264     TRACE("Importing %d line(s)\n", count);
1265
1266     /* Compute number of lines */
1267     srclen = strlen(srcstr[0]);
1268     for (i = 0, lcount = 0; i <= srclen; i++)
1269     {
1270         if (srcstr[0][i] == '\n')
1271             lcount++;
1272     }
1273
1274     destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
1275
1276     TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
1277
1278     if ((hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (destlen + lcount + 1) * sizeof(WCHAR))))
1279     {
1280         WCHAR *deststr = GlobalLock(hUnicodeText);
1281         MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1282
1283         if (lcount)
1284         {
1285             for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1286             {
1287                 deststr[j] = deststr[i];
1288
1289                 if (deststr[i] == '\n')
1290                     deststr[--j] = '\r';
1291             }
1292         }
1293
1294         GlobalUnlock(hUnicodeText);
1295     }
1296
1297     XFreeStringList(srcstr);
1298
1299     return hUnicodeText;
1300 }
1301
1302
1303 /**************************************************************************
1304  *              X11DRV_CLIPBOARD_ImportXAPIXMAP
1305  *
1306  *  Import XA_PIXMAP, converting the image to CF_DIB.
1307  */
1308 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *display, Window w, Atom prop)
1309 {
1310     LPBYTE lpdata;
1311     unsigned long cbytes;
1312     Pixmap *pPixmap;
1313     HANDLE hClipData = 0;
1314
1315     if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1316     {
1317         XVisualInfo vis = default_visual;
1318         char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
1319         BITMAPINFO *info = (BITMAPINFO *)buffer;
1320         struct gdi_image_bits bits;
1321         Window root;
1322         int x,y;               /* Unused */
1323         unsigned border_width; /* Unused */
1324         unsigned int depth, width, height;
1325
1326         pPixmap = (Pixmap *) lpdata;
1327
1328         /* Get the Pixmap dimensions and bit depth */
1329         if (!XGetGeometry(gdi_display, *pPixmap, &root, &x, &y, &width, &height,
1330                           &border_width, &depth)) depth = 0;
1331         if (!pixmap_formats[depth]) return 0;
1332
1333         TRACE("\tPixmap properties: width=%d, height=%d, depth=%d\n",
1334               width, height, depth);
1335
1336         if (depth != vis.depth) switch (pixmap_formats[depth]->bits_per_pixel)
1337         {
1338         case 1:
1339         case 4:
1340         case 8:
1341             break;
1342         case 16:  /* assume R5G5B5 */
1343             vis.red_mask   = 0x7c00;
1344             vis.green_mask = 0x03e0;
1345             vis.blue_mask  = 0x001f;
1346             break;
1347         case 24:  /* assume R8G8B8 */
1348         case 32:  /* assume A8R8G8B8 */
1349             vis.red_mask   = 0xff0000;
1350             vis.green_mask = 0x00ff00;
1351             vis.blue_mask  = 0x0000ff;
1352             break;
1353         default:
1354             return 0;
1355         }
1356
1357         if (!get_pixmap_image( *pPixmap, width, height, &vis, info, &bits ))
1358         {
1359             DWORD info_size = bitmap_info_size( info, DIB_RGB_COLORS );
1360             BYTE *ptr;
1361
1362             hClipData = GlobalAlloc( GMEM_MOVEABLE | GMEM_DDESHARE,
1363                                      info_size + info->bmiHeader.biSizeImage );
1364             if (hClipData)
1365             {
1366                 ptr = GlobalLock( hClipData );
1367                 memcpy( ptr, info, info_size );
1368                 memcpy( ptr + info_size, bits.ptr, info->bmiHeader.biSizeImage );
1369                 GlobalUnlock( hClipData );
1370             }
1371             if (bits.free) bits.free( &bits );
1372         }
1373
1374         HeapFree(GetProcessHeap(), 0, lpdata);
1375     }
1376
1377     return hClipData;
1378 }
1379
1380
1381 /**************************************************************************
1382  *              X11DRV_CLIPBOARD_ImportImageBmp
1383  *
1384  *  Import image/bmp, converting the image to CF_DIB.
1385  */
1386 static HANDLE X11DRV_CLIPBOARD_ImportImageBmp(Display *display, Window w, Atom prop)
1387 {
1388     LPBYTE lpdata;
1389     unsigned long cbytes;
1390     HANDLE hClipData = 0;
1391
1392     if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1393     {
1394         BITMAPFILEHEADER *bfh = (BITMAPFILEHEADER*)lpdata;
1395
1396         if (cbytes >= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPCOREHEADER) &&
1397             bfh->bfType == 0x4d42 /* "BM" */)
1398         {
1399             BITMAPINFO *bmi = (BITMAPINFO*)(bfh+1);
1400             HBITMAP hbmp;
1401             HDC hdc;
1402
1403             hdc = GetDC(0);
1404             hbmp = CreateDIBitmap(
1405                 hdc,
1406                 &(bmi->bmiHeader),
1407                 CBM_INIT,
1408                 lpdata+bfh->bfOffBits,
1409                 bmi,
1410                 DIB_RGB_COLORS
1411                 );
1412
1413             hClipData = create_dib_from_bitmap( hbmp );
1414
1415             DeleteObject(hbmp);
1416             ReleaseDC(0, hdc);
1417         }
1418
1419         /* Free the retrieved property data */
1420         HeapFree(GetProcessHeap(), 0, lpdata);
1421     }
1422
1423     return hClipData;
1424 }
1425
1426
1427 /**************************************************************************
1428  *              X11DRV_CLIPBOARD_ImportMetaFilePict
1429  *
1430  *  Import MetaFilePict.
1431  */
1432 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *display, Window w, Atom prop)
1433 {
1434     LPBYTE lpdata;
1435     unsigned long cbytes;
1436     HANDLE hClipData = 0;
1437
1438     if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1439     {
1440         if (cbytes)
1441             hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata, (LPDWORD)&cbytes, FALSE);
1442
1443         /* Free the retrieved property data */
1444         HeapFree(GetProcessHeap(), 0, lpdata);
1445     }
1446
1447     return hClipData;
1448 }
1449
1450
1451 /**************************************************************************
1452  *              X11DRV_ImportEnhMetaFile
1453  *
1454  *  Import EnhMetaFile.
1455  */
1456 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *display, Window w, Atom prop)
1457 {
1458     LPBYTE lpdata;
1459     unsigned long cbytes;
1460     HANDLE hClipData = 0;
1461
1462     if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1463     {
1464         if (cbytes)
1465             hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata, (LPDWORD)&cbytes, FALSE);
1466
1467         /* Free the retrieved property data */
1468         HeapFree(GetProcessHeap(), 0, lpdata);
1469     }
1470
1471     return hClipData;
1472 }
1473
1474
1475 /**************************************************************************
1476  *              X11DRV_ImportClipbordaData
1477  *
1478  *  Generic import clipboard data routine.
1479  */
1480 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *display, Window w, Atom prop)
1481 {
1482     LPVOID lpClipData;
1483     LPBYTE lpdata;
1484     unsigned long cbytes;
1485     HANDLE hClipData = 0;
1486
1487     if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1488     {
1489         if (cbytes)
1490         {
1491             /* Turn on the DDESHARE flag to enable shared 32 bit memory */
1492             hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes);
1493             if (hClipData == 0)
1494             {
1495                 HeapFree(GetProcessHeap(), 0, lpdata);
1496                 return NULL;
1497             }
1498
1499             if ((lpClipData = GlobalLock(hClipData)))
1500             {
1501                 memcpy(lpClipData, lpdata, cbytes);
1502                 GlobalUnlock(hClipData);
1503             }
1504             else
1505             {
1506                 GlobalFree(hClipData);
1507                 hClipData = 0;
1508             }
1509         }
1510
1511         /* Free the retrieved property data */
1512         HeapFree(GetProcessHeap(), 0, lpdata);
1513     }
1514
1515     return hClipData;
1516 }
1517
1518
1519 /**************************************************************************
1520                 X11DRV_CLIPBOARD_ExportClipboardData
1521  *
1522  *  Generic export clipboard data routine.
1523  */
1524 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
1525                                             Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1526 {
1527     LPVOID lpClipData;
1528     UINT datasize = 0;
1529     HANDLE hClipData = 0;
1530
1531     *lpBytes = 0; /* Assume failure */
1532
1533     if (!X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1534         ERR("Failed to export %04x format\n", lpData->wFormatID);
1535     else
1536     {
1537         datasize = GlobalSize(lpData->hData);
1538
1539         hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, datasize);
1540         if (hClipData == 0) return NULL;
1541
1542         if ((lpClipData = GlobalLock(hClipData)))
1543         {
1544             LPVOID lpdata = GlobalLock(lpData->hData);
1545
1546             memcpy(lpClipData, lpdata, datasize);
1547             *lpBytes = datasize;
1548
1549             GlobalUnlock(lpData->hData);
1550             GlobalUnlock(hClipData);
1551         } else {
1552             GlobalFree(hClipData);
1553             hClipData = 0;
1554         }
1555     }
1556
1557     return hClipData;
1558 }
1559
1560
1561 /**************************************************************************
1562  *              X11DRV_CLIPBOARD_ExportXAString
1563  *
1564  *  Export CF_TEXT converting the string to XA_STRING.
1565  *  Helper function for X11DRV_CLIPBOARD_ExportString.
1566  */
1567 static HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1568 {
1569     UINT i, j;
1570     UINT size;
1571     LPSTR text, lpstr = NULL;
1572
1573     *lpBytes = 0; /* Assume return has zero bytes */
1574
1575     text = GlobalLock(lpData->hData);
1576     size = strlen(text);
1577
1578     /* remove carriage returns */
1579     lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1580     if (lpstr == NULL)
1581         goto done;
1582
1583     for (i = 0,j = 0; i < size && text[i]; i++)
1584     {
1585         if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1586             continue;
1587         lpstr[j++] = text[i];
1588     }
1589
1590     lpstr[j]='\0';
1591     *lpBytes = j; /* Number of bytes in string */
1592
1593 done:
1594     GlobalUnlock(lpData->hData);
1595
1596     return lpstr;
1597 }
1598
1599
1600 /**************************************************************************
1601  *              X11DRV_CLIPBOARD_ExportUTF8String
1602  *
1603  *  Export CF_UNICODE converting the string to UTF8.
1604  *  Helper function for X11DRV_CLIPBOARD_ExportString.
1605  */
1606 static HANDLE X11DRV_CLIPBOARD_ExportUTF8String(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1607 {
1608     UINT i, j;
1609     UINT size;
1610     LPWSTR uni_text;
1611     LPSTR text, lpstr = NULL;
1612
1613     *lpBytes = 0; /* Assume return has zero bytes */
1614
1615     uni_text = GlobalLock(lpData->hData);
1616
1617     size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1618
1619     text = HeapAlloc(GetProcessHeap(), 0, size);
1620     if (!text)
1621         goto done;
1622     WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1623
1624     /* remove carriage returns */
1625     lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1626     if (lpstr == NULL)
1627         goto done;
1628
1629     for (i = 0,j = 0; i < size && text[i]; i++)
1630     {
1631         if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1632             continue;
1633         lpstr[j++] = text[i];
1634     }
1635     lpstr[j]='\0';
1636
1637     *lpBytes = j; /* Number of bytes in string */
1638
1639 done:
1640     HeapFree(GetProcessHeap(), 0, text);
1641     GlobalUnlock(lpData->hData);
1642
1643     return lpstr;
1644 }
1645
1646
1647
1648 /**************************************************************************
1649  *              X11DRV_CLIPBOARD_ExportCompoundText
1650  *
1651  *  Export CF_UNICODE to COMPOUND_TEXT
1652  *  Helper function for X11DRV_CLIPBOARD_ExportString.
1653  */
1654 static HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Display *display, Window requestor, Atom aTarget, Atom rprop,
1655     LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1656 {
1657     char* lpstr = 0;
1658     XTextProperty prop;
1659     XICCEncodingStyle style;
1660     UINT i, j;
1661     UINT size;
1662     LPWSTR uni_text;
1663
1664     uni_text = GlobalLock(lpData->hData);
1665
1666     size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1667     lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1668     if (!lpstr)
1669         return 0;
1670
1671     WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1672
1673     /* remove carriage returns */
1674     for (i = 0, j = 0; i < size && lpstr[i]; i++)
1675     {
1676         if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1677             continue;
1678         lpstr[j++] = lpstr[i];
1679     }
1680     lpstr[j]='\0';
1681
1682     GlobalUnlock(lpData->hData);
1683
1684     if (aTarget == x11drv_atom(COMPOUND_TEXT))
1685         style = XCompoundTextStyle;
1686     else
1687         style = XStdICCTextStyle;
1688
1689     /* Update the X property */
1690     if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1691     {
1692         XSetTextProperty(display, requestor, &prop, rprop);
1693         XFree(prop.value);
1694     }
1695
1696     HeapFree(GetProcessHeap(), 0, lpstr);
1697
1698     return 0;
1699 }
1700
1701 /**************************************************************************
1702  *              X11DRV_CLIPBOARD_ExportString
1703  *
1704  *  Export string
1705  */
1706 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget, Atom rprop,
1707                                      LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1708 {
1709     if (X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1710     {
1711         if (aTarget == XA_STRING)
1712             return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1713         else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1714             return X11DRV_CLIPBOARD_ExportCompoundText(display, requestor, aTarget,
1715                 rprop, lpData, lpBytes);
1716         else
1717         {
1718             TRACE("Exporting target %ld to default UTF8_STRING\n", aTarget);
1719             return X11DRV_CLIPBOARD_ExportUTF8String(lpData, lpBytes);
1720         }
1721     }
1722     else
1723         ERR("Failed to render %04x format\n", lpData->wFormatID);
1724
1725     return 0;
1726 }
1727
1728
1729 /**************************************************************************
1730  *              X11DRV_CLIPBOARD_ExportXAPIXMAP
1731  *
1732  *  Export CF_DIB to XA_PIXMAP.
1733  */
1734 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget, Atom rprop,
1735     LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1736 {
1737     HANDLE hData;
1738     unsigned char* lpData;
1739
1740     if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1741     {
1742         ERR("Failed to export %04x format\n", lpdata->wFormatID);
1743         return 0;
1744     }
1745
1746     if (!lpdata->drvData) /* If not already rendered */
1747     {
1748         Pixmap pixmap;
1749         LPBITMAPINFO pbmi;
1750         struct gdi_image_bits bits;
1751
1752         pbmi = GlobalLock( lpdata->hData );
1753         bits.ptr = (LPBYTE)pbmi + bitmap_info_size( pbmi, DIB_RGB_COLORS );
1754         bits.free = NULL;
1755         bits.is_copy = FALSE;
1756         pixmap = create_pixmap_from_image( 0, &default_visual, pbmi, &bits, DIB_RGB_COLORS );
1757         GlobalUnlock( lpdata->hData );
1758         lpdata->drvData = pixmap;
1759     }
1760
1761     *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1762
1763     /* Wrap pixmap so we can return a handle */
1764     hData = GlobalAlloc(0, *lpBytes);
1765     lpData = GlobalLock(hData);
1766     memcpy(lpData, &lpdata->drvData, *lpBytes);
1767     GlobalUnlock(hData);
1768
1769     return hData;
1770 }
1771
1772
1773 /**************************************************************************
1774  *              X11DRV_CLIPBOARD_ExportImageBmp
1775  *
1776  *  Export CF_DIB to image/bmp.
1777  */
1778 static HANDLE X11DRV_CLIPBOARD_ExportImageBmp(Display *display, Window requestor, Atom aTarget, Atom rprop,
1779     LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1780 {
1781     HANDLE hpackeddib;
1782     LPBYTE dibdata;
1783     UINT bmpsize;
1784     HANDLE hbmpdata;
1785     LPBYTE bmpdata;
1786     BITMAPFILEHEADER *bfh;
1787
1788     *lpBytes = 0;
1789
1790     if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1791     {
1792         ERR("Failed to export %04x format\n", lpdata->wFormatID);
1793         return 0;
1794     }
1795
1796     hpackeddib = lpdata->hData;
1797
1798     dibdata = GlobalLock(hpackeddib);
1799     if (!dibdata)
1800     {
1801         ERR("Failed to lock packed DIB\n");
1802         return 0;
1803     }
1804
1805     bmpsize = sizeof(BITMAPFILEHEADER) + GlobalSize(hpackeddib);
1806
1807     hbmpdata = GlobalAlloc(0, bmpsize);
1808
1809     if (hbmpdata)
1810     {
1811         bmpdata = GlobalLock(hbmpdata);
1812
1813         if (!bmpdata)
1814         {
1815             GlobalFree(hbmpdata);
1816             GlobalUnlock(hpackeddib);
1817             return 0;
1818         }
1819
1820         /* bitmap file header */
1821         bfh = (BITMAPFILEHEADER*)bmpdata;
1822         bfh->bfType = 0x4d42; /* "BM" */
1823         bfh->bfSize = bmpsize;
1824         bfh->bfReserved1 = 0;
1825         bfh->bfReserved2 = 0;
1826         bfh->bfOffBits = sizeof(BITMAPFILEHEADER) + bitmap_info_size((BITMAPINFO*)dibdata, DIB_RGB_COLORS);
1827
1828         /* rest of bitmap is the same as the packed dib */
1829         memcpy(bfh+1, dibdata, bmpsize-sizeof(BITMAPFILEHEADER));
1830
1831         *lpBytes = bmpsize;
1832
1833         GlobalUnlock(hbmpdata);
1834     }
1835
1836     GlobalUnlock(hpackeddib);
1837
1838     return hbmpdata;
1839 }
1840
1841
1842 /**************************************************************************
1843  *              X11DRV_CLIPBOARD_ExportMetaFilePict
1844  *
1845  *  Export MetaFilePict.
1846  */
1847 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget, Atom rprop,
1848                                            LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1849 {
1850     if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1851     {
1852         ERR("Failed to export %04x format\n", lpdata->wFormatID);
1853         return 0;
1854     }
1855
1856     return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata->hData, lpBytes, TRUE);
1857 }
1858
1859
1860 /**************************************************************************
1861  *              X11DRV_CLIPBOARD_ExportEnhMetaFile
1862  *
1863  *  Export EnhMetaFile.
1864  */
1865 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget, Atom rprop,
1866                                           LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1867 {
1868     if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1869     {
1870         ERR("Failed to export %04x format\n", lpdata->wFormatID);
1871         return 0;
1872     }
1873
1874     return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata->hData, lpBytes, TRUE);
1875 }
1876
1877
1878 /**************************************************************************
1879  *              get_html_description_field
1880  *
1881  *  Find the value of a field in an HTML Format description.
1882  */
1883 static LPCSTR get_html_description_field(LPCSTR data, LPCSTR keyword)
1884 {
1885     LPCSTR pos=data;
1886
1887     while (pos && *pos && *pos != '<')
1888     {
1889         if (memcmp(pos, keyword, strlen(keyword)) == 0)
1890             return pos+strlen(keyword);
1891
1892         pos = strchr(pos, '\n');
1893         if (pos) pos++;
1894     }
1895
1896     return NULL;
1897 }
1898
1899
1900 /**************************************************************************
1901  *              X11DRV_CLIPBOARD_ExportTextHtml
1902  *
1903  *  Export HTML Format to text/html.
1904  *
1905  * FIXME: We should attempt to add an <a base> tag and convert windows paths.
1906  */
1907 static HANDLE X11DRV_CLIPBOARD_ExportTextHtml(Display *display, Window requestor, Atom aTarget,
1908     Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1909 {
1910     HANDLE hdata;
1911     LPCSTR data, field_value;
1912     UINT fragmentstart, fragmentend, htmlsize;
1913     HANDLE hhtmldata=NULL;
1914     LPSTR htmldata;
1915
1916     *lpBytes = 0;
1917
1918     if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1919     {
1920         ERR("Failed to export %04x format\n", lpdata->wFormatID);
1921         return 0;
1922     }
1923
1924     hdata = lpdata->hData;
1925
1926     data = GlobalLock(hdata);
1927     if (!data)
1928     {
1929         ERR("Failed to lock HTML Format data\n");
1930         return 0;
1931     }
1932
1933     /* read the important fields */
1934     field_value = get_html_description_field(data, "StartFragment:");
1935     if (!field_value)
1936     {
1937         ERR("Couldn't find StartFragment value\n");
1938         goto end;
1939     }
1940     fragmentstart = atoi(field_value);
1941
1942     field_value = get_html_description_field(data, "EndFragment:");
1943     if (!field_value)
1944     {
1945         ERR("Couldn't find EndFragment value\n");
1946         goto end;
1947     }
1948     fragmentend = atoi(field_value);
1949
1950     /* export only the fragment */
1951     htmlsize = fragmentend - fragmentstart + 1;
1952
1953     hhtmldata = GlobalAlloc(0, htmlsize);
1954
1955     if (hhtmldata)
1956     {
1957         htmldata = GlobalLock(hhtmldata);
1958
1959         if (!htmldata)
1960         {
1961             GlobalFree(hhtmldata);
1962             htmldata = NULL;
1963             goto end;
1964         }
1965
1966         memcpy(htmldata, &data[fragmentstart], fragmentend-fragmentstart);
1967         htmldata[htmlsize-1] = '\0';
1968
1969         *lpBytes = htmlsize;
1970
1971         GlobalUnlock(htmldata);
1972     }
1973
1974 end:
1975
1976     GlobalUnlock(hdata);
1977
1978     return hhtmldata;
1979 }
1980
1981
1982 /**************************************************************************
1983  *              X11DRV_CLIPBOARD_QueryTargets
1984  */
1985 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection,
1986     Atom target, XEvent *xe)
1987 {
1988     INT i;
1989
1990     XConvertSelection(display, selection, target, x11drv_atom(SELECTION_DATA), w, CurrentTime);
1991
1992     /*
1993      * Wait until SelectionNotify is received
1994      */
1995     for (i = 0; i < SELECTION_RETRIES; i++)
1996     {
1997         Bool res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
1998         if (res && xe->xselection.selection == selection) break;
1999
2000         usleep(SELECTION_WAIT);
2001     }
2002
2003     if (i == SELECTION_RETRIES)
2004     {
2005         ERR("Timed out waiting for SelectionNotify event\n");
2006         return FALSE;
2007     }
2008     /* Verify that the selection returned a valid TARGETS property */
2009     if ((xe->xselection.target != target) || (xe->xselection.property == None))
2010     {
2011         /* Selection owner failed to respond or we missed the SelectionNotify */
2012         WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
2013         return FALSE;
2014     }
2015
2016     return TRUE;
2017 }
2018
2019
2020 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
2021 {
2022     return (event->error_code == BadAtom);
2023 }
2024
2025 /**************************************************************************
2026  *              X11DRV_CLIPBOARD_InsertSelectionProperties
2027  *
2028  * Mark properties available for future retrieval.
2029  */
2030 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
2031 {
2032      UINT i, nb_atoms = 0;
2033      Atom *atoms = NULL;
2034
2035      /* Cache these formats in the clipboard cache */
2036      for (i = 0; i < count; i++)
2037      {
2038          LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
2039
2040          if (lpFormat)
2041          {
2042              /* We found at least one Window's format that mapps to the property.
2043               * Continue looking for more.
2044               *
2045               * If more than one property map to a Window's format then we use the first 
2046               * one and ignore the rest.
2047               */
2048              while (lpFormat)
2049              {
2050                  TRACE("Atom#%d Property(%d): --> Format %s\n",
2051                        i, lpFormat->drvData, debugstr_format(lpFormat->wFormatID));
2052                  X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, lpFormat, FALSE);
2053                  lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
2054              }
2055          }
2056          else if (properties[i])
2057          {
2058              /* add it to the list of atoms that we don't know about yet */
2059              if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
2060                                             (count - i) * sizeof(*atoms) );
2061              if (atoms) atoms[nb_atoms++] = properties[i];
2062          }
2063      }
2064
2065      /* query all unknown atoms in one go */
2066      if (atoms)
2067      {
2068          char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
2069          if (names)
2070          {
2071              X11DRV_expect_error( display, is_atom_error, NULL );
2072              if (!XGetAtomNames( display, atoms, nb_atoms, names )) nb_atoms = 0;
2073              if (X11DRV_check_error())
2074              {
2075                  WARN( "got some bad atoms, ignoring\n" );
2076                  nb_atoms = 0;
2077              }
2078              for (i = 0; i < nb_atoms; i++)
2079              {
2080                  WINE_CLIPFORMAT *lpFormat;
2081                  LPWSTR wname;
2082                  int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
2083                  wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2084                  MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
2085
2086                  lpFormat = register_format( RegisterClipboardFormatW(wname), atoms[i] );
2087                  HeapFree(GetProcessHeap(), 0, wname);
2088                  if (!lpFormat)
2089                  {
2090                      ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
2091                      continue;
2092                  }
2093                  TRACE("Atom#%d Property(%d): --> Format %s\n",
2094                        i, lpFormat->drvData, debugstr_format(lpFormat->wFormatID));
2095                  X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, lpFormat, FALSE);
2096              }
2097              for (i = 0; i < nb_atoms; i++) XFree( names[i] );
2098              HeapFree( GetProcessHeap(), 0, names );
2099          }
2100          HeapFree( GetProcessHeap(), 0, atoms );
2101      }
2102 }
2103
2104
2105 /**************************************************************************
2106  *              X11DRV_CLIPBOARD_QueryAvailableData
2107  *
2108  * Caches the list of data formats available from the current selection.
2109  * This queries the selection owner for the TARGETS property and saves all
2110  * reported property types.
2111  */
2112 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo)
2113 {
2114     XEvent         xe;
2115     Atom           atype=AnyPropertyType;
2116     int            aformat;
2117     unsigned long  remain;
2118     Atom*          targetList=NULL;
2119     Window         w;
2120     unsigned long  cSelectionTargets = 0;
2121
2122     if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
2123     {
2124         ERR("Received request to cache selection but process is owner=(%08x)\n", 
2125             (unsigned) selectionWindow);
2126         return -1; /* Prevent self request */
2127     }
2128
2129     w = thread_selection_wnd();
2130     if (!w)
2131     {
2132         ERR("No window available to retrieve selection!\n");
2133         return -1;
2134     }
2135
2136     /*
2137      * Query the selection owner for the TARGETS property
2138      */
2139     if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
2140         XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2141     {
2142         if (use_primary_selection && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
2143             selectionCacheSrc = XA_PRIMARY;
2144         else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
2145             selectionCacheSrc = x11drv_atom(CLIPBOARD);
2146         else
2147         {
2148             Atom xstr = XA_STRING;
2149
2150             /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
2151             if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
2152             {
2153                 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2154                 selectionCacheSrc = XA_PRIMARY;
2155                 return 1;
2156             }
2157             else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
2158             {
2159                 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2160                 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2161                 return 1;
2162             }
2163             else
2164             {
2165                 WARN("Failed to query selection owner for available data.\n");
2166                 return -1;
2167             }
2168         }
2169     }
2170     else return 0; /* No selection owner so report 0 targets available */
2171
2172     /* Read the TARGETS property contents */
2173     if (!XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
2174         0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets, 
2175         &remain, (unsigned char**)&targetList) != Success)
2176     {
2177        TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
2178              atype, aformat, cSelectionTargets, remain);
2179        /*
2180         * The TARGETS property should have returned us a list of atoms
2181         * corresponding to each selection target format supported.
2182         */
2183        if (atype == XA_ATOM || atype == x11drv_atom(TARGETS))
2184        {
2185            if (aformat == 32)
2186            {
2187                X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, cSelectionTargets);
2188            }
2189            else if (aformat == 8)  /* work around quartz-wm brain damage */
2190            {
2191                unsigned long i, count = cSelectionTargets / sizeof(CARD32);
2192                Atom *atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(Atom) );
2193                for (i = 0; i < count; i++)
2194                    atoms[i] = ((CARD32 *)targetList)[i];  /* FIXME: byte swapping */
2195                X11DRV_CLIPBOARD_InsertSelectionProperties( display, atoms, count );
2196                HeapFree( GetProcessHeap(), 0, atoms );
2197            }
2198        }
2199
2200        /* Free the list of targets */
2201        XFree(targetList);
2202     }
2203     else WARN("Failed to read TARGETS property\n");
2204
2205     return cSelectionTargets;
2206 }
2207
2208
2209 /**************************************************************************
2210  *      X11DRV_CLIPBOARD_ReadSelectionData
2211  *
2212  * This method is invoked only when we DO NOT own the X selection
2213  *
2214  * We always get the data from the selection client each time,
2215  * since we have no way of determining if the data in our cache is stale.
2216  */
2217 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData)
2218 {
2219     Bool res;
2220     DWORD i;
2221     XEvent xe;
2222     BOOL bRet = FALSE;
2223
2224     TRACE("%04x\n", lpData->wFormatID);
2225
2226     if (!lpData->lpFormat)
2227     {
2228         ERR("Requesting format %04x but no source format linked to data.\n",
2229             lpData->wFormatID);
2230         return FALSE;
2231     }
2232
2233     if (!selectionAcquired)
2234     {
2235         Window w = thread_selection_wnd();
2236         if(!w)
2237         {
2238             ERR("No window available to read selection data!\n");
2239             return FALSE;
2240         }
2241
2242         TRACE("Requesting conversion of %s property (%d) from selection type %08x\n",
2243               debugstr_format(lpData->lpFormat->wFormatID), lpData->lpFormat->drvData,
2244               (UINT)selectionCacheSrc);
2245
2246         XConvertSelection(display, selectionCacheSrc, lpData->lpFormat->drvData,
2247                           x11drv_atom(SELECTION_DATA), w, CurrentTime);
2248
2249         /* wait until SelectionNotify is received */
2250         for (i = 0; i < SELECTION_RETRIES; i++)
2251         {
2252             res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
2253             if (res && xe.xselection.selection == selectionCacheSrc) break;
2254
2255             usleep(SELECTION_WAIT);
2256         }
2257
2258         if (i == SELECTION_RETRIES)
2259         {
2260             ERR("Timed out waiting for SelectionNotify event\n");
2261         }
2262         /* Verify that the selection returned a valid TARGETS property */
2263         else if (xe.xselection.property != None)
2264         {
2265             /*
2266              *  Read the contents of the X selection property 
2267              *  into WINE's clipboard cache and converting the 
2268              *  data format if necessary.
2269              */
2270              HANDLE hData = lpData->lpFormat->lpDrvImportFunc(display, xe.xselection.requestor,
2271                  xe.xselection.property);
2272
2273              if (hData)
2274                  bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, hData, 0, lpData->lpFormat, TRUE);
2275              else
2276                  TRACE("Import function failed\n");
2277         }
2278         else
2279         {
2280             TRACE("Failed to convert selection\n");
2281         }
2282     }
2283     else
2284     {
2285         ERR("Received request to cache selection data but process is owner\n");
2286     }
2287
2288     TRACE("Returning %d\n", bRet);
2289
2290     return bRet;
2291 }
2292
2293
2294 /**************************************************************************
2295  *              X11DRV_CLIPBOARD_GetProperty
2296  *  Gets type, data and size.
2297  */
2298 static BOOL X11DRV_CLIPBOARD_GetProperty(Display *display, Window w, Atom prop,
2299     Atom *atype, unsigned char** data, unsigned long* datasize)
2300 {
2301     int aformat;
2302     unsigned long pos = 0, nitems, remain, count;
2303     unsigned char *val = NULL, *buffer;
2304
2305     TRACE("Reading property %lu from X window %lx\n", prop, w);
2306
2307     for (;;)
2308     {
2309         if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
2310                                AnyPropertyType, atype, &aformat, &nitems, &remain, &buffer) != Success)
2311         {
2312             WARN("Failed to read property\n");
2313             HeapFree( GetProcessHeap(), 0, val );
2314             return FALSE;
2315         }
2316
2317         count = get_property_size( aformat, nitems );
2318         if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
2319         else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
2320
2321         if (!*data)
2322         {
2323             XFree( buffer );
2324             HeapFree( GetProcessHeap(), 0, val );
2325             return FALSE;
2326         }
2327         val = *data;
2328         memcpy( (int *)val + pos, buffer, count );
2329         XFree( buffer );
2330         if (!remain)
2331         {
2332             *datasize = pos * sizeof(int) + count;
2333             val[*datasize] = 0;
2334             break;
2335         }
2336         pos += count / sizeof(int);
2337     }
2338
2339     /* Delete the property on the window now that we are done
2340      * This will send a PropertyNotify event to the selection owner. */
2341     XDeleteProperty(display, w, prop);
2342     return TRUE;
2343 }
2344
2345
2346 /**************************************************************************
2347  *              X11DRV_CLIPBOARD_ReadProperty
2348  *  Reads the contents of the X selection property.
2349  */
2350 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
2351     unsigned char** data, unsigned long* datasize)
2352 {
2353     Atom atype;
2354     XEvent xe;
2355
2356     if (prop == None)
2357         return FALSE;
2358
2359     if (!X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, data, datasize))
2360         return FALSE;
2361
2362     while (XCheckTypedWindowEvent(display, w, PropertyNotify, &xe))
2363         ;
2364
2365     if (atype == x11drv_atom(INCR))
2366     {
2367         unsigned char *buf = *data;
2368         unsigned long bufsize = 0;
2369
2370         for (;;)
2371         {
2372             int i;
2373             unsigned char *prop_data, *tmp;
2374             unsigned long prop_size;
2375
2376             /* Wait until PropertyNotify is received */
2377             for (i = 0; i < SELECTION_RETRIES; i++)
2378             {
2379                 Bool res;
2380
2381                 res = XCheckTypedWindowEvent(display, w, PropertyNotify, &xe);
2382                 if (res && xe.xproperty.atom == prop &&
2383                     xe.xproperty.state == PropertyNewValue)
2384                     break;
2385                 usleep(SELECTION_WAIT);
2386             }
2387
2388             if (i >= SELECTION_RETRIES ||
2389                 !X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, &prop_data, &prop_size))
2390             {
2391                 HeapFree(GetProcessHeap(), 0, buf);
2392                 return FALSE;
2393             }
2394
2395             /* Retrieved entire data. */
2396             if (prop_size == 0)
2397             {
2398                 HeapFree(GetProcessHeap(), 0, prop_data);
2399                 *data = buf;
2400                 *datasize = bufsize;
2401                 return TRUE;
2402             }
2403
2404             tmp = HeapReAlloc(GetProcessHeap(), 0, buf, bufsize + prop_size + 1);
2405             if (!tmp)
2406             {
2407                 HeapFree(GetProcessHeap(), 0, buf);
2408                 HeapFree(GetProcessHeap(), 0, prop_data);
2409                 return FALSE;
2410             }
2411
2412             buf = tmp;
2413             memcpy(buf + bufsize, prop_data, prop_size + 1);
2414             bufsize += prop_size;
2415             HeapFree(GetProcessHeap(), 0, prop_data);
2416         }
2417     }
2418
2419     return TRUE;
2420 }
2421
2422
2423 /**************************************************************************
2424  *              CLIPBOARD_SerializeMetafile
2425  */
2426 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
2427 {
2428     HANDLE h = 0;
2429
2430     TRACE(" wFormat=%d hdata=%p out=%d\n", wformat, hdata, out);
2431
2432     if (out) /* Serialize out, caller should free memory */
2433     {
2434         *lpcbytes = 0; /* Assume failure */
2435
2436         if (wformat == CF_METAFILEPICT)
2437         {
2438             LPMETAFILEPICT lpmfp = GlobalLock(hdata);
2439             unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2440
2441             h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
2442             if (h)
2443             {
2444                 char *pdata = GlobalLock(h);
2445
2446                 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
2447                 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
2448
2449                 *lpcbytes = size + sizeof(METAFILEPICT);
2450
2451                 GlobalUnlock(h);
2452             }
2453
2454             GlobalUnlock(hdata);
2455         }
2456         else if (wformat == CF_ENHMETAFILE)
2457         {
2458             int size = GetEnhMetaFileBits(hdata, 0, NULL);
2459
2460             h = GlobalAlloc(0, size);
2461             if (h)
2462             {
2463                 LPVOID pdata = GlobalLock(h);
2464
2465                 GetEnhMetaFileBits(hdata, size, pdata);
2466                 *lpcbytes = size;
2467
2468                 GlobalUnlock(h);
2469             }
2470         }
2471     }
2472     else
2473     {
2474         if (wformat == CF_METAFILEPICT)
2475         {
2476             h = GlobalAlloc(0, sizeof(METAFILEPICT));
2477             if (h)
2478             {
2479                 unsigned int wiresize;
2480                 LPMETAFILEPICT lpmfp = GlobalLock(h);
2481
2482                 memcpy(lpmfp, hdata, sizeof(METAFILEPICT));
2483                 wiresize = *lpcbytes - sizeof(METAFILEPICT);
2484                 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
2485                     ((const BYTE *)hdata) + sizeof(METAFILEPICT));
2486                 GlobalUnlock(h);
2487             }
2488         }
2489         else if (wformat == CF_ENHMETAFILE)
2490         {
2491             h = SetEnhMetaFileBits(*lpcbytes, hdata);
2492         }
2493     }
2494
2495     return h;
2496 }
2497
2498
2499 /**************************************************************************
2500  *              X11DRV_CLIPBOARD_ReleaseSelection
2501  *
2502  * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
2503  */
2504 static void X11DRV_CLIPBOARD_ReleaseSelection(Display *display, Atom selType, Window w, HWND hwnd, Time time)
2505 {
2506     /* w is the window that lost the selection
2507      */
2508     TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
2509           (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
2510
2511     if (selectionAcquired && (w == selectionWindow))
2512     {
2513         CLIPBOARDINFO cbinfo;
2514
2515         /* completely give up the selection */
2516         TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
2517
2518         X11DRV_CLIPBOARD_GetClipboardInfo(&cbinfo);
2519
2520         if (cbinfo.flags & CB_PROCESS)
2521         {
2522             /* Since we're still the owner, this wasn't initiated by
2523                another Wine process */
2524             if (OpenClipboard(hwnd))
2525             {
2526                 /* Destroy private objects */
2527                 SendMessageW(cbinfo.hWndOwner, WM_DESTROYCLIPBOARD, 0, 0);
2528
2529                 /* Give up ownership of the windows clipboard */
2530                 X11DRV_CLIPBOARD_ReleaseOwnership();
2531                 CloseClipboard();
2532             }
2533         }
2534
2535         if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2536         {
2537             TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2538
2539             if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2540             {
2541                 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2542                 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2543             }
2544             else
2545                 TRACE("We no longer own PRIMARY\n");
2546         }
2547         else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2548         {
2549             TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2550
2551             if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2552             {
2553                 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2554                 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2555             }
2556             else
2557                 TRACE("We no longer own CLIPBOARD\n");
2558         }
2559
2560         selectionWindow = None;
2561
2562         X11DRV_EmptyClipboard(FALSE);
2563
2564         /* Reset the selection flags now that we are done */
2565         selectionAcquired = S_NOSELECTION;
2566     }
2567 }
2568
2569
2570 /**************************************************************************
2571  *              IsSelectionOwner (X11DRV.@)
2572  *
2573  * Returns: TRUE if the selection is owned by this process, FALSE otherwise
2574  */
2575 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void)
2576 {
2577     return selectionAcquired;
2578 }
2579
2580
2581 /**************************************************************************
2582  *                X11DRV Clipboard Exports
2583  **************************************************************************/
2584
2585
2586 static void selection_acquire(void)
2587 {
2588     Window owner;
2589     Display *display;
2590
2591     owner = thread_selection_wnd();
2592     display = thread_display();
2593
2594     selectionAcquired = 0;
2595     selectionWindow = 0;
2596
2597     /* Grab PRIMARY selection if not owned */
2598     if (use_primary_selection)
2599         XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2600
2601     /* Grab CLIPBOARD selection if not owned */
2602     XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2603
2604     if (use_primary_selection && XGetSelectionOwner(display, XA_PRIMARY) == owner)
2605         selectionAcquired |= S_PRIMARY;
2606
2607     if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2608         selectionAcquired |= S_CLIPBOARD;
2609
2610     if (selectionAcquired)
2611     {
2612         selectionWindow = owner;
2613         TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2614     }
2615 }
2616
2617 static DWORD WINAPI selection_thread_proc(LPVOID p)
2618 {
2619     HANDLE event = p;
2620
2621     TRACE("\n");
2622
2623     selection_acquire();
2624     SetEvent(event);
2625
2626     while (selectionAcquired)
2627     {
2628         MsgWaitForMultipleObjectsEx(0, NULL, INFINITE, QS_SENDMESSAGE, 0);
2629     }
2630
2631     return 0;
2632 }
2633
2634 /**************************************************************************
2635  *              AcquireClipboard (X11DRV.@)
2636  */
2637 int CDECL X11DRV_AcquireClipboard(HWND hWndClipWindow)
2638 {
2639     DWORD procid;
2640     HANDLE selectionThread;
2641
2642     TRACE(" %p\n", hWndClipWindow);
2643
2644     /*
2645      * It's important that the selection get acquired from the thread
2646      * that owns the clipboard window. The primary reason is that we know 
2647      * it is running a message loop and therefore can process the 
2648      * X selection events.
2649      */
2650     if (hWndClipWindow &&
2651         GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, &procid))
2652     {
2653         if (procid != GetCurrentProcessId())
2654         {
2655             WARN("Setting clipboard owner to other process is not supported\n");
2656             hWndClipWindow = NULL;
2657         }
2658         else
2659         {
2660             TRACE("Thread %x is acquiring selection with thread %x's window %p\n",
2661                 GetCurrentThreadId(),
2662                 GetWindowThreadProcessId(hWndClipWindow, NULL), hWndClipWindow);
2663
2664             return SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0);
2665         }
2666     }
2667
2668     if (hWndClipWindow)
2669     {
2670         selection_acquire();
2671     }
2672     else
2673     {
2674         HANDLE event = CreateEventW(NULL, FALSE, FALSE, NULL);
2675         selectionThread = CreateThread(NULL, 0, selection_thread_proc, event, 0, NULL);
2676
2677         if (!selectionThread)
2678         {
2679             WARN("Could not start clipboard thread\n");
2680             CloseHandle(event);
2681             return 0;
2682         }
2683
2684         WaitForSingleObject(event, INFINITE);
2685         CloseHandle(event);
2686         CloseHandle(selectionThread);
2687     }
2688
2689     return 1;
2690 }
2691
2692
2693 /**************************************************************************
2694  *      X11DRV_EmptyClipboard
2695  *
2696  * Empty cached clipboard data. 
2697  */
2698 void CDECL X11DRV_EmptyClipboard(BOOL keepunowned)
2699 {
2700     WINE_CLIPDATA *data, *next;
2701
2702     LIST_FOR_EACH_ENTRY_SAFE( data, next, &data_list, WINE_CLIPDATA, entry )
2703     {
2704         if (keepunowned && (data->wFlags & CF_FLAG_UNOWNED)) continue;
2705         list_remove( &data->entry );
2706         X11DRV_CLIPBOARD_FreeData( data );
2707         HeapFree( GetProcessHeap(), 0, data );
2708         ClipDataCount--;
2709     }
2710
2711     TRACE(" %d entries remaining in cache.\n", ClipDataCount);
2712 }
2713
2714
2715
2716 /**************************************************************************
2717  *              X11DRV_SetClipboardData
2718  */
2719 BOOL CDECL X11DRV_SetClipboardData(UINT wFormat, HANDLE hData, BOOL owner)
2720 {
2721     DWORD flags = 0;
2722     BOOL bResult = TRUE;
2723
2724     /* If it's not owned, data can only be set if the format data is not already owned
2725        and its rendering is not delayed */
2726     if (!owner)
2727     {
2728         CLIPBOARDINFO cbinfo;
2729         LPWINE_CLIPDATA lpRender;
2730
2731         X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2732
2733         if (!hData ||
2734             ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)) &&
2735             !(lpRender->wFlags & CF_FLAG_UNOWNED)))
2736             bResult = FALSE;
2737         else
2738             flags = CF_FLAG_UNOWNED;
2739     }
2740
2741     bResult &= X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData, flags, NULL, TRUE);
2742
2743     return bResult;
2744 }
2745
2746
2747 /**************************************************************************
2748  *              CountClipboardFormats
2749  */
2750 INT CDECL X11DRV_CountClipboardFormats(void)
2751 {
2752     CLIPBOARDINFO cbinfo;
2753
2754     X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2755
2756     TRACE(" count=%d\n", ClipDataCount);
2757
2758     return ClipDataCount;
2759 }
2760
2761
2762 /**************************************************************************
2763  *              X11DRV_EnumClipboardFormats
2764  */
2765 UINT CDECL X11DRV_EnumClipboardFormats(UINT wFormat)
2766 {
2767     CLIPBOARDINFO cbinfo;
2768     struct list *ptr = NULL;
2769
2770     TRACE("(%04X)\n", wFormat);
2771
2772     X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2773
2774     if (!wFormat)
2775     {
2776         ptr = list_head( &data_list );
2777     }
2778     else
2779     {
2780         LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
2781         if (lpData) ptr = list_next( &data_list, &lpData->entry );
2782     }
2783
2784     if (!ptr) return 0;
2785     return LIST_ENTRY( ptr, WINE_CLIPDATA, entry )->wFormatID;
2786 }
2787
2788
2789 /**************************************************************************
2790  *              X11DRV_IsClipboardFormatAvailable
2791  */
2792 BOOL CDECL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
2793 {
2794     BOOL bRet = FALSE;
2795     CLIPBOARDINFO cbinfo;
2796
2797     TRACE("(%04X)\n", wFormat);
2798
2799     X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2800
2801     if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
2802         bRet = TRUE;
2803
2804     TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
2805
2806     return bRet;
2807 }
2808
2809
2810 /**************************************************************************
2811  *              GetClipboardData (USER.142)
2812  */
2813 HANDLE CDECL X11DRV_GetClipboardData(UINT wFormat)
2814 {
2815     CLIPBOARDINFO cbinfo;
2816     LPWINE_CLIPDATA lpRender;
2817
2818     TRACE("(%04X)\n", wFormat);
2819
2820     X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2821
2822     if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
2823     {
2824         if ( !lpRender->hData )
2825             X11DRV_CLIPBOARD_RenderFormat(thread_init_display(), lpRender);
2826
2827         TRACE(" returning %p (type %04x)\n", lpRender->hData, lpRender->wFormatID);
2828         return lpRender->hData;
2829     }
2830
2831     return 0;
2832 }
2833
2834
2835 /**************************************************************************
2836  *              ResetSelectionOwner
2837  *
2838  * Called when the thread owning the selection is destroyed and we need to
2839  * preserve the selection ownership. We look for another top level window
2840  * in this process and send it a message to acquire the selection.
2841  */
2842 void X11DRV_ResetSelectionOwner(void)
2843 {
2844     HWND hwnd;
2845     DWORD procid;
2846
2847     TRACE("\n");
2848
2849     if (!selectionAcquired  || thread_selection_wnd() != selectionWindow)
2850         return;
2851
2852     selectionAcquired = S_NOSELECTION;
2853     selectionWindow = 0;
2854
2855     hwnd = GetWindow(GetDesktopWindow(), GW_CHILD);
2856     do
2857     {
2858         if (GetCurrentThreadId() != GetWindowThreadProcessId(hwnd, &procid))
2859         {
2860             if (GetCurrentProcessId() == procid)
2861             {
2862                 if (SendMessageW(hwnd, WM_X11DRV_ACQUIRE_SELECTION, 0, 0))
2863                     return;
2864             }
2865         }
2866     } while ((hwnd = GetWindow(hwnd, GW_HWNDNEXT)) != NULL);
2867
2868     WARN("Failed to find another thread to take selection ownership. Clipboard data will be lost.\n");
2869
2870     X11DRV_CLIPBOARD_ReleaseOwnership();
2871     X11DRV_EmptyClipboard(FALSE);
2872 }
2873
2874
2875 /**************************************************************************
2876  *                      X11DRV_CLIPBOARD_SynthesizeData
2877  */
2878 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID)
2879 {
2880     BOOL bsyn = TRUE;
2881     LPWINE_CLIPDATA lpSource = NULL;
2882
2883     TRACE(" %04x\n", wFormatID);
2884
2885     /* Don't need to synthesize if it already exists */
2886     if (X11DRV_CLIPBOARD_LookupData(wFormatID))
2887         return TRUE;
2888
2889     if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
2890     {
2891         bsyn = ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
2892             ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2893             ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
2894             ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2895             ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
2896             ~lpSource->wFlags & CF_FLAG_SYNTHESIZED);
2897     }
2898     else if (wFormatID == CF_ENHMETAFILE)
2899     {
2900         bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2901             ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2902     }
2903     else if (wFormatID == CF_METAFILEPICT)
2904     {
2905         bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_ENHMETAFILE)) &&
2906             ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2907     }
2908     else if (wFormatID == CF_DIB)
2909     {
2910         bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
2911             ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2912     }
2913     else if (wFormatID == CF_BITMAP)
2914     {
2915         bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
2916             ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2917     }
2918
2919     if (bsyn)
2920         X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, CF_FLAG_SYNTHESIZED, NULL, TRUE);
2921
2922     return bsyn;
2923 }
2924
2925
2926
2927 /**************************************************************************
2928  *              X11DRV_EndClipboardUpdate
2929  * TODO:
2930  *  Add locale if it hasn't already been added
2931  */
2932 void CDECL X11DRV_EndClipboardUpdate(void)
2933 {
2934     INT count = ClipDataCount;
2935
2936     /* Do Unicode <-> Text <-> OEM mapping */
2937     X11DRV_CLIPBOARD_SynthesizeData(CF_TEXT);
2938     X11DRV_CLIPBOARD_SynthesizeData(CF_OEMTEXT);
2939     X11DRV_CLIPBOARD_SynthesizeData(CF_UNICODETEXT);
2940
2941     /* Enhmetafile <-> MetafilePict mapping */
2942     X11DRV_CLIPBOARD_SynthesizeData(CF_ENHMETAFILE);
2943     X11DRV_CLIPBOARD_SynthesizeData(CF_METAFILEPICT);
2944
2945     /* DIB <-> Bitmap mapping */
2946     X11DRV_CLIPBOARD_SynthesizeData(CF_DIB);
2947     X11DRV_CLIPBOARD_SynthesizeData(CF_BITMAP);
2948
2949     TRACE("%d formats added to cached data\n", ClipDataCount - count);
2950 }
2951
2952
2953 /***********************************************************************
2954  *           X11DRV_SelectionRequest_TARGETS
2955  *  Service a TARGETS selection request event
2956  */
2957 static Atom X11DRV_SelectionRequest_TARGETS( Display *display, Window requestor,
2958                                              Atom target, Atom rprop )
2959 {
2960     UINT i;
2961     Atom* targets;
2962     ULONG cTargets;
2963     LPWINE_CLIPFORMAT format;
2964     LPWINE_CLIPDATA lpData;
2965
2966     /* Create X atoms for any clipboard types which don't have atoms yet.
2967      * This avoids sending bogus zero atoms.
2968      * Without this, copying might not have access to all clipboard types.
2969      * FIXME: is it safe to call this here?
2970      */
2971     intern_atoms();
2972
2973     /*
2974      * Count the number of items we wish to expose as selection targets.
2975      */
2976     cTargets = 1; /* Include TARGETS */
2977
2978     if (!list_head( &data_list )) return None;
2979
2980     LIST_FOR_EACH_ENTRY( lpData, &data_list, WINE_CLIPDATA, entry )
2981         LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
2982             if ((format->wFormatID == lpData->wFormatID) &&
2983                 format->lpDrvExportFunc && format->drvData)
2984                 cTargets++;
2985
2986     TRACE(" found %d formats\n", cTargets);
2987
2988     /* Allocate temp buffer */
2989     targets = HeapAlloc( GetProcessHeap(), 0, cTargets * sizeof(Atom));
2990     if(targets == NULL)
2991         return None;
2992
2993     i = 0;
2994     targets[i++] = x11drv_atom(TARGETS);
2995
2996     LIST_FOR_EACH_ENTRY( lpData, &data_list, WINE_CLIPDATA, entry )
2997         LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
2998             if ((format->wFormatID == lpData->wFormatID) &&
2999                 format->lpDrvExportFunc && format->drvData)
3000                 targets[i++] = format->drvData;
3001
3002     if (TRACE_ON(clipboard))
3003     {
3004         unsigned int i;
3005         for ( i = 0; i < cTargets; i++)
3006         {
3007             char *itemFmtName = XGetAtomName(display, targets[i]);
3008             TRACE("\tAtom# %d:  Property %ld Type %s\n", i, targets[i], itemFmtName);
3009             XFree(itemFmtName);
3010         }
3011     }
3012
3013     /* We may want to consider setting the type to xaTargets instead,
3014      * in case some apps expect this instead of XA_ATOM */
3015     XChangeProperty(display, requestor, rprop, XA_ATOM, 32,
3016                     PropModeReplace, (unsigned char *)targets, cTargets);
3017
3018     HeapFree(GetProcessHeap(), 0, targets);
3019
3020     return rprop;
3021 }
3022
3023
3024 /***********************************************************************
3025  *           X11DRV_SelectionRequest_MULTIPLE
3026  *  Service a MULTIPLE selection request event
3027  *  rprop contains a list of (target,property) atom pairs.
3028  *  The first atom names a target and the second names a property.
3029  *  The effect is as if we have received a sequence of SelectionRequest events
3030  *  (one for each atom pair) except that:
3031  *  1. We reply with a SelectionNotify only when all the requested conversions
3032  *  have been performed.
3033  *  2. If we fail to convert the target named by an atom in the MULTIPLE property,
3034  *  we replace the atom in the property by None.
3035  */
3036 static Atom X11DRV_SelectionRequest_MULTIPLE( HWND hWnd, XSelectionRequestEvent *pevent )
3037 {
3038     Display *display = pevent->display;
3039     Atom           rprop;
3040     Atom           atype=AnyPropertyType;
3041     int            aformat;
3042     unsigned long  remain;
3043     Atom*          targetPropList=NULL;
3044     unsigned long  cTargetPropList = 0;
3045
3046     /* If the specified property is None the requestor is an obsolete client.
3047      * We support these by using the specified target atom as the reply property.
3048      */
3049     rprop = pevent->property;
3050     if( rprop == None )
3051         rprop = pevent->target;
3052     if (!rprop)
3053         return 0;
3054
3055     /* Read the MULTIPLE property contents. This should contain a list of
3056      * (target,property) atom pairs.
3057      */
3058     if (!XGetWindowProperty(display, pevent->requestor, rprop,
3059                             0, 0x3FFF, False, AnyPropertyType, &atype,&aformat,
3060                             &cTargetPropList, &remain,
3061                             (unsigned char**)&targetPropList) != Success)
3062     {
3063         if (TRACE_ON(clipboard))
3064         {
3065             char * const typeName = XGetAtomName(display, atype);
3066             TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
3067                   typeName, aformat, cTargetPropList, remain);
3068             XFree(typeName);
3069         }
3070
3071         /*
3072          * Make sure we got what we expect.
3073          * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
3074          * in a MULTIPLE selection request should be of type ATOM_PAIR.
3075          * However some X apps(such as XPaint) are not compliant with this and return
3076          * a user defined atom in atype when XGetWindowProperty is called.
3077          * The data *is* an atom pair but is not denoted as such.
3078          */
3079         if(aformat == 32 /* atype == xAtomPair */ )
3080         {
3081             unsigned int i;
3082
3083             /* Iterate through the ATOM_PAIR list and execute a SelectionRequest
3084              * for each (target,property) pair */
3085
3086             for (i = 0; i < cTargetPropList; i+=2)
3087             {
3088                 XSelectionRequestEvent event;
3089
3090                 if (TRACE_ON(clipboard))
3091                 {
3092                     char *targetName, *propName;
3093                     targetName = XGetAtomName(display, targetPropList[i]);
3094                     propName = XGetAtomName(display, targetPropList[i+1]);
3095                     TRACE("MULTIPLE(%d): Target='%s' Prop='%s'\n",
3096                           i/2, targetName, propName);
3097                     XFree(targetName);
3098                     XFree(propName);
3099                 }
3100
3101                 /* We must have a non "None" property to service a MULTIPLE target atom */
3102                 if ( !targetPropList[i+1] )
3103                 {
3104                     TRACE("\tMULTIPLE(%d): Skipping target with empty property!\n", i);
3105                     continue;
3106                 }
3107
3108                 /* Set up an XSelectionRequestEvent for this (target,property) pair */
3109                 event = *pevent;
3110                 event.target = targetPropList[i];
3111                 event.property = targetPropList[i+1];
3112
3113                 /* Fire a SelectionRequest, informing the handler that we are processing
3114                  * a MULTIPLE selection request event.
3115                  */
3116                 X11DRV_HandleSelectionRequest( hWnd, &event, TRUE );
3117             }
3118         }
3119
3120         /* Free the list of targets/properties */
3121         XFree(targetPropList);
3122     }
3123     else TRACE("Couldn't read MULTIPLE property\n");
3124
3125     return rprop;
3126 }
3127
3128
3129 /***********************************************************************
3130  *           X11DRV_HandleSelectionRequest
3131  *  Process an event selection request event.
3132  *  The bIsMultiple flag is used to signal when EVENT_SelectionRequest is called
3133  *  recursively while servicing a "MULTIPLE" selection target.
3134  *
3135  *  Note: We only receive this event when WINE owns the X selection
3136  */
3137 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple )
3138 {
3139     Display *display = event->display;
3140     XSelectionEvent result;
3141     Atom rprop = None;
3142     Window request = event->requestor;
3143
3144     TRACE("\n");
3145
3146     /*
3147      * We can only handle the selection request if :
3148      * The selection is PRIMARY or CLIPBOARD, AND we can successfully open the clipboard.
3149      * Don't do these checks or open the clipboard while recursively processing MULTIPLE,
3150      * since this has been already done.
3151      */
3152     if ( !bIsMultiple )
3153     {
3154         if (((event->selection != XA_PRIMARY) && (event->selection != x11drv_atom(CLIPBOARD))))
3155             goto END;
3156     }
3157
3158     /* If the specified property is None the requestor is an obsolete client.
3159      * We support these by using the specified target atom as the reply property.
3160      */
3161     rprop = event->property;
3162     if( rprop == None )
3163         rprop = event->target;
3164
3165     if(event->target == x11drv_atom(TARGETS))  /*  Return a list of all supported targets */
3166     {
3167         /* TARGETS selection request */
3168         rprop = X11DRV_SelectionRequest_TARGETS( display, request, event->target, rprop );
3169     }
3170     else if(event->target == x11drv_atom(MULTIPLE))  /*  rprop contains a list of (target, property) atom pairs */
3171     {
3172         /* MULTIPLE selection request */
3173         rprop = X11DRV_SelectionRequest_MULTIPLE( hWnd, event );
3174     }
3175     else
3176     {
3177         LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, event->target);
3178
3179         if (lpFormat && lpFormat->lpDrvExportFunc)
3180         {
3181             LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(lpFormat->wFormatID);
3182
3183             if (lpData)
3184             {
3185                 unsigned char* lpClipData;
3186                 DWORD cBytes;
3187                 HANDLE hClipData = lpFormat->lpDrvExportFunc(display, request, event->target,
3188                                                              rprop, lpData, &cBytes);
3189
3190                 if (hClipData && (lpClipData = GlobalLock(hClipData)))
3191                 {
3192                     int mode = PropModeReplace;
3193
3194                     TRACE("\tUpdating property %s, %d bytes\n",
3195                           debugstr_format(lpFormat->wFormatID), cBytes);
3196                     do
3197                     {
3198                         int nelements = min(cBytes, 65536);
3199                         XChangeProperty(display, request, rprop, event->target,
3200                                         8, mode, lpClipData, nelements);
3201                         mode = PropModeAppend;
3202                         cBytes -= nelements;
3203                         lpClipData += nelements;
3204                     } while (cBytes > 0);
3205
3206                     GlobalUnlock(hClipData);
3207                     GlobalFree(hClipData);
3208                 }
3209             }
3210         }
3211     }
3212
3213 END:
3214     /* reply to sender
3215      * SelectionNotify should be sent only at the end of a MULTIPLE request
3216      */
3217     if ( !bIsMultiple )
3218     {
3219         result.type = SelectionNotify;
3220         result.display = display;
3221         result.requestor = request;
3222         result.selection = event->selection;
3223         result.property = rprop;
3224         result.target = event->target;
3225         result.time = event->time;
3226         TRACE("Sending SelectionNotify event...\n");
3227         XSendEvent(display,event->requestor,False,NoEventMask,(XEvent*)&result);
3228     }
3229 }
3230
3231
3232 /***********************************************************************
3233  *           X11DRV_SelectionRequest
3234  */
3235 void X11DRV_SelectionRequest( HWND hWnd, XEvent *event )
3236 {
3237     X11DRV_HandleSelectionRequest( hWnd, &event->xselectionrequest, FALSE );
3238 }
3239
3240
3241 /***********************************************************************
3242  *           X11DRV_SelectionClear
3243  */
3244 void X11DRV_SelectionClear( HWND hWnd, XEvent *xev )
3245 {
3246     XSelectionClearEvent *event = &xev->xselectionclear;
3247     if (event->selection == XA_PRIMARY || event->selection == x11drv_atom(CLIPBOARD))
3248         X11DRV_CLIPBOARD_ReleaseSelection( event->display, event->selection,
3249                                            event->window, hWnd, event->time );
3250 }