Implemented syslink control.
[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,
1427     Atom target, XEvent *xe)
1428 {
1429     INT i;
1430     Bool res;
1431
1432     wine_tsx11_lock();
1433     XConvertSelection(display, selection, target,
1434         x11drv_atom(SELECTION_DATA), w, CurrentTime);
1435     wine_tsx11_unlock();
1436
1437     /*
1438      * Wait until SelectionNotify is received
1439      */
1440     for (i = 0; i < SELECTION_RETRIES; i++)
1441     {
1442         wine_tsx11_lock();
1443         res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
1444         wine_tsx11_unlock();
1445         if (res && xe->xselection.selection == selection) break;
1446
1447         usleep(SELECTION_WAIT);
1448     }
1449
1450     /* Verify that the selection returned a valid TARGETS property */
1451     if ((xe->xselection.target != target) || (xe->xselection.property == None))
1452     {
1453         /* Selection owner failed to respond or we missed the SelectionNotify */
1454         WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
1455         return FALSE;
1456     }
1457
1458     return TRUE;
1459 }
1460
1461
1462 /**************************************************************************
1463  *              X11DRV_CLIPBOARD_InsertSelectionProperties
1464  *
1465  * Mark property available for future retrieval.
1466  */
1467 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
1468 {
1469      INT i, nb_atoms = 0;
1470      Atom *atoms = NULL;
1471
1472      /* Cache these formats in the clipboard cache */
1473      for (i = 0; i < count; i++)
1474      {
1475          LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(properties[i]);
1476
1477          if (!lpFormat)
1478              lpFormat = X11DRV_CLIPBOARD_LookupAliasProperty(properties[i]);
1479
1480          if (!lpFormat)
1481          {
1482              /* add it to the list of atoms that we don't know about yet */
1483              if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
1484                                             (count - i) * sizeof(*atoms) );
1485              if (atoms) atoms[nb_atoms++] = properties[i];
1486          }
1487          else
1488          {
1489              TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1490                    i, lpFormat->drvData, lpFormat->wFormatID, lpFormat->Name);
1491              X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0);
1492          }
1493      }
1494
1495      /* query all unknown atoms in one go */
1496      if (atoms)
1497      {
1498          char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
1499          if (names)
1500          {
1501              wine_tsx11_lock();
1502              XGetAtomNames( display, atoms, nb_atoms, names );
1503              wine_tsx11_unlock();
1504              for (i = 0; i < nb_atoms; i++)
1505              {
1506                  WINE_CLIPFORMAT *lpFormat = register_format( names[i], atoms[i] );
1507                  if (!lpFormat)
1508                  {
1509                      ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
1510                      continue;
1511                  }
1512                  TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1513                        i, lpFormat->drvData, lpFormat->wFormatID, lpFormat->Name);
1514                  X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0);
1515              }
1516              wine_tsx11_lock();
1517              for (i = 0; i < nb_atoms; i++) XFree( names[i] );
1518              wine_tsx11_unlock();
1519              HeapFree( GetProcessHeap(), 0, names );
1520          }
1521          HeapFree( GetProcessHeap(), 0, atoms );
1522      }
1523 }
1524
1525
1526 /**************************************************************************
1527  *              X11DRV_CLIPBOARD_QueryAvailableData
1528  *
1529  * Caches the list of data formats available from the current selection.
1530  * This queries the selection owner for the TARGETS property and saves all
1531  * reported property types.
1532  */
1533 static int X11DRV_CLIPBOARD_QueryAvailableData(LPCLIPBOARDINFO lpcbinfo)
1534 {
1535     Display *display = thread_display();
1536     XEvent         xe;
1537     Atom           atype=AnyPropertyType;
1538     int            aformat;
1539     unsigned long  remain;
1540     Atom*          targetList=NULL;
1541     Window         w;
1542     HWND           hWndClipWindow; 
1543     unsigned long  cSelectionTargets = 0;
1544
1545     if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
1546     {
1547         ERR("Received request to cache selection but process is owner=(%08x)\n", 
1548             (unsigned) selectionWindow);
1549
1550         selectionAcquired  = S_NOSELECTION;
1551
1552         wine_tsx11_lock();
1553         if (XGetSelectionOwner(display,XA_PRIMARY) == selectionWindow)
1554             selectionAcquired |= S_PRIMARY;
1555
1556         if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == selectionWindow)
1557             selectionAcquired |= S_CLIPBOARD;
1558         wine_tsx11_unlock();
1559
1560         if (!(selectionAcquired == (S_PRIMARY | S_CLIPBOARD)))
1561         {
1562             WARN("Lost selection but process didn't process SelectClear\n");
1563             selectionWindow = None;
1564         }
1565         else
1566         {
1567             return -1; /* Prevent self request */
1568         }
1569     }
1570
1571     if (lpcbinfo->flags & CB_OWNER)
1572         hWndClipWindow = lpcbinfo->hWndOwner;
1573     else if (lpcbinfo->flags & CB_OPEN)
1574         hWndClipWindow = lpcbinfo->hWndOpen;
1575     else
1576         hWndClipWindow = GetActiveWindow();
1577
1578     if (!hWndClipWindow)
1579     {
1580         WARN("No window available to retrieve selection!\n");
1581         return -1;
1582     }
1583
1584     w = X11DRV_get_whole_window(GetAncestor(hWndClipWindow, GA_ROOT));
1585
1586     /*
1587      * Query the selection owner for the TARGETS property
1588      */
1589     wine_tsx11_lock();
1590     if ((usePrimary && XGetSelectionOwner(display,XA_PRIMARY)) ||
1591         XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
1592     {
1593         wine_tsx11_unlock();
1594         if (usePrimary && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
1595             selectionCacheSrc = XA_PRIMARY;
1596         else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
1597             selectionCacheSrc = x11drv_atom(CLIPBOARD);
1598         else
1599         {
1600             Atom xstr = XA_PRIMARY;
1601
1602             /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
1603             if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
1604             {
1605                 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1606                 selectionCacheSrc = XA_PRIMARY;
1607                 return 1;
1608             }
1609             else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
1610             {
1611                 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1612                 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1613                 return 1;
1614             }
1615             else
1616             {
1617                 WARN("Failed to query selection owner for available data.\n");
1618                 return -1;
1619             }
1620         }
1621     }
1622     else /* No selection owner so report 0 targets available */
1623     {
1624         wine_tsx11_unlock();
1625         return 0;
1626     }
1627
1628     /* Read the TARGETS property contents */
1629     wine_tsx11_lock();
1630     if(XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
1631         0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets, 
1632         &remain, (unsigned char**)&targetList) != Success)
1633     {
1634         wine_tsx11_unlock();
1635         WARN("Failed to read TARGETS property\n");
1636     }
1637     else
1638     {
1639         wine_tsx11_unlock();
1640        TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
1641              atype, aformat, cSelectionTargets, remain);
1642        /*
1643         * The TARGETS property should have returned us a list of atoms
1644         * corresponding to each selection target format supported.
1645         */
1646        if ((atype == XA_ATOM || atype == x11drv_atom(TARGETS)) && aformat == 32)
1647            X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, cSelectionTargets);
1648
1649        /* Free the list of targets */
1650        wine_tsx11_lock();
1651        XFree(targetList);
1652        wine_tsx11_unlock();
1653     }
1654
1655     return cSelectionTargets;
1656 }
1657
1658
1659 /**************************************************************************
1660  *      X11DRV_CLIPBOARD_ReadClipboardData
1661  *
1662  * This method is invoked only when we DO NOT own the X selection
1663  *
1664  * We always get the data from the selection client each time,
1665  * since we have no way of determining if the data in our cache is stale.
1666  */
1667 static BOOL X11DRV_CLIPBOARD_ReadClipboardData(UINT wFormat)
1668 {
1669     Display *display = thread_display();
1670     BOOL bRet = FALSE;
1671     Bool res;
1672
1673     HWND hWndClipWindow = GetOpenClipboardWindow();
1674     HWND hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
1675
1676     LPWINE_CLIPFORMAT lpFormat;
1677
1678     TRACE("%d\n", wFormat);
1679
1680     if (!selectionAcquired)
1681     {
1682         Window w = X11DRV_get_whole_window(GetAncestor(hWnd, GA_ROOT));
1683         if(!w)
1684         {
1685             FIXME("No parent win found %p %p\n", hWnd, hWndClipWindow);
1686             return FALSE;
1687         }
1688
1689         lpFormat = X11DRV_CLIPBOARD_LookupFormat(wFormat);
1690
1691         if (lpFormat && lpFormat->drvData)
1692         {
1693             DWORD i;
1694             UINT alias;
1695             XEvent xe;
1696
1697             TRACE("Requesting %s selection (%d) from win(%08x)\n", 
1698                 lpFormat->Name, lpFormat->drvData, (UINT)selectionCacheSrc);
1699
1700             wine_tsx11_lock();
1701             XConvertSelection(display, selectionCacheSrc, lpFormat->drvData,
1702                               x11drv_atom(SELECTION_DATA), w, CurrentTime);
1703             wine_tsx11_unlock();
1704
1705             /* wait until SelectionNotify is received */
1706             for (i = 0; i < SELECTION_RETRIES; i++)
1707             {
1708                 wine_tsx11_lock();
1709                 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
1710                 wine_tsx11_unlock();
1711                 if (res && xe.xselection.selection == selectionCacheSrc) break;
1712
1713                 usleep(SELECTION_WAIT);
1714             }
1715
1716             /* If the property wasn't available check for aliases */
1717             if (xe.xselection.property == None &&
1718                 (alias = X11DRV_CLIPBOARD_LookupPropertyAlias(lpFormat->drvData)))
1719             {
1720                 wine_tsx11_lock();
1721                 XConvertSelection(display, selectionCacheSrc, alias,
1722                                   x11drv_atom(SELECTION_DATA), w, CurrentTime);
1723                 wine_tsx11_unlock();
1724
1725                 /* wait until SelectionNotify is received */
1726                 for (i = 0; i < SELECTION_RETRIES; i++)
1727                 {
1728                     wine_tsx11_lock();
1729                     res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
1730                     wine_tsx11_unlock();
1731                     if (res && xe.xselection.selection == selectionCacheSrc) break;
1732
1733                     usleep(SELECTION_WAIT);
1734                 }
1735             }
1736
1737             /* Verify that the selection returned a valid TARGETS property */
1738             if (xe.xselection.property != None)
1739             {
1740                 /*
1741                  *  Read the contents of the X selection property 
1742                  *  into WINE's clipboard cache converting the 
1743                  *  selection to be compatible if possible.
1744                  */
1745                 bRet = X11DRV_CLIPBOARD_ReadSelection(lpFormat, xe.xselection.requestor, 
1746                     xe.xselection.property);
1747             }
1748         }
1749     }
1750     else
1751     {
1752         ERR("Received request to cache selection data but process is owner\n");
1753     }
1754
1755     TRACE("Returning %d\n", bRet);
1756
1757     return bRet;
1758 }
1759
1760
1761 /**************************************************************************
1762  *              X11DRV_CLIPBOARD_ReadSelection
1763  *  Reads the contents of the X selection property into the WINE clipboard cache
1764  *  converting the selection into a format compatible with the windows clipboard
1765  *  if possible.
1766  *  This method is invoked only to read the contents of a the selection owned
1767  *  by an external application. i.e. when we do not own the X selection.
1768  */
1769 static BOOL X11DRV_CLIPBOARD_ReadSelection(LPWINE_CLIPFORMAT lpData, Window w, Atom prop)
1770 {
1771     Display *display = thread_display();
1772     Atom              atype=AnyPropertyType;
1773     int               aformat;
1774     unsigned long     total,nitems,remain,val_cnt;
1775     long              reqlen, bwc;
1776     unsigned char*    val;
1777     unsigned char*    buffer;
1778     BOOL              bRet = FALSE;
1779
1780     if(prop == None)
1781         return bRet;
1782
1783     TRACE("Reading X selection type %s\n", lpData->Name);
1784
1785     /*
1786      * First request a zero length in order to figure out the request size.
1787      */
1788     wine_tsx11_lock();
1789     if(XGetWindowProperty(display,w,prop,0,0,False, AnyPropertyType,
1790         &atype, &aformat, &nitems, &remain, &buffer) != Success)
1791     {
1792         wine_tsx11_unlock();
1793         WARN("Failed to get property size\n");
1794         return bRet;
1795     }
1796
1797     /* Free zero length return data if any */
1798     if (buffer)
1799     {
1800        XFree(buffer);
1801        buffer = NULL;
1802     }
1803
1804     bwc = aformat/8;
1805     reqlen = remain * bwc;
1806
1807     TRACE("Retrieving %ld bytes\n", reqlen);
1808
1809     val = (char*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, reqlen);
1810
1811     /* Read property in 4K blocks */
1812     for (total = 0, val_cnt = 0; remain;)
1813     {
1814        if (XGetWindowProperty(display, w, prop, (total / 4), 4096, False,
1815            AnyPropertyType, &atype, &aformat, &nitems, &remain, &buffer) != Success)
1816        {
1817            wine_tsx11_unlock();
1818            WARN("Failed to read property\n");
1819            HeapFree(GetProcessHeap(), 0, val);
1820            return bRet;
1821        }
1822
1823        bwc = aformat/8;
1824        memcpy(&val[val_cnt], buffer, nitems * bwc);
1825        val_cnt += nitems * bwc;
1826        total += nitems*bwc;
1827        XFree(buffer);
1828     }
1829     wine_tsx11_unlock();
1830
1831     bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, 0, lpData->lpDrvImportFunc(val, total), 0);
1832
1833     /* Delete the property on the window now that we are done
1834      * This will send a PropertyNotify event to the selection owner. */
1835     wine_tsx11_lock();
1836     XDeleteProperty(display,w,prop);
1837     wine_tsx11_unlock();
1838
1839     /* Free the retrieved property data */
1840     HeapFree(GetProcessHeap(),0,val);
1841
1842     return bRet;
1843 }
1844
1845
1846 /**************************************************************************
1847  *              CLIPBOARD_SerializeMetafile
1848  */
1849 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
1850 {
1851     HANDLE h = 0;
1852
1853     TRACE(" wFormat=%d hdata=%08x out=%d\n", wformat, (unsigned int) hdata, out);
1854
1855     if (out) /* Serialize out, caller should free memory */
1856     {
1857         *lpcbytes = 0; /* Assume failure */
1858
1859         if (wformat == CF_METAFILEPICT)
1860         {
1861             LPMETAFILEPICT lpmfp = (LPMETAFILEPICT) GlobalLock(hdata);
1862             unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
1863
1864             h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
1865             if (h)
1866             {
1867                 char *pdata = GlobalLock(h);
1868
1869                 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
1870                 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
1871
1872                 *lpcbytes = size + sizeof(METAFILEPICT);
1873
1874                 GlobalUnlock(h);
1875             }
1876
1877             GlobalUnlock(hdata);
1878         }
1879         else if (wformat == CF_ENHMETAFILE)
1880         {
1881             int size = GetEnhMetaFileBits(hdata, 0, NULL);
1882
1883             h = GlobalAlloc(0, size);
1884             if (h)
1885             {
1886                 LPVOID pdata = GlobalLock(h);
1887
1888                 GetEnhMetaFileBits(hdata, size, pdata);
1889                 *lpcbytes = size;
1890
1891                 GlobalUnlock(h);
1892             }
1893         }
1894     }
1895     else
1896     {
1897         if (wformat == CF_METAFILEPICT)
1898         {
1899             h = GlobalAlloc(0, sizeof(METAFILEPICT));
1900             if (h)
1901             {
1902                 unsigned int wiresize, size;
1903                 LPMETAFILEPICT lpmfp = (LPMETAFILEPICT) GlobalLock(h);
1904
1905                 memcpy(lpmfp, (LPVOID)hdata, sizeof(METAFILEPICT));
1906                 wiresize = *lpcbytes - sizeof(METAFILEPICT);
1907                 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
1908                     ((char *)hdata) + sizeof(METAFILEPICT));
1909                 size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
1910                 GlobalUnlock(h);
1911             }
1912         }
1913         else if (wformat == CF_ENHMETAFILE)
1914         {
1915             h = SetEnhMetaFileBits(*lpcbytes, (LPVOID)hdata);
1916         }
1917     }
1918
1919     return h;
1920 }
1921
1922
1923 /**************************************************************************
1924  *              X11DRV_CLIPBOARD_ReleaseSelection
1925  *
1926  * Release an XA_PRIMARY or XA_CLIPBOARD selection that we own, in response
1927  * to a SelectionClear event.
1928  * This can occur in response to another client grabbing the X selection.
1929  * If the XA_CLIPBOARD selection is lost, we relinquish XA_PRIMARY as well.
1930  */
1931 void X11DRV_CLIPBOARD_ReleaseSelection(Atom selType, Window w, HWND hwnd)
1932 {
1933     Display *display = thread_display();
1934
1935     /* w is the window that lost the selection
1936      */
1937     TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
1938           (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
1939
1940     if (selectionAcquired)
1941     {
1942         if (w == selectionWindow)
1943         {
1944             /* If we're losing the CLIPBOARD selection, or if the preferences in .winerc
1945              * dictate that *all* selections should be cleared on loss of a selection,
1946              * we must give up all the selections we own.
1947              */
1948             if (clearAllSelections || (selType == x11drv_atom(CLIPBOARD)))
1949             {
1950                 CLIPBOARDINFO cbinfo;
1951
1952                 /* completely give up the selection */
1953                 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
1954
1955               /* We are completely giving up the selection. There is a
1956                * potential race condition where the apps that now owns
1957                * the selection has already grabbed both selections. In
1958                * this case, if we clear any selection we may clear the
1959                * new owners selection. To prevent this common case we
1960                * try to open the clipboard. If we can't, we assume it
1961                * was a wine apps that took it and has taken both selections.
1962                * In this case, don't bother releasing the other selection.
1963                * Otherwise only release the selection if we still own it.
1964                */
1965                 X11DRV_CLIPBOARD_GetClipboardInfo(&cbinfo);
1966
1967                 if (cbinfo.flags & CB_OWNER)
1968                 {
1969                     /* Since we're still the owner, this wasn't initiated by 
1970                        another Wine process */
1971                     if (OpenClipboard(hwnd))
1972                     {
1973                       /* We really lost CLIPBOARD but want to voluntarily lose PRIMARY */
1974                       if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
1975                       {
1976                           TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
1977                           wine_tsx11_lock();
1978                           if (selectionWindow == XGetSelectionOwner(display,XA_PRIMARY))
1979                           {
1980                              TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
1981                              XSetSelectionOwner(display, XA_PRIMARY, None, CurrentTime);
1982                           }
1983                           else
1984                              TRACE("We no longer own PRIMARY\n");
1985                           wine_tsx11_unlock();
1986                       }
1987
1988                       /* We really lost PRIMARY but want to voluntarily lose CLIPBOARD  */
1989                       if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
1990                       {
1991                           TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
1992                           wine_tsx11_lock();
1993                           if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
1994                           {
1995                               TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
1996                               XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, CurrentTime);
1997                           }
1998                           else
1999                               TRACE("We no longer own CLIPBOARD\n");
2000                           wine_tsx11_unlock();
2001                       }
2002
2003                       /* Destroy private objects */
2004                       SendMessageW(cbinfo.hWndOwner, WM_DESTROYCLIPBOARD, 0, 0);
2005    
2006                       /* Give up ownership of the windows clipboard */
2007                       X11DRV_CLIPBOARD_ReleaseOwnership();
2008
2009                       CloseClipboard();
2010                     }
2011                 }
2012                 else
2013                 {
2014                     TRACE("Lost selection to other Wine process.\n");
2015                 }
2016
2017                 selectionWindow = None;
2018                 PrimarySelectionOwner = ClipboardSelectionOwner = 0;
2019
2020                 X11DRV_EmptyClipboard(FALSE);
2021
2022                 /* Reset the selection flags now that we are done */
2023                 selectionAcquired = S_NOSELECTION;
2024             }
2025             else if ( selType == XA_PRIMARY ) /* Give up only PRIMARY selection */
2026             {
2027                 TRACE("Lost PRIMARY selection\n");
2028                 PrimarySelectionOwner = 0;
2029                 selectionAcquired &= ~S_PRIMARY;  /* clear S_PRIMARY mask */
2030             }
2031         }
2032     }
2033 }
2034
2035
2036 /**************************************************************************
2037  *              IsSelectionOwner (X11DRV.@)
2038  *
2039  * Returns: TRUE if the selection is owned by this process, FALSE otherwise
2040  */
2041 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void)
2042 {
2043     return selectionAcquired;
2044 }
2045
2046
2047 /**************************************************************************
2048  *                X11DRV Clipboard Exports
2049  **************************************************************************/
2050
2051
2052 /**************************************************************************
2053  *              RegisterClipboardFormat (X11DRV.@)
2054  *
2055  * Registers a custom X clipboard format
2056  * Returns: Format id or 0 on failure
2057  */
2058 INT X11DRV_RegisterClipboardFormat(LPCSTR FormatName)
2059 {
2060     LPWINE_CLIPFORMAT lpFormat;
2061
2062     if (FormatName == NULL) return 0;
2063     if (!(lpFormat = register_format( FormatName, 0 ))) return 0;
2064     return lpFormat->wFormatID;
2065 }
2066
2067
2068 /**************************************************************************
2069  *              X11DRV_GetClipboardFormatName
2070  */
2071 INT X11DRV_GetClipboardFormatName(UINT wFormat, LPSTR retStr, INT maxlen)
2072 {
2073     INT len;
2074     LPWINE_CLIPFORMAT lpFormat;
2075
2076     TRACE("(%04X, %p, %d) !\n", wFormat, retStr, maxlen);
2077
2078     if (wFormat < 0xc000)
2079     {
2080         SetLastError(ERROR_INVALID_PARAMETER);
2081         return 0;
2082     }
2083
2084     lpFormat = X11DRV_CLIPBOARD_LookupFormat(wFormat);
2085
2086     if (!lpFormat || (lpFormat->wFlags & CF_FLAG_BUILTINFMT))
2087     {
2088         TRACE("Unknown format 0x%08x!\n", wFormat);
2089         SetLastError(ERROR_INVALID_HANDLE);
2090         return 0;
2091     }
2092
2093     strncpy(retStr, lpFormat->Name, maxlen - 1);
2094     retStr[maxlen - 1] = 0;
2095
2096     len = strlen(retStr);
2097     return len;
2098 }
2099
2100
2101 /**************************************************************************
2102  *              AcquireClipboard (X11DRV.@)
2103  */
2104 void X11DRV_AcquireClipboard(HWND hWndClipWindow)
2105 {
2106     Display *display = thread_display();
2107
2108     /*
2109      * Acquire X selection if we don't already own it.
2110      * Note that we only acquire the selection if it hasn't been already
2111      * acquired by us, and ignore the fact that another X window may be
2112      * asserting ownership. The reason for this is we need *any* top level
2113      * X window to hold selection ownership. The actual clipboard data requests
2114      * are made via GetClipboardData from EVENT_SelectionRequest and this
2115      * ensures that the real HWND owner services the request.
2116      * If the owning X window gets destroyed the selection ownership is
2117      * re-cycled to another top level X window in X11DRV_CLIPBOARD_ResetOwner.
2118      *
2119      */
2120     if (!(selectionAcquired == (S_PRIMARY | S_CLIPBOARD)))
2121     {
2122         Window owner;
2123
2124         if (!hWndClipWindow)
2125             hWndClipWindow = GetActiveWindow();
2126
2127         owner = X11DRV_get_whole_window(GetAncestor(hWndClipWindow, GA_ROOT));
2128
2129         wine_tsx11_lock();
2130         /* Grab PRIMARY selection if not owned */
2131         if (usePrimary && !(selectionAcquired & S_PRIMARY))
2132             XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2133
2134         /* Grab CLIPBOARD selection if not owned */
2135         if (!(selectionAcquired & S_CLIPBOARD))
2136             XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2137
2138         if (usePrimary && XGetSelectionOwner(display,XA_PRIMARY) == owner)
2139             selectionAcquired |= S_PRIMARY;
2140
2141         if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2142             selectionAcquired |= S_CLIPBOARD;
2143         wine_tsx11_unlock();
2144
2145         if (selectionAcquired)
2146         {
2147             selectionWindow = owner;
2148             TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2149         }
2150     }
2151     else
2152     {
2153         WARN("Received request to acquire selection but process is already owner=(%08x)\n", (unsigned) selectionWindow);
2154
2155         selectionAcquired  = S_NOSELECTION;
2156
2157         wine_tsx11_lock();
2158         if (XGetSelectionOwner(display,XA_PRIMARY) == selectionWindow)
2159             selectionAcquired |= S_PRIMARY;
2160
2161         if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == selectionWindow)
2162             selectionAcquired |= S_CLIPBOARD;
2163         wine_tsx11_unlock();
2164
2165         if (!(selectionAcquired == (S_PRIMARY | S_CLIPBOARD)))
2166         {
2167             WARN("Lost selection but process didn't process SelectClear\n");
2168             selectionWindow = None;
2169         }
2170     }
2171 }
2172
2173
2174 /**************************************************************************
2175  *      X11DRV_EmptyClipboard
2176  *
2177  * Empty cached clipboard data. 
2178  */
2179 void X11DRV_EmptyClipboard(BOOL keepunowned)
2180 {
2181     if (ClipData)
2182     {
2183         LPWINE_CLIPDATA lpData, lpStart;
2184         LPWINE_CLIPDATA lpNext = ClipData;
2185
2186         TRACE(" called with %d entries in cache.\n", ClipDataCount);
2187
2188         do
2189         {
2190             lpStart = ClipData;
2191             lpData = lpNext;
2192             lpNext = lpData->NextData;
2193
2194             if (!keepunowned || !(lpData->wFlags & CF_FLAG_UNOWNED))
2195             {
2196             lpData->PrevData->NextData = lpData->NextData;
2197             lpData->NextData->PrevData = lpData->PrevData;
2198
2199                 if (lpData == ClipData)
2200                     ClipData = lpNext != lpData ? lpNext : NULL;
2201
2202             X11DRV_CLIPBOARD_FreeData(lpData);
2203             HeapFree(GetProcessHeap(), 0, lpData);
2204
2205                 ClipDataCount--;
2206             }
2207         } while (lpNext != lpStart);
2208     }
2209
2210     TRACE(" %d entries remaining in cache.\n", ClipDataCount);
2211 }
2212
2213
2214
2215 /**************************************************************************
2216  *              X11DRV_SetClipboardData
2217  */
2218 BOOL X11DRV_SetClipboardData(UINT wFormat, HANDLE16 hData16, HANDLE hData32, BOOL owner)
2219 {
2220     DWORD flags = 0;
2221     BOOL bResult = TRUE;
2222
2223     /* If it's not owned, data can only be set if the format data is not already owned
2224        and its rendering is not delayed */
2225     if (!owner)
2226 {
2227         CLIPBOARDINFO cbinfo;
2228         LPWINE_CLIPDATA lpRender;
2229
2230         X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2231
2232         if ((!hData16 && !hData32) ||
2233             ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)) &&
2234             !(lpRender->wFlags & CF_FLAG_UNOWNED)))
2235             bResult = FALSE;
2236         else
2237             flags = CF_FLAG_UNOWNED;
2238     }
2239
2240     bResult &= X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData16, hData32, flags);
2241
2242     return bResult;
2243 }
2244
2245
2246 /**************************************************************************
2247  *              CountClipboardFormats
2248  */
2249 INT X11DRV_CountClipboardFormats(void)
2250 {
2251     CLIPBOARDINFO cbinfo;
2252
2253     X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2254
2255     TRACE(" count=%d\n", ClipDataCount);
2256
2257     return ClipDataCount;
2258 }
2259
2260
2261 /**************************************************************************
2262  *              X11DRV_EnumClipboardFormats
2263  */
2264 UINT X11DRV_EnumClipboardFormats(UINT wFormat)
2265 {
2266     CLIPBOARDINFO cbinfo;
2267     UINT wNextFormat = 0;
2268
2269     TRACE("(%04X)\n", wFormat);
2270
2271     X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2272
2273     if (!wFormat)
2274     {
2275         if (ClipData)
2276             wNextFormat = ClipData->wFormatID;
2277     }
2278     else
2279     {
2280         LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
2281
2282         if (lpData && lpData->NextData != ClipData)
2283             wNextFormat = lpData->NextData->wFormatID;
2284     }
2285
2286     return wNextFormat;
2287 }
2288
2289
2290 /**************************************************************************
2291  *              X11DRV_IsClipboardFormatAvailable
2292  */
2293 BOOL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
2294 {
2295     BOOL bRet = FALSE;
2296     CLIPBOARDINFO cbinfo;
2297
2298     TRACE("(%04X)\n", wFormat);
2299
2300     X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2301
2302     if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
2303         bRet = TRUE;
2304
2305     TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
2306
2307     return bRet;
2308 }
2309
2310
2311 /**************************************************************************
2312  *              GetClipboardData (USER.142)
2313  */
2314 BOOL X11DRV_GetClipboardData(UINT wFormat, HANDLE16* phData16, HANDLE* phData32)
2315 {
2316     CLIPBOARDINFO cbinfo;
2317     LPWINE_CLIPDATA lpRender;
2318
2319     TRACE("(%04X)\n", wFormat);
2320
2321     X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2322
2323     if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
2324     {
2325         if ( !lpRender->hData32 )
2326             X11DRV_CLIPBOARD_RenderFormat(lpRender);
2327
2328         /* Convert between 32 -> 16 bit data, if necessary */
2329         if (lpRender->hData32 && !lpRender->hData16)
2330         {
2331             int size;
2332
2333             if (lpRender->wFormatID == CF_METAFILEPICT)
2334                 size = sizeof(METAFILEPICT16);
2335             else
2336                 size = GlobalSize(lpRender->hData32);
2337
2338             lpRender->hData16 = GlobalAlloc16(GMEM_ZEROINIT, size);
2339
2340             if (!lpRender->hData16)
2341                 ERR("(%04X) -- not enough memory in 16b heap\n", wFormat);
2342             else
2343             {
2344                 if (lpRender->wFormatID == CF_METAFILEPICT)
2345                 {
2346                     FIXME("\timplement function CopyMetaFilePict32to16\n");
2347                     FIXME("\tin the appropriate file.\n");
2348   #ifdef SOMEONE_IMPLEMENTED_ME
2349                     CopyMetaFilePict32to16(GlobalLock16(lpRender->hData16),
2350                         GlobalLock(lpRender->hData32));
2351   #endif
2352                 }
2353                 else
2354                 {
2355                     memcpy(GlobalLock16(lpRender->hData16),
2356                         GlobalLock(lpRender->hData32), size);
2357                 }
2358
2359                 GlobalUnlock16(lpRender->hData16);
2360                 GlobalUnlock(lpRender->hData32);
2361             }
2362         }
2363
2364         /* Convert between 32 -> 16 bit data, if necessary */
2365         if (lpRender->hData16 && !lpRender->hData32)
2366         {
2367             int size;
2368
2369             if (lpRender->wFormatID == CF_METAFILEPICT)
2370                 size = sizeof(METAFILEPICT16);
2371             else
2372                 size = GlobalSize(lpRender->hData32);
2373
2374             lpRender->hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE | 
2375                 GMEM_DDESHARE, size);
2376
2377             if (lpRender->wFormatID == CF_METAFILEPICT)
2378             {
2379                 FIXME("\timplement function CopyMetaFilePict16to32\n");
2380                 FIXME("\tin the appropriate file.\n");
2381 #ifdef SOMEONE_IMPLEMENTED_ME
2382                 CopyMetaFilePict16to32(GlobalLock16(lpRender->hData32),
2383                     GlobalLock(lpRender->hData16));
2384 #endif
2385             }
2386             else
2387             {
2388                 memcpy(GlobalLock(lpRender->hData32),
2389                     GlobalLock16(lpRender->hData16), size);
2390             }
2391
2392             GlobalUnlock(lpRender->hData32);
2393             GlobalUnlock16(lpRender->hData16);
2394         }
2395
2396         if (phData16)
2397             *phData16 = lpRender->hData16;
2398
2399         if (phData32)
2400             *phData32 = lpRender->hData32;
2401
2402         TRACE(" returning hData16(%04x) hData32(%04x) (type %d)\n", 
2403             lpRender->hData16, (unsigned int) lpRender->hData32, lpRender->wFormatID);
2404
2405         return lpRender->hData16 || lpRender->hData32;
2406     }
2407
2408     return 0;
2409 }
2410
2411
2412 /**************************************************************************
2413  *              ResetSelectionOwner (X11DRV.@)
2414  *
2415  * Called from DestroyWindow() to prevent X selection from being lost when
2416  * a top level window is destroyed, by switching ownership to another top
2417  * level window.
2418  * Any top level window can own the selection. See X11DRV_CLIPBOARD_Acquire
2419  * for a more detailed description of this.
2420  */
2421 void X11DRV_ResetSelectionOwner(HWND hwnd, BOOL bFooBar)
2422 {
2423     Display *display = thread_display();
2424     HWND hWndClipOwner = 0;
2425     HWND tmp;
2426     Window XWnd = X11DRV_get_whole_window(hwnd);
2427     BOOL bLostSelection = FALSE;
2428     Window selectionPrevWindow;
2429
2430     /* There is nothing to do if we don't own the selection,
2431      * or if the X window which currently owns the selection is different
2432      * from the one passed in.
2433      */
2434     if (!selectionAcquired || XWnd != selectionWindow
2435          || selectionWindow == None )
2436        return;
2437
2438     if ((bFooBar && XWnd) || (!bFooBar && !XWnd))
2439        return;
2440
2441     hWndClipOwner = GetClipboardOwner();
2442
2443     TRACE("clipboard owner = %p, selection window = %08x\n",
2444           hWndClipOwner, (unsigned)selectionWindow);
2445
2446     /* now try to salvage current selection from being destroyed by X */
2447     TRACE("checking %08x\n", (unsigned) XWnd);
2448
2449     selectionPrevWindow = selectionWindow;
2450     selectionWindow = None;
2451
2452     if (!(tmp = GetWindow(hwnd, GW_HWNDNEXT)))
2453         tmp = GetWindow(hwnd, GW_HWNDFIRST);
2454
2455     if (tmp && tmp != hwnd) 
2456         selectionWindow = X11DRV_get_whole_window(tmp);
2457
2458     if (selectionWindow != None)
2459     {
2460         /* We must pretend that we don't own the selection while making the switch
2461          * since a SelectionClear event will be sent to the last owner.
2462          * If there is no owner X11DRV_CLIPBOARD_ReleaseSelection will do nothing.
2463          */
2464         int saveSelectionState = selectionAcquired;
2465         selectionAcquired = S_NOSELECTION;
2466
2467         TRACE("\tswitching selection from %08x to %08x\n",
2468                     (unsigned)selectionPrevWindow, (unsigned)selectionWindow);
2469
2470         wine_tsx11_lock();
2471
2472         /* Assume ownership for the PRIMARY and CLIPBOARD selection */
2473         if (saveSelectionState & S_PRIMARY)
2474             XSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
2475
2476         XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), selectionWindow, CurrentTime);
2477
2478         /* Restore the selection masks */
2479         selectionAcquired = saveSelectionState;
2480
2481         /* Lose the selection if something went wrong */
2482         if (((saveSelectionState & S_PRIMARY) &&
2483            (XGetSelectionOwner(display, XA_PRIMARY) != selectionWindow)) || 
2484            (XGetSelectionOwner(display, x11drv_atom(CLIPBOARD)) != selectionWindow))
2485         {
2486             bLostSelection = TRUE;
2487         }
2488         else
2489         {
2490             /* Update selection state */
2491             if (saveSelectionState & S_PRIMARY)
2492                PrimarySelectionOwner = selectionWindow;
2493
2494             ClipboardSelectionOwner = selectionWindow;
2495         }
2496         wine_tsx11_unlock();
2497     }
2498     else
2499     {
2500         bLostSelection = TRUE;
2501     }
2502
2503     if (bLostSelection)
2504     {
2505         TRACE("Lost the selection!\n");
2506
2507         X11DRV_CLIPBOARD_ReleaseOwnership();
2508         selectionAcquired = S_NOSELECTION;
2509         ClipboardSelectionOwner = PrimarySelectionOwner = 0;
2510         selectionWindow = 0;
2511     }
2512 }
2513
2514
2515 /**************************************************************************
2516  *                      X11DRV_CLIPBOARD_SynthesizeData
2517  */
2518 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID)
2519 {
2520     BOOL bsyn = TRUE;
2521     LPWINE_CLIPDATA lpSource = NULL;
2522
2523     TRACE(" %d\n", wFormatID);
2524
2525     /* Don't need to synthesize if it already exists */
2526     if (X11DRV_CLIPBOARD_LookupData(wFormatID))
2527         return TRUE;
2528
2529     if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
2530     {
2531         bsyn = ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
2532             ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2533             ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
2534             ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2535             ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
2536             ~lpSource->wFlags & CF_FLAG_SYNTHESIZED);
2537     }
2538     else if (wFormatID == CF_ENHMETAFILE)
2539     {
2540         bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2541             ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2542     }
2543     else if (wFormatID == CF_METAFILEPICT)
2544     {
2545         bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2546             ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2547     }
2548     else if (wFormatID == CF_DIB)
2549     {
2550         bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
2551             ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2552     }
2553     else if (wFormatID == CF_BITMAP)
2554     {
2555         bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
2556             ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2557     }
2558
2559     if (bsyn)
2560         X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, 0, CF_FLAG_SYNTHESIZED);
2561
2562     return bsyn;
2563 }
2564
2565
2566
2567 /**************************************************************************
2568  *              X11DRV_EndClipboardUpdate
2569  * TODO:
2570  *  Add locale if it hasn't already been added
2571  */
2572 void X11DRV_EndClipboardUpdate(void)
2573 {
2574     INT count = ClipDataCount;
2575
2576     /* Do Unicode <-> Text <-> OEM mapping */
2577     X11DRV_CLIPBOARD_SynthesizeData(CF_UNICODETEXT);
2578     X11DRV_CLIPBOARD_SynthesizeData(CF_TEXT);
2579     X11DRV_CLIPBOARD_SynthesizeData(CF_OEMTEXT);
2580
2581     /* Enhmetafile <-> MetafilePict mapping */
2582     X11DRV_CLIPBOARD_SynthesizeData(CF_ENHMETAFILE);
2583     X11DRV_CLIPBOARD_SynthesizeData(CF_METAFILEPICT);
2584
2585     /* DIB <-> Bitmap mapping */
2586     X11DRV_CLIPBOARD_SynthesizeData(CF_DIB);
2587     X11DRV_CLIPBOARD_SynthesizeData(CF_BITMAP);
2588
2589     TRACE("%d formats added to cached data\n", ClipDataCount - count);
2590 }