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