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