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