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 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).
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 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.
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.
50 #ifndef X_DISPLAY_MISSING
53 #include <X11/Xatom.h>
63 #include "wine/winuser16.h"
64 #include "clipboard.h"
71 #include "debugtools.h"
73 DEFAULT_DEBUG_CHANNEL(clipboard);
77 #define S_NOSELECTION 0
81 /* X selection context info */
83 static char _CLIPBOARD[] = "CLIPBOARD"; /* CLIPBOARD atom name */
84 static char FMT_PREFIX[] = "<WCF>"; /* Prefix for windows specific formats */
85 static int selectionAcquired = 0; /* Contains the current selection masks */
86 static Window selectionWindow = None; /* The top level X window which owns the selection */
87 static Window selectionPrevWindow = None; /* The last X window that owned the selection */
88 static Window PrimarySelectionOwner = None; /* The window which owns the primary selection */
89 static Window ClipboardSelectionOwner = None; /* The window which owns the clipboard selection */
90 static unsigned long cSelectionTargets = 0; /* Number of target formats reported by TARGETS selection */
91 static Atom selectionCacheSrc = XA_PRIMARY; /* The selection source from which the clipboard cache was filled */
92 static HANDLE selectionClearEvent = 0;/* Synchronization object used to block until server is started */
94 typedef struct tagPROPERTY
96 struct tagPROPERTY *next;
101 static PROPERTY *prop_head;
104 /**************************************************************************
105 * X11DRV_CLIPBOARD_MapPropertyToFormat
107 * Map an X selection property type atom name to a windows clipboard format ID
109 UINT X11DRV_CLIPBOARD_MapPropertyToFormat(char *itemFmtName)
112 * If the property name starts with FMT_PREFIX strip this off and
113 * get the ID for a custom Windows registered format with this name.
114 * We can also understand STRING, PIXMAP and BITMAP.
116 if ( NULL == itemFmtName )
118 else if ( 0 == strncmp(itemFmtName, FMT_PREFIX, strlen(FMT_PREFIX)) )
119 return RegisterClipboardFormatA(itemFmtName + strlen(FMT_PREFIX));
120 else if ( 0 == strcmp(itemFmtName, "STRING") )
122 else if ( 0 == strcmp(itemFmtName, "PIXMAP")
123 || 0 == strcmp(itemFmtName, "BITMAP") )
126 * Return CF_DIB as first preference, if WINE is the selection owner
127 * and if CF_DIB exists in the cache.
128 * If wine dowsn't own the selection we always return CF_DIB
130 if ( !X11DRV_CLIPBOARD_IsSelectionowner() )
132 else if ( CLIPBOARD_IsPresent(CF_DIB) )
138 WARN("\tNo mapping to Windows clipboard format for property %s\n", itemFmtName);
142 /**************************************************************************
143 * X11DRV_CLIPBOARD_MapFormatToProperty
145 * Map a windows clipboard format ID to an X selection property atom
147 Atom X11DRV_CLIPBOARD_MapFormatToProperty(UINT wFormat)
162 * Request a PIXMAP, only if WINE is NOT the selection owner,
163 * AND the requested format is not in the cache.
165 if ( !X11DRV_CLIPBOARD_IsSelectionowner() && !CLIPBOARD_IsPresent(wFormat) )
170 /* Fall thru to the default case in order to use the native format */
176 * If an X atom is registered for this format, return that
177 * Otherwise register a new atom.
180 char *fmtName = CLIPBOARD_GetFormatName(wFormat);
181 strcpy(str, FMT_PREFIX);
185 strncat(str, fmtName, sizeof(str) - strlen(FMT_PREFIX));
186 prop = TSXInternAtom(display, str, False);
193 TRACE("\tNo mapping to X property for Windows clipboard format %d(%s)\n",
194 wFormat, CLIPBOARD_GetFormatName(wFormat));
199 /**************************************************************************
200 * X11DRV_CLIPBOARD_IsNativeProperty
202 * Checks if a property is a native property type
204 BOOL X11DRV_CLIPBOARD_IsNativeProperty(Atom prop)
206 char *itemFmtName = TSXGetAtomName(display, prop);
209 if ( 0 == strncmp(itemFmtName, FMT_PREFIX, strlen(FMT_PREFIX)) )
212 TSXFree(itemFmtName);
217 /**************************************************************************
218 * X11DRV_CLIPBOARD_LaunchServer
219 * Launches the clipboard server. This is called from X11DRV_CLIPBOARD_ResetOwner
220 * when the selection can no longer be recyled to another top level window.
221 * In order to make the selection persist after Wine shuts down a server
222 * process is launched which services subsequent selection requests.
224 BOOL X11DRV_CLIPBOARD_LaunchServer()
228 /* If persistant selection has been disabled in the .winerc Clipboard section,
229 * don't launch the server
231 if ( !PROFILE_GetWineIniInt("Clipboard", "PersistentSelection", 1) )
234 /* Start up persistant WINE X clipboard server process which will
235 * take ownership of the X selection and continue to service selection
236 * requests from other apps.
238 selectionWindow = selectionPrevWindow;
241 /* NOTE: This code only executes in the context of the child process
242 * Do note make any Wine specific calls here.
246 char selMask[8], dbgClassMask[8], clearSelection[8];
249 /* Don't inherit wine's X sockets to the wineclipsrv, otherwise
250 * windows stay around when you have to kill a hanging wine...
252 for (i = 3; i < 256; ++i)
253 fcntl(i, F_SETFD, 1);
255 sprintf(selMask, "%d", selectionAcquired);
257 /* Build the debug class mask to pass to the server, by inheriting
258 * the settings for the clipboard debug channel.
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);
266 /* Get the clear selection preference */
267 sprintf(clearSelection, "%d",
268 PROFILE_GetWineIniInt("Clipboard", "ClearAllSelections", 0));
270 /* Exec the clipboard server passing it the selection and debug class masks */
271 execl( BINDIR "/wineclipsrv", "wineclipsrv",
272 selMask, dbgClassMask, clearSelection, NULL );
273 execlp( "wineclipsrv", "wineclipsrv", selMask, dbgClassMask, clearSelection, NULL );
274 execl( "./windows/x11drv/wineclipsrv", "wineclipsrv",
275 selMask, dbgClassMask, clearSelection, NULL );
278 perror("Could not start Wine clipboard server");
279 exit( 1 ); /* Exit the child process */
282 /* Wait until the clipboard server acquires the selection.
283 * We must release the windows lock to enable Wine to process
284 * selection messages in response to the servers requests.
287 iWndsLocks = WIN_SuspendWndsLock();
289 /* We must wait until the server finishes acquiring the selection,
290 * before proceeding, otherwise the window which owns the selection
291 * will be destroyed prematurely!
292 * Create a non-signalled, auto-reset event which will be set by
293 * X11DRV_CLIPBOARD_ReleaseSelection, and wait until this gets
294 * signalled before proceeding.
297 if ( !(selectionClearEvent = CreateEventA(NULL, FALSE, FALSE, NULL)) )
298 ERR("Could not create wait object. Clipboard server won't start!\n");
301 /* Make the event object's handle global */
302 selectionClearEvent = ConvertToGlobalHandle(selectionClearEvent);
304 /* Wait until we lose the selection, timing out after a minute */
306 TRACE("Waiting for clipboard server to acquire selection\n");
308 if ( WaitForSingleObject( selectionClearEvent, 60000 ) != WAIT_OBJECT_0 )
309 TRACE("Server could not acquire selection, or a time out occured!\n");
311 TRACE("Server successfully acquired selection\n");
313 /* Release the event */
314 CloseHandle(selectionClearEvent);
315 selectionClearEvent = 0;
318 WIN_RestoreWndsLock(iWndsLocks);
324 /**************************************************************************
325 * X11DRV_CLIPBOARD_CacheDataFormats
327 * Caches the list of data formats available from the current selection.
328 * This queries the selection owner for the TARGETS property and saves all
329 * reported property types.
331 int X11DRV_CLIPBOARD_CacheDataFormats( Atom SelectionName )
334 HWND hWndClipWindow = GetOpenClipboardWindow();
338 Atom atype=AnyPropertyType;
340 unsigned long remain;
341 Atom* targetList=NULL;
343 Window ownerSelection = 0;
346 * Empty the clipboard cache
348 CLIPBOARD_EmptyCache(TRUE);
350 cSelectionTargets = 0;
351 selectionCacheSrc = SelectionName;
353 hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
355 ownerSelection = TSXGetSelectionOwner(display, SelectionName);
356 if ( !hWnd || (ownerSelection == None) )
357 return cSelectionTargets;
360 * Query the selection owner for the TARGETS property
362 wnd = WIN_FindWndPtr(hWnd);
363 w = X11DRV_WND_FindXWindow(wnd);
364 WIN_ReleaseWndPtr(wnd);
367 aTargets = TSXInternAtom(display, "TARGETS", False);
369 TRACE("Requesting TARGETS selection for '%s' (owner=%08x)...\n",
370 TSXGetAtomName(display, selectionCacheSrc), (unsigned)ownerSelection );
372 EnterCriticalSection( &X11DRV_CritSection );
373 XConvertSelection(display, selectionCacheSrc, aTargets,
374 TSXInternAtom(display, "SELECTION_DATA", False),
378 * Wait until SelectionNotify is received
382 if( XCheckTypedWindowEvent(display, w, SelectionNotify, &xe) )
383 if( xe.xselection.selection == selectionCacheSrc )
386 LeaveCriticalSection( &X11DRV_CritSection );
388 /* Verify that the selection returned a valid TARGETS property */
389 if ( (xe.xselection.target != aTargets)
390 || (xe.xselection.property == None) )
392 TRACE("\tCould not retrieve TARGETS\n");
393 return cSelectionTargets;
396 /* Read the TARGETS property contents */
397 if(TSXGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
398 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat,
399 &cSelectionTargets, &remain, (unsigned char**)&targetList) != Success)
400 TRACE("\tCouldn't read TARGETS property\n");
403 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
404 TSXGetAtomName(display,atype),aformat,cSelectionTargets, remain);
406 * The TARGETS property should have returned us a list of atoms
407 * corresponding to each selection target format supported.
409 if( (atype == XA_ATOM || atype == aTargets) && aformat == 32 )
412 LPWINE_CLIPFORMAT lpFormat;
414 /* Cache these formats in the clipboard cache */
416 for (i = 0; i < cSelectionTargets; i++)
418 char *itemFmtName = TSXGetAtomName(display, targetList[i]);
419 UINT wFormat = X11DRV_CLIPBOARD_MapPropertyToFormat(itemFmtName);
422 * If the clipboard format maps to a Windows format, simply store
423 * the atom identifier and record its availablity status
424 * in the clipboard cache.
428 lpFormat = CLIPBOARD_LookupFormat( wFormat );
430 /* Don't replace if the property already cached is a native format,
431 * or if a PIXMAP is being replaced by a BITMAP.
433 if (lpFormat->wDataPresent &&
434 ( X11DRV_CLIPBOARD_IsNativeProperty(lpFormat->drvData)
435 || (lpFormat->drvData == XA_PIXMAP && targetList[i] == XA_BITMAP) )
438 TRACE("\tAtom# %d: '%s' --> FormatID(%d) %s (Skipped)\n",
439 i, itemFmtName, wFormat, lpFormat->Name);
443 lpFormat->wDataPresent = 1;
444 lpFormat->drvData = targetList[i];
445 TRACE("\tAtom# %d: '%s' --> FormatID(%d) %s\n",
446 i, itemFmtName, wFormat, lpFormat->Name);
450 TSXFree(itemFmtName);
454 /* Free the list of targets */
458 return cSelectionTargets;
461 /**************************************************************************
462 * X11DRV_CLIPBOARD_ReadSelection
463 * Reads the contents of the X selection property into the WINE clipboard cache
464 * converting the selection into a format compatible with the windows clipboard
466 * This method is invoked only to read the contents of a the selection owned
467 * by an external application. i.e. when we do not own the X selection.
469 static BOOL X11DRV_CLIPBOARD_ReadSelection(UINT wFormat, Window w, Atom prop, Atom reqType)
471 Atom atype=AnyPropertyType;
473 unsigned long nitems,remain,itemSize;
475 unsigned char* val=NULL;
476 LPWINE_CLIPFORMAT lpFormat;
478 HWND hWndClipWindow = GetOpenClipboardWindow();
484 TRACE("Reading X selection...\n");
486 TRACE("\tretrieving property %s from window %ld into %s\n",
487 TSXGetAtomName(display,reqType), (long)w, TSXGetAtomName(display,prop) );
490 * First request a zero length in order to figure out the request size.
492 if(TSXGetWindowProperty(display,w,prop,0,0,False, AnyPropertyType/*reqType*/,
493 &atype, &aformat, &nitems, &itemSize, &val) != Success)
495 WARN("\tcouldn't get property size\n");
499 /* Free zero length return data if any */
506 TRACE("\tretrieving %ld bytes...\n", itemSize * aformat/8);
507 lRequestLength = (itemSize * aformat/8)/4 + 1;
510 * Retrieve the actual property in the required X format.
512 if(TSXGetWindowProperty(display,w,prop,0,lRequestLength,False,AnyPropertyType/*reqType*/,
513 &atype, &aformat, &nitems, &remain, &val) != Success)
515 WARN("\tcouldn't read property\n");
519 TRACE("\tType %s,Format %d,nitems %ld,remain %ld,value %s\n",
520 atype ? TSXGetAtomName(display,atype) : NULL, aformat,nitems,remain,val);
524 WARN("\tCouldn't read entire property- selection may be too large! Remain=%ld\n", remain);
529 * Translate the X property into the appropriate Windows clipboard
530 * format, if possible.
532 if ( (reqType == XA_STRING)
533 && (atype == XA_STRING) && (aformat == 8) ) /* treat Unix text as CF_OEMTEXT */
539 TRACE("\tselection is '%s'\n",val);
541 for(i=0; i <= nitems; i++)
542 if( val[i] == '\n' ) inlcount++;
546 hText=GlobalAlloc16(GMEM_MOVEABLE, nitems + inlcount + 1);
547 if( (lpstr = (char*)GlobalLock16(hText)) )
549 for(i=0,inlcount=0; i <= nitems; i++)
551 if( val[i] == '\n' ) lpstr[inlcount++]='\r';
552 lpstr[inlcount++]=val[i];
554 GlobalUnlock16(hText);
562 /* delete previous CF_TEXT and CF_OEMTEXT data */
563 lpFormat = CLIPBOARD_LookupFormat(CF_TEXT);
564 if (lpFormat->wDataPresent || lpFormat->hData16 || lpFormat->hData32)
565 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
567 lpFormat = CLIPBOARD_LookupFormat(CF_OEMTEXT);
568 if (lpFormat->wDataPresent || lpFormat->hData16 || lpFormat->hData32)
569 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
571 /* Update the CF_OEMTEXT record */
572 lpFormat->wDataPresent = 1;
573 lpFormat->hData32 = 0;
574 lpFormat->hData16 = hText;
579 else if ( reqType == XA_PIXMAP || reqType == XA_BITMAP ) /* treat PIXMAP as CF_DIB or CF_BITMAP */
581 /* Get the first pixmap handle passed to us */
582 Pixmap *pPixmap = (Pixmap *)val;
583 HANDLE hTargetImage = 0; /* Handle to store the converted bitmap or DIB */
585 if (aformat != 32 || nitems < 1 || atype != XA_PIXMAP
586 || (wFormat != CF_BITMAP && wFormat != CF_DIB))
588 WARN("\tUnimplemented format conversion request\n");
592 if ( wFormat == CF_BITMAP )
594 /* For CF_BITMAP requests we must return an HBITMAP */
595 hTargetImage = X11DRV_BITMAP_CreateBitmapFromPixmap(*pPixmap, TRUE);
597 else if (wFormat == CF_DIB)
599 HWND hwnd = GetOpenClipboardWindow();
600 HDC hdc = GetDC(hwnd);
602 /* For CF_DIB requests we must return an HGLOBAL storing a packed DIB */
603 hTargetImage = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc, TRUE);
605 ReleaseDC(hdc, hwnd);
610 WARN("PIXMAP conversion failed!\n" );
614 /* Delete previous clipboard data */
615 lpFormat = CLIPBOARD_LookupFormat(wFormat);
616 if (lpFormat->wDataPresent && (lpFormat->hData16 || lpFormat->hData32))
617 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
619 /* Update the clipboard record */
620 lpFormat->wDataPresent = 1;
621 lpFormat->hData32 = hTargetImage;
622 lpFormat->hData16 = 0;
627 /* For native properties simply copy the X data without conversion */
628 else if (X11DRV_CLIPBOARD_IsNativeProperty(reqType)) /* <WCF>* */
630 HANDLE hClipData = 0;
632 int cBytes = nitems * aformat/8;
636 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
637 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cBytes );
638 if( (lpClipData = GlobalLock(hClipData)) )
640 memcpy(lpClipData, val, cBytes);
641 GlobalUnlock(hClipData);
649 /* delete previous clipboard record if any */
650 lpFormat = CLIPBOARD_LookupFormat(wFormat);
651 if (lpFormat->wDataPresent || lpFormat->hData16 || lpFormat->hData32)
652 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
654 /* Update the clipboard record */
655 lpFormat->wDataPresent = 1;
656 lpFormat->hData32 = hClipData;
657 lpFormat->hData16 = 0;
664 WARN("\tUnimplemented format conversion request\n");
669 /* Delete the property on the window now that we are done
670 * This will send a PropertyNotify event to the selection owner. */
671 TSXDeleteProperty(display,w,prop);
673 /* Free the retrieved property data */
680 /**************************************************************************
681 * X11DRV_CLIPBOARD_ReleaseSelection
683 * Release an XA_PRIMARY or XA_CLIPBOARD selection that we own, in response
684 * to a SelectionClear event.
685 * This can occur in response to another client grabbing the X selection.
686 * If the XA_CLIPBOARD selection is lost, we relinquish XA_PRIMARY as well.
688 void X11DRV_CLIPBOARD_ReleaseSelection(Atom selType, Window w, HWND hwnd)
690 Atom xaClipboard = TSXInternAtom(display, "CLIPBOARD", False);
691 int clearAllSelections = PROFILE_GetWineIniInt("Clipboard", "ClearAllSelections", 0);
693 /* w is the window that lost the selection
694 * selectionPrevWindow is nonzero if CheckSelection() was called.
697 TRACE("\tevent->window = %08x (sw = %08x, spw=%08x)\n",
698 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionPrevWindow );
700 if( selectionAcquired )
702 if( w == selectionWindow || selectionPrevWindow == None)
704 /* If we're losing the CLIPBOARD selection, or if the preferences in .winerc
705 * dictate that *all* selections should be cleared on loss of a selection,
706 * we must give up all the selections we own.
708 if ( clearAllSelections || (selType == xaClipboard) )
710 /* completely give up the selection */
711 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
713 /* We are completely giving up the selection.
714 * Make sure we can open the windows clipboard first. */
716 if ( !OpenClipboard(hwnd) )
719 * We can't empty the clipboard if we cant open it so abandon.
720 * Wine will think that it still owns the selection but this is
721 * safer than losing the selection without properly emptying
722 * the clipboard. Perhaps we should forcibly re-assert ownership
723 * of the CLIPBOARD selection in this case...
725 ERR("\tClipboard is busy. Could not give up selection!\n");
729 /* We really lost CLIPBOARD but want to voluntarily lose PRIMARY */
730 if ( (selType == xaClipboard)
731 && (selectionAcquired & S_PRIMARY) )
733 XSetSelectionOwner(display, XA_PRIMARY, None, CurrentTime);
736 /* We really lost PRIMARY but want to voluntarily lose CLIPBOARD */
737 if ( (selType == XA_PRIMARY)
738 && (selectionAcquired & S_CLIPBOARD) )
740 XSetSelectionOwner(display, xaClipboard, None, CurrentTime);
743 selectionWindow = None;
744 PrimarySelectionOwner = ClipboardSelectionOwner = 0;
746 /* Empty the windows clipboard.
747 * We should pretend that we still own the selection BEFORE calling
748 * EmptyClipboard() since otherwise this has the side effect of
749 * triggering X11DRV_CLIPBOARD_Acquire() and causing the X selection
750 * to be re-acquired by us!
752 selectionAcquired = (S_PRIMARY | S_CLIPBOARD);
756 /* Give up ownership of the windows clipboard */
757 CLIPBOARD_ReleaseOwner();
759 /* Reset the selection flags now that we are done */
760 selectionAcquired = S_NOSELECTION;
762 else if ( selType == XA_PRIMARY ) /* Give up only PRIMARY selection */
764 TRACE("Lost PRIMARY selection\n");
765 PrimarySelectionOwner = 0;
766 selectionAcquired &= ~S_PRIMARY; /* clear S_PRIMARY mask */
769 cSelectionTargets = 0;
771 /* but we'll keep existing data for internal use */
772 else if( w == selectionPrevWindow )
774 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
776 w = TSXGetSelectionOwner(display, XA_PRIMARY);
778 TSXSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
780 w = TSXGetSelectionOwner(display, xaClipboard);
782 TSXSetSelectionOwner(display, xaClipboard, selectionWindow, CurrentTime);
786 /* Signal to a selectionClearEvent listener if the selection is completely lost */
787 if (selectionClearEvent && !selectionAcquired)
789 TRACE("Lost all selections, signalling to selectionClearEvent listener\n");
790 SetEvent(selectionClearEvent);
793 selectionPrevWindow = None;
796 /**************************************************************************
797 * X11DRV_CLIPBOARD_Empty
798 * Voluntarily release all currently owned X selections
800 void X11DRV_CLIPBOARD_Release()
802 if( selectionAcquired )
805 Window savePrevWindow = selectionWindow;
806 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
807 BOOL bHasPrimarySelection = selectionAcquired & S_PRIMARY;
809 selectionAcquired = S_NOSELECTION;
810 selectionPrevWindow = selectionWindow;
811 selectionWindow = None;
813 TRACE("\tgiving up selection (spw = %08x)\n",
814 (unsigned)selectionPrevWindow);
816 EnterCriticalSection(&X11DRV_CritSection);
818 TRACE("Releasing CLIPBOARD selection\n");
819 XSetSelectionOwner(display, xaClipboard, None, CurrentTime);
820 if( selectionPrevWindow )
821 while( !XCheckTypedWindowEvent( display, selectionPrevWindow,
822 SelectionClear, &xe ) );
824 if ( bHasPrimarySelection )
826 TRACE("Releasing XA_PRIMARY selection\n");
827 selectionPrevWindow = savePrevWindow; /* May be cleared in X11DRV_CLIPBOARD_ReleaseSelection */
828 XSetSelectionOwner(display, XA_PRIMARY, None, CurrentTime);
830 if( selectionPrevWindow )
831 while( !XCheckTypedWindowEvent( display, selectionPrevWindow,
832 SelectionClear, &xe ) );
835 LeaveCriticalSection(&X11DRV_CritSection);
838 /* Get rid of any Pixmap resources we may still have */
841 PROPERTY *prop = prop_head;
842 prop_head = prop->next;
843 XFreePixmap( display, prop->pixmap );
844 HeapFree( GetProcessHeap(), 0, prop );
848 /**************************************************************************
849 * X11DRV_CLIPBOARD_Acquire()
851 void X11DRV_CLIPBOARD_Acquire()
854 HWND hWndClipWindow = GetOpenClipboardWindow();
857 * Acquire X selection if we don't already own it.
858 * Note that we only acquire the selection if it hasn't been already
859 * acquired by us, and ignore the fact that another X window may be
860 * asserting ownership. The reason for this is we need *any* top level
861 * X window to hold selection ownership. The actual clipboard data requests
862 * are made via GetClipboardData from EVENT_SelectionRequest and this
863 * ensures that the real HWND owner services the request.
864 * If the owning X window gets destroyed the selection ownership is
865 * re-cycled to another top level X window in X11DRV_CLIPBOARD_ResetOwner.
869 if ( !(selectionAcquired == (S_PRIMARY | S_CLIPBOARD)) )
871 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
872 WND *tmpWnd = WIN_FindWndPtr( hWndClipWindow ? hWndClipWindow : AnyPopup() );
873 owner = X11DRV_WND_FindXWindow(tmpWnd );
874 WIN_ReleaseWndPtr(tmpWnd);
876 /* Grab PRIMARY selection if not owned */
877 if ( !(selectionAcquired & S_PRIMARY) )
878 TSXSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
880 /* Grab CLIPBOARD selection if not owned */
881 if ( !(selectionAcquired & S_CLIPBOARD) )
882 TSXSetSelectionOwner(display, xaClipboard, owner, CurrentTime);
884 if( TSXGetSelectionOwner(display,XA_PRIMARY) == owner )
885 selectionAcquired |= S_PRIMARY;
887 if( TSXGetSelectionOwner(display,xaClipboard) == owner)
888 selectionAcquired |= S_CLIPBOARD;
890 if (selectionAcquired)
892 selectionWindow = owner;
893 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
898 /**************************************************************************
899 * X11DRV_CLIPBOARD_IsFormatAvailable
901 * Checks if the specified format is available in the current selection
902 * Only invoked when WINE is not the selection owner
904 BOOL X11DRV_CLIPBOARD_IsFormatAvailable(UINT wFormat)
906 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
907 Window ownerPrimary = TSXGetSelectionOwner(display,XA_PRIMARY);
908 Window ownerClipboard = TSXGetSelectionOwner(display,xaClipboard);
911 * If the selection has not been previously cached, or the selection has changed,
912 * try and cache the list of available selection targets from the current selection.
914 if ( !cSelectionTargets || (PrimarySelectionOwner != ownerPrimary)
915 || (ClipboardSelectionOwner != ownerClipboard) )
918 * First try cacheing the CLIPBOARD selection.
919 * If unavailable try PRIMARY.
921 if ( X11DRV_CLIPBOARD_CacheDataFormats(xaClipboard) == 0 )
923 X11DRV_CLIPBOARD_CacheDataFormats(XA_PRIMARY);
926 ClipboardSelectionOwner = ownerClipboard;
927 PrimarySelectionOwner = ownerPrimary;
930 /* Exit if there is no selection */
931 if ( !ownerClipboard && !ownerPrimary )
934 if ( wFormat == CF_TEXT )
935 wFormat = CF_OEMTEXT;
937 /* Check if the format is available in the clipboard cache */
938 if ( CLIPBOARD_IsPresent(wFormat) )
942 * Many X client apps (such as XTerminal) don't support being queried
943 * for the "TARGETS" target atom. To handle such clients we must actually
944 * try to convert the selection to the requested type.
946 if ( !cSelectionTargets )
947 return X11DRV_CLIPBOARD_GetData( wFormat );
952 /**************************************************************************
953 * X11DRV_CLIPBOARD_RegisterFormat
955 * Registers a custom X clipboard format
956 * Returns: TRUE - success, FALSE - failure
958 BOOL X11DRV_CLIPBOARD_RegisterFormat( LPCSTR FormatName )
964 * If an X atom is registered for this format, return that
965 * Otherwise register a new atom.
969 /* Add a WINE specific prefix to the format */
970 strcpy(str, FMT_PREFIX);
971 strncat(str, FormatName, sizeof(str) - strlen(FMT_PREFIX));
972 prop = TSXInternAtom(display, str, False);
975 return (prop) ? TRUE : FALSE;
978 /**************************************************************************
979 * X11DRV_CLIPBOARD_IsSelectionowner
981 * Returns: TRUE - We(WINE) own the selection, FALSE - Selection not owned by us
983 BOOL X11DRV_CLIPBOARD_IsSelectionowner()
985 return selectionAcquired;
988 /**************************************************************************
989 * X11DRV_CLIPBOARD_SetData
991 * We don't need to do anything special here since the clipboard code
992 * maintains the cache.
995 void X11DRV_CLIPBOARD_SetData(UINT wFormat)
997 /* Make sure we have acquired the X selection */
998 X11DRV_CLIPBOARD_Acquire();
1001 /**************************************************************************
1002 * X11DRV_CLIPBOARD_GetData
1004 * This method is invoked only when we DO NOT own the X selection
1006 * NOTE: Clipboard driver doesn't get requests for CF_TEXT data, only
1008 * We always get the data from the selection client each time,
1009 * since we have no way of determining if the data in our cache is stale.
1011 BOOL X11DRV_CLIPBOARD_GetData(UINT wFormat)
1013 BOOL bRet = selectionAcquired;
1014 HWND hWndClipWindow = GetOpenClipboardWindow();
1015 HWND hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
1017 LPWINE_CLIPFORMAT lpFormat;
1019 if( !selectionAcquired && (wnd = WIN_FindWndPtr(hWnd)) )
1023 Window w = X11DRV_WND_FindXWindow(wnd);
1024 WIN_ReleaseWndPtr(wnd);
1027 /* Map the format ID requested to an X selection property.
1028 * If the format is in the cache, use the atom associated
1032 lpFormat = CLIPBOARD_LookupFormat( wFormat );
1033 if (lpFormat && lpFormat->wDataPresent && lpFormat->drvData)
1034 propRequest = (Atom)lpFormat->drvData;
1036 propRequest = X11DRV_CLIPBOARD_MapFormatToProperty(wFormat);
1040 TRACE("Requesting %s selection from %s...\n",
1041 TSXGetAtomName(display, propRequest),
1042 TSXGetAtomName(display, selectionCacheSrc) );
1044 EnterCriticalSection( &X11DRV_CritSection );
1045 XConvertSelection(display, selectionCacheSrc, propRequest,
1046 TSXInternAtom(display, "SELECTION_DATA", False),
1049 /* wait until SelectionNotify is received */
1053 if( XCheckTypedWindowEvent(display, w, SelectionNotify, &xe) )
1054 if( xe.xselection.selection == selectionCacheSrc )
1057 LeaveCriticalSection( &X11DRV_CritSection );
1060 * Read the contents of the X selection property into WINE's
1061 * clipboard cache converting the selection to be compatible if possible.
1063 bRet = X11DRV_CLIPBOARD_ReadSelection( wFormat,
1064 xe.xselection.requestor,
1065 xe.xselection.property,
1066 xe.xselection.target);
1071 TRACE("\tpresent %s = %i\n", CLIPBOARD_GetFormatName(wFormat), bRet );
1077 /**************************************************************************
1078 * X11DRV_CLIPBOARD_ResetOwner
1080 * Called from DestroyWindow() to prevent X selection from being lost when
1081 * a top level window is destroyed, by switching ownership to another top
1083 * Any top level window can own the selection. See X11DRV_CLIPBOARD_Acquire
1084 * for a more detailed description of this.
1086 void X11DRV_CLIPBOARD_ResetOwner(WND *pWnd, BOOL bFooBar)
1088 HWND hWndClipOwner = 0;
1089 Window XWnd = X11DRV_WND_GetXWindow(pWnd);
1091 BOOL bLostSelection = FALSE;
1093 /* There is nothing to do if we don't own the selection,
1094 * or if the X window which currently owns the selecion is different
1095 * from the one passed in.
1097 if ( !selectionAcquired || XWnd != selectionWindow
1098 || selectionWindow == None )
1101 if ( (bFooBar && XWnd) || (!bFooBar && !XWnd) )
1104 hWndClipOwner = GetClipboardOwner();
1105 xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
1107 TRACE("clipboard owner = %04x, selection window = %08x\n",
1108 hWndClipOwner, (unsigned)selectionWindow);
1110 /* now try to salvage current selection from being destroyed by X */
1112 TRACE("\tchecking %08x\n", (unsigned) XWnd);
1114 selectionPrevWindow = selectionWindow;
1115 selectionWindow = None;
1118 selectionWindow = X11DRV_WND_GetXWindow(pWnd->next);
1119 else if( pWnd->parent )
1120 if( pWnd->parent->child != pWnd )
1121 selectionWindow = X11DRV_WND_GetXWindow(pWnd->parent->child);
1123 if( selectionWindow != None )
1125 /* We must pretend that we don't own the selection while making the switch
1126 * since a SelectionClear event will be sent to the last owner.
1127 * If there is no owner X11DRV_CLIPBOARD_ReleaseSelection will do nothing.
1129 int saveSelectionState = selectionAcquired;
1130 selectionAcquired = False;
1132 TRACE("\tswitching selection from %08x to %08x\n",
1133 (unsigned)selectionPrevWindow, (unsigned)selectionWindow);
1135 /* Assume ownership for the PRIMARY and CLIPBOARD selection */
1136 if ( saveSelectionState & S_PRIMARY )
1137 TSXSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
1139 TSXSetSelectionOwner(display, xaClipboard, selectionWindow, CurrentTime);
1141 /* Restore the selection masks */
1142 selectionAcquired = saveSelectionState;
1144 /* Lose the selection if something went wrong */
1145 if ( ( (saveSelectionState & S_PRIMARY) &&
1146 (TSXGetSelectionOwner(display, XA_PRIMARY) != selectionWindow) )
1147 || (TSXGetSelectionOwner(display, xaClipboard) != selectionWindow) )
1149 bLostSelection = TRUE;
1154 /* Update selection state */
1155 if (saveSelectionState & S_PRIMARY)
1156 PrimarySelectionOwner = selectionWindow;
1158 ClipboardSelectionOwner = selectionWindow;
1163 bLostSelection = TRUE;
1170 /* Launch the clipboard server if the selection can no longer be recyled
1171 * to another top level window. */
1173 if ( !X11DRV_CLIPBOARD_LaunchServer() )
1175 /* Empty the windows clipboard if the server was not launched.
1176 * We should pretend that we still own the selection BEFORE calling
1177 * EmptyClipboard() since otherwise this has the side effect of
1178 * triggering X11DRV_CLIPBOARD_Acquire() and causing the X selection
1179 * to be re-acquired by us!
1182 TRACE("\tLost the selection! Emptying the clipboard...\n");
1185 selectionAcquired = (S_PRIMARY | S_CLIPBOARD);
1190 /* Give up ownership of the windows clipboard */
1191 CLIPBOARD_ReleaseOwner();
1194 selectionAcquired = S_NOSELECTION;
1195 ClipboardSelectionOwner = PrimarySelectionOwner = 0;
1196 selectionWindow = 0;
1200 /**************************************************************************
1201 * X11DRV_CLIPBOARD_RegisterPixmapResource
1202 * Registers a Pixmap resource which is to be associated with a property Atom.
1203 * When the property is destroyed we also destroy the Pixmap through the
1204 * PropertyNotify event.
1206 BOOL X11DRV_CLIPBOARD_RegisterPixmapResource( Atom property, Pixmap pixmap )
1208 PROPERTY *prop = HeapAlloc( GetProcessHeap(), 0, sizeof(*prop) );
1209 if (!prop) return FALSE;
1210 prop->atom = property;
1211 prop->pixmap = pixmap;
1212 prop->next = prop_head;
1217 /**************************************************************************
1218 * X11DRV_CLIPBOARD_FreeResources
1220 * Called from EVENT_PropertyNotify() to give us a chance to destroy
1221 * any resources associated with this property.
1223 void X11DRV_CLIPBOARD_FreeResources( Atom property )
1225 /* Do a simple linear search to see if we have a Pixmap resource
1226 * associated with this property and release it.
1228 PROPERTY **prop = &prop_head;
1232 if ((*prop)->atom == property)
1234 PROPERTY *next = (*prop)->next;
1235 XFreePixmap( display, (*prop)->pixmap );
1236 HeapFree( GetProcessHeap(), 0, *prop );
1239 else prop = &(*prop)->next;
1243 #endif /* !defined(X_DISPLAY_MISSING) */