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