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