inetcomm: Implement IMimeInternational_CanConvertCodePages.
[wine] / dlls / winex11.drv / clipboard.c
1 /*
2  * X11 clipboard windows driver
3  *
4  * Copyright 1994 Martin Ayotte
5  *           1996 Alex Korobka
6  *           1999 Noel Borthwick
7  *           2003 Ulrich Czekalla for CodeWeavers
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  *
23  * NOTES:
24  *    This file contains the X specific implementation for the windows
25  *    Clipboard API.
26  *
27  *    Wine's internal clipboard is exposed to external apps via the X
28  *    selection mechanism.
29  *    Currently the driver asserts ownership via two selection atoms:
30  *    1. PRIMARY(XA_PRIMARY)
31  *    2. CLIPBOARD
32  *
33  *    In our implementation, the CLIPBOARD selection takes precedence over PRIMARY,
34  *    i.e. if a CLIPBOARD selection is available, it is used instead of PRIMARY.
35  *    When Wine takes ownership of the clipboard, it takes ownership of BOTH selections.
36  *    While giving up selection ownership, if the CLIPBOARD selection is lost,
37  *    it will lose both PRIMARY and CLIPBOARD and empty the clipboard.
38  *    However if only PRIMARY is lost, it will continue to hold the CLIPBOARD selection
39  *    (leaving the clipboard cache content unaffected).
40  *
41  *      Every format exposed via a windows clipboard format is also exposed through
42  *    a corresponding X selection target. A selection target atom is synthesized
43  *    whenever a new Windows clipboard format is registered via RegisterClipboardFormat,
44  *    or when a built-in format is used for the first time.
45  *    Windows native format are exposed by prefixing the format name with "<WCF>"
46  *    This allows us to uniquely identify windows native formats exposed by other
47  *    running WINE apps.
48  *
49  *      In order to allow external applications to query WINE for supported formats,
50  *    we respond to the "TARGETS" selection target. (See EVENT_SelectionRequest
51  *    for implementation) We use the same mechanism to query external clients for
52  *    availability of a particular format, by caching the list of available targets
53  *    by using the clipboard cache's "delayed render" mechanism. If a selection client
54  *    does not support the "TARGETS" selection target, we actually attempt to retrieve
55  *    the format requested as a fallback mechanism.
56  *
57  *      Certain Windows native formats are automatically converted to X native formats
58  *    and vice versa. If a native format is available in the selection, it takes
59  *    precedence, in order to avoid unnecessary conversions.
60  *
61  * FIXME: global format list needs a critical section
62  */
63
64 #include "config.h"
65 #include "wine/port.h"
66
67 #include <string.h>
68 #include <stdarg.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #ifdef HAVE_UNISTD_H
72 # include <unistd.h>
73 #endif
74 #include <fcntl.h>
75 #include <limits.h>
76 #include <time.h>
77 #include <assert.h>
78
79 #include "windef.h"
80 #include "winbase.h"
81 #include "wine/wingdi16.h"
82 #include "x11drv.h"
83 #include "wine/debug.h"
84 #include "wine/unicode.h"
85 #include "wine/server.h"
86
87 WINE_DEFAULT_DEBUG_CHANNEL(clipboard);
88
89 #define HGDIOBJ_32(handle16)  ((HGDIOBJ)(ULONG_PTR)(handle16))
90
91 /* Maximum wait time for selection notify */
92 #define SELECTION_RETRIES 500  /* wait for .1 seconds */
93 #define SELECTION_WAIT    1000 /* us */
94 /* Minimum seconds that must lapse between owner queries */
95 #define OWNERQUERYLAPSETIME 1
96
97 /* Selection masks */
98 #define S_NOSELECTION    0
99 #define S_PRIMARY        1
100 #define S_CLIPBOARD      2
101
102 typedef struct
103 {
104     HWND hWndOpen;
105     HWND hWndOwner;
106     HWND hWndViewer;
107     UINT seqno;
108     UINT flags;
109 } CLIPBOARDINFO, *LPCLIPBOARDINFO;
110
111 struct tagWINE_CLIPDATA; /* Forward */
112
113 typedef HANDLE (*DRVEXPORTFUNC)(Display *display, Window requestor, Atom aTarget, Atom rprop,
114     struct tagWINE_CLIPDATA* lpData, LPDWORD lpBytes);
115 typedef HANDLE (*DRVIMPORTFUNC)(Display *d, Window w, Atom prop);
116
117 typedef struct tagWINE_CLIPFORMAT {
118     UINT        wFormatID;
119     LPCWSTR     Name;
120     UINT        drvData;
121     UINT        wFlags;
122     DRVIMPORTFUNC  lpDrvImportFunc;
123     DRVEXPORTFUNC  lpDrvExportFunc;
124     struct tagWINE_CLIPFORMAT *PrevFormat;
125     struct tagWINE_CLIPFORMAT *NextFormat;
126 } WINE_CLIPFORMAT, *LPWINE_CLIPFORMAT;
127
128 typedef struct tagWINE_CLIPDATA {
129     UINT        wFormatID;
130     HANDLE16    hData16;
131     HANDLE      hData32;
132     UINT        wFlags;
133     UINT        drvData;
134     LPWINE_CLIPFORMAT lpFormat;
135     struct tagWINE_CLIPDATA *PrevData;
136     struct tagWINE_CLIPDATA *NextData;
137 } WINE_CLIPDATA, *LPWINE_CLIPDATA;
138
139 #define CF_FLAG_BUILTINFMT   0x0001 /* Built-in windows format */
140 #define CF_FLAG_UNOWNED      0x0002 /* cached data is not owned */
141 #define CF_FLAG_SYNTHESIZED  0x0004 /* Implicitly converted data */
142 #define CF_FLAG_UNICODE      0x0008 /* Data is in unicode */
143
144 static int selectionAcquired = 0;              /* Contains the current selection masks */
145 static Window selectionWindow = None;          /* The top level X window which owns the selection */
146 static Atom selectionCacheSrc = XA_PRIMARY;    /* The selection source from which the clipboard cache was filled */
147
148 void X11DRV_EmptyClipboard(BOOL keepunowned);
149 void X11DRV_EndClipboardUpdate(void);
150 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *d, Window w, Atom prop);
151 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *d, Window w, Atom prop);
152 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *d, Window w, Atom prop);
153 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *d, Window w, Atom prop);
154 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *d, Window w, Atom prop);
155 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *d, Window w, Atom prop);
156 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *d, Window w, Atom prop);
157 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
158     Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
159 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget,
160     Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
161 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget,
162     Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
163 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget,
164     Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
165 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget,
166     Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
167 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCWSTR FormatName, Atom prop);
168 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID);
169 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData);
170 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void);
171 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo);
172 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData);
173 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
174     unsigned char** data, unsigned long* datasize);
175 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData);
176 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out);
177 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID);
178 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData);
179 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display);
180 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display);
181 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple );
182
183 /* Clipboard formats
184  * WARNING: This data ordering is dependent on the WINE_CLIPFORMAT structure
185  * declared in clipboard.h
186  */
187 static const WCHAR wszCF_TEXT[] = {'W','C','F','_','T','E','X','T',0};
188 static const WCHAR wszCF_BITMAP[] = {'W','C','F','_','B','I','T','M','A','P',0};
189 static const WCHAR wszCF_METAFILEPICT[] = {'W','C','F','_','M','E','T','A','F','I','L','E','P','I','C','T',0};
190 static const WCHAR wszCF_SYLK[] = {'W','C','F','_','S','Y','L','K',0};
191 static const WCHAR wszCF_DIF[] = {'W','C','F','_','D','I','F',0};
192 static const WCHAR wszCF_TIFF[] = {'W','C','F','_','T','I','F','F',0};
193 static const WCHAR wszCF_OEMTEXT[] = {'W','C','F','_','O','E','M','T','E','X','T',0};
194 static const WCHAR wszCF_DIB[] = {'W','C','F','_','D','I','B',0};
195 static const WCHAR wszCF_PALETTE[] = {'W','C','F','_','P','A','L','E','T','T','E',0};
196 static const WCHAR wszCF_PENDATA[] = {'W','C','F','_','P','E','N','D','A','T','A',0};
197 static const WCHAR wszCF_RIFF[] = {'W','C','F','_','R','I','F','F',0};
198 static const WCHAR wszCF_WAVE[] = {'W','C','F','_','W','A','V','E',0};
199 static const WCHAR wszCOMPOUNDTEXT[] = {'C','O','M','P','O','U','N','D','_','T','E','X','T',0};
200 static const WCHAR wszUTF8STRING[] = {'U','T','F','8','_','S','T','R','I','N','G',0};
201 static const WCHAR wszCF_ENHMETAFILE[] = {'W','C','F','_','E','N','H','M','E','T','A','F','I','L','E',0};
202 static const WCHAR wszCF_HDROP[] = {'W','C','F','_','H','D','R','O','P',0};
203 static const WCHAR wszCF_LOCALE[] = {'W','C','F','_','L','O','C','A','L','E',0};
204 static const WCHAR wszCF_DIBV5[] = {'W','C','F','_','D','I','B','V','5',0};
205 static const WCHAR wszCF_OWNERDISPLAY[] = {'W','C','F','_','O','W','N','E','R','D','I','S','P','L','A','Y',0};
206 static const WCHAR wszCF_DSPTEXT[] = {'W','C','F','_','D','S','P','T','E','X','T',0};
207 static const WCHAR wszCF_DSPBITMAP[] = {'W','C','F','_','D','S','P','B','I','T','M','A','P',0};
208 static const WCHAR wszCF_DSPMETAFILEPICT[] = {'W','C','F','_','D','S','P','M','E','T','A','F','I','L','E','P','I','C','T',0};
209 static const WCHAR wszCF_DSPENHMETAFILE[] = {'W','C','F','_','D','S','P','E','N','H','M','E','T','A','F','I','L','E',0};
210
211 static WINE_CLIPFORMAT ClipFormats[]  =
212 {
213     { CF_TEXT, wszCF_TEXT, XA_STRING, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAString,
214         X11DRV_CLIPBOARD_ExportString, NULL, &ClipFormats[1]},
215
216     { CF_BITMAP, wszCF_BITMAP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
217         NULL, &ClipFormats[0], &ClipFormats[2]},
218
219     { CF_METAFILEPICT, wszCF_METAFILEPICT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportMetaFilePict,
220         X11DRV_CLIPBOARD_ExportMetaFilePict, &ClipFormats[1], &ClipFormats[3]},
221
222     { CF_SYLK, wszCF_SYLK, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
223         X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[2], &ClipFormats[4]},
224
225     { CF_DIF, wszCF_DIF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
226         X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[3], &ClipFormats[5]},
227
228     { CF_TIFF, wszCF_TIFF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
229         X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[4], &ClipFormats[6]},
230
231     { CF_OEMTEXT, wszCF_OEMTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
232         X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[5], &ClipFormats[7]},
233
234     { CF_DIB, wszCF_DIB, XA_PIXMAP, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAPIXMAP,
235         X11DRV_CLIPBOARD_ExportXAPIXMAP, &ClipFormats[6], &ClipFormats[8]},
236
237     { CF_PALETTE, wszCF_PALETTE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
238         X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[7], &ClipFormats[9]},
239
240     { CF_PENDATA, wszCF_PENDATA, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
241         X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[8], &ClipFormats[10]},
242
243     { CF_RIFF, wszCF_RIFF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
244         X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[9], &ClipFormats[11]},
245
246     { CF_WAVE, wszCF_WAVE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
247         X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[10], &ClipFormats[12]},
248
249     { CF_UNICODETEXT, wszUTF8STRING, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportUTF8,
250         X11DRV_CLIPBOARD_ExportString, &ClipFormats[11], &ClipFormats[13]},
251
252     /* If UTF8_STRING is not available, attempt COMPUND_TEXT */
253     { CF_UNICODETEXT, wszCOMPOUNDTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportCompoundText,
254         X11DRV_CLIPBOARD_ExportString, &ClipFormats[12], &ClipFormats[14]},
255
256     { CF_ENHMETAFILE, wszCF_ENHMETAFILE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportEnhMetaFile,
257         X11DRV_CLIPBOARD_ExportEnhMetaFile, &ClipFormats[13], &ClipFormats[15]},
258
259     { CF_HDROP, wszCF_HDROP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
260         X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[14], &ClipFormats[16]},
261
262     { CF_LOCALE, wszCF_LOCALE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
263         X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[15], &ClipFormats[17]},
264
265     { CF_DIBV5, wszCF_DIBV5, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
266         X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[16], &ClipFormats[18]},
267
268     { CF_OWNERDISPLAY, wszCF_OWNERDISPLAY, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
269         X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[17], &ClipFormats[19]},
270
271     { CF_DSPTEXT, wszCF_DSPTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
272         X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[18], &ClipFormats[20]},
273
274     { CF_DSPBITMAP, wszCF_DSPBITMAP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
275         X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[19], &ClipFormats[21]},
276
277     { CF_DSPMETAFILEPICT, wszCF_DSPMETAFILEPICT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
278         X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[20], &ClipFormats[22]},
279
280     { CF_DSPENHMETAFILE, wszCF_DSPENHMETAFILE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
281         X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[21], NULL}
282 };
283
284 #define GET_ATOM(prop)  (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
285
286 /* Maps X properties to Windows formats */
287 static const WCHAR wszRichTextFormat[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
288 static const WCHAR wszGIF[] = {'G','I','F',0};
289 static const WCHAR wszHTMLFormat[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
290 static const struct
291 {
292     LPCWSTR lpszFormat;
293     UINT   prop;
294 } PropertyFormatMap[] =
295 {
296     { wszRichTextFormat, XATOM_text_rtf },
297     { wszRichTextFormat, XATOM_text_richtext },
298     { wszGIF, XATOM_image_gif },
299     { wszHTMLFormat, XATOM_text_html },
300 };
301
302
303 /*
304  * Cached clipboard data.
305  */
306 static LPWINE_CLIPDATA ClipData = NULL;
307 static UINT ClipDataCount = 0;
308
309 /*
310  * Clipboard sequence number
311  */
312 static UINT wSeqNo = 0;
313
314 /**************************************************************************
315  *                Internal Clipboard implementation methods
316  **************************************************************************/
317
318 static Window thread_selection_wnd(void)
319 {
320     struct x11drv_thread_data *thread_data = x11drv_init_thread_data();
321     Window w = thread_data->selection_wnd;
322
323     if (!w)
324     {
325         XSetWindowAttributes attr;
326
327         attr.event_mask = (ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
328                        ButtonPressMask | ButtonReleaseMask | EnterWindowMask);
329
330         wine_tsx11_lock();
331         w = XCreateWindow(thread_data->display, root_window, 0, 0, 1, 1, 0, screen_depth,
332                           InputOutput, CopyFromParent, CWEventMask, &attr);
333         wine_tsx11_unlock();
334
335         if (w)
336             thread_data->selection_wnd = w;
337         else
338             FIXME("Failed to create window. Fetching selection data will fail.\n");
339     }
340
341     return w;
342 }
343
344 /**************************************************************************
345  *              X11DRV_InitClipboard
346  */
347 void X11DRV_InitClipboard(void)
348 {
349     UINT i;
350
351     /* Register known mapping between window formats and X properties */
352     for (i = 0; i < sizeof(PropertyFormatMap)/sizeof(PropertyFormatMap[0]); i++)
353         X11DRV_CLIPBOARD_InsertClipboardFormat(PropertyFormatMap[i].lpszFormat, GET_ATOM(PropertyFormatMap[i].prop));
354 }
355
356
357 /**************************************************************************
358  *                intern_atoms
359  *
360  * Intern atoms for formats that don't have one yet.
361  */
362 static void intern_atoms(void)
363 {
364     LPWINE_CLIPFORMAT format;
365     int i, count, len;
366     char **names;
367     Atom *atoms;
368     Display *display;
369
370     for (format = ClipFormats, count = 0; format; format = format->NextFormat)
371         if (!format->drvData) count++;
372     if (!count) return;
373
374     display = thread_init_display();
375
376     names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
377     atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
378
379     for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
380         if (!format->drvData) {
381             len = WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, NULL, 0, NULL, NULL);
382             names[i] = HeapAlloc(GetProcessHeap(), 0, len);
383             WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, names[i++], len, NULL, NULL);
384         }
385     }
386
387     wine_tsx11_lock();
388     XInternAtoms( display, names, count, False, atoms );
389     wine_tsx11_unlock();
390
391     for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
392         if (!format->drvData) {
393             HeapFree(GetProcessHeap(), 0, names[i]);
394             format->drvData = atoms[i++];
395         }
396     }
397
398     HeapFree( GetProcessHeap(), 0, names );
399     HeapFree( GetProcessHeap(), 0, atoms );
400 }
401
402
403 /**************************************************************************
404  *              register_format
405  *
406  * Register a custom X clipboard format.
407  */
408 static WINE_CLIPFORMAT *register_format( LPCWSTR FormatName, Atom prop )
409 {
410     LPWINE_CLIPFORMAT lpFormat = ClipFormats;
411
412     TRACE("%s\n", debugstr_w(FormatName));
413
414     /* walk format chain to see if it's already registered */
415     while (lpFormat)
416     {
417         if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE, lpFormat->Name, -1, FormatName, -1) == CSTR_EQUAL
418             && (lpFormat->wFlags & CF_FLAG_BUILTINFMT) == 0)
419              return lpFormat;
420         lpFormat = lpFormat->NextFormat;
421     }
422
423     return X11DRV_CLIPBOARD_InsertClipboardFormat(FormatName, prop);
424 }
425
426
427 /**************************************************************************
428  *                X11DRV_CLIPBOARD_LookupFormat
429  */
430 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupFormat(WORD wID)
431 {
432     LPWINE_CLIPFORMAT lpFormat = ClipFormats;
433
434     while(lpFormat)
435     {
436         if (lpFormat->wFormatID == wID) 
437             break;
438
439         lpFormat = lpFormat->NextFormat;
440     }
441     if (lpFormat && !lpFormat->drvData) intern_atoms();
442     return lpFormat;
443 }
444
445
446 /**************************************************************************
447  *                X11DRV_CLIPBOARD_LookupProperty
448  */
449 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupProperty(LPWINE_CLIPFORMAT current, UINT drvData)
450 {
451     for (;;)
452     {
453         LPWINE_CLIPFORMAT lpFormat = ClipFormats;
454         BOOL need_intern = FALSE;
455
456         if (current)
457             lpFormat = current->NextFormat;
458
459         while(lpFormat)
460         {
461             if (lpFormat->drvData == drvData) return lpFormat;
462             if (!lpFormat->drvData) need_intern = TRUE;
463             lpFormat = lpFormat->NextFormat;
464         }
465         if (!need_intern) return NULL;
466         intern_atoms();
467         /* restart the search for the new atoms */
468     }
469 }
470
471
472 /**************************************************************************
473  *               X11DRV_CLIPBOARD_LookupData
474  */
475 static LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
476 {
477     LPWINE_CLIPDATA lpData = ClipData;
478
479     if (lpData)
480     {
481         do
482         {
483             if (lpData->wFormatID == wID) 
484                 break;
485
486             lpData = lpData->NextData;
487         }
488         while(lpData != ClipData);
489
490         if (lpData->wFormatID != wID)
491             lpData = NULL;
492     }
493
494     return lpData;
495 }
496
497
498 /**************************************************************************
499  *              InsertClipboardFormat
500  */
501 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCWSTR FormatName, Atom prop)
502 {
503     LPWINE_CLIPFORMAT lpFormat;
504     LPWINE_CLIPFORMAT lpNewFormat;
505     LPWSTR new_name;
506
507     /* allocate storage for new format entry */
508     lpNewFormat = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPFORMAT));
509
510     if(lpNewFormat == NULL) 
511     {
512         WARN("No more memory for a new format!\n");
513         return NULL;
514     }
515
516     if (!(new_name = HeapAlloc(GetProcessHeap(), 0, (strlenW(FormatName)+1)*sizeof(WCHAR))))
517     {
518         WARN("No more memory for the new format name!\n");
519         HeapFree(GetProcessHeap(), 0, lpNewFormat);
520         return NULL;
521     }
522
523     lpNewFormat->Name = strcpyW(new_name, FormatName);
524     lpNewFormat->wFlags = 0;
525     lpNewFormat->wFormatID = GlobalAddAtomW(lpNewFormat->Name);
526     lpNewFormat->drvData = prop;
527     lpNewFormat->lpDrvImportFunc = X11DRV_CLIPBOARD_ImportClipboardData;
528     lpNewFormat->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportClipboardData;
529
530     /* Link Format */
531     lpFormat = ClipFormats;
532
533     while(lpFormat->NextFormat) /* Move to last entry */
534         lpFormat = lpFormat->NextFormat;
535
536     lpNewFormat->NextFormat = NULL;
537     lpFormat->NextFormat = lpNewFormat;
538     lpNewFormat->PrevFormat = lpFormat;
539
540     TRACE("Registering format(%d): %s drvData %d\n",
541         lpNewFormat->wFormatID, debugstr_w(FormatName), lpNewFormat->drvData);
542
543     return lpNewFormat;
544 }
545
546
547
548
549 /**************************************************************************
550  *                      X11DRV_CLIPBOARD_GetClipboardInfo
551  */
552 static BOOL X11DRV_CLIPBOARD_GetClipboardInfo(LPCLIPBOARDINFO cbInfo)
553 {
554     BOOL bRet = FALSE;
555
556     SERVER_START_REQ( set_clipboard_info )
557     {
558         req->flags = 0;
559
560         if (wine_server_call_err( req ))
561         {
562             ERR("Failed to get clipboard owner.\n");
563         }
564         else
565         {
566             cbInfo->hWndOpen = reply->old_clipboard;
567             cbInfo->hWndOwner = reply->old_owner;
568             cbInfo->hWndViewer = reply->old_viewer;
569             cbInfo->seqno = reply->seqno;
570             cbInfo->flags = reply->flags;
571
572             bRet = TRUE;
573         }
574     }
575     SERVER_END_REQ;
576
577     return bRet;
578 }
579
580
581 /**************************************************************************
582  *      X11DRV_CLIPBOARD_ReleaseOwnership
583  */
584 static BOOL X11DRV_CLIPBOARD_ReleaseOwnership(void)
585 {
586     BOOL bRet = FALSE;
587
588     SERVER_START_REQ( set_clipboard_info )
589     {
590         req->flags = SET_CB_RELOWNER | SET_CB_SEQNO;
591
592         if (wine_server_call_err( req ))
593         {
594             ERR("Failed to set clipboard.\n");
595         }
596         else
597         {
598             bRet = TRUE;
599         }
600     }
601     SERVER_END_REQ;
602
603     return bRet;
604 }
605
606
607
608 /**************************************************************************
609  *                      X11DRV_CLIPBOARD_InsertClipboardData
610  *
611  * Caller *must* have the clipboard open and be the owner.
612  */
613 static BOOL X11DRV_CLIPBOARD_InsertClipboardData(UINT wFormatID, HANDLE16 hData16,
614     HANDLE hData32, DWORD flags, LPWINE_CLIPFORMAT lpFormat, BOOL override)
615 {
616     LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormatID);
617
618     TRACE("format=%d lpData=%p hData16=%08x hData32=%p flags=0x%08x lpFormat=%p override=%d\n",
619         wFormatID, lpData, hData16, hData32, flags, lpFormat, override);
620
621     if (lpData && !override)
622         return TRUE;
623
624     if (lpData)
625     {
626         X11DRV_CLIPBOARD_FreeData(lpData);
627
628         lpData->hData16 = hData16;  /* 0 is legal, see WM_RENDERFORMAT */
629         lpData->hData32 = hData32;
630     }
631     else
632     {
633         lpData = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPDATA));
634
635         lpData->wFormatID = wFormatID;
636         lpData->hData16 = hData16;  /* 0 is legal, see WM_RENDERFORMAT */
637         lpData->hData32 = hData32;
638         lpData->lpFormat = lpFormat;
639         lpData->drvData = 0;
640
641         if (ClipData)
642         {
643             LPWINE_CLIPDATA lpPrevData = ClipData->PrevData;
644
645             lpData->PrevData = lpPrevData;
646             lpData->NextData = ClipData;
647
648             lpPrevData->NextData = lpData;
649             ClipData->PrevData = lpData;
650         }
651         else
652         {
653             lpData->NextData = lpData;
654             lpData->PrevData = lpData;
655             ClipData = lpData;
656         }
657
658         ClipDataCount++;
659     }
660
661     lpData->wFlags = flags;
662
663     return TRUE;
664 }
665
666
667 /**************************************************************************
668  *                      X11DRV_CLIPBOARD_FreeData
669  *
670  * Free clipboard data handle.
671  */
672 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData)
673 {
674     TRACE("%d\n", lpData->wFormatID);
675
676     if ((lpData->wFormatID >= CF_GDIOBJFIRST &&
677         lpData->wFormatID <= CF_GDIOBJLAST) || 
678         lpData->wFormatID == CF_BITMAP || 
679         lpData->wFormatID == CF_DIB || 
680         lpData->wFormatID == CF_PALETTE)
681     {
682       if (lpData->hData32)
683         DeleteObject(lpData->hData32);
684
685       if (lpData->hData16)
686         DeleteObject(HGDIOBJ_32(lpData->hData16));
687
688       if ((lpData->wFormatID == CF_DIB) && lpData->drvData)
689           XFreePixmap(gdi_display, lpData->drvData);
690     }
691     else if (lpData->wFormatID == CF_METAFILEPICT)
692     {
693       if (lpData->hData32)
694       {
695         DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData32 ))->hMF );
696         GlobalFree(lpData->hData32);
697
698         if (lpData->hData16)
699           /* HMETAFILE16 and HMETAFILE32 are apparently the same thing,
700              and a shallow copy is enough to share a METAFILEPICT
701              structure between 16bit and 32bit clipboards.  The MetaFile
702              should of course only be deleted once. */
703           GlobalFree16(lpData->hData16);
704       }
705
706       if (lpData->hData16)
707       {
708         METAFILEPICT16* lpMetaPict = (METAFILEPICT16 *) GlobalLock16(lpData->hData16);
709
710         if (lpMetaPict)
711         {
712             /* To delete 16-bit meta file, we just need to free the associated
713                handle. See DeleteMetaFile16() in dlls/gdi/metafile.c. */
714             GlobalFree16(lpMetaPict->hMF);
715             lpMetaPict->hMF = 0;
716         }
717
718         GlobalFree16(lpData->hData16);
719       }
720     }
721     else if (lpData->wFormatID == CF_ENHMETAFILE)
722     {
723         if (lpData->hData32)
724             DeleteEnhMetaFile(lpData->hData32);
725     }
726     else if (lpData->wFormatID < CF_PRIVATEFIRST ||
727              lpData->wFormatID > CF_PRIVATELAST)
728     {
729       if (lpData->hData32)
730         GlobalFree(lpData->hData32);
731
732       if (lpData->hData16)
733         GlobalFree16(lpData->hData16);
734     }
735
736     lpData->hData16 = 0;
737     lpData->hData32 = 0;
738     lpData->drvData = 0;
739 }
740
741
742 /**************************************************************************
743  *                      X11DRV_CLIPBOARD_UpdateCache
744  */
745 static BOOL X11DRV_CLIPBOARD_UpdateCache(LPCLIPBOARDINFO lpcbinfo)
746 {
747     BOOL bret = TRUE;
748
749     if (!X11DRV_CLIPBOARD_IsSelectionOwner())
750     {
751         if (!X11DRV_CLIPBOARD_GetClipboardInfo(lpcbinfo))
752         {
753             ERR("Failed to retrieve clipboard information.\n");
754             bret = FALSE;
755         }
756         else if (wSeqNo < lpcbinfo->seqno)
757         {
758             X11DRV_EmptyClipboard(TRUE);
759
760             if (X11DRV_CLIPBOARD_QueryAvailableData(thread_init_display(), lpcbinfo) < 0)
761             {
762                 ERR("Failed to cache clipboard data owned by another process.\n");
763                 bret = FALSE;
764             }
765             else
766             {
767                 X11DRV_EndClipboardUpdate();
768             }
769
770             wSeqNo = lpcbinfo->seqno;
771         }
772     }
773
774     return bret;
775 }
776
777
778 /**************************************************************************
779  *                      X11DRV_CLIPBOARD_RenderFormat
780  */
781 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData)
782 {
783     BOOL bret = TRUE;
784
785     TRACE(" 0x%04x hData32(%p) hData16(0x%08x)\n",
786         lpData->wFormatID, lpData->hData32, lpData->hData16);
787
788     if (lpData->hData32 || lpData->hData16)
789         return bret; /* Already rendered */
790
791     if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
792         bret = X11DRV_CLIPBOARD_RenderSynthesizedFormat(display, lpData);
793     else if (!X11DRV_CLIPBOARD_IsSelectionOwner())
794     {
795         if (!X11DRV_CLIPBOARD_ReadSelectionData(display, lpData))
796         {
797             ERR("Failed to cache clipboard data owned by another process. Format=%d\n", 
798                 lpData->wFormatID);
799             bret = FALSE;
800         }
801     }
802     else
803     {
804         CLIPBOARDINFO cbInfo;
805
806         if (X11DRV_CLIPBOARD_GetClipboardInfo(&cbInfo) && cbInfo.hWndOwner)
807         {
808             /* Send a WM_RENDERFORMAT message to notify the owner to render the
809              * data requested into the clipboard.
810              */
811             TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", cbInfo.hWndOwner);
812             SendMessageW(cbInfo.hWndOwner, WM_RENDERFORMAT, (WPARAM)lpData->wFormatID, 0);
813
814             if (!lpData->hData32 && !lpData->hData16)
815                 bret = FALSE;
816         }
817         else
818         {
819             ERR("hWndClipOwner is lost!\n");
820             bret = FALSE;
821         }
822     }
823
824     return bret;
825 }
826
827
828 /**************************************************************************
829  *                      CLIPBOARD_ConvertText
830  * Returns number of required/converted characters - not bytes!
831  */
832 static INT CLIPBOARD_ConvertText(WORD src_fmt, void const *src, INT src_size,
833                                  WORD dst_fmt, void *dst, INT dst_size)
834 {
835     UINT cp;
836
837     if(src_fmt == CF_UNICODETEXT)
838     {
839         switch(dst_fmt)
840         {
841         case CF_TEXT:
842             cp = CP_ACP;
843             break;
844         case CF_OEMTEXT:
845             cp = CP_OEMCP;
846             break;
847         default:
848             return 0;
849         }
850         return WideCharToMultiByte(cp, 0, src, src_size, dst, dst_size, NULL, NULL);
851     }
852
853     if(dst_fmt == CF_UNICODETEXT)
854     {
855         switch(src_fmt)
856         {
857         case CF_TEXT:
858             cp = CP_ACP;
859             break;
860         case CF_OEMTEXT:
861             cp = CP_OEMCP;
862             break;
863         default:
864             return 0;
865         }
866         return MultiByteToWideChar(cp, 0, src, src_size, dst, dst_size);
867     }
868
869     if(!dst_size) return src_size;
870
871     if(dst_size > src_size) dst_size = src_size;
872
873     if(src_fmt == CF_TEXT )
874         CharToOemBuffA(src, dst, dst_size);
875     else
876         OemToCharBuffA(src, dst, dst_size);
877
878     return dst_size;
879 }
880
881
882 /**************************************************************************
883  *                      X11DRV_CLIPBOARD_RenderSynthesizedFormat
884  */
885 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData)
886 {
887     BOOL bret = FALSE;
888
889     TRACE("\n");
890
891     if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
892     {
893         UINT wFormatID = lpData->wFormatID;
894
895         if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
896             bret = X11DRV_CLIPBOARD_RenderSynthesizedText(display, wFormatID);
897         else 
898         {
899             switch (wFormatID)
900             {
901                 case CF_DIB:
902                     bret = X11DRV_CLIPBOARD_RenderSynthesizedDIB( display );
903                     break;
904
905                 case CF_BITMAP:
906                     bret = X11DRV_CLIPBOARD_RenderSynthesizedBitmap( display );
907                     break;
908
909                 case CF_ENHMETAFILE:
910                 case CF_METAFILEPICT:
911                     FIXME("Synthesizing wFormatID(0x%08x) not implemented\n", wFormatID);
912                     break;
913
914                 default:
915                     FIXME("Called to synthesize unknown format\n");
916                     break;
917             }
918         }
919
920         lpData->wFlags &= ~CF_FLAG_SYNTHESIZED;
921     }
922
923     return bret;
924 }
925
926
927 /**************************************************************************
928  *                      X11DRV_CLIPBOARD_RenderSynthesizedText
929  *
930  * Renders synthesized text
931  */
932 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID)
933 {
934     LPCSTR lpstrS;
935     LPSTR  lpstrT;
936     HANDLE hData32;
937     INT src_chars, dst_chars, alloc_size;
938     LPWINE_CLIPDATA lpSource = NULL;
939
940     TRACE(" %d\n", wFormatID);
941
942     if ((lpSource = X11DRV_CLIPBOARD_LookupData(wFormatID)) &&
943         lpSource->hData32)
944         return TRUE;
945
946     /* Look for rendered source or non-synthesized source */
947     if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
948         (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
949     {
950         TRACE("UNICODETEXT -> %d\n", wFormatID);
951     }
952     else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
953         (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
954     {
955         TRACE("TEXT -> %d\n", wFormatID);
956     }
957     else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
958         (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
959     {
960         TRACE("OEMTEXT -> %d\n", wFormatID);
961     }
962
963     if (!lpSource || (lpSource->wFlags & CF_FLAG_SYNTHESIZED &&
964         !lpSource->hData32))
965         return FALSE;
966
967     /* Ask the clipboard owner to render the source text if necessary */
968     if (!lpSource->hData32 && !X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
969         return FALSE;
970
971     if (lpSource->hData32)
972     {
973         lpstrS = (LPSTR)GlobalLock(lpSource->hData32);
974     }
975     else
976     {
977         lpstrS = (LPSTR)GlobalLock16(lpSource->hData16);
978     }
979
980     if (!lpstrS)
981         return FALSE;
982
983     /* Text always NULL terminated */
984     if(lpSource->wFormatID == CF_UNICODETEXT)
985         src_chars = strlenW((LPCWSTR)lpstrS) + 1;
986     else
987         src_chars = strlen(lpstrS) + 1;
988
989     /* Calculate number of characters in the destination buffer */
990     dst_chars = CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS, 
991         src_chars, wFormatID, NULL, 0);
992
993     if (!dst_chars)
994         return FALSE;
995
996     TRACE("Converting from '%d' to '%d', %i chars\n",
997         lpSource->wFormatID, wFormatID, src_chars);
998
999     /* Convert characters to bytes */
1000     if(wFormatID == CF_UNICODETEXT)
1001         alloc_size = dst_chars * sizeof(WCHAR);
1002     else
1003         alloc_size = dst_chars;
1004
1005     hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE | 
1006         GMEM_DDESHARE, alloc_size);
1007
1008     lpstrT = (LPSTR)GlobalLock(hData32);
1009
1010     if (lpstrT)
1011     {
1012         CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS, src_chars,
1013             wFormatID, lpstrT, dst_chars);
1014         GlobalUnlock(hData32);
1015     }
1016
1017     /* Unlock source */
1018     if (lpSource->hData32)
1019         GlobalUnlock(lpSource->hData32);
1020     else
1021         GlobalUnlock16(lpSource->hData16);
1022
1023     return X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, hData32, 0, NULL, TRUE);
1024 }
1025
1026
1027 /**************************************************************************
1028  *                      X11DRV_CLIPBOARD_RenderSynthesizedDIB
1029  *
1030  * Renders synthesized DIB
1031  */
1032 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display)
1033 {
1034     BOOL bret = FALSE;
1035     LPWINE_CLIPDATA lpSource = NULL;
1036
1037     TRACE("\n");
1038
1039     if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) && lpSource->hData32)
1040     {
1041         bret = TRUE;
1042     }
1043     /* If we have a bitmap and it's not synthesized or it has been rendered */
1044     else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
1045         (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
1046     {
1047         /* Render source if required */
1048         if (lpSource->hData32 || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1049         {
1050             HDC hdc;
1051             HGLOBAL hData32;
1052
1053             hdc = GetDC(NULL);
1054             hData32 = X11DRV_DIB_CreateDIBFromBitmap(hdc, lpSource->hData32);
1055             ReleaseDC(NULL, hdc);
1056
1057             if (hData32)
1058             {
1059                 X11DRV_CLIPBOARD_InsertClipboardData(CF_DIB, 0, hData32, 0, NULL, TRUE);
1060                 bret = TRUE;
1061             }
1062         }
1063     }
1064
1065     return bret;
1066 }
1067
1068
1069 /**************************************************************************
1070  *                      X11DRV_CLIPBOARD_RenderSynthesizedBitmap
1071  *
1072  * Renders synthesized bitmap
1073  */
1074 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display)
1075 {
1076     BOOL bret = FALSE;
1077     LPWINE_CLIPDATA lpSource = NULL;
1078
1079     TRACE("\n");
1080
1081     if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) && lpSource->hData32)
1082     {
1083         bret = TRUE;
1084     }
1085     /* If we have a dib and it's not synthesized or it has been rendered */
1086     else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
1087         (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
1088     {
1089         /* Render source if required */
1090         if (lpSource->hData32 || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1091         {
1092             HDC hdc;
1093             HBITMAP hData32;
1094             unsigned int offset;
1095             LPBITMAPINFOHEADER lpbmih;
1096
1097             hdc = GetDC(NULL);
1098             lpbmih = (LPBITMAPINFOHEADER) GlobalLock(lpSource->hData32);
1099
1100             offset = sizeof(BITMAPINFOHEADER)
1101                   + ((lpbmih->biBitCount <= 8) ? (sizeof(RGBQUAD) *
1102                     (1 << lpbmih->biBitCount)) : 0);
1103
1104             hData32 = CreateDIBitmap(hdc, lpbmih, CBM_INIT, (LPBYTE)lpbmih +
1105                 offset, (LPBITMAPINFO) lpbmih, DIB_RGB_COLORS);
1106
1107             GlobalUnlock(lpSource->hData32);
1108             ReleaseDC(NULL, hdc);
1109
1110             if (hData32)
1111             {
1112                 X11DRV_CLIPBOARD_InsertClipboardData(CF_BITMAP, 0, hData32, 0, NULL, TRUE);
1113                 bret = TRUE;
1114             }
1115         }
1116     }
1117
1118     return bret;
1119 }
1120
1121
1122 /**************************************************************************
1123  *              X11DRV_CLIPBOARD_ImportXAString
1124  *
1125  *  Import XA_STRING, converting the string to CF_TEXT.
1126  */
1127 HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *display, Window w, Atom prop)
1128 {
1129     LPBYTE lpdata;
1130     unsigned long cbytes;
1131     LPSTR lpstr;
1132     unsigned long i, inlcount = 0;
1133     HANDLE hText = 0;
1134
1135     if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1136         return 0;
1137
1138     for (i = 0; i <= cbytes; i++)
1139     {
1140         if (lpdata[i] == '\n')
1141             inlcount++;
1142     }
1143
1144     if ((hText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes + inlcount + 1)))
1145     {
1146         lpstr = GlobalLock(hText);
1147
1148         for (i = 0, inlcount = 0; i <= cbytes; i++)
1149         {
1150             if (lpdata[i] == '\n')
1151                 lpstr[inlcount++] = '\r';
1152
1153             lpstr[inlcount++] = lpdata[i];
1154         }
1155
1156         GlobalUnlock(hText);
1157     }
1158
1159     /* Free the retrieved property data */
1160     HeapFree(GetProcessHeap(), 0, lpdata);
1161
1162     return hText;
1163 }
1164
1165
1166 /**************************************************************************
1167  *              X11DRV_CLIPBOARD_ImportUTF8
1168  *
1169  *  Import XA_STRING, converting the string to CF_UNICODE.
1170  */
1171 HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *display, Window w, Atom prop)
1172 {
1173     LPBYTE lpdata;
1174     unsigned long cbytes;
1175     LPSTR lpstr;
1176     unsigned long i, inlcount = 0;
1177     HANDLE hUnicodeText = 0;
1178
1179     if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1180         return 0;
1181
1182     for (i = 0; i <= cbytes; i++)
1183     {
1184         if (lpdata[i] == '\n')
1185             inlcount++;
1186     }
1187
1188     if ((lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbytes + inlcount + 1)))
1189     {
1190         UINT count;
1191
1192         for (i = 0, inlcount = 0; i <= cbytes; i++)
1193         {
1194             if (lpdata[i] == '\n')
1195                 lpstr[inlcount++] = '\r';
1196
1197             lpstr[inlcount++] = lpdata[i];
1198         }
1199
1200         count = MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, NULL, 0);
1201         hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
1202
1203         if (hUnicodeText)
1204         {
1205             WCHAR *textW = GlobalLock(hUnicodeText);
1206             MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, textW, count);
1207             GlobalUnlock(hUnicodeText);
1208         }
1209
1210         HeapFree(GetProcessHeap(), 0, lpstr);
1211     }
1212
1213     /* Free the retrieved property data */
1214     HeapFree(GetProcessHeap(), 0, lpdata);
1215
1216     return hUnicodeText;
1217 }
1218
1219
1220 /**************************************************************************
1221  *              X11DRV_CLIPBOARD_ImportCompoundText
1222  *
1223  *  Import COMPOUND_TEXT to CF_UNICODE
1224  */
1225 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *display, Window w, Atom prop)
1226 {
1227     int i, j;
1228     char** srcstr;
1229     int count, lcount;
1230     int srclen, destlen;
1231     HANDLE hUnicodeText;
1232     XTextProperty txtprop;
1233
1234     wine_tsx11_lock();
1235     if (!XGetTextProperty(display, w, &txtprop, prop))
1236     {
1237         wine_tsx11_unlock();
1238         return 0;
1239     }
1240
1241     XmbTextPropertyToTextList(display, &txtprop, &srcstr, &count);
1242     wine_tsx11_unlock();
1243
1244     TRACE("Importing %d line(s)\n", count);
1245
1246     /* Compute number of lines */
1247     srclen = strlen(srcstr[0]);
1248     for (i = 0, lcount = 0; i <= srclen; i++)
1249     {
1250         if (srcstr[0][i] == '\n')
1251             lcount++;
1252     }
1253
1254     destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
1255
1256     TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
1257
1258     if ((hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (destlen + lcount + 1) * sizeof(WCHAR))))
1259     {
1260         WCHAR *deststr = GlobalLock(hUnicodeText);
1261         MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1262
1263         if (lcount)
1264         {
1265             for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1266             {
1267                 deststr[j] = deststr[i];
1268
1269                 if (deststr[i] == '\n')
1270                     deststr[--j] = '\r';
1271             }
1272         }
1273
1274         GlobalUnlock(hUnicodeText);
1275     }
1276
1277     wine_tsx11_lock();
1278     XFreeStringList(srcstr);
1279     XFree(txtprop.value);
1280     wine_tsx11_unlock();
1281
1282     return hUnicodeText;
1283 }
1284
1285
1286 /**************************************************************************
1287  *              X11DRV_CLIPBOARD_ImportXAPIXMAP
1288  *
1289  *  Import XA_PIXMAP, converting the image to CF_DIB.
1290  */
1291 HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *display, Window w, Atom prop)
1292 {
1293     HWND hwnd;
1294     HDC hdc;
1295     LPBYTE lpdata;
1296     unsigned long cbytes;
1297     Pixmap *pPixmap;
1298     HANDLE hClipData = 0;
1299
1300     if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1301     {
1302         pPixmap = (Pixmap *) lpdata;
1303
1304         hwnd = GetOpenClipboardWindow();
1305         hdc = GetDC(hwnd);
1306
1307         hClipData = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc);
1308         ReleaseDC(hwnd, hdc);
1309
1310         /* Free the retrieved property data */
1311         HeapFree(GetProcessHeap(), 0, lpdata);
1312     }
1313
1314     return hClipData;
1315 }
1316
1317
1318 /**************************************************************************
1319  *              X11DRV_CLIPBOARD_ImportMetaFilePict
1320  *
1321  *  Import MetaFilePict.
1322  */
1323 HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *display, Window w, Atom prop)
1324 {
1325     LPBYTE lpdata;
1326     unsigned long cbytes;
1327     HANDLE hClipData = 0;
1328
1329     if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1330     {
1331         if (cbytes)
1332             hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, (HANDLE)lpdata, (LPDWORD)&cbytes, FALSE);
1333
1334         /* Free the retrieved property data */
1335         HeapFree(GetProcessHeap(), 0, lpdata);
1336     }
1337
1338     return hClipData;
1339 }
1340
1341
1342 /**************************************************************************
1343  *              X11DRV_ImportEnhMetaFile
1344  *
1345  *  Import EnhMetaFile.
1346  */
1347 HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *display, Window w, Atom prop)
1348 {
1349     LPBYTE lpdata;
1350     unsigned long cbytes;
1351     HANDLE hClipData = 0;
1352
1353     if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1354     {
1355         if (cbytes)
1356             hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, (HANDLE)lpdata, (LPDWORD)&cbytes, FALSE);
1357
1358         /* Free the retrieved property data */
1359         HeapFree(GetProcessHeap(), 0, lpdata);
1360     }
1361
1362     return hClipData;
1363 }
1364
1365
1366 /**************************************************************************
1367  *              X11DRV_ImportClipbordaData
1368  *
1369  *  Generic import clipboard data routine.
1370  */
1371 HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *display, Window w, Atom prop)
1372 {
1373     LPVOID lpClipData;
1374     LPBYTE lpdata;
1375     unsigned long cbytes;
1376     HANDLE hClipData = 0;
1377
1378     if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1379     {
1380         if (cbytes)
1381         {
1382             /* Turn on the DDESHARE flag to enable shared 32 bit memory */
1383             hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes);
1384             if (hClipData == 0)
1385                 return NULL;
1386
1387             if ((lpClipData = GlobalLock(hClipData)))
1388             {
1389                 memcpy(lpClipData, lpdata, cbytes);
1390                 GlobalUnlock(hClipData);
1391             }
1392             else
1393             {
1394                 GlobalFree(hClipData);
1395                 hClipData = 0;
1396             }
1397         }
1398
1399         /* Free the retrieved property data */
1400         HeapFree(GetProcessHeap(), 0, lpdata);
1401     }
1402
1403     return hClipData;
1404 }
1405
1406
1407 /**************************************************************************
1408                 X11DRV_CLIPBOARD_ExportClipboardData
1409  *
1410  *  Generic export clipboard data routine.
1411  */
1412 HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
1413                                             Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1414 {
1415     LPVOID lpClipData;
1416     UINT datasize = 0;
1417     HANDLE hClipData = 0;
1418
1419     *lpBytes = 0; /* Assume failure */
1420
1421     if (!X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1422         ERR("Failed to export %d format\n", lpData->wFormatID);
1423     else
1424     {
1425         datasize = GlobalSize(lpData->hData32);
1426
1427         hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, datasize);
1428         if (hClipData == 0) return NULL;
1429
1430         if ((lpClipData = GlobalLock(hClipData)))
1431         {
1432             LPVOID lpdata = GlobalLock(lpData->hData32);
1433
1434             memcpy(lpClipData, lpdata, datasize);
1435             *lpBytes = datasize;
1436
1437             GlobalUnlock(lpData->hData32);
1438             GlobalUnlock(hClipData);
1439         } else {
1440             GlobalFree(hClipData);
1441             hClipData = 0;
1442         }
1443     }
1444
1445     return hClipData;
1446 }
1447
1448
1449 /**************************************************************************
1450  *              X11DRV_CLIPBOARD_ExportXAString
1451  *
1452  *  Export CF_TEXT converting the string to XA_STRING.
1453  *  Helper function for X11DRV_CLIPBOARD_ExportString.
1454  */
1455 static HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1456 {
1457     UINT i, j;
1458     UINT size;
1459     LPSTR text, lpstr = NULL;
1460
1461     *lpBytes = 0; /* Assume return has zero bytes */
1462
1463     text = GlobalLock(lpData->hData32);
1464     size = strlen(text);
1465
1466     /* remove carriage returns */
1467     lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1468     if (lpstr == NULL)
1469         goto done;
1470
1471     for (i = 0,j = 0; i < size && text[i]; i++)
1472     {
1473         if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1474             continue;
1475         lpstr[j++] = text[i];
1476     }
1477
1478     lpstr[j]='\0';
1479     *lpBytes = j; /* Number of bytes in string */
1480
1481 done:
1482     HeapFree(GetProcessHeap(), 0, text);
1483     GlobalUnlock(lpData->hData32);
1484
1485     return lpstr;
1486 }
1487
1488
1489 /**************************************************************************
1490  *              X11DRV_CLIPBOARD_ExportUTF8String
1491  *
1492  *  Export CF_UNICODE converting the string to UTF8.
1493  *  Helper function for X11DRV_CLIPBOARD_ExportString.
1494  */
1495 static HANDLE X11DRV_CLIPBOARD_ExportUTF8String(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1496 {
1497     UINT i, j;
1498     UINT size;
1499     LPWSTR uni_text;
1500     LPSTR text, lpstr = NULL;
1501
1502     *lpBytes = 0; /* Assume return has zero bytes */
1503
1504     uni_text = GlobalLock(lpData->hData32);
1505
1506     size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1507
1508     text = HeapAlloc(GetProcessHeap(), 0, size);
1509     if (!text)
1510         goto done;
1511     WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1512
1513     /* remove carriage returns */
1514     lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1515     if (lpstr == NULL)
1516         goto done;
1517
1518     for (i = 0,j = 0; i < size && text[i]; i++)
1519     {
1520         if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1521             continue;
1522         lpstr[j++] = text[i];
1523     }
1524     lpstr[j]='\0';
1525
1526     *lpBytes = j; /* Number of bytes in string */
1527
1528 done:
1529     HeapFree(GetProcessHeap(), 0, text);
1530     GlobalUnlock(lpData->hData32);
1531
1532     return lpstr;
1533 }
1534
1535
1536
1537 /**************************************************************************
1538  *              X11DRV_CLIPBOARD_ExportCompoundText
1539  *
1540  *  Export CF_UNICODE to COMPOUND_TEXT
1541  *  Helper function for X11DRV_CLIPBOARD_ExportString.
1542  */
1543 static HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Display *display, Window requestor, Atom aTarget, Atom rprop,
1544     LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1545 {
1546     char* lpstr = 0;
1547     XTextProperty prop;
1548     XICCEncodingStyle style;
1549     UINT i, j;
1550     UINT size;
1551     LPWSTR uni_text;
1552
1553     uni_text = GlobalLock(lpData->hData32);
1554
1555     size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1556     lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1557     if (!lpstr)
1558         return 0;
1559
1560     WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1561
1562     /* remove carriage returns */
1563     for (i = 0, j = 0; i < size && lpstr[i]; i++)
1564     {
1565         if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1566             continue;
1567         lpstr[j++] = lpstr[i];
1568     }
1569     lpstr[j]='\0';
1570
1571     GlobalUnlock(lpData->hData32);
1572
1573     if (aTarget == x11drv_atom(COMPOUND_TEXT))
1574         style = XCompoundTextStyle;
1575     else
1576         style = XStdICCTextStyle;
1577
1578     /* Update the X property */
1579     wine_tsx11_lock();
1580     if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1581     {
1582         XSetTextProperty(display, requestor, &prop, rprop);
1583         XFree(prop.value);
1584     }
1585     wine_tsx11_unlock();
1586
1587     HeapFree(GetProcessHeap(), 0, lpstr);
1588
1589     return 0;
1590 }
1591
1592 /**************************************************************************
1593  *              X11DRV_CLIPBOARD_ExportString
1594  *
1595  *  Export string
1596  */
1597 HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget, Atom rprop,
1598                                      LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1599 {
1600     if (X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1601     {
1602         if (aTarget == XA_STRING)
1603             return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1604         else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1605             return X11DRV_CLIPBOARD_ExportCompoundText(display, requestor, aTarget,
1606                 rprop, lpData, lpBytes);
1607         else
1608         {
1609             TRACE("Exporting target %ld to default UTF8_STRING\n", aTarget);
1610             return X11DRV_CLIPBOARD_ExportUTF8String(lpData, lpBytes);
1611         }
1612     }
1613     else
1614         ERR("Failed to render %d format\n", lpData->wFormatID);
1615
1616     return 0;
1617 }
1618
1619
1620 /**************************************************************************
1621  *              X11DRV_CLIPBOARD_ExportXAPIXMAP
1622  *
1623  *  Export CF_DIB to XA_PIXMAP.
1624  */
1625 HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget, Atom rprop,
1626     LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1627 {
1628     HDC hdc;
1629     HANDLE hData;
1630     unsigned char* lpData;
1631
1632     if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1633     {
1634         ERR("Failed to export %d format\n", lpdata->wFormatID);
1635         return 0;
1636     }
1637
1638     if (!lpdata->drvData) /* If not already rendered */
1639     {
1640         /* For convert from packed DIB to Pixmap */
1641         hdc = GetDC(0);
1642         lpdata->drvData = (UINT) X11DRV_DIB_CreatePixmapFromDIB(lpdata->hData32, hdc);
1643         ReleaseDC(0, hdc);
1644     }
1645
1646     *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1647
1648     /* Wrap pixmap so we can return a handle */
1649     hData = GlobalAlloc(0, *lpBytes);
1650     lpData = GlobalLock(hData);
1651     memcpy(lpData, &lpdata->drvData, *lpBytes);
1652     GlobalUnlock(hData);
1653
1654     return hData;
1655 }
1656
1657
1658 /**************************************************************************
1659  *              X11DRV_CLIPBOARD_ExportMetaFilePict
1660  *
1661  *  Export MetaFilePict.
1662  */
1663 HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget, Atom rprop,
1664                                            LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1665 {
1666     if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1667     {
1668         ERR("Failed to export %d format\n", lpdata->wFormatID);
1669         return 0;
1670     }
1671
1672     return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata->hData32, lpBytes, TRUE);
1673 }
1674
1675
1676 /**************************************************************************
1677  *              X11DRV_CLIPBOARD_ExportEnhMetaFile
1678  *
1679  *  Export EnhMetaFile.
1680  */
1681 HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget, Atom rprop,
1682                                           LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1683 {
1684     if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1685     {
1686         ERR("Failed to export %d format\n", lpdata->wFormatID);
1687         return 0;
1688     }
1689
1690     return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata->hData32, lpBytes, TRUE);
1691 }
1692
1693
1694 /**************************************************************************
1695  *              X11DRV_CLIPBOARD_QueryTargets
1696  */
1697 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection,
1698     Atom target, XEvent *xe)
1699 {
1700     INT i;
1701     Bool res;
1702
1703     wine_tsx11_lock();
1704     XConvertSelection(display, selection, target,
1705         x11drv_atom(SELECTION_DATA), w, CurrentTime);
1706     wine_tsx11_unlock();
1707
1708     /*
1709      * Wait until SelectionNotify is received
1710      */
1711     for (i = 0; i < SELECTION_RETRIES; i++)
1712     {
1713         wine_tsx11_lock();
1714         res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
1715         wine_tsx11_unlock();
1716         if (res && xe->xselection.selection == selection) break;
1717
1718         usleep(SELECTION_WAIT);
1719     }
1720
1721     /* Verify that the selection returned a valid TARGETS property */
1722     if ((xe->xselection.target != target) || (xe->xselection.property == None))
1723     {
1724         /* Selection owner failed to respond or we missed the SelectionNotify */
1725         WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
1726         return FALSE;
1727     }
1728
1729     return TRUE;
1730 }
1731
1732
1733 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
1734 {
1735     return (event->error_code == BadAtom);
1736 }
1737
1738 /**************************************************************************
1739  *              X11DRV_CLIPBOARD_InsertSelectionProperties
1740  *
1741  * Mark properties available for future retrieval.
1742  */
1743 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
1744 {
1745      UINT i, nb_atoms = 0;
1746      Atom *atoms = NULL;
1747
1748      /* Cache these formats in the clipboard cache */
1749      for (i = 0; i < count; i++)
1750      {
1751          LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
1752
1753          if (lpFormat)
1754          {
1755              /* We found at least one Window's format that mapps to the property.
1756               * Continue looking for more.
1757               *
1758               * If more than one property map to a Window's format then we use the first 
1759               * one and ignore the rest.
1760               */
1761              while (lpFormat)
1762              {
1763                  TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1764                        i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
1765                  X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0, lpFormat, FALSE);
1766                  lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
1767              }
1768          }
1769          else if (properties[i])
1770          {
1771              /* add it to the list of atoms that we don't know about yet */
1772              if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
1773                                             (count - i) * sizeof(*atoms) );
1774              if (atoms) atoms[nb_atoms++] = properties[i];
1775          }
1776      }
1777
1778      /* query all unknown atoms in one go */
1779      if (atoms)
1780      {
1781          char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
1782          if (names)
1783          {
1784              X11DRV_expect_error( display, is_atom_error, NULL );
1785              if (!XGetAtomNames( display, atoms, nb_atoms, names )) nb_atoms = 0;
1786              if (X11DRV_check_error())
1787              {
1788                  WARN( "got some bad atoms, ignoring\n" );
1789                  nb_atoms = 0;
1790              }
1791              for (i = 0; i < nb_atoms; i++)
1792              {
1793                  WINE_CLIPFORMAT *lpFormat;
1794                  LPWSTR wname;
1795                  int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
1796                  wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1797                  MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
1798
1799                  lpFormat = register_format( wname, atoms[i] );
1800                  HeapFree(GetProcessHeap(), 0, wname);
1801                  if (!lpFormat)
1802                  {
1803                      ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
1804                      continue;
1805                  }
1806                  TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1807                        i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
1808                  X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0, lpFormat, FALSE);
1809              }
1810              wine_tsx11_lock();
1811              for (i = 0; i < nb_atoms; i++) XFree( names[i] );
1812              wine_tsx11_unlock();
1813              HeapFree( GetProcessHeap(), 0, names );
1814          }
1815          HeapFree( GetProcessHeap(), 0, atoms );
1816      }
1817 }
1818
1819
1820 /**************************************************************************
1821  *              X11DRV_CLIPBOARD_QueryAvailableData
1822  *
1823  * Caches the list of data formats available from the current selection.
1824  * This queries the selection owner for the TARGETS property and saves all
1825  * reported property types.
1826  */
1827 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo)
1828 {
1829     XEvent         xe;
1830     Atom           atype=AnyPropertyType;
1831     int            aformat;
1832     unsigned long  remain;
1833     Atom*          targetList=NULL;
1834     Window         w;
1835     unsigned long  cSelectionTargets = 0;
1836
1837     if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
1838     {
1839         ERR("Received request to cache selection but process is owner=(%08x)\n", 
1840             (unsigned) selectionWindow);
1841         return -1; /* Prevent self request */
1842     }
1843
1844     w = thread_selection_wnd();
1845     if (!w)
1846     {
1847         ERR("No window available to retrieve selection!\n");
1848         return -1;
1849     }
1850
1851     /*
1852      * Query the selection owner for the TARGETS property
1853      */
1854     wine_tsx11_lock();
1855     if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
1856         XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
1857     {
1858         wine_tsx11_unlock();
1859         if (use_primary_selection && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
1860             selectionCacheSrc = XA_PRIMARY;
1861         else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
1862             selectionCacheSrc = x11drv_atom(CLIPBOARD);
1863         else
1864         {
1865             Atom xstr = XA_STRING;
1866
1867             /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
1868             if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
1869             {
1870                 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1871                 selectionCacheSrc = XA_PRIMARY;
1872                 return 1;
1873             }
1874             else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
1875             {
1876                 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1877                 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1878                 return 1;
1879             }
1880             else
1881             {
1882                 WARN("Failed to query selection owner for available data.\n");
1883                 return -1;
1884             }
1885         }
1886     }
1887     else /* No selection owner so report 0 targets available */
1888     {
1889         wine_tsx11_unlock();
1890         return 0;
1891     }
1892
1893     /* Read the TARGETS property contents */
1894     wine_tsx11_lock();
1895     if(XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
1896         0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets, 
1897         &remain, (unsigned char**)&targetList) != Success)
1898     {
1899         wine_tsx11_unlock();
1900         WARN("Failed to read TARGETS property\n");
1901     }
1902     else
1903     {
1904         wine_tsx11_unlock();
1905        TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
1906              atype, aformat, cSelectionTargets, remain);
1907        /*
1908         * The TARGETS property should have returned us a list of atoms
1909         * corresponding to each selection target format supported.
1910         */
1911        if (atype == XA_ATOM || atype == x11drv_atom(TARGETS))
1912        {
1913            if (aformat == 32)
1914            {
1915                X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, cSelectionTargets);
1916            }
1917            else if (aformat == 8)  /* work around quartz-wm brain damage */
1918            {
1919                unsigned long i, count = cSelectionTargets / sizeof(CARD32);
1920                Atom *atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(Atom) );
1921                for (i = 0; i < count; i++)
1922                    atoms[i] = ((CARD32 *)targetList)[i];  /* FIXME: byte swapping */
1923                X11DRV_CLIPBOARD_InsertSelectionProperties( display, atoms, count );
1924                HeapFree( GetProcessHeap(), 0, atoms );
1925            }
1926        }
1927
1928        /* Free the list of targets */
1929        wine_tsx11_lock();
1930        XFree(targetList);
1931        wine_tsx11_unlock();
1932     }
1933
1934     return cSelectionTargets;
1935 }
1936
1937
1938 /**************************************************************************
1939  *      X11DRV_CLIPBOARD_ReadSelectionData
1940  *
1941  * This method is invoked only when we DO NOT own the X selection
1942  *
1943  * We always get the data from the selection client each time,
1944  * since we have no way of determining if the data in our cache is stale.
1945  */
1946 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData)
1947 {
1948     Bool res;
1949     DWORD i;
1950     XEvent xe;
1951     BOOL bRet = FALSE;
1952
1953     TRACE("%d\n", lpData->wFormatID);
1954
1955     if (!lpData->lpFormat)
1956     {
1957         ERR("Requesting format %d but no source format linked to data.\n",
1958             lpData->wFormatID);
1959         return FALSE;
1960     }
1961
1962     if (!selectionAcquired)
1963     {
1964         Window w = thread_selection_wnd();
1965         if(!w)
1966         {
1967             ERR("No window available to read selection data!\n");
1968             return FALSE;
1969         }
1970
1971         TRACE("Requesting conversion of %s property (%d) from selection type %08x\n",
1972             debugstr_w(lpData->lpFormat->Name), lpData->lpFormat->drvData, (UINT)selectionCacheSrc);
1973
1974         wine_tsx11_lock();
1975         XConvertSelection(display, selectionCacheSrc, lpData->lpFormat->drvData,
1976             x11drv_atom(SELECTION_DATA), w, CurrentTime);
1977         wine_tsx11_unlock();
1978
1979         /* wait until SelectionNotify is received */
1980         for (i = 0; i < SELECTION_RETRIES; i++)
1981         {
1982             wine_tsx11_lock();
1983             res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
1984             wine_tsx11_unlock();
1985             if (res && xe.xselection.selection == selectionCacheSrc) break;
1986
1987             usleep(SELECTION_WAIT);
1988         }
1989
1990         /* Verify that the selection returned a valid TARGETS property */
1991         if (xe.xselection.property != None)
1992         {
1993             /*
1994              *  Read the contents of the X selection property 
1995              *  into WINE's clipboard cache and converting the 
1996              *  data format if necessary.
1997              */
1998              HANDLE hData = lpData->lpFormat->lpDrvImportFunc(display, xe.xselection.requestor,
1999                  xe.xselection.property);
2000
2001              bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, 0, hData, 0, lpData->lpFormat, TRUE);
2002         }
2003         else
2004         {
2005             TRACE("Failed to convert selection\n");
2006         }
2007     }
2008     else
2009     {
2010         ERR("Received request to cache selection data but process is owner\n");
2011     }
2012
2013     TRACE("Returning %d\n", bRet);
2014
2015     return bRet;
2016 }
2017
2018
2019 /**************************************************************************
2020  *              X11DRV_CLIPBOARD_ReadProperty
2021  *  Reads the contents of the X selection property.
2022  */
2023 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
2024     unsigned char** data, unsigned long* datasize)
2025 {
2026     Atom atype = AnyPropertyType;
2027     int aformat;
2028     unsigned long pos = 0, nitems, remain, count;
2029     unsigned char *val = NULL, *buffer;
2030
2031     if (prop == None)
2032         return FALSE;
2033
2034     TRACE("Reading property %lu from X window %lx\n", prop, w);
2035
2036     for (;;)
2037     {
2038         wine_tsx11_lock();
2039         if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
2040                                AnyPropertyType, &atype, &aformat, &nitems, &remain, &buffer) != Success)
2041         {
2042             wine_tsx11_unlock();
2043             WARN("Failed to read property\n");
2044             HeapFree( GetProcessHeap(), 0, val );
2045             return FALSE;
2046         }
2047
2048         count = get_property_size( aformat, nitems );
2049         if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
2050         else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
2051
2052         if (!*data)
2053         {
2054             XFree( buffer );
2055             wine_tsx11_unlock();
2056             HeapFree( GetProcessHeap(), 0, val );
2057             return FALSE;
2058         }
2059         val = *data;
2060         memcpy( (int *)val + pos, buffer, count );
2061         XFree( buffer );
2062         wine_tsx11_unlock();
2063         if (!remain)
2064         {
2065             *datasize = pos * sizeof(int) + count;
2066             val[*datasize] = 0;
2067             break;
2068         }
2069         pos += count / sizeof(int);
2070     }
2071
2072     /* Delete the property on the window now that we are done
2073      * This will send a PropertyNotify event to the selection owner. */
2074     wine_tsx11_lock();
2075     XDeleteProperty(display, w, prop);
2076     wine_tsx11_unlock();
2077     return TRUE;
2078 }
2079
2080
2081 /**************************************************************************
2082  *              CLIPBOARD_SerializeMetafile
2083  */
2084 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
2085 {
2086     HANDLE h = 0;
2087
2088     TRACE(" wFormat=%d hdata=%p out=%d\n", wformat, hdata, out);
2089
2090     if (out) /* Serialize out, caller should free memory */
2091     {
2092         *lpcbytes = 0; /* Assume failure */
2093
2094         if (wformat == CF_METAFILEPICT)
2095         {
2096             LPMETAFILEPICT lpmfp = (LPMETAFILEPICT) GlobalLock(hdata);
2097             unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2098
2099             h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
2100             if (h)
2101             {
2102                 char *pdata = GlobalLock(h);
2103
2104                 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
2105                 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
2106
2107                 *lpcbytes = size + sizeof(METAFILEPICT);
2108
2109                 GlobalUnlock(h);
2110             }
2111
2112             GlobalUnlock(hdata);
2113         }
2114         else if (wformat == CF_ENHMETAFILE)
2115         {
2116             int size = GetEnhMetaFileBits(hdata, 0, NULL);
2117
2118             h = GlobalAlloc(0, size);
2119             if (h)
2120             {
2121                 LPVOID pdata = GlobalLock(h);
2122
2123                 GetEnhMetaFileBits(hdata, size, pdata);
2124                 *lpcbytes = size;
2125
2126                 GlobalUnlock(h);
2127             }
2128         }
2129     }
2130     else
2131     {
2132         if (wformat == CF_METAFILEPICT)
2133         {
2134             h = GlobalAlloc(0, sizeof(METAFILEPICT));
2135             if (h)
2136             {
2137                 unsigned int wiresize, size;
2138                 LPMETAFILEPICT lpmfp = (LPMETAFILEPICT) GlobalLock(h);
2139
2140                 memcpy(lpmfp, hdata, sizeof(METAFILEPICT));
2141                 wiresize = *lpcbytes - sizeof(METAFILEPICT);
2142                 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
2143                     ((const BYTE *)hdata) + sizeof(METAFILEPICT));
2144                 size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2145                 GlobalUnlock(h);
2146             }
2147         }
2148         else if (wformat == CF_ENHMETAFILE)
2149         {
2150             h = SetEnhMetaFileBits(*lpcbytes, hdata);
2151         }
2152     }
2153
2154     return h;
2155 }
2156
2157
2158 /**************************************************************************
2159  *              X11DRV_CLIPBOARD_ReleaseSelection
2160  *
2161  * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
2162  */
2163 static void X11DRV_CLIPBOARD_ReleaseSelection(Display *display, Atom selType, Window w, HWND hwnd, Time time)
2164 {
2165     /* w is the window that lost the selection
2166      */
2167     TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
2168           (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
2169
2170     if (selectionAcquired && (w == selectionWindow))
2171     {
2172         CLIPBOARDINFO cbinfo;
2173
2174         /* completely give up the selection */
2175         TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
2176
2177         X11DRV_CLIPBOARD_GetClipboardInfo(&cbinfo);
2178
2179         if (cbinfo.flags & CB_PROCESS)
2180         {
2181             /* Since we're still the owner, this wasn't initiated by
2182                another Wine process */
2183             if (OpenClipboard(hwnd))
2184             {
2185                 /* Destroy private objects */
2186                 SendMessageW(cbinfo.hWndOwner, WM_DESTROYCLIPBOARD, 0, 0);
2187
2188                 /* Give up ownership of the windows clipboard */
2189                 X11DRV_CLIPBOARD_ReleaseOwnership();
2190                 CloseClipboard();
2191             }
2192         }
2193
2194         if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2195         {
2196             TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2197
2198             wine_tsx11_lock();
2199             if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2200             {
2201                 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2202                 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2203             }
2204             else
2205                 TRACE("We no longer own PRIMARY\n");
2206             wine_tsx11_unlock();
2207         }
2208         else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2209         {
2210             TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2211
2212             wine_tsx11_lock();
2213             if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2214             {
2215                 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2216                 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2217             }
2218             else
2219                 TRACE("We no longer own CLIPBOARD\n");
2220             wine_tsx11_unlock();
2221         }
2222
2223         selectionWindow = None;
2224
2225         X11DRV_EmptyClipboard(FALSE);
2226
2227         /* Reset the selection flags now that we are done */
2228         selectionAcquired = S_NOSELECTION;
2229     }
2230 }
2231
2232
2233 /**************************************************************************
2234  *              IsSelectionOwner (X11DRV.@)
2235  *
2236  * Returns: TRUE if the selection is owned by this process, FALSE otherwise
2237  */
2238 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void)
2239 {
2240     return selectionAcquired;
2241 }
2242
2243
2244 /**************************************************************************
2245  *                X11DRV Clipboard Exports
2246  **************************************************************************/
2247
2248
2249 /**************************************************************************
2250  *              RegisterClipboardFormat (X11DRV.@)
2251  *
2252  * Registers a custom X clipboard format
2253  * Returns: Format id or 0 on failure
2254  */
2255 UINT X11DRV_RegisterClipboardFormat(LPCWSTR FormatName)
2256 {
2257     LPWINE_CLIPFORMAT lpFormat;
2258
2259     if (FormatName == NULL) return 0;
2260     if (!(lpFormat = register_format( FormatName, 0 ))) return 0;
2261     return lpFormat->wFormatID;
2262 }
2263
2264
2265 /**************************************************************************
2266  *              X11DRV_GetClipboardFormatName
2267  */
2268 INT X11DRV_GetClipboardFormatName(UINT wFormat, LPWSTR retStr, INT maxlen)
2269 {
2270     LPWINE_CLIPFORMAT lpFormat;
2271
2272     TRACE("(%04X, %p, %d) !\n", wFormat, retStr, maxlen);
2273
2274     if (wFormat < 0xc000)
2275     {
2276         SetLastError(ERROR_INVALID_PARAMETER);
2277         return 0;
2278     }
2279
2280     lpFormat = X11DRV_CLIPBOARD_LookupFormat(wFormat);
2281
2282     if (!lpFormat || (lpFormat->wFlags & CF_FLAG_BUILTINFMT))
2283     {
2284         TRACE("Unknown format 0x%08x!\n", wFormat);
2285         SetLastError(ERROR_INVALID_HANDLE);
2286         return 0;
2287     }
2288
2289     lstrcpynW(retStr, lpFormat->Name, maxlen);
2290
2291     return strlenW(retStr);
2292 }
2293
2294
2295 /**************************************************************************
2296  *              AcquireClipboard (X11DRV.@)
2297  */
2298 int X11DRV_AcquireClipboard(HWND hWndClipWindow)
2299 {
2300     DWORD procid;
2301     Window owner;
2302     Display *display;
2303
2304     TRACE(" %p\n", hWndClipWindow);
2305
2306     /*
2307      * It's important that the selection get acquired from the thread
2308      * that owns the clipboard window. The primary reason is that we know 
2309      * it is running a message loop and therefore can process the 
2310      * X selection events.
2311      */
2312     if (hWndClipWindow &&
2313         GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, &procid))
2314     {
2315         if (procid != GetCurrentProcessId())
2316         {
2317             WARN("Setting clipboard owner to other process is not supported\n");
2318             hWndClipWindow = NULL;
2319         }
2320         else
2321         {
2322             TRACE("Thread %x is acquiring selection with thread %x's window %p\n",
2323                 GetCurrentThreadId(),
2324                 GetWindowThreadProcessId(hWndClipWindow, NULL), hWndClipWindow);
2325
2326             return SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0);
2327         }
2328     }
2329
2330     owner = thread_selection_wnd();
2331     display = thread_display();
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(thread_init_display(), 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                 event = *pevent;
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(display, 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, 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->display, event->selection,
3041                                            event->window, hWnd, event->time );
3042 }