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