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