2 * X11 clipboard windows driver
4 * Copyright 1994 Martin Ayotte
9 * This file contains the X specific implementation for the windows
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)
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).
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
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.
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.
58 #include "clipboard.h"
61 #include "debugtools.h"
63 DEFAULT_DEBUG_CHANNEL(clipboard);
67 #define S_NOSELECTION 0
71 /* X selection context info */
73 static char _CLIPBOARD[] = "CLIPBOARD"; /* CLIPBOARD atom name */
74 static char FMT_PREFIX[] = "<WCF>"; /* Prefix for windows specific formats */
75 static int selectionAcquired = 0; /* Contains the current selection masks */
76 static Window selectionWindow = None; /* The top level X window which owns the selection */
77 static Window selectionPrevWindow = None; /* The last X window that owned the selection */
78 static Window PrimarySelectionOwner = None; /* The window which owns the primary selection */
79 static Window ClipboardSelectionOwner = None; /* The window which owns the clipboard selection */
80 static unsigned long cSelectionTargets = 0; /* Number of target formats reported by TARGETS selection */
81 static Atom selectionCacheSrc = XA_PRIMARY; /* The selection source from which the clipboard cache was filled */
82 static HANDLE selectionClearEvent = 0;/* Synchronization object used to block until server is started */
84 typedef struct tagPROPERTY
86 struct tagPROPERTY *next;
91 static PROPERTY *prop_head;
94 /**************************************************************************
95 * X11DRV_CLIPBOARD_MapPropertyToFormat
97 * Map an X selection property type atom name to a windows clipboard format ID
99 UINT X11DRV_CLIPBOARD_MapPropertyToFormat(char *itemFmtName)
102 * If the property name starts with FMT_PREFIX strip this off and
103 * get the ID for a custom Windows registered format with this name.
104 * We can also understand STRING, PIXMAP and BITMAP.
106 if ( NULL == itemFmtName )
108 else if ( 0 == strncmp(itemFmtName, FMT_PREFIX, strlen(FMT_PREFIX)) )
109 return RegisterClipboardFormatA(itemFmtName + strlen(FMT_PREFIX));
110 else if ( 0 == strcmp(itemFmtName, "STRING") )
111 return CF_UNICODETEXT;
112 else if ( 0 == strcmp(itemFmtName, "PIXMAP")
113 || 0 == strcmp(itemFmtName, "BITMAP") )
116 * Return CF_DIB as first preference, if WINE is the selection owner
117 * and if CF_DIB exists in the cache.
118 * If wine dowsn't own the selection we always return CF_DIB
120 if ( !X11DRV_IsSelectionOwner() )
122 else if ( CLIPBOARD_IsPresent(CF_DIB) )
128 WARN("\tNo mapping to Windows clipboard format for property %s\n", itemFmtName);
132 /**************************************************************************
133 * X11DRV_CLIPBOARD_MapFormatToProperty
135 * Map a windows clipboard format ID to an X selection property atom
137 Atom X11DRV_CLIPBOARD_MapFormatToProperty(UINT wFormat)
143 /* We support only CF_UNICODETEXT, other formats are synthesized */
156 * Request a PIXMAP, only if WINE is NOT the selection owner,
157 * AND the requested format is not in the cache.
159 if ( !X11DRV_IsSelectionOwner() && !CLIPBOARD_IsPresent(wFormat) )
164 /* Fall through to the default case in order to use the native format */
170 * If an X atom is registered for this format, return that
171 * Otherwise register a new atom.
174 char *fmtName = CLIPBOARD_GetFormatName(wFormat);
175 strcpy(str, FMT_PREFIX);
179 strncat(str, fmtName, sizeof(str) - strlen(FMT_PREFIX));
180 prop = TSXInternAtom(thread_display(), str, False);
187 TRACE("\tNo mapping to X property for Windows clipboard format %d(%s)\n",
188 wFormat, CLIPBOARD_GetFormatName(wFormat));
193 /**************************************************************************
194 * X11DRV_CLIPBOARD_IsNativeProperty
196 * Checks if a property is a native Wine property type
198 BOOL X11DRV_CLIPBOARD_IsNativeProperty(Atom prop)
200 char *itemFmtName = TSXGetAtomName(thread_display(), prop);
203 if ( 0 == strncmp(itemFmtName, FMT_PREFIX, strlen(FMT_PREFIX)) )
206 TSXFree(itemFmtName);
211 /**************************************************************************
212 * X11DRV_CLIPBOARD_LaunchServer
213 * Launches the clipboard server. This is called from X11DRV_CLIPBOARD_ResetOwner
214 * when the selection can no longer be recyled to another top level window.
215 * In order to make the selection persist after Wine shuts down a server
216 * process is launched which services subsequent selection requests.
218 BOOL X11DRV_CLIPBOARD_LaunchServer()
221 char clearSelection[8] = "0";
222 int persistent_selection = 1;
225 /* If persistant selection has been disabled in the .winerc Clipboard section,
226 * don't launch the server
228 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\Clipboard", &hkey))
231 DWORD type, count = sizeof(buffer);
232 if(!RegQueryValueExA(hkey, "PersistentSelection", 0, &type, buffer, &count))
233 persistent_selection = atoi(buffer);
235 /* Get the clear selection preference */
236 count = sizeof(clearSelection);
237 RegQueryValueExA(hkey, "ClearAllSelections", 0, &type, clearSelection, &count);
240 if ( !persistent_selection )
243 /* Start up persistant WINE X clipboard server process which will
244 * take ownership of the X selection and continue to service selection
245 * requests from other apps.
247 selectionWindow = selectionPrevWindow;
250 /* NOTE: This code only executes in the context of the child process
251 * Do note make any Wine specific calls here.
254 char selMask[8], dbgClassMask[8];
256 sprintf(selMask, "%d", selectionAcquired);
258 /* Build the debug class mask to pass to the server, by inheriting
259 * the settings for the clipboard debug channel.
261 dbgClasses |= FIXME_ON(clipboard) ? 1 : 0;
262 dbgClasses |= ERR_ON(clipboard) ? 2 : 0;
263 dbgClasses |= WARN_ON(clipboard) ? 4 : 0;
264 dbgClasses |= TRACE_ON(clipboard) ? 8 : 0;
265 sprintf(dbgClassMask, "%d", dbgClasses);
267 /* Exec the clipboard server passing it the selection and debug class masks */
268 execl( BINDIR "/wineclipsrv", "wineclipsrv",
269 selMask, dbgClassMask, clearSelection, NULL );
270 execlp( "wineclipsrv", "wineclipsrv", selMask, dbgClassMask, clearSelection, NULL );
271 execl( "./windows/x11drv/wineclipsrv", "wineclipsrv",
272 selMask, dbgClassMask, clearSelection, NULL );
275 perror("Could not start Wine clipboard server");
276 exit( 1 ); /* Exit the child process */
279 /* Wait until the clipboard server acquires the selection.
280 * We must release the windows lock to enable Wine to process
281 * selection messages in response to the servers requests.
284 iWndsLocks = WIN_SuspendWndsLock();
286 /* We must wait until the server finishes acquiring the selection,
287 * before proceeding, otherwise the window which owns the selection
288 * will be destroyed prematurely!
289 * Create a non-signalled, auto-reset event which will be set by
290 * X11DRV_CLIPBOARD_ReleaseSelection, and wait until this gets
291 * signalled before proceeding.
294 if ( !(selectionClearEvent = CreateEventA(NULL, FALSE, FALSE, NULL)) )
295 ERR("Could not create wait object. Clipboard server won't start!\n");
298 /* Wait until we lose the selection, timing out after a minute */
299 DWORD start_time, timeout, elapsed, ret;
301 TRACE("Waiting for clipboard server to acquire selection\n");
304 start_time = GetTickCount();
308 ret = MsgWaitForMultipleObjects( 1, &selectionClearEvent, FALSE, timeout - elapsed, QS_ALLINPUT );
309 if (ret != WAIT_OBJECT_0+1)
311 elapsed = GetTickCount() - start_time;
312 if (elapsed > timeout)
316 if ( ret != WAIT_OBJECT_0 )
317 TRACE("Server could not acquire selection, or a timeout occurred!\n");
319 TRACE("Server successfully acquired selection\n");
321 /* Release the event */
322 CloseHandle(selectionClearEvent);
323 selectionClearEvent = 0;
326 WIN_RestoreWndsLock(iWndsLocks);
332 /**************************************************************************
333 * X11DRV_CLIPBOARD_CacheDataFormats
335 * Caches the list of data formats available from the current selection.
336 * This queries the selection owner for the TARGETS property and saves all
337 * reported property types.
339 int X11DRV_CLIPBOARD_CacheDataFormats( Atom SelectionName )
341 Display *display = thread_display();
343 HWND hWndClipWindow = GetOpenClipboardWindow();
346 Atom atype=AnyPropertyType;
348 unsigned long remain;
349 Atom* targetList=NULL;
351 Window ownerSelection = 0;
355 * Empty the clipboard cache
357 CLIPBOARD_EmptyCache(TRUE);
359 cSelectionTargets = 0;
360 selectionCacheSrc = SelectionName;
362 hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
364 ownerSelection = TSXGetSelectionOwner(display, SelectionName);
365 if ( !hWnd || (ownerSelection == None) )
366 return cSelectionTargets;
369 * Query the selection owner for the TARGETS property
371 w = X11DRV_get_whole_window( GetAncestor(hWnd,GA_ROOT) );
373 aTargets = TSXInternAtom(display, "TARGETS", False);
375 TRACE("Requesting TARGETS selection for '%s' (owner=%08x)...\n",
376 TSXGetAtomName(display, selectionCacheSrc), (unsigned)ownerSelection );
378 XConvertSelection(display, selectionCacheSrc, aTargets,
379 TSXInternAtom(display, "SELECTION_DATA", False),
383 * Wait until SelectionNotify is received
387 if( XCheckTypedWindowEvent(display, w, SelectionNotify, &xe) )
388 if( xe.xselection.selection == selectionCacheSrc )
393 /* Verify that the selection returned a valid TARGETS property */
394 if ( (xe.xselection.target != aTargets)
395 || (xe.xselection.property == None) )
397 TRACE("\tExit, could not retrieve TARGETS\n");
398 return cSelectionTargets;
401 /* Read the TARGETS property contents */
402 if(TSXGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
403 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat,
404 &cSelectionTargets, &remain, (unsigned char**)&targetList) != Success)
405 TRACE("\tCouldn't read TARGETS property\n");
408 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
409 TSXGetAtomName(display,atype),aformat,cSelectionTargets, remain);
411 * The TARGETS property should have returned us a list of atoms
412 * corresponding to each selection target format supported.
414 if( (atype == XA_ATOM || atype == aTargets) && aformat == 32 )
417 LPWINE_CLIPFORMAT lpFormat;
419 /* Cache these formats in the clipboard cache */
421 for (i = 0; i < cSelectionTargets; i++)
423 char *itemFmtName = TSXGetAtomName(display, targetList[i]);
424 UINT wFormat = X11DRV_CLIPBOARD_MapPropertyToFormat(itemFmtName);
427 * If the clipboard format maps to a Windows format, simply store
428 * the atom identifier and record its availablity status
429 * in the clipboard cache.
433 lpFormat = CLIPBOARD_LookupFormat( wFormat );
435 /* Don't replace if the property already cached is a native format,
436 * or if a PIXMAP is being replaced by a BITMAP.
438 if (lpFormat->wDataPresent &&
439 ( X11DRV_CLIPBOARD_IsNativeProperty(lpFormat->drvData)
440 || (lpFormat->drvData == XA_PIXMAP && targetList[i] == XA_BITMAP) )
443 TRACE("\tAtom# %d: '%s' --> FormatID(%d) %s (Skipped)\n",
444 i, itemFmtName, wFormat, lpFormat->Name);
448 lpFormat->wDataPresent = 1;
449 lpFormat->drvData = targetList[i];
450 TRACE("\tAtom# %d: '%s' --> FormatID(%d) %s\n",
451 i, itemFmtName, wFormat, lpFormat->Name);
455 TSXFree(itemFmtName);
459 /* Free the list of targets */
463 return cSelectionTargets;
466 /**************************************************************************
467 * X11DRV_CLIPBOARD_ReadSelection
468 * Reads the contents of the X selection property into the WINE clipboard cache
469 * converting the selection into a format compatible with the windows clipboard
471 * This method is invoked only to read the contents of a the selection owned
472 * by an external application. i.e. when we do not own the X selection.
474 static BOOL X11DRV_CLIPBOARD_ReadSelection(UINT wFormat, Window w, Atom prop, Atom reqType)
476 Display *display = thread_display();
477 Atom atype=AnyPropertyType;
479 unsigned long total,nitems,remain,itemSize,val_cnt;
480 long lRequestLength,bwc;
482 unsigned char* buffer;
483 LPWINE_CLIPFORMAT lpFormat;
485 HWND hWndClipWindow = GetOpenClipboardWindow();
491 TRACE("Reading X selection...\n");
493 TRACE("\tretrieving property %s from window %ld into %s\n",
494 TSXGetAtomName(display,reqType), (long)w, TSXGetAtomName(display,prop) );
497 * First request a zero length in order to figure out the request size.
499 if(TSXGetWindowProperty(display,w,prop,0,0,False, AnyPropertyType/*reqType*/,
500 &atype, &aformat, &nitems, &itemSize, &val) != Success)
502 WARN("\tcouldn't get property size\n");
506 /* Free zero length return data if any */
513 TRACE("\tretrieving %ld bytes...\n", itemSize * aformat/8);
514 lRequestLength = (itemSize * aformat/8)/4 + 1;
517 /* we want to read the property, but not it too large of chunks or
518 we could hang the cause problems. Lets go for 4k blocks */
520 if(TSXGetWindowProperty(display,w,prop,0,4096,False,
521 AnyPropertyType/*reqType*/,
522 &atype, &aformat, &nitems, &remain, &buffer)
525 WARN("\tcouldn't read property\n");
528 val = (char*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
530 memcpy(val,buffer,nitems*bwc);
533 for (total = nitems*bwc,val_cnt=0; remain;)
535 val_cnt +=nitems*bwc;
536 TSXGetWindowProperty(display, w, prop,
537 (total / 4), 4096, False,
538 AnyPropertyType, &atype,
539 &aformat, &nitems, &remain,
543 HeapReAlloc(GetProcessHeap(),0,val, total);
544 memcpy(&val[val_cnt], buffer, nitems*(aformat/8));
550 * Translate the X property into the appropriate Windows clipboard
551 * format, if possible.
553 if ( (reqType == XA_STRING)
554 && (atype == XA_STRING) && (aformat == 8) )
555 /* convert Unix text to CF_UNICODETEXT */
560 for(i=0; i <= nitems; i++)
561 if( val[i] == '\n' ) inlcount++;
563 if( (lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, nitems + inlcount + 1)) )
565 static UINT text_cp = (UINT)-1;
569 for(i=0,inlcount=0; i <= nitems; i++)
571 if( val[i] == '\n' ) lpstr[inlcount++]='\r';
572 lpstr[inlcount++]=val[i];
575 if(text_cp == (UINT)-1)
580 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\x11drv", &hkey))
583 DWORD type, count = sizeof(buf);
584 if(!RegQueryValueExA(hkey, "TextCP", 0, &type, buf, &count))
590 count = MultiByteToWideChar(text_cp, 0, lpstr, -1, NULL, 0);
591 hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
594 WCHAR *textW = GlobalLock(hUnicodeText);
595 MultiByteToWideChar(text_cp, 0, lpstr, -1, textW, count);
596 GlobalUnlock(hUnicodeText);
597 if (!SetClipboardData(CF_UNICODETEXT, hUnicodeText))
599 ERR("Not SET! Need to free our own block\n");
600 GlobalFree(hUnicodeText);
604 HeapFree(GetProcessHeap(), 0, lpstr);
607 else if ( reqType == XA_PIXMAP || reqType == XA_BITMAP ) /* treat PIXMAP as CF_DIB or CF_BITMAP */
609 /* Get the first pixmap handle passed to us */
610 Pixmap *pPixmap = (Pixmap *)val;
611 HANDLE hTargetImage = 0; /* Handle to store the converted bitmap or DIB */
613 if (aformat != 32 || nitems < 1 || atype != XA_PIXMAP
614 || (wFormat != CF_BITMAP && wFormat != CF_DIB))
616 WARN("\tUnimplemented format conversion request\n");
620 if ( wFormat == CF_BITMAP )
622 /* For CF_BITMAP requests we must return an HBITMAP */
623 hTargetImage = X11DRV_BITMAP_CreateBitmapFromPixmap(*pPixmap, TRUE);
625 else if (wFormat == CF_DIB)
627 HWND hwnd = GetOpenClipboardWindow();
628 HDC hdc = GetDC(hwnd);
630 /* For CF_DIB requests we must return an HGLOBAL storing a packed DIB */
631 hTargetImage = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc, TRUE);
633 ReleaseDC(hwnd, hdc);
638 WARN("PIXMAP conversion failed!\n" );
642 /* Delete previous clipboard data */
643 lpFormat = CLIPBOARD_LookupFormat(wFormat);
644 if (lpFormat->wDataPresent && (lpFormat->hData16 || lpFormat->hData32))
645 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
647 /* Update the clipboard record */
648 lpFormat->wDataPresent = 1;
649 lpFormat->hData32 = hTargetImage;
650 lpFormat->hData16 = 0;
655 /* For native properties simply copy the X data without conversion */
656 else if (X11DRV_CLIPBOARD_IsNativeProperty(reqType)) /* <WCF>* */
658 HANDLE hClipData = 0;
660 int cBytes = nitems * aformat/8;
664 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
665 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cBytes );
666 if( (lpClipData = GlobalLock(hClipData)) )
668 memcpy(lpClipData, val, cBytes);
669 GlobalUnlock(hClipData);
677 /* delete previous clipboard record if any */
678 lpFormat = CLIPBOARD_LookupFormat(wFormat);
679 if (lpFormat->wDataPresent || lpFormat->hData16 || lpFormat->hData32)
680 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
682 /* Update the clipboard record */
683 lpFormat->wDataPresent = 1;
684 lpFormat->hData32 = hClipData;
685 lpFormat->hData16 = 0;
692 WARN("\tUnimplemented format conversion request\n");
697 /* Delete the property on the window now that we are done
698 * This will send a PropertyNotify event to the selection owner. */
699 TSXDeleteProperty(display,w,prop);
701 /* Free the retrieved property data */
702 HeapFree(GetProcessHeap(),0,val);
706 /**************************************************************************
707 * X11DRV_CLIPBOARD_ReleaseSelection
709 * Release an XA_PRIMARY or XA_CLIPBOARD selection that we own, in response
710 * to a SelectionClear event.
711 * This can occur in response to another client grabbing the X selection.
712 * If the XA_CLIPBOARD selection is lost, we relinquish XA_PRIMARY as well.
714 void X11DRV_CLIPBOARD_ReleaseSelection(Atom selType, Window w, HWND hwnd)
716 Display *display = thread_display();
717 Atom xaClipboard = TSXInternAtom(display, "CLIPBOARD", False);
718 int clearAllSelections = 0;
721 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\Clipboard", &hkey))
724 DWORD type, count = sizeof(buffer);
725 if(!RegQueryValueExA(hkey, "ClearAllSelections", 0, &type, buffer, &count))
726 clearAllSelections = atoi(buffer);
730 /* w is the window that lost the selection
731 * selectionPrevWindow is nonzero if CheckSelection() was called.
734 TRACE("\tevent->window = %08x (sw = %08x, spw=%08x)\n",
735 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionPrevWindow );
737 if( selectionAcquired )
739 if( w == selectionWindow || selectionPrevWindow == None)
741 /* If we're losing the CLIPBOARD selection, or if the preferences in .winerc
742 * dictate that *all* selections should be cleared on loss of a selection,
743 * we must give up all the selections we own.
745 if ( clearAllSelections || (selType == xaClipboard) )
747 /* completely give up the selection */
748 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
750 /* We are completely giving up the selection.
751 * Make sure we can open the windows clipboard first. */
753 if ( !OpenClipboard(hwnd) )
756 * We can't empty the clipboard if we cant open it so abandon.
757 * Wine will think that it still owns the selection but this is
758 * safer than losing the selection without properly emptying
759 * the clipboard. Perhaps we should forcibly re-assert ownership
760 * of the CLIPBOARD selection in this case...
762 ERR("\tClipboard is busy. Could not give up selection!\n");
766 /* We really lost CLIPBOARD but want to voluntarily lose PRIMARY */
767 if ( (selType == xaClipboard)
768 && (selectionAcquired & S_PRIMARY) )
770 XSetSelectionOwner(display, XA_PRIMARY, None, CurrentTime);
773 /* We really lost PRIMARY but want to voluntarily lose CLIPBOARD */
774 if ( (selType == XA_PRIMARY)
775 && (selectionAcquired & S_CLIPBOARD) )
777 XSetSelectionOwner(display, xaClipboard, None, CurrentTime);
780 selectionWindow = None;
781 PrimarySelectionOwner = ClipboardSelectionOwner = 0;
783 /* Empty the windows clipboard.
784 * We should pretend that we still own the selection BEFORE calling
785 * EmptyClipboard() since otherwise this has the side effect of
786 * triggering X11DRV_CLIPBOARD_Acquire() and causing the X selection
787 * to be re-acquired by us!
789 selectionAcquired = (S_PRIMARY | S_CLIPBOARD);
793 /* Give up ownership of the windows clipboard */
794 CLIPBOARD_ReleaseOwner();
796 /* Reset the selection flags now that we are done */
797 selectionAcquired = S_NOSELECTION;
799 else if ( selType == XA_PRIMARY ) /* Give up only PRIMARY selection */
801 TRACE("Lost PRIMARY selection\n");
802 PrimarySelectionOwner = 0;
803 selectionAcquired &= ~S_PRIMARY; /* clear S_PRIMARY mask */
806 cSelectionTargets = 0;
808 /* but we'll keep existing data for internal use */
809 else if( w == selectionPrevWindow )
811 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
813 w = TSXGetSelectionOwner(display, XA_PRIMARY);
815 TSXSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
817 w = TSXGetSelectionOwner(display, xaClipboard);
819 TSXSetSelectionOwner(display, xaClipboard, selectionWindow, CurrentTime);
823 /* Signal to a selectionClearEvent listener if the selection is completely lost */
824 if (selectionClearEvent && !selectionAcquired)
826 TRACE("Lost all selections, signalling to selectionClearEvent listener\n");
827 SetEvent(selectionClearEvent);
830 selectionPrevWindow = None;
833 /**************************************************************************
834 * ReleaseClipboard (X11DRV.@)
835 * Voluntarily release all currently owned X selections
837 void X11DRV_ReleaseClipboard(void)
839 Display *display = thread_display();
840 if( selectionAcquired )
843 Window savePrevWindow = selectionWindow;
844 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
845 BOOL bHasPrimarySelection = selectionAcquired & S_PRIMARY;
847 selectionAcquired = S_NOSELECTION;
848 selectionPrevWindow = selectionWindow;
849 selectionWindow = None;
851 TRACE("\tgiving up selection (spw = %08x)\n",
852 (unsigned)selectionPrevWindow);
856 TRACE("Releasing CLIPBOARD selection\n");
857 XSetSelectionOwner(display, xaClipboard, None, CurrentTime);
858 if( selectionPrevWindow )
859 while( !XCheckTypedWindowEvent( display, selectionPrevWindow,
860 SelectionClear, &xe ) );
862 if ( bHasPrimarySelection )
864 TRACE("Releasing XA_PRIMARY selection\n");
865 selectionPrevWindow = savePrevWindow; /* May be cleared in X11DRV_CLIPBOARD_ReleaseSelection */
866 XSetSelectionOwner(display, XA_PRIMARY, None, CurrentTime);
868 if( selectionPrevWindow )
869 while( !XCheckTypedWindowEvent( display, selectionPrevWindow,
870 SelectionClear, &xe ) );
875 /* Get rid of any Pixmap resources we may still have */
878 PROPERTY *prop = prop_head;
879 prop_head = prop->next;
880 XFreePixmap( gdi_display, prop->pixmap );
881 HeapFree( GetProcessHeap(), 0, prop );
885 /**************************************************************************
886 * AcquireClipboard (X11DRV.@)
888 void X11DRV_AcquireClipboard(void)
890 Display *display = thread_display();
892 HWND hWndClipWindow = GetOpenClipboardWindow();
895 * Acquire X selection if we don't already own it.
896 * Note that we only acquire the selection if it hasn't been already
897 * acquired by us, and ignore the fact that another X window may be
898 * asserting ownership. The reason for this is we need *any* top level
899 * X window to hold selection ownership. The actual clipboard data requests
900 * are made via GetClipboardData from EVENT_SelectionRequest and this
901 * ensures that the real HWND owner services the request.
902 * If the owning X window gets destroyed the selection ownership is
903 * re-cycled to another top level X window in X11DRV_CLIPBOARD_ResetOwner.
907 if ( !(selectionAcquired == (S_PRIMARY | S_CLIPBOARD)) )
909 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
910 owner = X11DRV_get_whole_window( GetAncestor( hWndClipWindow ? hWndClipWindow : AnyPopup(),
913 /* Grab PRIMARY selection if not owned */
914 if ( !(selectionAcquired & S_PRIMARY) )
915 TSXSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
917 /* Grab CLIPBOARD selection if not owned */
918 if ( !(selectionAcquired & S_CLIPBOARD) )
919 TSXSetSelectionOwner(display, xaClipboard, owner, CurrentTime);
921 if( TSXGetSelectionOwner(display,XA_PRIMARY) == owner )
922 selectionAcquired |= S_PRIMARY;
924 if( TSXGetSelectionOwner(display,xaClipboard) == owner)
925 selectionAcquired |= S_CLIPBOARD;
927 if (selectionAcquired)
929 selectionWindow = owner;
930 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
935 /**************************************************************************
936 * IsClipboardFormatAvailable (X11DRV.@)
938 * Checks if the specified format is available in the current selection
939 * Only invoked when WINE is not the selection owner
941 BOOL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
943 Display *display = thread_display();
944 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
945 Window ownerPrimary = TSXGetSelectionOwner(display,XA_PRIMARY);
946 Window ownerClipboard = TSXGetSelectionOwner(display,xaClipboard);
948 TRACE("enter for %d\n", wFormat);
951 * If the selection has not been previously cached, or the selection has changed,
952 * try and cache the list of available selection targets from the current selection.
954 if ( !cSelectionTargets || (PrimarySelectionOwner != ownerPrimary)
955 || (ClipboardSelectionOwner != ownerClipboard) )
958 * First try caching the CLIPBOARD selection.
959 * If unavailable try PRIMARY.
961 if ( X11DRV_CLIPBOARD_CacheDataFormats(xaClipboard) == 0 )
963 X11DRV_CLIPBOARD_CacheDataFormats(XA_PRIMARY);
966 ClipboardSelectionOwner = ownerClipboard;
967 PrimarySelectionOwner = ownerPrimary;
970 /* Exit if there is no selection */
971 if ( !ownerClipboard && !ownerPrimary )
973 TRACE("There is no selection owner\n");
977 /* Check if the format is available in the clipboard cache */
978 if ( CLIPBOARD_IsPresent(wFormat) )
982 * Many X client apps (such as XTerminal) don't support being queried
983 * for the "TARGETS" target atom. To handle such clients we must actually
984 * try to convert the selection to the requested type.
986 if ( !cSelectionTargets )
987 return X11DRV_GetClipboardData( wFormat );
989 TRACE("There is no selection\n");
993 /**************************************************************************
994 * RegisterClipboardFormat (X11DRV.@)
996 * Registers a custom X clipboard format
997 * Returns: TRUE - success, FALSE - failure
999 BOOL X11DRV_RegisterClipboardFormat( LPCSTR FormatName )
1001 Display *display = thread_display();
1006 * If an X atom is registered for this format, return that
1007 * Otherwise register a new atom.
1011 /* Add a WINE specific prefix to the format */
1012 strcpy(str, FMT_PREFIX);
1013 strncat(str, FormatName, sizeof(str) - strlen(FMT_PREFIX));
1014 prop = TSXInternAtom(display, str, False);
1017 return (prop) ? TRUE : FALSE;
1020 /**************************************************************************
1021 * IsSelectionOwner (X11DRV.@)
1023 * Returns: TRUE - We(WINE) own the selection, FALSE - Selection not owned by us
1025 BOOL X11DRV_IsSelectionOwner(void)
1027 return selectionAcquired;
1030 /**************************************************************************
1031 * SetClipboardData (X11DRV.@)
1033 * We don't need to do anything special here since the clipboard code
1034 * maintains the cache.
1037 void X11DRV_SetClipboardData(UINT wFormat)
1039 /* Make sure we have acquired the X selection */
1040 X11DRV_AcquireClipboard();
1043 /**************************************************************************
1044 * GetClipboardData (X11DRV.@)
1046 * This method is invoked only when we DO NOT own the X selection
1048 * NOTE: Clipboard driver get requests only for CF_UNICODETEXT data.
1049 * We always get the data from the selection client each time,
1050 * since we have no way of determining if the data in our cache is stale.
1052 BOOL X11DRV_GetClipboardData(UINT wFormat)
1054 Display *display = thread_display();
1055 BOOL bRet = selectionAcquired;
1056 HWND hWndClipWindow = GetOpenClipboardWindow();
1057 HWND hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
1058 LPWINE_CLIPFORMAT lpFormat;
1060 TRACE("%d\n", wFormat);
1062 if (!selectionAcquired)
1066 Window w = X11DRV_get_whole_window( GetAncestor( hWnd, GA_ROOT ));
1069 FIXME("No parent win found %x %x\n", hWnd, hWndClipWindow);
1073 /* Map the format ID requested to an X selection property.
1074 * If the format is in the cache, use the atom associated
1078 lpFormat = CLIPBOARD_LookupFormat( wFormat );
1079 if (lpFormat && lpFormat->wDataPresent && lpFormat->drvData)
1080 propRequest = (Atom)lpFormat->drvData;
1082 propRequest = X11DRV_CLIPBOARD_MapFormatToProperty(wFormat);
1086 TRACE("Requesting %s selection from %s...\n",
1087 TSXGetAtomName(display, propRequest),
1088 TSXGetAtomName(display, selectionCacheSrc) );
1090 XConvertSelection(display, selectionCacheSrc, propRequest,
1091 TSXInternAtom(display, "SELECTION_DATA", False),
1094 /* wait until SelectionNotify is received */
1098 if( XCheckTypedWindowEvent(display, w, SelectionNotify, &xe) )
1099 if( xe.xselection.selection == selectionCacheSrc )
1102 wine_tsx11_unlock();
1105 * Read the contents of the X selection property into WINE's
1106 * clipboard cache converting the selection to be compatible if possible.
1108 bRet = X11DRV_CLIPBOARD_ReadSelection( wFormat,
1109 xe.xselection.requestor,
1110 xe.xselection.property,
1111 xe.xselection.target);
1116 TRACE("\tpresent %s = %i\n", CLIPBOARD_GetFormatName(wFormat), bRet );
1119 TRACE("Returning %d\n", bRet);
1124 /**************************************************************************
1125 * ResetSelectionOwner (X11DRV.@)
1127 * Called from DestroyWindow() to prevent X selection from being lost when
1128 * a top level window is destroyed, by switching ownership to another top
1130 * Any top level window can own the selection. See X11DRV_CLIPBOARD_Acquire
1131 * for a more detailed description of this.
1133 void X11DRV_ResetSelectionOwner(HWND hwnd, BOOL bFooBar)
1135 Display *display = thread_display();
1136 HWND hWndClipOwner = 0;
1138 Window XWnd = X11DRV_get_whole_window(hwnd);
1140 BOOL bLostSelection = FALSE;
1142 /* There is nothing to do if we don't own the selection,
1143 * or if the X window which currently owns the selecion is different
1144 * from the one passed in.
1146 if ( !selectionAcquired || XWnd != selectionWindow
1147 || selectionWindow == None )
1150 if ( (bFooBar && XWnd) || (!bFooBar && !XWnd) )
1153 hWndClipOwner = GetClipboardOwner();
1154 xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
1156 TRACE("clipboard owner = %04x, selection window = %08x\n",
1157 hWndClipOwner, (unsigned)selectionWindow);
1159 /* now try to salvage current selection from being destroyed by X */
1161 TRACE("\tchecking %08x\n", (unsigned) XWnd);
1163 selectionPrevWindow = selectionWindow;
1164 selectionWindow = None;
1166 if (!(tmp = GetWindow( hwnd, GW_HWNDNEXT ))) tmp = GetWindow( hwnd, GW_HWNDFIRST );
1167 if (tmp && tmp != hwnd) selectionWindow = X11DRV_get_whole_window(tmp);
1169 if( selectionWindow != None )
1171 /* We must pretend that we don't own the selection while making the switch
1172 * since a SelectionClear event will be sent to the last owner.
1173 * If there is no owner X11DRV_CLIPBOARD_ReleaseSelection will do nothing.
1175 int saveSelectionState = selectionAcquired;
1176 selectionAcquired = False;
1178 TRACE("\tswitching selection from %08x to %08x\n",
1179 (unsigned)selectionPrevWindow, (unsigned)selectionWindow);
1181 /* Assume ownership for the PRIMARY and CLIPBOARD selection */
1182 if ( saveSelectionState & S_PRIMARY )
1183 TSXSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
1185 TSXSetSelectionOwner(display, xaClipboard, selectionWindow, CurrentTime);
1187 /* Restore the selection masks */
1188 selectionAcquired = saveSelectionState;
1190 /* Lose the selection if something went wrong */
1191 if ( ( (saveSelectionState & S_PRIMARY) &&
1192 (TSXGetSelectionOwner(display, XA_PRIMARY) != selectionWindow) )
1193 || (TSXGetSelectionOwner(display, xaClipboard) != selectionWindow) )
1195 bLostSelection = TRUE;
1200 /* Update selection state */
1201 if (saveSelectionState & S_PRIMARY)
1202 PrimarySelectionOwner = selectionWindow;
1204 ClipboardSelectionOwner = selectionWindow;
1209 bLostSelection = TRUE;
1216 /* Launch the clipboard server if the selection can no longer be recyled
1217 * to another top level window. */
1219 if ( !X11DRV_CLIPBOARD_LaunchServer() )
1221 /* Empty the windows clipboard if the server was not launched.
1222 * We should pretend that we still own the selection BEFORE calling
1223 * EmptyClipboard() since otherwise this has the side effect of
1224 * triggering X11DRV_CLIPBOARD_Acquire() and causing the X selection
1225 * to be re-acquired by us!
1228 TRACE("\tLost the selection! Emptying the clipboard...\n");
1231 selectionAcquired = (S_PRIMARY | S_CLIPBOARD);
1236 /* Give up ownership of the windows clipboard */
1237 CLIPBOARD_ReleaseOwner();
1240 selectionAcquired = S_NOSELECTION;
1241 ClipboardSelectionOwner = PrimarySelectionOwner = 0;
1242 selectionWindow = 0;
1246 /**************************************************************************
1247 * X11DRV_CLIPBOARD_RegisterPixmapResource
1248 * Registers a Pixmap resource which is to be associated with a property Atom.
1249 * When the property is destroyed we also destroy the Pixmap through the
1250 * PropertyNotify event.
1252 BOOL X11DRV_CLIPBOARD_RegisterPixmapResource( Atom property, Pixmap pixmap )
1254 PROPERTY *prop = HeapAlloc( GetProcessHeap(), 0, sizeof(*prop) );
1255 if (!prop) return FALSE;
1256 prop->atom = property;
1257 prop->pixmap = pixmap;
1258 prop->next = prop_head;
1263 /**************************************************************************
1264 * X11DRV_CLIPBOARD_FreeResources
1266 * Called from EVENT_PropertyNotify() to give us a chance to destroy
1267 * any resources associated with this property.
1269 void X11DRV_CLIPBOARD_FreeResources( Atom property )
1271 /* Do a simple linear search to see if we have a Pixmap resource
1272 * associated with this property and release it.
1274 PROPERTY **prop = &prop_head;
1278 if ((*prop)->atom == property)
1280 PROPERTY *next = (*prop)->next;
1281 XFreePixmap( gdi_display, (*prop)->pixmap );
1282 HeapFree( GetProcessHeap(), 0, *prop );
1285 else prop = &(*prop)->next;