Fixed a number of -DSTRICT warnings.
[wine] / dlls / x11drv / clipboard.c
1 /*
2  * X11 clipboard windows driver
3  *
4  * Copyright 1994 Martin Ayotte
5  *           1996 Alex Korobka
6  *           1999 Noel Borthwick
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  * NOTES:
23  *    This file contains the X specific implementation for the windows
24  *    Clipboard API.
25  *
26  *    Wine's internal clipboard is exposed to external apps via the X
27  *    selection mechanism.
28  *    Currently the driver asserts ownership via two selection atoms:
29  *    1. PRIMARY(XA_PRIMARY)
30  *    2. CLIPBOARD
31  *
32  *    In our implementation, the CLIPBOARD selection takes precedence over PRIMARY,
33  *    i.e. if a CLIPBOARD selection is available, it is used instead of PRIMARY.
34  *    When Wine takes ownership of the clipboard, it takes ownership of BOTH selections.
35  *    While giving up selection ownership, if the CLIPBOARD selection is lost,
36  *    it will lose both PRIMARY and CLIPBOARD and empty the clipboard.
37  *    However if only PRIMARY is lost, it will continue to hold the CLIPBOARD selection
38  *    (leaving the clipboard cache content unaffected).
39  *
40  *      Every format exposed via a windows clipboard format is also exposed through
41  *    a corresponding X selection target. A selection target atom is synthesized
42  *    whenever a new Windows clipboard format is registered via RegisterClipboardFormat,
43  *    or when a built-in format is used for the first time.
44  *    Windows native format are exposed by prefixing the format name with "<WCF>"
45  *    This allows us to uniquely identify windows native formats exposed by other
46  *    running WINE apps.
47  *
48  *      In order to allow external applications to query WINE for supported formats,
49  *    we respond to the "TARGETS" selection target. (See EVENT_SelectionRequest
50  *    for implementation) We use the same mechanism to query external clients for
51  *    availability of a particular format, by caching the list of available targets
52  *    by using the clipboard cache's "delayed render" mechanism. If a selection client
53  *    does not support the "TARGETS" selection target, we actually attempt to retrieve
54  *    the format requested as a fallback mechanism.
55  *
56  *      Certain Windows native formats are automatically converted to X native formats
57  *    and vice versa. If a native format is available in the selection, it takes
58  *    precedence, in order to avoid unnecessary conversions.
59  *
60  */
61
62 #include "config.h"
63
64 #include <string.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #ifdef HAVE_UNISTD_H
68 # include <unistd.h>
69 #endif
70 #include <fcntl.h>
71 #include <time.h>
72
73 #include "ts_xlib.h"
74 #include "winreg.h"
75 #include "clipboard.h"
76 #include "win.h"
77 #include "x11drv.h"
78 #include "wine/debug.h"
79
80 WINE_DEFAULT_DEBUG_CHANNEL(clipboard);
81
82 /* Maximum wait time for slection notify */
83 #define MAXSELECTIONNOTIFYWAIT 5
84
85 /* Selection masks */
86
87 #define S_NOSELECTION    0
88 #define S_PRIMARY        1
89 #define S_CLIPBOARD      2
90
91 /* X selection context info */
92
93 static char _CLIPBOARD[] = "CLIPBOARD";        /* CLIPBOARD atom name */
94 static char FMT_PREFIX[] = "<WCF>";            /* Prefix for windows specific formats */
95 static int selectionAcquired = 0;              /* Contains the current selection masks */
96 static Window selectionWindow = None;          /* The top level X window which owns the selection */
97 static Window selectionPrevWindow = None;      /* The last X window that owned the selection */
98 static Window PrimarySelectionOwner = None;    /* The window which owns the primary selection */
99 static Window ClipboardSelectionOwner = None;  /* The window which owns the clipboard selection */
100 static unsigned long cSelectionTargets = 0;    /* Number of target formats reported by TARGETS selection */
101 static Atom selectionCacheSrc = XA_PRIMARY;    /* The selection source from which the clipboard cache was filled */
102 static HANDLE selectionClearEvent = 0;/* Synchronization object used to block until server is started */
103
104 typedef struct tagPROPERTY
105 {
106     struct tagPROPERTY *next;
107     Atom                atom;
108     Pixmap              pixmap;
109 } PROPERTY;
110
111 static PROPERTY *prop_head;
112
113
114 /**************************************************************************
115  *              X11DRV_CLIPBOARD_MapPropertyToFormat
116  *
117  *  Map an X selection property type atom name to a windows clipboard format ID
118  */
119 UINT X11DRV_CLIPBOARD_MapPropertyToFormat(char *itemFmtName)
120 {
121     /*
122      * If the property name starts with FMT_PREFIX strip this off and
123      * get the ID for a custom Windows registered format with this name.
124      * We can also understand STRING, PIXMAP and BITMAP.
125      */
126     if ( NULL == itemFmtName )
127         return 0;
128     else if ( 0 == strncmp(itemFmtName, FMT_PREFIX, strlen(FMT_PREFIX)) )
129         return RegisterClipboardFormatA(itemFmtName + strlen(FMT_PREFIX));
130     else if ( 0 == strcmp(itemFmtName, "STRING") )
131         return CF_UNICODETEXT;
132     else if ( 0 == strcmp(itemFmtName, "PIXMAP")
133                 ||  0 == strcmp(itemFmtName, "BITMAP") )
134     {
135         /*
136          * Return CF_DIB as first preference, if WINE is the selection owner
137          * and if CF_DIB exists in the cache.
138          * If wine dowsn't own the selection we always return CF_DIB
139          */
140         if ( !X11DRV_IsSelectionOwner() )
141             return CF_DIB;
142         else if ( CLIPBOARD_IsPresent(CF_DIB) )
143             return CF_DIB;
144         else
145             return CF_BITMAP;
146     }
147
148     WARN("\tNo mapping to Windows clipboard format for property %s\n", itemFmtName);
149     return 0;
150 }
151
152 /**************************************************************************
153  *              X11DRV_CLIPBOARD_MapFormatToProperty
154  *
155  *  Map a windows clipboard format ID to an X selection property atom
156  */
157 Atom X11DRV_CLIPBOARD_MapFormatToProperty(UINT wFormat)
158 {
159     Atom prop = None;
160
161     switch (wFormat)
162     {
163         /* We support only CF_UNICODETEXT, other formats are synthesized */
164         case CF_OEMTEXT:
165         case CF_TEXT:
166             return None;
167
168         case CF_UNICODETEXT:
169             prop = XA_STRING;
170             break;
171
172         case CF_DIB:
173         case CF_BITMAP:
174         {
175             /*
176              * Request a PIXMAP, only if WINE is NOT the selection owner,
177              * AND the requested format is not in the cache.
178              */
179             if ( !X11DRV_IsSelectionOwner() && !CLIPBOARD_IsPresent(wFormat) )
180             {
181               prop = XA_PIXMAP;
182               break;
183             }
184             /* Fall through to the default case in order to use the native format */
185         }
186
187         default:
188         {
189             /*
190              * If an X atom is registered for this format, return that
191              * Otherwise register a new atom.
192              */
193             char str[256];
194             int plen = strlen(FMT_PREFIX);
195
196             strcpy(str, FMT_PREFIX);
197
198             if (CLIPBOARD_GetFormatName(wFormat, str + plen, sizeof(str) - plen))
199                 prop = TSXInternAtom(thread_display(), str, False);
200
201             break;
202         }
203     }
204
205     if (prop == None)
206         TRACE("\tNo mapping to X property for Windows clipboard format %d(%s)\n",
207               wFormat, CLIPBOARD_GetFormatName(wFormat, NULL, 0));
208
209     return prop;
210 }
211
212 /**************************************************************************
213  *              X11DRV_CLIPBOARD_IsNativeProperty
214  *
215  *  Checks if a property is a native Wine property type
216  */
217 BOOL X11DRV_CLIPBOARD_IsNativeProperty(Atom prop)
218 {
219     char *itemFmtName = TSXGetAtomName(thread_display(), prop);
220     BOOL bRet = FALSE;
221
222     if ( 0 == strncmp(itemFmtName, FMT_PREFIX, strlen(FMT_PREFIX)) )
223         bRet = TRUE;
224
225     TSXFree(itemFmtName);
226     return bRet;
227 }
228
229
230 /**************************************************************************
231  *              X11DRV_CLIPBOARD_LaunchServer
232  * Launches the clipboard server. This is called from X11DRV_CLIPBOARD_ResetOwner
233  * when the selection can no longer be recyled to another top level window.
234  * In order to make the selection persist after Wine shuts down a server
235  * process is launched which services subsequent selection requests.
236  */
237 BOOL X11DRV_CLIPBOARD_LaunchServer()
238 {
239     int iWndsLocks;
240     char clearSelection[8] = "0";
241     int persistent_selection = 1;
242     HKEY hkey;
243     int fd[2], err;
244
245     /* If persistant selection has been disabled in the .winerc Clipboard section,
246      * don't launch the server
247      */
248     if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\Clipboard", &hkey))
249     {
250         char buffer[20];
251         DWORD type, count = sizeof(buffer);
252         if(!RegQueryValueExA(hkey, "PersistentSelection", 0, &type, buffer, &count))
253             persistent_selection = atoi(buffer);
254
255         /* Get the clear selection preference */
256         count = sizeof(clearSelection);
257         RegQueryValueExA(hkey, "ClearAllSelections", 0, &type, clearSelection, &count);
258         RegCloseKey(hkey);
259     }
260     if ( !persistent_selection )
261         return FALSE;
262
263     /*  Start up persistant WINE X clipboard server process which will
264      *  take ownership of the X selection and continue to service selection
265      *  requests from other apps.
266      */
267
268     if(pipe(fd) == -1) return FALSE;
269     fcntl(fd[1], F_SETFD, 1); /* set close on exec */
270
271     selectionWindow = selectionPrevWindow;
272     if ( !fork() )
273     {
274         /* NOTE: This code only executes in the context of the child process
275          * Do note make any Wine specific calls here.
276          */
277         int dbgClasses = 0;
278         char selMask[8], dbgClassMask[8];
279
280         close(fd[0]);
281         sprintf(selMask, "%d", selectionAcquired);
282
283         /* Build the debug class mask to pass to the server, by inheriting
284          * the settings for the clipboard debug channel.
285          */
286         dbgClasses |= FIXME_ON(clipboard) ? 1 : 0;
287         dbgClasses |= ERR_ON(clipboard) ? 2 : 0;
288         dbgClasses |= WARN_ON(clipboard) ? 4 : 0;
289         dbgClasses |= TRACE_ON(clipboard) ? 8 : 0;
290         sprintf(dbgClassMask, "%d", dbgClasses);
291
292         /* Exec the clipboard server passing it the selection and debug class masks */
293         execl( BINDIR "/wineclipsrv", "wineclipsrv",
294                selMask, dbgClassMask, clearSelection, NULL );
295         execlp( "wineclipsrv", "wineclipsrv", selMask, dbgClassMask, clearSelection, NULL );
296
297         /* Exec Failed! */
298         perror("Could not start Wine clipboard server");
299         write(fd[1], &err, sizeof(err));
300         _exit( 1 ); /* Exit the child process */
301     }
302     close(fd[1]);
303
304     if(read(fd[0], &err, sizeof(err)) > 0) { /* exec failed */
305         close(fd[0]);
306         return FALSE;
307     }
308     close(fd[0]);
309
310     /* Wait until the clipboard server acquires the selection.
311      * We must release the windows lock to enable Wine to process
312      * selection messages in response to the servers requests.
313      */
314
315     iWndsLocks = WIN_SuspendWndsLock();
316
317     /* We must wait until the server finishes acquiring the selection,
318      * before proceeding, otherwise the window which owns the selection
319      * will be destroyed prematurely!
320      * Create a non-signalled, auto-reset event which will be set by
321      * X11DRV_CLIPBOARD_ReleaseSelection, and wait until this gets
322      * signalled before proceeding.
323      */
324
325     if ( !(selectionClearEvent = CreateEventA(NULL, FALSE, FALSE, NULL)) )
326         ERR("Could not create wait object. Clipboard server won't start!\n");
327     else
328     {
329         /* Wait until we lose the selection, timing out after a minute */
330         DWORD start_time, timeout, elapsed, ret;
331
332         TRACE("Waiting for clipboard server to acquire selection\n");
333
334         timeout = 60000;
335         start_time = GetTickCount();
336         elapsed=0;
337         do
338         {
339             ret = MsgWaitForMultipleObjects( 1, &selectionClearEvent, FALSE, timeout - elapsed, QS_ALLINPUT );
340             if (ret != WAIT_OBJECT_0+1)
341                 break;
342             elapsed = GetTickCount() - start_time;
343             if (elapsed > timeout)
344                 break;
345         }
346         while (1);
347         if ( ret != WAIT_OBJECT_0 )
348             TRACE("Server could not acquire selection, or a timeout occurred!\n");
349         else
350             TRACE("Server successfully acquired selection\n");
351
352         /* Release the event */
353         CloseHandle(selectionClearEvent);
354         selectionClearEvent = 0;
355     }
356
357     WIN_RestoreWndsLock(iWndsLocks);
358
359     return TRUE;
360 }
361
362
363 /**************************************************************************
364  *              X11DRV_CLIPBOARD_CacheDataFormats
365  *
366  * Caches the list of data formats available from the current selection.
367  * This queries the selection owner for the TARGETS property and saves all
368  * reported property types.
369  */
370 int X11DRV_CLIPBOARD_CacheDataFormats( Atom SelectionName )
371 {
372     Display *display = thread_display();
373     HWND           hWnd = 0;
374     HWND           hWndClipWindow = GetOpenClipboardWindow();
375     XEvent         xe;
376     Atom           aTargets;
377     Atom           atype=AnyPropertyType;
378     int            aformat;
379     unsigned long  remain;
380     Atom*          targetList=NULL;
381     Window         w;
382     Window         ownerSelection = 0;
383     time_t         maxtm;
384
385     TRACE("enter\n");
386     /*
387      * Empty the clipboard cache
388      */
389     CLIPBOARD_EmptyCache(TRUE);
390
391     cSelectionTargets = 0;
392     selectionCacheSrc = SelectionName;
393
394     hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
395
396     ownerSelection = TSXGetSelectionOwner(display, SelectionName);
397     if ( !hWnd || (ownerSelection == None) )
398         return cSelectionTargets;
399
400     /*
401      * Query the selection owner for the TARGETS property
402      */
403     w = X11DRV_get_whole_window( GetAncestor(hWnd,GA_ROOT) );
404
405     aTargets = TSXInternAtom(display, "TARGETS", False);
406
407     TRACE("Requesting TARGETS selection for '%s' (owner=%08x)...\n",
408           TSXGetAtomName(display, selectionCacheSrc), (unsigned)ownerSelection );
409     wine_tsx11_lock();
410     XConvertSelection(display, selectionCacheSrc, aTargets,
411                     TSXInternAtom(display, "SELECTION_DATA", False),
412                     w, CurrentTime);
413
414     /*
415      * Wait until SelectionNotify is received
416      */
417     maxtm = time(NULL) + MAXSELECTIONNOTIFYWAIT; /* Timeout after a maximum wait */
418     while( maxtm - time(NULL) > 0 )
419     {
420        if( XCheckTypedWindowEvent(display, w, SelectionNotify, &xe) )
421            if( xe.xselection.selection == selectionCacheSrc )
422                break;
423     }
424     wine_tsx11_unlock();
425
426     /* Verify that the selection returned a valid TARGETS property */
427     if ( (xe.xselection.target != aTargets)
428           || (xe.xselection.property == None) )
429     {
430         TRACE("\tExit, could not retrieve TARGETS\n");
431         return cSelectionTargets;
432     }
433
434     /* Read the TARGETS property contents */
435     if(TSXGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
436                             0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat,
437                             &cSelectionTargets, &remain, (unsigned char**)&targetList) != Success)
438         TRACE("\tCouldn't read TARGETS property\n");
439     else
440     {
441        TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
442              TSXGetAtomName(display,atype),aformat,cSelectionTargets, remain);
443        /*
444         * The TARGETS property should have returned us a list of atoms
445         * corresponding to each selection target format supported.
446         */
447        if( (atype == XA_ATOM || atype == aTargets) && aformat == 32 )
448        {
449           int i;
450           LPWINE_CLIPFORMAT lpFormat;
451
452           /* Cache these formats in the clipboard cache */
453
454           for (i = 0; i < cSelectionTargets; i++)
455           {
456               char *itemFmtName = TSXGetAtomName(display, targetList[i]);
457               UINT wFormat = X11DRV_CLIPBOARD_MapPropertyToFormat(itemFmtName);
458
459               /*
460                * If the clipboard format maps to a Windows format, simply store
461                * the atom identifier and record its availablity status
462                * in the clipboard cache.
463                */
464               if (wFormat)
465               {
466                   lpFormat = CLIPBOARD_LookupFormat( wFormat );
467
468                   /* Don't replace if the property already cached is a native format,
469                    * or if a PIXMAP is being replaced by a BITMAP.
470                    */
471                   if (lpFormat->wDataPresent &&
472                         ( X11DRV_CLIPBOARD_IsNativeProperty(lpFormat->drvData)
473                           || (lpFormat->drvData == XA_PIXMAP && targetList[i] == XA_BITMAP) )
474                      )
475                   {
476                       TRACE("\tAtom# %d: '%s' --> FormatID(%d) %s (Skipped)\n",
477                             i, itemFmtName, wFormat, lpFormat->Name);
478                   }
479                   else
480                   {
481                       lpFormat->wDataPresent = 1;
482                       lpFormat->drvData = targetList[i];
483                       TRACE("\tAtom# %d: '%s' --> FormatID(%d) %s\n",
484                             i, itemFmtName, wFormat, lpFormat->Name);
485                   }
486               }
487
488               TSXFree(itemFmtName);
489           }
490        }
491
492        /* Free the list of targets */
493        TSXFree(targetList);
494     }
495
496     return cSelectionTargets;
497 }
498
499 /**************************************************************************
500  *              X11DRV_CLIPBOARD_ReadSelection
501  *  Reads the contents of the X selection property into the WINE clipboard cache
502  *  converting the selection into a format compatible with the windows clipboard
503  *  if possible.
504  *  This method is invoked only to read the contents of a the selection owned
505  *  by an external application. i.e. when we do not own the X selection.
506  */
507 static BOOL X11DRV_CLIPBOARD_ReadSelection(UINT wFormat, Window w, Atom prop, Atom reqType)
508 {
509     Display *display = thread_display();
510     Atom              atype=AnyPropertyType;
511     int               aformat;
512     unsigned long     total,nitems,remain,itemSize,val_cnt;
513     long              lRequestLength,bwc;
514     unsigned char*    val;
515     unsigned char*    buffer;
516     LPWINE_CLIPFORMAT lpFormat;
517     BOOL              bRet = FALSE;
518     HWND              hWndClipWindow = GetOpenClipboardWindow();
519
520
521     if(prop == None)
522         return bRet;
523
524     TRACE("Reading X selection...\n");
525
526     TRACE("\tretrieving property %s from window %ld into %s\n",
527           TSXGetAtomName(display,reqType), (long)w, TSXGetAtomName(display,prop) );
528
529     /*
530      * First request a zero length in order to figure out the request size.
531      */
532     if(TSXGetWindowProperty(display,w,prop,0,0,False, AnyPropertyType/*reqType*/,
533                             &atype, &aformat, &nitems, &itemSize, &val) != Success)
534     {
535         WARN("\tcouldn't get property size\n");
536         return bRet;
537     }
538
539     /* Free zero length return data if any */
540     if ( val )
541     {
542        TSXFree(val);
543        val = NULL;
544     }
545
546     TRACE("\tretrieving %ld bytes...\n", itemSize * aformat/8);
547     lRequestLength = (itemSize * aformat/8)/4  + 1;
548
549    bwc = aformat/8;
550    /* we want to read the property, but not it too large of chunks or
551       we could hang the cause problems. Lets go for 4k blocks */
552
553     if(TSXGetWindowProperty(display,w,prop,0,4096,False,
554                             AnyPropertyType/*reqType*/,
555                             &atype, &aformat, &nitems, &remain, &buffer)
556         != Success)
557     {
558         WARN("\tcouldn't read property\n");
559         return bRet;
560     }
561    val = (char*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
562                           nitems*bwc);
563    memcpy(val,buffer,nitems*bwc);
564    TSXFree(buffer);
565
566    for (total = nitems*bwc,val_cnt=0; remain;)
567    {
568        val_cnt +=nitems*bwc;
569        TSXGetWindowProperty(display, w, prop,
570                           (total / 4), 4096, False,
571                           AnyPropertyType, &atype,
572                           &aformat, &nitems, &remain,
573                           &buffer);
574
575        total += nitems*bwc;
576        HeapReAlloc(GetProcessHeap(),0,val, total);
577        memcpy(&val[val_cnt], buffer, nitems*(aformat/8));
578        TSXFree(buffer);
579    }
580    nitems = total;
581
582     /*
583      * Translate the X property into the appropriate Windows clipboard
584      * format, if possible.
585      */
586     if ( (reqType == XA_STRING)
587          && (atype == XA_STRING) && (aformat == 8) )
588     /* convert Unix text to CF_UNICODETEXT */
589     {
590       int          i,inlcount = 0;
591       char*      lpstr;
592
593       for(i=0; i <= nitems; i++)
594           if( val[i] == '\n' ) inlcount++;
595
596       if( (lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, nitems + inlcount + 1)) )
597       {
598           static UINT text_cp = (UINT)-1;
599           UINT count;
600           HANDLE hUnicodeText;
601
602           for(i=0,inlcount=0; i <= nitems; i++)
603           {
604              if( val[i] == '\n' ) lpstr[inlcount++]='\r';
605              lpstr[inlcount++]=val[i];
606           }
607
608           if(text_cp == (UINT)-1)
609           {
610               HKEY hkey;
611               /* default value */
612               text_cp = CP_ACP;
613               if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\x11drv", &hkey))
614               {
615                   char buf[20];
616                   DWORD type, count = sizeof(buf);
617                   if(!RegQueryValueExA(hkey, "TextCP", 0, &type, buf, &count))
618                       text_cp = atoi(buf);
619                   RegCloseKey(hkey);
620               }
621           }
622
623           count = MultiByteToWideChar(text_cp, 0, lpstr, -1, NULL, 0);
624           hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
625           if(hUnicodeText)
626           {
627               WCHAR *textW = GlobalLock(hUnicodeText);
628               MultiByteToWideChar(text_cp, 0, lpstr, -1, textW, count);
629               GlobalUnlock(hUnicodeText);
630               if (!SetClipboardData(CF_UNICODETEXT, hUnicodeText))
631               {
632                   ERR("Not SET! Need to free our own block\n");
633                   GlobalFree(hUnicodeText);
634               }
635               bRet = TRUE;
636           }
637           HeapFree(GetProcessHeap(), 0, lpstr);
638       }
639     }
640     else if ( reqType == XA_PIXMAP || reqType == XA_BITMAP ) /* treat PIXMAP as CF_DIB or CF_BITMAP */
641     {
642       /* Get the first pixmap handle passed to us */
643       Pixmap *pPixmap = (Pixmap *)val;
644       HANDLE hTargetImage = 0;  /* Handle to store the converted bitmap or DIB */
645
646       if (aformat != 32 || nitems < 1 || atype != XA_PIXMAP
647           || (wFormat != CF_BITMAP && wFormat != CF_DIB))
648       {
649           WARN("\tUnimplemented format conversion request\n");
650           goto END;
651       }
652
653       if ( wFormat == CF_BITMAP )
654       {
655         /* For CF_BITMAP requests we must return an HBITMAP */
656         hTargetImage = X11DRV_BITMAP_CreateBitmapFromPixmap(*pPixmap, TRUE);
657       }
658       else if (wFormat == CF_DIB)
659       {
660         HWND hwnd = GetOpenClipboardWindow();
661         HDC hdc = GetDC(hwnd);
662
663         /* For CF_DIB requests we must return an HGLOBAL storing a packed DIB */
664         hTargetImage = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc, TRUE);
665
666         ReleaseDC(hwnd, hdc);
667       }
668
669       if (!hTargetImage)
670       {
671           WARN("PIXMAP conversion failed!\n" );
672           goto END;
673       }
674
675       /* Delete previous clipboard data */
676       lpFormat = CLIPBOARD_LookupFormat(wFormat);
677       if (lpFormat->wDataPresent && (lpFormat->hData16 || lpFormat->hData32))
678           CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
679
680       /* Update the clipboard record */
681       lpFormat->wDataPresent = 1;
682       lpFormat->hData32 = hTargetImage;
683       lpFormat->hData16 = 0;
684
685       bRet = TRUE;
686     }
687
688     /* For native properties simply copy the X data without conversion */
689     else if (X11DRV_CLIPBOARD_IsNativeProperty(reqType)) /* <WCF>* */
690     {
691       HANDLE hClipData = 0;
692       void*  lpClipData;
693       int cBytes = nitems * aformat/8;
694
695       if( cBytes )
696       {
697           if (wFormat == CF_METAFILEPICT || wFormat == CF_ENHMETAFILE)
698           {
699               hClipData = X11DRV_CLIPBOARD_SerializeMetafile(wFormat, (HANDLE)val, cBytes, FALSE);
700           }
701           else
702           {
703               /* Turn on the DDESHARE flag to enable shared 32 bit memory */
704               hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cBytes );
705               if( (lpClipData = GlobalLock(hClipData)) )
706               {
707                   memcpy(lpClipData, val, cBytes);
708                   GlobalUnlock(hClipData);
709               }
710               else
711                   hClipData = 0;
712           }
713       }
714
715       if( hClipData )
716       {
717           /* delete previous clipboard record if any */
718           lpFormat = CLIPBOARD_LookupFormat(wFormat);
719           if (lpFormat->wDataPresent || lpFormat->hData16 || lpFormat->hData32)
720               CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
721
722           /* Update the clipboard record */
723           lpFormat->wDataPresent = 1;
724           lpFormat->hData32 = hClipData;
725           lpFormat->hData16 = 0;
726
727           bRet = TRUE;
728       }
729     }
730     else
731     {
732         WARN("\tUnimplemented format conversion request\n");
733         goto END;
734     }
735
736 END:
737     /* Delete the property on the window now that we are done
738      * This will send a PropertyNotify event to the selection owner. */
739     TSXDeleteProperty(display,w,prop);
740
741     /* Free the retrieved property data */
742     HeapFree(GetProcessHeap(),0,val);
743     return bRet;
744 }
745
746 /**************************************************************************
747  *              X11DRV_CLIPBOARD_ReleaseSelection
748  *
749  * Release an XA_PRIMARY or XA_CLIPBOARD selection that we own, in response
750  * to a SelectionClear event.
751  * This can occur in response to another client grabbing the X selection.
752  * If the XA_CLIPBOARD selection is lost, we relinquish XA_PRIMARY as well.
753  */
754 void X11DRV_CLIPBOARD_ReleaseSelection(Atom selType, Window w, HWND hwnd)
755 {
756     Display *display = thread_display();
757     Atom xaClipboard = TSXInternAtom(display, "CLIPBOARD", False);
758     int clearAllSelections = 0;
759     HKEY hkey;
760
761     if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\Clipboard", &hkey))
762     {
763         char buffer[20];
764         DWORD type, count = sizeof(buffer);
765         if(!RegQueryValueExA(hkey, "ClearAllSelections", 0, &type, buffer, &count))
766             clearAllSelections = atoi(buffer);
767         RegCloseKey(hkey);
768     }
769
770     /* w is the window that lost the selection
771      * selectionPrevWindow is nonzero if CheckSelection() was called.
772      */
773
774     TRACE("\tevent->window = %08x (sw = %08x, spw=%08x)\n",
775           (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionPrevWindow );
776
777     if( selectionAcquired )
778     {
779         if( w == selectionWindow || selectionPrevWindow == None)
780         {
781             /* If we're losing the CLIPBOARD selection, or if the preferences in .winerc
782              * dictate that *all* selections should be cleared on loss of a selection,
783              * we must give up all the selections we own.
784              */
785             if ( clearAllSelections || (selType == xaClipboard) )
786             {
787               /* completely give up the selection */
788               TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
789
790               /* We are completely giving up the selection.
791                * Make sure we can open the windows clipboard first. */
792
793               if ( !OpenClipboard(hwnd) )
794               {
795                   /*
796                    * We can't empty the clipboard if we cant open it so abandon.
797                    * Wine will think that it still owns the selection but this is
798                    * safer than losing the selection without properly emptying
799                    * the clipboard. Perhaps we should forcibly re-assert ownership
800                    * of the CLIPBOARD selection in this case...
801                    */
802                   ERR("\tClipboard is busy. Could not give up selection!\n");
803                   return;
804               }
805
806               /* We really lost CLIPBOARD but want to voluntarily lose PRIMARY */
807               if ( (selType == xaClipboard)
808                    && (selectionAcquired & S_PRIMARY) )
809               {
810                   XSetSelectionOwner(display, XA_PRIMARY, None, CurrentTime);
811               }
812
813               /* We really lost PRIMARY but want to voluntarily lose CLIPBOARD  */
814               if ( (selType == XA_PRIMARY)
815                    && (selectionAcquired & S_CLIPBOARD) )
816               {
817                   XSetSelectionOwner(display, xaClipboard, None, CurrentTime);
818               }
819
820               selectionWindow = None;
821               PrimarySelectionOwner = ClipboardSelectionOwner = 0;
822
823               /* Empty the windows clipboard.
824                * We should pretend that we still own the selection BEFORE calling
825                * EmptyClipboard() since otherwise this has the side effect of
826                * triggering X11DRV_CLIPBOARD_Acquire() and causing the X selection
827                * to be re-acquired by us!
828                */
829               selectionAcquired = (S_PRIMARY | S_CLIPBOARD);
830               EmptyClipboard();
831               CloseClipboard();
832
833               /* Give up ownership of the windows clipboard */
834               CLIPBOARD_ReleaseOwner();
835
836               /* Reset the selection flags now that we are done */
837               selectionAcquired = S_NOSELECTION;
838             }
839             else if ( selType == XA_PRIMARY ) /* Give up only PRIMARY selection */
840             {
841                 TRACE("Lost PRIMARY selection\n");
842                 PrimarySelectionOwner = 0;
843                 selectionAcquired &= ~S_PRIMARY;  /* clear S_PRIMARY mask */
844             }
845
846             cSelectionTargets = 0;
847         }
848         /* but we'll keep existing data for internal use */
849         else if( w == selectionPrevWindow )
850         {
851             Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
852
853             w = TSXGetSelectionOwner(display, XA_PRIMARY);
854             if( w == None )
855                 TSXSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
856
857             w = TSXGetSelectionOwner(display, xaClipboard);
858             if( w == None )
859                 TSXSetSelectionOwner(display, xaClipboard, selectionWindow, CurrentTime);
860         }
861     }
862
863     /* Signal to a selectionClearEvent listener if the selection is completely lost */
864     if (selectionClearEvent && !selectionAcquired)
865     {
866         TRACE("Lost all selections, signalling to selectionClearEvent listener\n");
867         SetEvent(selectionClearEvent);
868     }
869
870     selectionPrevWindow = None;
871 }
872
873 /**************************************************************************
874  *              ReleaseClipboard (X11DRV.@)
875  *  Voluntarily release all currently owned X selections
876  */
877 void X11DRV_ReleaseClipboard(void)
878 {
879     Display *display = thread_display();
880     if( selectionAcquired )
881     {
882         XEvent xe;
883         Window savePrevWindow = selectionWindow;
884         Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
885         BOOL bHasPrimarySelection = selectionAcquired & S_PRIMARY;
886
887         selectionAcquired   = S_NOSELECTION;
888         selectionPrevWindow = selectionWindow;
889         selectionWindow     = None;
890
891         TRACE("\tgiving up selection (spw = %08x)\n",
892              (unsigned)selectionPrevWindow);
893
894         wine_tsx11_lock();
895
896         TRACE("Releasing CLIPBOARD selection\n");
897         XSetSelectionOwner(display, xaClipboard, None, CurrentTime);
898         if( selectionPrevWindow )
899             while( !XCheckTypedWindowEvent( display, selectionPrevWindow,
900                                             SelectionClear, &xe ) );
901
902         if ( bHasPrimarySelection )
903         {
904             TRACE("Releasing XA_PRIMARY selection\n");
905             selectionPrevWindow = savePrevWindow; /* May be cleared in X11DRV_CLIPBOARD_ReleaseSelection */
906             XSetSelectionOwner(display, XA_PRIMARY, None, CurrentTime);
907
908             if( selectionPrevWindow )
909                 while( !XCheckTypedWindowEvent( display, selectionPrevWindow,
910                                                 SelectionClear, &xe ) );
911         }
912         wine_tsx11_unlock();
913     }
914
915     /* Get rid of any Pixmap resources we may still have */
916     while (prop_head)
917     {
918         PROPERTY *prop = prop_head;
919         prop_head = prop->next;
920         XFreePixmap( gdi_display, prop->pixmap );
921         HeapFree( GetProcessHeap(), 0, prop );
922     }
923 }
924
925 /**************************************************************************
926  *              AcquireClipboard (X11DRV.@)
927  */
928 void X11DRV_AcquireClipboard(void)
929 {
930     Display *display = thread_display();
931     Window       owner;
932     HWND         hWndClipWindow = GetOpenClipboardWindow();
933
934     /*
935      * Acquire X selection if we don't already own it.
936      * Note that we only acquire the selection if it hasn't been already
937      * acquired by us, and ignore the fact that another X window may be
938      * asserting ownership. The reason for this is we need *any* top level
939      * X window to hold selection ownership. The actual clipboard data requests
940      * are made via GetClipboardData from EVENT_SelectionRequest and this
941      * ensures that the real HWND owner services the request.
942      * If the owning X window gets destroyed the selection ownership is
943      * re-cycled to another top level X window in X11DRV_CLIPBOARD_ResetOwner.
944      *
945      */
946
947     if ( !(selectionAcquired == (S_PRIMARY | S_CLIPBOARD)) )
948     {
949         Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
950         owner = X11DRV_get_whole_window( GetAncestor( hWndClipWindow, GA_ROOT ) );
951
952         /* Grab PRIMARY selection if not owned */
953         if ( !(selectionAcquired & S_PRIMARY) )
954             TSXSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
955
956         /* Grab CLIPBOARD selection if not owned */
957         if ( !(selectionAcquired & S_CLIPBOARD) )
958             TSXSetSelectionOwner(display, xaClipboard, owner, CurrentTime);
959
960         if( TSXGetSelectionOwner(display,XA_PRIMARY) == owner )
961             selectionAcquired |= S_PRIMARY;
962
963         if( TSXGetSelectionOwner(display,xaClipboard) == owner)
964             selectionAcquired |= S_CLIPBOARD;
965
966         if (selectionAcquired)
967         {
968             selectionWindow = owner;
969             TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
970         }
971     }
972 }
973
974 /**************************************************************************
975  *              IsClipboardFormatAvailable (X11DRV.@)
976  *
977  * Checks if the specified format is available in the current selection
978  * Only invoked when WINE is not the selection owner
979  */
980 BOOL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
981 {
982     Display *display = thread_display();
983     Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
984     Window ownerPrimary = TSXGetSelectionOwner(display,XA_PRIMARY);
985     Window ownerClipboard = TSXGetSelectionOwner(display,xaClipboard);
986
987     TRACE("enter for %d\n", wFormat);
988
989     /*
990      * If the selection has not been previously cached, or the selection has changed,
991      * try and cache the list of available selection targets from the current selection.
992      */
993     if ( !cSelectionTargets || (PrimarySelectionOwner != ownerPrimary)
994                          || (ClipboardSelectionOwner != ownerClipboard) )
995     {
996         /*
997          * First try caching the CLIPBOARD selection.
998          * If unavailable try PRIMARY.
999          */
1000         if ( X11DRV_CLIPBOARD_CacheDataFormats(xaClipboard) == 0 )
1001         {
1002             X11DRV_CLIPBOARD_CacheDataFormats(XA_PRIMARY);
1003         }
1004
1005         ClipboardSelectionOwner = ownerClipboard;
1006         PrimarySelectionOwner = ownerPrimary;
1007     }
1008
1009     /* Exit if there is no selection */
1010     if ( !ownerClipboard && !ownerPrimary )
1011     {
1012         TRACE("There is no selection owner\n");
1013         return FALSE;
1014     }
1015
1016     /* Check if the format is available in the clipboard cache */
1017     if ( CLIPBOARD_IsPresent(wFormat) )
1018         return TRUE;
1019
1020     /*
1021      * Many X client apps (such as XTerminal) don't support being queried
1022      * for the "TARGETS" target atom. To handle such clients we must actually
1023      * try to convert the selection to the requested type.
1024      */
1025     if ( !cSelectionTargets )
1026         return X11DRV_GetClipboardData( wFormat );
1027
1028     TRACE("There is no selection\n");
1029     return FALSE;
1030 }
1031
1032 /**************************************************************************
1033  *              RegisterClipboardFormat (X11DRV.@)
1034  *
1035  * Registers a custom X clipboard format
1036  * Returns: Format id or 0 on failure
1037  */
1038 INT X11DRV_RegisterClipboardFormat( LPCSTR FormatName )
1039 {
1040     Display *display = thread_display();
1041     Atom prop = None;
1042     char str[256];
1043
1044     /*
1045      * If an X atom is registered for this format, return that
1046      * Otherwise register a new atom.
1047      */
1048     if (FormatName)
1049     {
1050         /* Add a WINE specific prefix to the format */
1051         strcpy(str, FMT_PREFIX);
1052         strncat(str, FormatName, sizeof(str) - strlen(FMT_PREFIX));
1053         prop = TSXInternAtom(display, str, False);
1054     }
1055
1056     return prop;
1057 }
1058
1059 /**************************************************************************
1060  *              IsSelectionOwner (X11DRV.@)
1061  *
1062  * Returns: TRUE - We(WINE) own the selection, FALSE - Selection not owned by us
1063  */
1064 BOOL X11DRV_IsSelectionOwner(void)
1065 {
1066     return selectionAcquired;
1067 }
1068
1069 /**************************************************************************
1070  *              SetClipboardData (X11DRV.@)
1071  *
1072  * We don't need to do anything special here since the clipboard code
1073  * maintains the cache.
1074  *
1075  */
1076 void X11DRV_SetClipboardData(UINT wFormat)
1077 {
1078     /* Make sure we have acquired the X selection */
1079     X11DRV_AcquireClipboard();
1080 }
1081
1082 /**************************************************************************
1083  *              GetClipboardData (X11DRV.@)
1084  *
1085  * This method is invoked only when we DO NOT own the X selection
1086  *
1087  * NOTE: Clipboard driver get requests only for CF_UNICODETEXT data.
1088  * We always get the data from the selection client each time,
1089  * since we have no way of determining if the data in our cache is stale.
1090  */
1091 BOOL X11DRV_GetClipboardData(UINT wFormat)
1092 {
1093     Display *display = thread_display();
1094     BOOL bRet = selectionAcquired;
1095     HWND hWndClipWindow = GetOpenClipboardWindow();
1096     HWND hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
1097     LPWINE_CLIPFORMAT lpFormat;
1098
1099     TRACE("%d\n", wFormat);
1100
1101     if (!selectionAcquired)
1102     {
1103         XEvent xe;
1104         Atom propRequest;
1105         Window w = X11DRV_get_whole_window( GetAncestor( hWnd, GA_ROOT ));
1106         if(!w)
1107         {
1108             FIXME("No parent win found %x %x\n", hWnd, hWndClipWindow);
1109             return FALSE;
1110         }
1111
1112         /* Map the format ID requested to an X selection property.
1113          * If the format is in the cache, use the atom associated
1114          * with it.
1115          */
1116
1117         lpFormat = CLIPBOARD_LookupFormat( wFormat );
1118         if (lpFormat && lpFormat->wDataPresent && lpFormat->drvData)
1119             propRequest = (Atom)lpFormat->drvData;
1120         else
1121             propRequest = X11DRV_CLIPBOARD_MapFormatToProperty(wFormat);
1122
1123         if (propRequest)
1124         {
1125             TRACE("Requesting %s selection from %s...\n",
1126                   TSXGetAtomName(display, propRequest),
1127                   TSXGetAtomName(display, selectionCacheSrc) );
1128             wine_tsx11_lock();
1129             XConvertSelection(display, selectionCacheSrc, propRequest,
1130                             TSXInternAtom(display, "SELECTION_DATA", False),
1131                             w, CurrentTime);
1132
1133             /* wait until SelectionNotify is received */
1134
1135             while( TRUE )
1136             {
1137                if( XCheckTypedWindowEvent(display, w, SelectionNotify, &xe) )
1138                    if( xe.xselection.selection == selectionCacheSrc )
1139                        break;
1140             }
1141             wine_tsx11_unlock();
1142
1143             /*
1144              *  Read the contents of the X selection property into WINE's
1145              *  clipboard cache converting the selection to be compatible if possible.
1146              */
1147             bRet = X11DRV_CLIPBOARD_ReadSelection( wFormat,
1148                                                    xe.xselection.requestor,
1149                                                    xe.xselection.property,
1150                                                    xe.xselection.target);
1151         }
1152         else
1153             bRet = FALSE;
1154
1155         TRACE("\tpresent %s = %i\n", CLIPBOARD_GetFormatName(wFormat, NULL, 0), bRet );
1156     }
1157
1158     TRACE("Returning %d\n", bRet);
1159
1160     return bRet;
1161 }
1162
1163 /**************************************************************************
1164  *              ResetSelectionOwner (X11DRV.@)
1165  *
1166  * Called from DestroyWindow() to prevent X selection from being lost when
1167  * a top level window is destroyed, by switching ownership to another top
1168  * level window.
1169  * Any top level window can own the selection. See X11DRV_CLIPBOARD_Acquire
1170  * for a more detailed description of this.
1171  */
1172 void X11DRV_ResetSelectionOwner(HWND hwnd, BOOL bFooBar)
1173 {
1174     Display *display = thread_display();
1175     HWND hWndClipOwner = 0;
1176     HWND tmp;
1177     Window XWnd = X11DRV_get_whole_window(hwnd);
1178     Atom xaClipboard;
1179     BOOL bLostSelection = FALSE;
1180
1181     /* There is nothing to do if we don't own the selection,
1182      * or if the X window which currently owns the selecion is different
1183      * from the one passed in.
1184      */
1185     if ( !selectionAcquired || XWnd != selectionWindow
1186          || selectionWindow == None )
1187        return;
1188
1189     if ( (bFooBar && XWnd) || (!bFooBar && !XWnd) )
1190        return;
1191
1192     hWndClipOwner = GetClipboardOwner();
1193     xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
1194
1195     TRACE("clipboard owner = %04x, selection window = %08x\n",
1196           hWndClipOwner, (unsigned)selectionWindow);
1197
1198     /* now try to salvage current selection from being destroyed by X */
1199
1200     TRACE("\tchecking %08x\n", (unsigned) XWnd);
1201
1202     selectionPrevWindow = selectionWindow;
1203     selectionWindow = None;
1204
1205     if (!(tmp = GetWindow( hwnd, GW_HWNDNEXT ))) tmp = GetWindow( hwnd, GW_HWNDFIRST );
1206     if (tmp && tmp != hwnd) selectionWindow = X11DRV_get_whole_window(tmp);
1207
1208     if( selectionWindow != None )
1209     {
1210         /* We must pretend that we don't own the selection while making the switch
1211          * since a SelectionClear event will be sent to the last owner.
1212          * If there is no owner X11DRV_CLIPBOARD_ReleaseSelection will do nothing.
1213          */
1214         int saveSelectionState = selectionAcquired;
1215         selectionAcquired = False;
1216
1217         TRACE("\tswitching selection from %08x to %08x\n",
1218                     (unsigned)selectionPrevWindow, (unsigned)selectionWindow);
1219
1220         /* Assume ownership for the PRIMARY and CLIPBOARD selection */
1221         if ( saveSelectionState & S_PRIMARY )
1222             TSXSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
1223
1224         TSXSetSelectionOwner(display, xaClipboard, selectionWindow, CurrentTime);
1225
1226         /* Restore the selection masks */
1227         selectionAcquired = saveSelectionState;
1228
1229         /* Lose the selection if something went wrong */
1230         if ( ( (saveSelectionState & S_PRIMARY) &&
1231                (TSXGetSelectionOwner(display, XA_PRIMARY) != selectionWindow) )
1232              || (TSXGetSelectionOwner(display, xaClipboard) != selectionWindow) )
1233         {
1234             bLostSelection = TRUE;
1235             goto END;
1236         }
1237         else
1238         {
1239             /* Update selection state */
1240             if (saveSelectionState & S_PRIMARY)
1241                PrimarySelectionOwner = selectionWindow;
1242
1243             ClipboardSelectionOwner = selectionWindow;
1244         }
1245     }
1246     else
1247     {
1248         bLostSelection = TRUE;
1249         goto END;
1250     }
1251
1252 END:
1253     if (bLostSelection)
1254     {
1255       /* Launch the clipboard server if the selection can no longer be recyled
1256        * to another top level window. */
1257
1258       if ( !X11DRV_CLIPBOARD_LaunchServer() )
1259       {
1260          /* Empty the windows clipboard if the server was not launched.
1261           * We should pretend that we still own the selection BEFORE calling
1262           * EmptyClipboard() since otherwise this has the side effect of
1263           * triggering X11DRV_CLIPBOARD_Acquire() and causing the X selection
1264           * to be re-acquired by us!
1265           */
1266
1267          TRACE("\tLost the selection! Emptying the clipboard...\n");
1268
1269          OpenClipboard( 0 );
1270          selectionAcquired = (S_PRIMARY | S_CLIPBOARD);
1271          EmptyClipboard();
1272
1273          CloseClipboard();
1274
1275          /* Give up ownership of the windows clipboard */
1276          CLIPBOARD_ReleaseOwner();
1277       }
1278
1279       selectionAcquired = S_NOSELECTION;
1280       ClipboardSelectionOwner = PrimarySelectionOwner = 0;
1281       selectionWindow = 0;
1282     }
1283 }
1284
1285 /**************************************************************************
1286  *              X11DRV_CLIPBOARD_RegisterPixmapResource
1287  * Registers a Pixmap resource which is to be associated with a property Atom.
1288  * When the property is destroyed we also destroy the Pixmap through the
1289  * PropertyNotify event.
1290  */
1291 BOOL X11DRV_CLIPBOARD_RegisterPixmapResource( Atom property, Pixmap pixmap )
1292 {
1293     PROPERTY *prop = HeapAlloc( GetProcessHeap(), 0, sizeof(*prop) );
1294     if (!prop) return FALSE;
1295     prop->atom = property;
1296     prop->pixmap = pixmap;
1297     prop->next = prop_head;
1298     prop_head = prop;
1299     return TRUE;
1300 }
1301
1302 /**************************************************************************
1303  *              X11DRV_CLIPBOARD_FreeResources
1304  *
1305  * Called from EVENT_PropertyNotify() to give us a chance to destroy
1306  * any resources associated with this property.
1307  */
1308 void X11DRV_CLIPBOARD_FreeResources( Atom property )
1309 {
1310     /* Do a simple linear search to see if we have a Pixmap resource
1311      * associated with this property and release it.
1312      */
1313     PROPERTY **prop = &prop_head;
1314
1315     while (*prop)
1316     {
1317         if ((*prop)->atom == property)
1318         {
1319             PROPERTY *next = (*prop)->next;
1320             XFreePixmap( gdi_display, (*prop)->pixmap );
1321             HeapFree( GetProcessHeap(), 0, *prop );
1322             *prop = next;
1323         }
1324         else prop = &(*prop)->next;
1325     }
1326 }
1327
1328 /**************************************************************************
1329  *              X11DRV_GetClipboardFormatName
1330  */
1331 BOOL X11DRV_GetClipboardFormatName( UINT wFormat, LPSTR retStr, UINT maxlen )
1332 {
1333     BOOL bRet = FALSE;
1334     char *itemFmtName = TSXGetAtomName(thread_display(), wFormat);
1335     INT prefixlen = strlen(FMT_PREFIX);
1336
1337     if ( 0 == strncmp(itemFmtName, FMT_PREFIX, prefixlen ) )
1338     {
1339         strncpy(retStr, itemFmtName + prefixlen, maxlen);
1340         bRet = TRUE;
1341     }
1342
1343     TSXFree(itemFmtName);
1344
1345     return bRet;
1346 }
1347
1348
1349 /**************************************************************************
1350  *              CLIPBOARD_SerializeMetafile
1351  */
1352 HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, INT cbytes, BOOL out)
1353 {
1354     HANDLE h = 0;
1355
1356     if (out) /* Serialize out, caller should free memory */
1357     {
1358         if (wformat == CF_METAFILEPICT)
1359         {
1360             LPMETAFILEPICT lpmfp = (LPMETAFILEPICT) GlobalLock(hdata);
1361             int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
1362
1363             h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
1364             if (h)
1365             {
1366                 LPVOID pdata = GlobalLock(h);
1367
1368                 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
1369                 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
1370
1371                 GlobalUnlock(h);
1372             }
1373
1374             GlobalUnlock(hdata);
1375         }
1376         else if (wformat == CF_ENHMETAFILE)
1377         {
1378             int size = GetEnhMetaFileBits(hdata, 0, NULL);
1379
1380             h = GlobalAlloc(0, size);
1381             if (h)
1382             {
1383                 LPVOID pdata = GlobalLock(h);
1384                 GetEnhMetaFileBits(hdata, size, pdata);
1385                 GlobalUnlock(h);
1386             }
1387         }
1388     }
1389     else
1390     {
1391         if (wformat == CF_METAFILEPICT)
1392         {
1393             h = GlobalAlloc(0, sizeof(METAFILEPICT));
1394             if (h)
1395             {
1396                 LPMETAFILEPICT pmfp = (LPMETAFILEPICT) GlobalLock(h);
1397
1398                 memcpy(pmfp, (LPVOID)hdata, sizeof(METAFILEPICT));
1399                 pmfp->hMF = SetMetaFileBitsEx(cbytes - sizeof(METAFILEPICT),
1400                                               (LPVOID)hdata + sizeof(METAFILEPICT));
1401
1402                 GlobalUnlock(h);
1403             }
1404         }
1405         else if (wformat == CF_ENHMETAFILE)
1406         {
1407             h = SetEnhMetaFileBits(cbytes, (LPVOID)hdata);
1408         }
1409     }
1410
1411     return h;
1412 }