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