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