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