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