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