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