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