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"
72 #include "debugtools.h"
74 DEFAULT_DEBUG_CHANNEL(clipboard);
78 #define S_NOSELECTION 0
82 /* X selection context info */
84 static char _CLIPBOARD[] = "CLIPBOARD"; /* CLIPBOARD atom name */
85 static char FMT_PREFIX[] = "<WCF>"; /* Prefix for windows specific formats */
86 static int selectionAcquired = 0; /* Contains the current selection masks */
87 static Window selectionWindow = None; /* The top level X window which owns the selection */
88 static Window selectionPrevWindow = None; /* The last X window that owned the selection */
89 static Window PrimarySelectionOwner = None; /* The window which owns the primary selection */
90 static Window ClipboardSelectionOwner = None; /* The window which owns the clipboard selection */
91 static unsigned long cSelectionTargets = 0; /* Number of target formats reported by TARGETS selection */
92 static Atom selectionCacheSrc = XA_PRIMARY; /* The selection source from which the clipboard cache was filled */
93 static HANDLE selectionClearEvent = 0;/* Synchronization object used to block until server is started */
95 typedef struct tagPROPERTY
97 struct tagPROPERTY *next;
102 static PROPERTY *prop_head;
105 /**************************************************************************
106 * X11DRV_CLIPBOARD_MapPropertyToFormat
108 * Map an X selection property type atom name to a windows clipboard format ID
110 UINT X11DRV_CLIPBOARD_MapPropertyToFormat(char *itemFmtName)
113 * If the property name starts with FMT_PREFIX strip this off and
114 * get the ID for a custom Windows registered format with this name.
115 * We can also understand STRING, PIXMAP and BITMAP.
117 if ( NULL == itemFmtName )
119 else if ( 0 == strncmp(itemFmtName, FMT_PREFIX, strlen(FMT_PREFIX)) )
120 return RegisterClipboardFormatA(itemFmtName + strlen(FMT_PREFIX));
121 else if ( 0 == strcmp(itemFmtName, "STRING") )
123 else if ( 0 == strcmp(itemFmtName, "PIXMAP")
124 || 0 == strcmp(itemFmtName, "BITMAP") )
127 * Return CF_DIB as first preference, if WINE is the selection owner
128 * and if CF_DIB exists in the cache.
129 * If wine dowsn't own the selection we always return CF_DIB
131 if ( !X11DRV_CLIPBOARD_IsSelectionowner() )
133 else if ( CLIPBOARD_IsPresent(CF_DIB) )
139 WARN("\tNo mapping to Windows clipboard format for property %s\n", itemFmtName);
143 /**************************************************************************
144 * X11DRV_CLIPBOARD_MapFormatToProperty
146 * Map a windows clipboard format ID to an X selection property atom
148 Atom X11DRV_CLIPBOARD_MapFormatToProperty(UINT wFormat)
163 * Request a PIXMAP, only if WINE is NOT the selection owner,
164 * AND the requested format is not in the cache.
166 if ( !X11DRV_CLIPBOARD_IsSelectionowner() && !CLIPBOARD_IsPresent(wFormat) )
171 /* Fall thru to the default case in order to use the native format */
177 * If an X atom is registered for this format, return that
178 * Otherwise register a new atom.
181 char *fmtName = CLIPBOARD_GetFormatName(wFormat);
182 strcpy(str, FMT_PREFIX);
186 strncat(str, fmtName, sizeof(str) - strlen(FMT_PREFIX));
187 prop = TSXInternAtom(display, str, False);
194 TRACE("\tNo mapping to X property for Windows clipboard format %d(%s)\n",
195 wFormat, CLIPBOARD_GetFormatName(wFormat));
200 /**************************************************************************
201 * X11DRV_CLIPBOARD_IsNativeProperty
203 * Checks if a property is a native property type
205 BOOL X11DRV_CLIPBOARD_IsNativeProperty(Atom prop)
207 char *itemFmtName = TSXGetAtomName(display, prop);
210 if ( 0 == strncmp(itemFmtName, FMT_PREFIX, strlen(FMT_PREFIX)) )
213 TSXFree(itemFmtName);
218 /**************************************************************************
219 * X11DRV_CLIPBOARD_LaunchServer
220 * Launches the clipboard server. This is called from X11DRV_CLIPBOARD_ResetOwner
221 * when the selection can no longer be recyled to another top level window.
222 * In order to make the selection persist after Wine shuts down a server
223 * process is launched which services subsequent selection requests.
225 BOOL X11DRV_CLIPBOARD_LaunchServer()
229 /* If persistant selection has been disabled in the .winerc Clipboard section,
230 * don't launch the server
232 if ( !PROFILE_GetWineIniInt("Clipboard", "PersistentSelection", 1) )
235 /* Start up persistant WINE X clipboard server process which will
236 * take ownership of the X selection and continue to service selection
237 * requests from other apps.
239 selectionWindow = selectionPrevWindow;
242 /* NOTE: This code only executes in the context of the child process
243 * Do note make any Wine specific calls here.
247 char selMask[8], dbgClassMask[8], clearSelection[8];
250 /* Don't inherit wine's X sockets to the wineclipsrv, otherwise
251 * windows stay around when you have to kill a hanging wine...
253 for (i = 3; i < 256; ++i)
254 fcntl(i, F_SETFD, 1);
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 /* Get the clear selection preference */
268 sprintf(clearSelection, "%d",
269 PROFILE_GetWineIniInt("Clipboard", "ClearAllSelections", 0));
271 /* Exec the clipboard server passing it the selection and debug class masks */
272 execl( BINDIR "/wineclipsrv", "wineclipsrv",
273 selMask, dbgClassMask, clearSelection, NULL );
274 execlp( "wineclipsrv", "wineclipsrv", selMask, dbgClassMask, clearSelection, NULL );
275 execl( "./windows/x11drv/wineclipsrv", "wineclipsrv",
276 selMask, dbgClassMask, clearSelection, NULL );
279 perror("Could not start Wine clipboard server");
280 exit( 1 ); /* Exit the child process */
283 /* Wait until the clipboard server acquires the selection.
284 * We must release the windows lock to enable Wine to process
285 * selection messages in response to the servers requests.
288 iWndsLocks = WIN_SuspendWndsLock();
290 /* We must wait until the server finishes acquiring the selection,
291 * before proceeding, otherwise the window which owns the selection
292 * will be destroyed prematurely!
293 * Create a non-signalled, auto-reset event which will be set by
294 * X11DRV_CLIPBOARD_ReleaseSelection, and wait until this gets
295 * signalled before proceeding.
298 if ( !(selectionClearEvent = CreateEventA(NULL, FALSE, FALSE, NULL)) )
299 ERR("Could not create wait object. Clipboard server won't start!\n");
302 /* Make the event object's handle global */
303 selectionClearEvent = ConvertToGlobalHandle(selectionClearEvent);
305 /* Wait until we lose the selection, timing out after a minute */
307 TRACE("Waiting for clipboard server to acquire selection\n");
309 if ( WaitForSingleObject( selectionClearEvent, 60000 ) != WAIT_OBJECT_0 )
310 TRACE("Server could not acquire selection, or a time out occured!\n");
312 TRACE("Server successfully acquired selection\n");
314 /* Release the event */
315 CloseHandle(selectionClearEvent);
316 selectionClearEvent = 0;
319 WIN_RestoreWndsLock(iWndsLocks);
325 /**************************************************************************
326 * X11DRV_CLIPBOARD_CacheDataFormats
328 * Caches the list of data formats available from the current selection.
329 * This queries the selection owner for the TARGETS property and saves all
330 * reported property types.
332 int X11DRV_CLIPBOARD_CacheDataFormats( Atom SelectionName )
335 HWND hWndClipWindow = GetOpenClipboardWindow();
339 Atom atype=AnyPropertyType;
341 unsigned long remain;
342 Atom* targetList=NULL;
344 Window ownerSelection = 0;
347 * Empty the clipboard cache
349 CLIPBOARD_EmptyCache(TRUE);
351 cSelectionTargets = 0;
352 selectionCacheSrc = SelectionName;
354 hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
356 ownerSelection = TSXGetSelectionOwner(display, SelectionName);
357 if ( !hWnd || (ownerSelection == None) )
358 return cSelectionTargets;
361 * Query the selection owner for the TARGETS property
363 wnd = WIN_FindWndPtr(hWnd);
364 w = X11DRV_WND_FindXWindow(wnd);
365 WIN_ReleaseWndPtr(wnd);
368 aTargets = TSXInternAtom(display, "TARGETS", False);
370 TRACE("Requesting TARGETS selection for '%s' (owner=%08x)...\n",
371 TSXGetAtomName(display, selectionCacheSrc), (unsigned)ownerSelection );
373 EnterCriticalSection( &X11DRV_CritSection );
374 XConvertSelection(display, selectionCacheSrc, aTargets,
375 TSXInternAtom(display, "SELECTION_DATA", False),
379 * Wait until SelectionNotify is received
383 if( XCheckTypedWindowEvent(display, w, SelectionNotify, &xe) )
384 if( xe.xselection.selection == selectionCacheSrc )
387 LeaveCriticalSection( &X11DRV_CritSection );
389 /* Verify that the selection returned a valid TARGETS property */
390 if ( (xe.xselection.target != aTargets)
391 || (xe.xselection.property == None) )
393 TRACE("\tCould not retrieve TARGETS\n");
394 return cSelectionTargets;
397 /* Read the TARGETS property contents */
398 if(TSXGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
399 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat,
400 &cSelectionTargets, &remain, (unsigned char**)&targetList) != Success)
401 TRACE("\tCouldn't read TARGETS property\n");
404 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
405 TSXGetAtomName(display,atype),aformat,cSelectionTargets, remain);
407 * The TARGETS property should have returned us a list of atoms
408 * corresponding to each selection target format supported.
410 if( (atype == XA_ATOM || atype == aTargets) && aformat == 32 )
413 LPWINE_CLIPFORMAT lpFormat;
415 /* Cache these formats in the clipboard cache */
417 for (i = 0; i < cSelectionTargets; i++)
419 char *itemFmtName = TSXGetAtomName(display, targetList[i]);
420 UINT wFormat = X11DRV_CLIPBOARD_MapPropertyToFormat(itemFmtName);
423 * If the clipboard format maps to a Windows format, simply store
424 * the atom identifier and record its availablity status
425 * in the clipboard cache.
429 lpFormat = CLIPBOARD_LookupFormat( wFormat );
431 /* Don't replace if the property already cached is a native format,
432 * or if a PIXMAP is being replaced by a BITMAP.
434 if (lpFormat->wDataPresent &&
435 ( X11DRV_CLIPBOARD_IsNativeProperty(lpFormat->drvData)
436 || (lpFormat->drvData == XA_PIXMAP && targetList[i] == XA_BITMAP) )
439 TRACE("\tAtom# %d: '%s' --> FormatID(%d) %s (Skipped)\n",
440 i, itemFmtName, wFormat, lpFormat->Name);
444 lpFormat->wDataPresent = 1;
445 lpFormat->drvData = targetList[i];
446 TRACE("\tAtom# %d: '%s' --> FormatID(%d) %s\n",
447 i, itemFmtName, wFormat, lpFormat->Name);
451 TSXFree(itemFmtName);
455 /* Free the list of targets */
459 return cSelectionTargets;
462 /**************************************************************************
463 * X11DRV_CLIPBOARD_ReadSelection
464 * Reads the contents of the X selection property into the WINE clipboard cache
465 * converting the selection into a format compatible with the windows clipboard
467 * This method is invoked only to read the contents of a the selection owned
468 * by an external application. i.e. when we do not own the X selection.
470 static BOOL X11DRV_CLIPBOARD_ReadSelection(UINT wFormat, Window w, Atom prop, Atom reqType)
472 Atom atype=AnyPropertyType;
474 unsigned long nitems,remain,itemSize;
476 unsigned char* val=NULL;
477 LPWINE_CLIPFORMAT lpFormat;
479 HWND hWndClipWindow = GetOpenClipboardWindow();
485 TRACE("Reading X selection...\n");
487 TRACE("\tretrieving property %s from window %ld into %s\n",
488 TSXGetAtomName(display,reqType), (long)w, TSXGetAtomName(display,prop) );
491 * First request a zero length in order to figure out the request size.
493 if(TSXGetWindowProperty(display,w,prop,0,0,False, AnyPropertyType/*reqType*/,
494 &atype, &aformat, &nitems, &itemSize, &val) != Success)
496 WARN("\tcouldn't get property size\n");
500 /* Free zero length return data if any */
507 TRACE("\tretrieving %ld bytes...\n", itemSize * aformat/8);
508 lRequestLength = (itemSize * aformat/8)/4 + 1;
511 * Retrieve the actual property in the required X format.
513 if(TSXGetWindowProperty(display,w,prop,0,lRequestLength,False,AnyPropertyType/*reqType*/,
514 &atype, &aformat, &nitems, &remain, &val) != Success)
516 WARN("\tcouldn't read property\n");
520 TRACE("\tType %s,Format %d,nitems %ld,remain %ld,value %s\n",
521 atype ? TSXGetAtomName(display,atype) : NULL, aformat,nitems,remain,val);
525 WARN("\tCouldn't read entire property- selection may be too large! Remain=%ld\n", remain);
530 * Translate the X property into the appropriate Windows clipboard
531 * format, if possible.
533 if ( (reqType == XA_STRING)
534 && (atype == XA_STRING) && (aformat == 8) ) /* treat Unix text as CF_OEMTEXT */
540 TRACE("\tselection is '%s'\n",val);
542 for(i=0; i <= nitems; i++)
543 if( val[i] == '\n' ) inlcount++;
547 hText=GlobalAlloc16(GMEM_MOVEABLE, nitems + inlcount + 1);
548 if( (lpstr = (char*)GlobalLock16(hText)) )
550 for(i=0,inlcount=0; i <= nitems; i++)
552 if( val[i] == '\n' ) lpstr[inlcount++]='\r';
553 lpstr[inlcount++]=val[i];
555 GlobalUnlock16(hText);
563 /* delete previous CF_TEXT and CF_OEMTEXT data */
564 lpFormat = CLIPBOARD_LookupFormat(CF_TEXT);
565 if (lpFormat->wDataPresent || lpFormat->hData16 || lpFormat->hData32)
566 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
568 lpFormat = CLIPBOARD_LookupFormat(CF_OEMTEXT);
569 if (lpFormat->wDataPresent || lpFormat->hData16 || lpFormat->hData32)
570 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
572 /* Update the CF_OEMTEXT record */
573 lpFormat->wDataPresent = 1;
574 lpFormat->hData32 = 0;
575 lpFormat->hData16 = hText;
580 else if ( reqType == XA_PIXMAP || reqType == XA_BITMAP ) /* treat PIXMAP as CF_DIB or CF_BITMAP */
582 /* Get the first pixmap handle passed to us */
583 Pixmap *pPixmap = (Pixmap *)val;
584 HANDLE hTargetImage = 0; /* Handle to store the converted bitmap or DIB */
586 if (aformat != 32 || nitems < 1 || atype != XA_PIXMAP
587 || (wFormat != CF_BITMAP && wFormat != CF_DIB))
589 WARN("\tUnimplemented format conversion request\n");
593 if ( wFormat == CF_BITMAP )
595 /* For CF_BITMAP requests we must return an HBITMAP */
596 hTargetImage = X11DRV_BITMAP_CreateBitmapFromPixmap(*pPixmap, TRUE);
598 else if (wFormat == CF_DIB)
600 HWND hwnd = GetOpenClipboardWindow();
601 HDC hdc = GetDC(hwnd);
603 /* For CF_DIB requests we must return an HGLOBAL storing a packed DIB */
604 hTargetImage = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc, TRUE);
606 ReleaseDC(hdc, hwnd);
611 WARN("PIXMAP conversion failed!\n" );
615 /* Delete previous clipboard data */
616 lpFormat = CLIPBOARD_LookupFormat(wFormat);
617 if (lpFormat->wDataPresent && (lpFormat->hData16 || lpFormat->hData32))
618 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
620 /* Update the clipboard record */
621 lpFormat->wDataPresent = 1;
622 lpFormat->hData32 = hTargetImage;
623 lpFormat->hData16 = 0;
628 /* For native properties simply copy the X data without conversion */
629 else if (X11DRV_CLIPBOARD_IsNativeProperty(reqType)) /* <WCF>* */
631 HANDLE hClipData = 0;
633 int cBytes = nitems * aformat/8;
637 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
638 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cBytes );
639 if( (lpClipData = GlobalLock(hClipData)) )
641 memcpy(lpClipData, val, cBytes);
642 GlobalUnlock(hClipData);
650 /* delete previous clipboard record if any */
651 lpFormat = CLIPBOARD_LookupFormat(wFormat);
652 if (lpFormat->wDataPresent || lpFormat->hData16 || lpFormat->hData32)
653 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
655 /* Update the clipboard record */
656 lpFormat->wDataPresent = 1;
657 lpFormat->hData32 = hClipData;
658 lpFormat->hData16 = 0;
665 WARN("\tUnimplemented format conversion request\n");
670 /* Delete the property on the window now that we are done
671 * This will send a PropertyNotify event to the selection owner. */
672 TSXDeleteProperty(display,w,prop);
674 /* Free the retrieved property data */
681 /**************************************************************************
682 * X11DRV_CLIPBOARD_ReleaseSelection
684 * Release an XA_PRIMARY or XA_CLIPBOARD selection that we own, in response
685 * to a SelectionClear event.
686 * This can occur in response to another client grabbing the X selection.
687 * If the XA_CLIPBOARD selection is lost, we relinquish XA_PRIMARY as well.
689 void X11DRV_CLIPBOARD_ReleaseSelection(Atom selType, Window w, HWND hwnd)
691 Atom xaClipboard = TSXInternAtom(display, "CLIPBOARD", False);
692 int clearAllSelections = PROFILE_GetWineIniInt("Clipboard", "ClearAllSelections", 0);
694 /* w is the window that lost the selection
695 * selectionPrevWindow is nonzero if CheckSelection() was called.
698 TRACE("\tevent->window = %08x (sw = %08x, spw=%08x)\n",
699 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionPrevWindow );
701 if( selectionAcquired )
703 if( w == selectionWindow || selectionPrevWindow == None)
705 /* If we're losing the CLIPBOARD selection, or if the preferences in .winerc
706 * dictate that *all* selections should be cleared on loss of a selection,
707 * we must give up all the selections we own.
709 if ( clearAllSelections || (selType == xaClipboard) )
711 /* completely give up the selection */
712 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
714 /* We are completely giving up the selection.
715 * Make sure we can open the windows clipboard first. */
717 if ( !OpenClipboard(hwnd) )
720 * We can't empty the clipboard if we cant open it so abandon.
721 * Wine will think that it still owns the selection but this is
722 * safer than losing the selection without properly emptying
723 * the clipboard. Perhaps we should forcibly re-assert ownership
724 * of the CLIPBOARD selection in this case...
726 ERR("\tClipboard is busy. Could not give up selection!\n");
730 /* We really lost CLIPBOARD but want to voluntarily lose PRIMARY */
731 if ( (selType == xaClipboard)
732 && (selectionAcquired & S_PRIMARY) )
734 XSetSelectionOwner(display, XA_PRIMARY, None, CurrentTime);
737 /* We really lost PRIMARY but want to voluntarily lose CLIPBOARD */
738 if ( (selType == XA_PRIMARY)
739 && (selectionAcquired & S_CLIPBOARD) )
741 XSetSelectionOwner(display, xaClipboard, None, CurrentTime);
744 selectionWindow = None;
745 PrimarySelectionOwner = ClipboardSelectionOwner = 0;
747 /* Empty the windows clipboard.
748 * We should pretend that we still own the selection BEFORE calling
749 * EmptyClipboard() since otherwise this has the side effect of
750 * triggering X11DRV_CLIPBOARD_Acquire() and causing the X selection
751 * to be re-acquired by us!
753 selectionAcquired = (S_PRIMARY | S_CLIPBOARD);
757 /* Give up ownership of the windows clipboard */
758 CLIPBOARD_ReleaseOwner();
760 /* Reset the selection flags now that we are done */
761 selectionAcquired = S_NOSELECTION;
763 else if ( selType == XA_PRIMARY ) /* Give up only PRIMARY selection */
765 TRACE("Lost PRIMARY selection\n");
766 PrimarySelectionOwner = 0;
767 selectionAcquired &= ~S_PRIMARY; /* clear S_PRIMARY mask */
770 cSelectionTargets = 0;
772 /* but we'll keep existing data for internal use */
773 else if( w == selectionPrevWindow )
775 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
777 w = TSXGetSelectionOwner(display, XA_PRIMARY);
779 TSXSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
781 w = TSXGetSelectionOwner(display, xaClipboard);
783 TSXSetSelectionOwner(display, xaClipboard, selectionWindow, CurrentTime);
787 /* Signal to a selectionClearEvent listener if the selection is completely lost */
788 if (selectionClearEvent && !selectionAcquired)
790 TRACE("Lost all selections, signalling to selectionClearEvent listener\n");
791 SetEvent(selectionClearEvent);
794 selectionPrevWindow = None;
797 /**************************************************************************
798 * X11DRV_CLIPBOARD_Empty
799 * Voluntarily release all currently owned X selections
801 void X11DRV_CLIPBOARD_Release()
803 if( selectionAcquired )
806 Window savePrevWindow = selectionWindow;
807 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
808 BOOL bHasPrimarySelection = selectionAcquired & S_PRIMARY;
810 selectionAcquired = S_NOSELECTION;
811 selectionPrevWindow = selectionWindow;
812 selectionWindow = None;
814 TRACE("\tgiving up selection (spw = %08x)\n",
815 (unsigned)selectionPrevWindow);
817 EnterCriticalSection(&X11DRV_CritSection);
819 TRACE("Releasing CLIPBOARD selection\n");
820 XSetSelectionOwner(display, xaClipboard, None, CurrentTime);
821 if( selectionPrevWindow )
822 while( !XCheckTypedWindowEvent( display, selectionPrevWindow,
823 SelectionClear, &xe ) );
825 if ( bHasPrimarySelection )
827 TRACE("Releasing XA_PRIMARY selection\n");
828 selectionPrevWindow = savePrevWindow; /* May be cleared in X11DRV_CLIPBOARD_ReleaseSelection */
829 XSetSelectionOwner(display, XA_PRIMARY, None, CurrentTime);
831 if( selectionPrevWindow )
832 while( !XCheckTypedWindowEvent( display, selectionPrevWindow,
833 SelectionClear, &xe ) );
836 LeaveCriticalSection(&X11DRV_CritSection);
839 /* Get rid of any Pixmap resources we may still have */
842 PROPERTY *prop = prop_head;
843 prop_head = prop->next;
844 XFreePixmap( display, prop->pixmap );
845 HeapFree( GetProcessHeap(), 0, prop );
849 /**************************************************************************
850 * X11DRV_CLIPBOARD_Acquire()
852 void X11DRV_CLIPBOARD_Acquire()
855 HWND hWndClipWindow = GetOpenClipboardWindow();
858 * Acquire X selection if we don't already own it.
859 * Note that we only acquire the selection if it hasn't been already
860 * acquired by us, and ignore the fact that another X window may be
861 * asserting ownership. The reason for this is we need *any* top level
862 * X window to hold selection ownership. The actual clipboard data requests
863 * are made via GetClipboardData from EVENT_SelectionRequest and this
864 * ensures that the real HWND owner services the request.
865 * If the owning X window gets destroyed the selection ownership is
866 * re-cycled to another top level X window in X11DRV_CLIPBOARD_ResetOwner.
870 if ( !(selectionAcquired == (S_PRIMARY | S_CLIPBOARD)) )
872 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
873 WND *tmpWnd = WIN_FindWndPtr( hWndClipWindow ? hWndClipWindow : AnyPopup() );
874 owner = X11DRV_WND_FindXWindow(tmpWnd );
875 WIN_ReleaseWndPtr(tmpWnd);
877 /* Grab PRIMARY selection if not owned */
878 if ( !(selectionAcquired & S_PRIMARY) )
879 TSXSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
881 /* Grab CLIPBOARD selection if not owned */
882 if ( !(selectionAcquired & S_CLIPBOARD) )
883 TSXSetSelectionOwner(display, xaClipboard, owner, CurrentTime);
885 if( TSXGetSelectionOwner(display,XA_PRIMARY) == owner )
886 selectionAcquired |= S_PRIMARY;
888 if( TSXGetSelectionOwner(display,xaClipboard) == owner)
889 selectionAcquired |= S_CLIPBOARD;
891 if (selectionAcquired)
893 selectionWindow = owner;
894 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
899 /**************************************************************************
900 * X11DRV_CLIPBOARD_IsFormatAvailable
902 * Checks if the specified format is available in the current selection
903 * Only invoked when WINE is not the selection owner
905 BOOL X11DRV_CLIPBOARD_IsFormatAvailable(UINT wFormat)
907 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
908 Window ownerPrimary = TSXGetSelectionOwner(display,XA_PRIMARY);
909 Window ownerClipboard = TSXGetSelectionOwner(display,xaClipboard);
912 * If the selection has not been previously cached, or the selection has changed,
913 * try and cache the list of available selection targets from the current selection.
915 if ( !cSelectionTargets || (PrimarySelectionOwner != ownerPrimary)
916 || (ClipboardSelectionOwner != ownerClipboard) )
919 * First try cacheing the CLIPBOARD selection.
920 * If unavailable try PRIMARY.
922 if ( X11DRV_CLIPBOARD_CacheDataFormats(xaClipboard) == 0 )
924 X11DRV_CLIPBOARD_CacheDataFormats(XA_PRIMARY);
927 ClipboardSelectionOwner = ownerClipboard;
928 PrimarySelectionOwner = ownerPrimary;
931 /* Exit if there is no selection */
932 if ( !ownerClipboard && !ownerPrimary )
935 if ( wFormat == CF_TEXT )
936 wFormat = CF_OEMTEXT;
938 /* Check if the format is available in the clipboard cache */
939 if ( CLIPBOARD_IsPresent(wFormat) )
943 * Many X client apps (such as XTerminal) don't support being queried
944 * for the "TARGETS" target atom. To handle such clients we must actually
945 * try to convert the selection to the requested type.
947 if ( !cSelectionTargets )
948 return X11DRV_CLIPBOARD_GetData( wFormat );
953 /**************************************************************************
954 * X11DRV_CLIPBOARD_RegisterFormat
956 * Registers a custom X clipboard format
957 * Returns: TRUE - success, FALSE - failure
959 BOOL X11DRV_CLIPBOARD_RegisterFormat( LPCSTR FormatName )
965 * If an X atom is registered for this format, return that
966 * Otherwise register a new atom.
970 /* Add a WINE specific prefix to the format */
971 strcpy(str, FMT_PREFIX);
972 strncat(str, FormatName, sizeof(str) - strlen(FMT_PREFIX));
973 prop = TSXInternAtom(display, str, False);
976 return (prop) ? TRUE : FALSE;
979 /**************************************************************************
980 * X11DRV_CLIPBOARD_IsSelectionowner
982 * Returns: TRUE - We(WINE) own the selection, FALSE - Selection not owned by us
984 BOOL X11DRV_CLIPBOARD_IsSelectionowner()
986 return selectionAcquired;
989 /**************************************************************************
990 * X11DRV_CLIPBOARD_SetData
992 * We don't need to do anything special here since the clipboard code
993 * maintains the cache.
996 void X11DRV_CLIPBOARD_SetData(UINT wFormat)
998 /* Make sure we have acquired the X selection */
999 X11DRV_CLIPBOARD_Acquire();
1002 /**************************************************************************
1003 * X11DRV_CLIPBOARD_GetData
1005 * This method is invoked only when we DO NOT own the X selection
1007 * NOTE: Clipboard driver doesn't get requests for CF_TEXT data, only
1009 * We always get the data from the selection client each time,
1010 * since we have no way of determining if the data in our cache is stale.
1012 BOOL X11DRV_CLIPBOARD_GetData(UINT wFormat)
1014 BOOL bRet = selectionAcquired;
1015 HWND hWndClipWindow = GetOpenClipboardWindow();
1016 HWND hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
1018 LPWINE_CLIPFORMAT lpFormat;
1020 if( !selectionAcquired && (wnd = WIN_FindWndPtr(hWnd)) )
1024 Window w = X11DRV_WND_FindXWindow(wnd);
1025 WIN_ReleaseWndPtr(wnd);
1028 /* Map the format ID requested to an X selection property.
1029 * If the format is in the cache, use the atom associated
1033 lpFormat = CLIPBOARD_LookupFormat( wFormat );
1034 if (lpFormat && lpFormat->wDataPresent && lpFormat->drvData)
1035 propRequest = (Atom)lpFormat->drvData;
1037 propRequest = X11DRV_CLIPBOARD_MapFormatToProperty(wFormat);
1041 TRACE("Requesting %s selection from %s...\n",
1042 TSXGetAtomName(display, propRequest),
1043 TSXGetAtomName(display, selectionCacheSrc) );
1045 EnterCriticalSection( &X11DRV_CritSection );
1046 XConvertSelection(display, selectionCacheSrc, propRequest,
1047 TSXInternAtom(display, "SELECTION_DATA", False),
1050 /* wait until SelectionNotify is received */
1054 if( XCheckTypedWindowEvent(display, w, SelectionNotify, &xe) )
1055 if( xe.xselection.selection == selectionCacheSrc )
1058 LeaveCriticalSection( &X11DRV_CritSection );
1061 * Read the contents of the X selection property into WINE's
1062 * clipboard cache converting the selection to be compatible if possible.
1064 bRet = X11DRV_CLIPBOARD_ReadSelection( wFormat,
1065 xe.xselection.requestor,
1066 xe.xselection.property,
1067 xe.xselection.target);
1072 TRACE("\tpresent %s = %i\n", CLIPBOARD_GetFormatName(wFormat), bRet );
1078 /**************************************************************************
1079 * X11DRV_CLIPBOARD_ResetOwner
1081 * Called from DestroyWindow() to prevent X selection from being lost when
1082 * a top level window is destroyed, by switching ownership to another top
1084 * Any top level window can own the selection. See X11DRV_CLIPBOARD_Acquire
1085 * for a more detailed description of this.
1087 void X11DRV_CLIPBOARD_ResetOwner(WND *pWnd, BOOL bFooBar)
1089 HWND hWndClipOwner = 0;
1090 Window XWnd = X11DRV_WND_GetXWindow(pWnd);
1092 BOOL bLostSelection = FALSE;
1094 /* There is nothing to do if we don't own the selection,
1095 * or if the X window which currently owns the selecion is different
1096 * from the one passed in.
1098 if ( !selectionAcquired || XWnd != selectionWindow
1099 || selectionWindow == None )
1102 if ( (bFooBar && XWnd) || (!bFooBar && !XWnd) )
1105 hWndClipOwner = GetClipboardOwner();
1106 xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
1108 TRACE("clipboard owner = %04x, selection window = %08x\n",
1109 hWndClipOwner, (unsigned)selectionWindow);
1111 /* now try to salvage current selection from being destroyed by X */
1113 TRACE("\tchecking %08x\n", (unsigned) XWnd);
1115 selectionPrevWindow = selectionWindow;
1116 selectionWindow = None;
1119 selectionWindow = X11DRV_WND_GetXWindow(pWnd->next);
1120 else if( pWnd->parent )
1121 if( pWnd->parent->child != pWnd )
1122 selectionWindow = X11DRV_WND_GetXWindow(pWnd->parent->child);
1124 if( selectionWindow != None )
1126 /* We must pretend that we don't own the selection while making the switch
1127 * since a SelectionClear event will be sent to the last owner.
1128 * If there is no owner X11DRV_CLIPBOARD_ReleaseSelection will do nothing.
1130 int saveSelectionState = selectionAcquired;
1131 selectionAcquired = False;
1133 TRACE("\tswitching selection from %08x to %08x\n",
1134 (unsigned)selectionPrevWindow, (unsigned)selectionWindow);
1136 /* Assume ownership for the PRIMARY and CLIPBOARD selection */
1137 if ( saveSelectionState & S_PRIMARY )
1138 TSXSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
1140 TSXSetSelectionOwner(display, xaClipboard, selectionWindow, CurrentTime);
1142 /* Restore the selection masks */
1143 selectionAcquired = saveSelectionState;
1145 /* Lose the selection if something went wrong */
1146 if ( ( (saveSelectionState & S_PRIMARY) &&
1147 (TSXGetSelectionOwner(display, XA_PRIMARY) != selectionWindow) )
1148 || (TSXGetSelectionOwner(display, xaClipboard) != selectionWindow) )
1150 bLostSelection = TRUE;
1155 /* Update selection state */
1156 if (saveSelectionState & S_PRIMARY)
1157 PrimarySelectionOwner = selectionWindow;
1159 ClipboardSelectionOwner = selectionWindow;
1164 bLostSelection = TRUE;
1171 /* Launch the clipboard server if the selection can no longer be recyled
1172 * to another top level window. */
1174 if ( !X11DRV_CLIPBOARD_LaunchServer() )
1176 /* Empty the windows clipboard if the server was not launched.
1177 * We should pretend that we still own the selection BEFORE calling
1178 * EmptyClipboard() since otherwise this has the side effect of
1179 * triggering X11DRV_CLIPBOARD_Acquire() and causing the X selection
1180 * to be re-acquired by us!
1183 TRACE("\tLost the selection! Emptying the clipboard...\n");
1186 selectionAcquired = (S_PRIMARY | S_CLIPBOARD);
1191 /* Give up ownership of the windows clipboard */
1192 CLIPBOARD_ReleaseOwner();
1195 selectionAcquired = S_NOSELECTION;
1196 ClipboardSelectionOwner = PrimarySelectionOwner = 0;
1197 selectionWindow = 0;
1201 /**************************************************************************
1202 * X11DRV_CLIPBOARD_RegisterPixmapResource
1203 * Registers a Pixmap resource which is to be associated with a property Atom.
1204 * When the property is destroyed we also destroy the Pixmap through the
1205 * PropertyNotify event.
1207 BOOL X11DRV_CLIPBOARD_RegisterPixmapResource( Atom property, Pixmap pixmap )
1209 PROPERTY *prop = HeapAlloc( GetProcessHeap(), 0, sizeof(*prop) );
1210 if (!prop) return FALSE;
1211 prop->atom = property;
1212 prop->pixmap = pixmap;
1213 prop->next = prop_head;
1218 /**************************************************************************
1219 * X11DRV_CLIPBOARD_FreeResources
1221 * Called from EVENT_PropertyNotify() to give us a chance to destroy
1222 * any resources associated with this property.
1224 void X11DRV_CLIPBOARD_FreeResources( Atom property )
1226 /* Do a simple linear search to see if we have a Pixmap resource
1227 * associated with this property and release it.
1229 PROPERTY **prop = &prop_head;
1233 if ((*prop)->atom == property)
1235 PROPERTY *next = (*prop)->next;
1236 XFreePixmap( display, (*prop)->pixmap );
1237 HeapFree( GetProcessHeap(), 0, *prop );
1240 else prop = &(*prop)->next;
1244 #endif /* !defined(X_DISPLAY_MISSING) */