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