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