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