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