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