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.
56 #include "clipboard.h"
60 #include "debugtools.h"
62 DEFAULT_DEBUG_CHANNEL(clipboard);
66 #define S_NOSELECTION 0
70 /* X selection context info */
72 static char _CLIPBOARD[] = "CLIPBOARD"; /* CLIPBOARD atom name */
73 static char FMT_PREFIX[] = "<WCF>"; /* Prefix for windows specific formats */
74 static int selectionAcquired = 0; /* Contains the current selection masks */
75 static Window selectionWindow = None; /* The top level X window which owns the selection */
76 static Window selectionPrevWindow = None; /* The last X window that owned the selection */
77 static Window PrimarySelectionOwner = None; /* The window which owns the primary selection */
78 static Window ClipboardSelectionOwner = None; /* The window which owns the clipboard selection */
79 static unsigned long cSelectionTargets = 0; /* Number of target formats reported by TARGETS selection */
80 static Atom selectionCacheSrc = XA_PRIMARY; /* The selection source from which the clipboard cache was filled */
81 static HANDLE selectionClearEvent = 0;/* Synchronization object used to block until server is started */
83 typedef struct tagPROPERTY
85 struct tagPROPERTY *next;
90 static PROPERTY *prop_head;
93 /**************************************************************************
94 * X11DRV_CLIPBOARD_MapPropertyToFormat
96 * Map an X selection property type atom name to a windows clipboard format ID
98 UINT X11DRV_CLIPBOARD_MapPropertyToFormat(char *itemFmtName)
101 * If the property name starts with FMT_PREFIX strip this off and
102 * get the ID for a custom Windows registered format with this name.
103 * We can also understand STRING, PIXMAP and BITMAP.
105 if ( NULL == itemFmtName )
107 else if ( 0 == strncmp(itemFmtName, FMT_PREFIX, strlen(FMT_PREFIX)) )
108 return RegisterClipboardFormatA(itemFmtName + strlen(FMT_PREFIX));
109 else if ( 0 == strcmp(itemFmtName, "STRING") )
110 return CF_UNICODETEXT;
111 else if ( 0 == strcmp(itemFmtName, "PIXMAP")
112 || 0 == strcmp(itemFmtName, "BITMAP") )
115 * Return CF_DIB as first preference, if WINE is the selection owner
116 * and if CF_DIB exists in the cache.
117 * If wine dowsn't own the selection we always return CF_DIB
119 if ( !X11DRV_IsSelectionOwner() )
121 else if ( CLIPBOARD_IsPresent(CF_DIB) )
127 WARN("\tNo mapping to Windows clipboard format for property %s\n", itemFmtName);
131 /**************************************************************************
132 * X11DRV_CLIPBOARD_MapFormatToProperty
134 * Map a windows clipboard format ID to an X selection property atom
136 Atom X11DRV_CLIPBOARD_MapFormatToProperty(UINT wFormat)
142 /* We support only CF_UNICODETEXT, other formats are synthesized */
155 * Request a PIXMAP, only if WINE is NOT the selection owner,
156 * AND the requested format is not in the cache.
158 if ( !X11DRV_IsSelectionOwner() && !CLIPBOARD_IsPresent(wFormat) )
163 /* Fall thru to the default case in order to use the native format */
169 * If an X atom is registered for this format, return that
170 * Otherwise register a new atom.
173 char *fmtName = CLIPBOARD_GetFormatName(wFormat);
174 strcpy(str, FMT_PREFIX);
178 strncat(str, fmtName, sizeof(str) - strlen(FMT_PREFIX));
179 prop = TSXInternAtom(display, str, False);
186 TRACE("\tNo mapping to X property for Windows clipboard format %d(%s)\n",
187 wFormat, CLIPBOARD_GetFormatName(wFormat));
192 /**************************************************************************
193 * X11DRV_CLIPBOARD_IsNativeProperty
195 * Checks if a property is a native Wine property type
197 BOOL X11DRV_CLIPBOARD_IsNativeProperty(Atom prop)
199 char *itemFmtName = TSXGetAtomName(display, prop);
202 if ( 0 == strncmp(itemFmtName, FMT_PREFIX, strlen(FMT_PREFIX)) )
205 TSXFree(itemFmtName);
210 /**************************************************************************
211 * X11DRV_CLIPBOARD_LaunchServer
212 * Launches the clipboard server. This is called from X11DRV_CLIPBOARD_ResetOwner
213 * when the selection can no longer be recyled to another top level window.
214 * In order to make the selection persist after Wine shuts down a server
215 * process is launched which services subsequent selection requests.
217 BOOL X11DRV_CLIPBOARD_LaunchServer()
221 /* If persistant selection has been disabled in the .winerc Clipboard section,
222 * don't launch the server
224 if ( !PROFILE_GetWineIniInt("Clipboard", "PersistentSelection", 1) )
227 /* Start up persistant WINE X clipboard server process which will
228 * take ownership of the X selection and continue to service selection
229 * requests from other apps.
231 selectionWindow = selectionPrevWindow;
234 /* NOTE: This code only executes in the context of the child process
235 * Do note make any Wine specific calls here.
239 char selMask[8], dbgClassMask[8], clearSelection[8];
242 /* Don't inherit wine's X sockets to the wineclipsrv, otherwise
243 * windows stay around when you have to kill a hanging wine...
245 for (i = 3; i < 256; ++i)
246 fcntl(i, F_SETFD, 1);
248 sprintf(selMask, "%d", selectionAcquired);
250 /* Build the debug class mask to pass to the server, by inheriting
251 * the settings for the clipboard debug channel.
253 dbgClasses |= FIXME_ON(clipboard) ? 1 : 0;
254 dbgClasses |= ERR_ON(clipboard) ? 2 : 0;
255 dbgClasses |= WARN_ON(clipboard) ? 4 : 0;
256 dbgClasses |= TRACE_ON(clipboard) ? 8 : 0;
257 sprintf(dbgClassMask, "%d", dbgClasses);
259 /* Get the clear selection preference */
260 sprintf(clearSelection, "%d",
261 PROFILE_GetWineIniInt("Clipboard", "ClearAllSelections", 0));
263 /* Exec the clipboard server passing it the selection and debug class masks */
264 execl( BINDIR "/wineclipsrv", "wineclipsrv",
265 selMask, dbgClassMask, clearSelection, NULL );
266 execlp( "wineclipsrv", "wineclipsrv", selMask, dbgClassMask, clearSelection, NULL );
267 execl( "./windows/x11drv/wineclipsrv", "wineclipsrv",
268 selMask, dbgClassMask, clearSelection, NULL );
271 perror("Could not start Wine clipboard server");
272 exit( 1 ); /* Exit the child process */
275 /* Wait until the clipboard server acquires the selection.
276 * We must release the windows lock to enable Wine to process
277 * selection messages in response to the servers requests.
280 iWndsLocks = WIN_SuspendWndsLock();
282 /* We must wait until the server finishes acquiring the selection,
283 * before proceeding, otherwise the window which owns the selection
284 * will be destroyed prematurely!
285 * Create a non-signalled, auto-reset event which will be set by
286 * X11DRV_CLIPBOARD_ReleaseSelection, and wait until this gets
287 * signalled before proceeding.
290 if ( !(selectionClearEvent = CreateEventA(NULL, FALSE, FALSE, NULL)) )
291 ERR("Could not create wait object. Clipboard server won't start!\n");
294 /* Wait until we lose the selection, timing out after a minute */
296 TRACE("Waiting for clipboard server to acquire selection\n");
298 if ( WaitForSingleObject( selectionClearEvent, 60000 ) != WAIT_OBJECT_0 )
299 TRACE("Server could not acquire selection, or a timeout occurred!\n");
301 TRACE("Server successfully acquired selection\n");
303 /* Release the event */
304 CloseHandle(selectionClearEvent);
305 selectionClearEvent = 0;
308 WIN_RestoreWndsLock(iWndsLocks);
314 /**************************************************************************
315 * X11DRV_CLIPBOARD_CacheDataFormats
317 * Caches the list of data formats available from the current selection.
318 * This queries the selection owner for the TARGETS property and saves all
319 * reported property types.
321 int X11DRV_CLIPBOARD_CacheDataFormats( Atom SelectionName )
324 HWND hWndClipWindow = GetOpenClipboardWindow();
328 Atom atype=AnyPropertyType;
330 unsigned long remain;
331 Atom* targetList=NULL;
333 Window ownerSelection = 0;
337 * Empty the clipboard cache
339 CLIPBOARD_EmptyCache(TRUE);
341 cSelectionTargets = 0;
342 selectionCacheSrc = SelectionName;
344 hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
346 ownerSelection = TSXGetSelectionOwner(display, SelectionName);
347 if ( !hWnd || (ownerSelection == None) )
348 return cSelectionTargets;
351 * Query the selection owner for the TARGETS property
353 wnd = WIN_FindWndPtr(hWnd);
354 w = X11DRV_WND_FindXWindow(wnd);
355 WIN_ReleaseWndPtr(wnd);
358 aTargets = TSXInternAtom(display, "TARGETS", False);
360 TRACE("Requesting TARGETS selection for '%s' (owner=%08x)...\n",
361 TSXGetAtomName(display, selectionCacheSrc), (unsigned)ownerSelection );
363 XConvertSelection(display, selectionCacheSrc, aTargets,
364 TSXInternAtom(display, "SELECTION_DATA", False),
368 * Wait until SelectionNotify is received
372 if( XCheckTypedWindowEvent(display, w, SelectionNotify, &xe) )
373 if( xe.xselection.selection == selectionCacheSrc )
378 /* Verify that the selection returned a valid TARGETS property */
379 if ( (xe.xselection.target != aTargets)
380 || (xe.xselection.property == None) )
382 TRACE("\tExit, could not retrieve TARGETS\n");
383 return cSelectionTargets;
386 /* Read the TARGETS property contents */
387 if(TSXGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
388 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat,
389 &cSelectionTargets, &remain, (unsigned char**)&targetList) != Success)
390 TRACE("\tCouldn't read TARGETS property\n");
393 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
394 TSXGetAtomName(display,atype),aformat,cSelectionTargets, remain);
396 * The TARGETS property should have returned us a list of atoms
397 * corresponding to each selection target format supported.
399 if( (atype == XA_ATOM || atype == aTargets) && aformat == 32 )
402 LPWINE_CLIPFORMAT lpFormat;
404 /* Cache these formats in the clipboard cache */
406 for (i = 0; i < cSelectionTargets; i++)
408 char *itemFmtName = TSXGetAtomName(display, targetList[i]);
409 UINT wFormat = X11DRV_CLIPBOARD_MapPropertyToFormat(itemFmtName);
412 * If the clipboard format maps to a Windows format, simply store
413 * the atom identifier and record its availablity status
414 * in the clipboard cache.
418 lpFormat = CLIPBOARD_LookupFormat( wFormat );
420 /* Don't replace if the property already cached is a native format,
421 * or if a PIXMAP is being replaced by a BITMAP.
423 if (lpFormat->wDataPresent &&
424 ( X11DRV_CLIPBOARD_IsNativeProperty(lpFormat->drvData)
425 || (lpFormat->drvData == XA_PIXMAP && targetList[i] == XA_BITMAP) )
428 TRACE("\tAtom# %d: '%s' --> FormatID(%d) %s (Skipped)\n",
429 i, itemFmtName, wFormat, lpFormat->Name);
433 lpFormat->wDataPresent = 1;
434 lpFormat->drvData = targetList[i];
435 TRACE("\tAtom# %d: '%s' --> FormatID(%d) %s\n",
436 i, itemFmtName, wFormat, lpFormat->Name);
440 TSXFree(itemFmtName);
444 /* Free the list of targets */
448 return cSelectionTargets;
451 /**************************************************************************
452 * X11DRV_CLIPBOARD_ReadSelection
453 * Reads the contents of the X selection property into the WINE clipboard cache
454 * converting the selection into a format compatible with the windows clipboard
456 * This method is invoked only to read the contents of a the selection owned
457 * by an external application. i.e. when we do not own the X selection.
459 static BOOL X11DRV_CLIPBOARD_ReadSelection(UINT wFormat, Window w, Atom prop, Atom reqType)
461 Atom atype=AnyPropertyType;
463 unsigned long total,nitems,remain,itemSize,val_cnt;
464 long lRequestLength,bwc;
466 unsigned char* buffer;
467 LPWINE_CLIPFORMAT lpFormat;
469 HWND hWndClipWindow = GetOpenClipboardWindow();
475 TRACE("Reading X selection...\n");
477 TRACE("\tretrieving property %s from window %ld into %s\n",
478 TSXGetAtomName(display,reqType), (long)w, TSXGetAtomName(display,prop) );
481 * First request a zero length in order to figure out the request size.
483 if(TSXGetWindowProperty(display,w,prop,0,0,False, AnyPropertyType/*reqType*/,
484 &atype, &aformat, &nitems, &itemSize, &val) != Success)
486 WARN("\tcouldn't get property size\n");
490 /* Free zero length return data if any */
497 TRACE("\tretrieving %ld bytes...\n", itemSize * aformat/8);
498 lRequestLength = (itemSize * aformat/8)/4 + 1;
501 /* we want to read the property, but not it too large of chunks or
502 we could hang the cause problems. Lets go for 4k blocks */
504 if(TSXGetWindowProperty(display,w,prop,0,4096,False,
505 AnyPropertyType/*reqType*/,
506 &atype, &aformat, &nitems, &remain, &buffer)
509 WARN("\tcouldn't read property\n");
512 val = (char*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
514 memcpy(val,buffer,nitems*bwc);
517 for (total = nitems*bwc,val_cnt=0; remain;)
519 val_cnt +=nitems*bwc;
520 TSXGetWindowProperty(display, w, prop,
521 (total / 4), 4096, False,
522 AnyPropertyType, &atype,
523 &aformat, &nitems, &remain,
527 HeapReAlloc(GetProcessHeap(),0,val, total);
528 memcpy(&val[val_cnt], buffer, nitems*(aformat/8));
534 * Translate the X property into the appropriate Windows clipboard
535 * format, if possible.
537 if ( (reqType == XA_STRING)
538 && (atype == XA_STRING) && (aformat == 8) )
539 /* convert Unix text to CF_UNICODETEXT */
544 for(i=0; i <= nitems; i++)
545 if( val[i] == '\n' ) inlcount++;
547 if( (lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, nitems + inlcount + 1)) )
549 static UINT text_cp = (UINT)-1;
553 for(i=0,inlcount=0; i <= nitems; i++)
555 if( val[i] == '\n' ) lpstr[inlcount++]='\r';
556 lpstr[inlcount++]=val[i];
559 if(text_cp == (UINT)-1)
560 text_cp = PROFILE_GetWineIniInt("x11drv", "TextCP", CP_ACP);
562 count = MultiByteToWideChar(text_cp, 0, lpstr, -1, NULL, 0);
563 hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
566 WCHAR *textW = GlobalLock(hUnicodeText);
567 MultiByteToWideChar(text_cp, 0, lpstr, -1, textW, count);
568 GlobalUnlock(hUnicodeText);
569 if (!SetClipboardData(CF_UNICODETEXT, hUnicodeText))
571 ERR("Not SET! Need to free our own block\n");
572 GlobalFree(hUnicodeText);
576 HeapFree(GetProcessHeap(), 0, lpstr);
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 */
674 HeapFree(GetProcessHeap(),0,val);
678 /**************************************************************************
679 * X11DRV_CLIPBOARD_ReleaseSelection
681 * Release an XA_PRIMARY or XA_CLIPBOARD selection that we own, in response
682 * to a SelectionClear event.
683 * This can occur in response to another client grabbing the X selection.
684 * If the XA_CLIPBOARD selection is lost, we relinquish XA_PRIMARY as well.
686 void X11DRV_CLIPBOARD_ReleaseSelection(Atom selType, Window w, HWND hwnd)
688 Atom xaClipboard = TSXInternAtom(display, "CLIPBOARD", False);
689 int clearAllSelections = PROFILE_GetWineIniInt("Clipboard", "ClearAllSelections", 0);
691 /* w is the window that lost the selection
692 * selectionPrevWindow is nonzero if CheckSelection() was called.
695 TRACE("\tevent->window = %08x (sw = %08x, spw=%08x)\n",
696 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionPrevWindow );
698 if( selectionAcquired )
700 if( w == selectionWindow || selectionPrevWindow == None)
702 /* If we're losing the CLIPBOARD selection, or if the preferences in .winerc
703 * dictate that *all* selections should be cleared on loss of a selection,
704 * we must give up all the selections we own.
706 if ( clearAllSelections || (selType == xaClipboard) )
708 /* completely give up the selection */
709 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
711 /* We are completely giving up the selection.
712 * Make sure we can open the windows clipboard first. */
714 if ( !OpenClipboard(hwnd) )
717 * We can't empty the clipboard if we cant open it so abandon.
718 * Wine will think that it still owns the selection but this is
719 * safer than losing the selection without properly emptying
720 * the clipboard. Perhaps we should forcibly re-assert ownership
721 * of the CLIPBOARD selection in this case...
723 ERR("\tClipboard is busy. Could not give up selection!\n");
727 /* We really lost CLIPBOARD but want to voluntarily lose PRIMARY */
728 if ( (selType == xaClipboard)
729 && (selectionAcquired & S_PRIMARY) )
731 XSetSelectionOwner(display, XA_PRIMARY, None, CurrentTime);
734 /* We really lost PRIMARY but want to voluntarily lose CLIPBOARD */
735 if ( (selType == XA_PRIMARY)
736 && (selectionAcquired & S_CLIPBOARD) )
738 XSetSelectionOwner(display, xaClipboard, None, CurrentTime);
741 selectionWindow = None;
742 PrimarySelectionOwner = ClipboardSelectionOwner = 0;
744 /* Empty the windows clipboard.
745 * We should pretend that we still own the selection BEFORE calling
746 * EmptyClipboard() since otherwise this has the side effect of
747 * triggering X11DRV_CLIPBOARD_Acquire() and causing the X selection
748 * to be re-acquired by us!
750 selectionAcquired = (S_PRIMARY | S_CLIPBOARD);
754 /* Give up ownership of the windows clipboard */
755 CLIPBOARD_ReleaseOwner();
757 /* Reset the selection flags now that we are done */
758 selectionAcquired = S_NOSELECTION;
760 else if ( selType == XA_PRIMARY ) /* Give up only PRIMARY selection */
762 TRACE("Lost PRIMARY selection\n");
763 PrimarySelectionOwner = 0;
764 selectionAcquired &= ~S_PRIMARY; /* clear S_PRIMARY mask */
767 cSelectionTargets = 0;
769 /* but we'll keep existing data for internal use */
770 else if( w == selectionPrevWindow )
772 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
774 w = TSXGetSelectionOwner(display, XA_PRIMARY);
776 TSXSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
778 w = TSXGetSelectionOwner(display, xaClipboard);
780 TSXSetSelectionOwner(display, xaClipboard, selectionWindow, CurrentTime);
784 /* Signal to a selectionClearEvent listener if the selection is completely lost */
785 if (selectionClearEvent && !selectionAcquired)
787 TRACE("Lost all selections, signalling to selectionClearEvent listener\n");
788 SetEvent(selectionClearEvent);
791 selectionPrevWindow = None;
794 /**************************************************************************
795 * ReleaseClipboard (X11DRV.@)
796 * Voluntarily release all currently owned X selections
798 void X11DRV_ReleaseClipboard(void)
800 if( selectionAcquired )
803 Window savePrevWindow = selectionWindow;
804 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
805 BOOL bHasPrimarySelection = selectionAcquired & S_PRIMARY;
807 selectionAcquired = S_NOSELECTION;
808 selectionPrevWindow = selectionWindow;
809 selectionWindow = None;
811 TRACE("\tgiving up selection (spw = %08x)\n",
812 (unsigned)selectionPrevWindow);
816 TRACE("Releasing CLIPBOARD selection\n");
817 XSetSelectionOwner(display, xaClipboard, None, CurrentTime);
818 if( selectionPrevWindow )
819 while( !XCheckTypedWindowEvent( display, selectionPrevWindow,
820 SelectionClear, &xe ) );
822 if ( bHasPrimarySelection )
824 TRACE("Releasing XA_PRIMARY selection\n");
825 selectionPrevWindow = savePrevWindow; /* May be cleared in X11DRV_CLIPBOARD_ReleaseSelection */
826 XSetSelectionOwner(display, XA_PRIMARY, None, CurrentTime);
828 if( selectionPrevWindow )
829 while( !XCheckTypedWindowEvent( display, selectionPrevWindow,
830 SelectionClear, &xe ) );
835 /* Get rid of any Pixmap resources we may still have */
838 PROPERTY *prop = prop_head;
839 prop_head = prop->next;
840 XFreePixmap( display, prop->pixmap );
841 HeapFree( GetProcessHeap(), 0, prop );
845 /**************************************************************************
846 * AcquireClipboard (X11DRV.@)
848 void X11DRV_AcquireClipboard(void)
851 HWND hWndClipWindow = GetOpenClipboardWindow();
854 * Acquire X selection if we don't already own it.
855 * Note that we only acquire the selection if it hasn't been already
856 * acquired by us, and ignore the fact that another X window may be
857 * asserting ownership. The reason for this is we need *any* top level
858 * X window to hold selection ownership. The actual clipboard data requests
859 * are made via GetClipboardData from EVENT_SelectionRequest and this
860 * ensures that the real HWND owner services the request.
861 * If the owning X window gets destroyed the selection ownership is
862 * re-cycled to another top level X window in X11DRV_CLIPBOARD_ResetOwner.
866 if ( !(selectionAcquired == (S_PRIMARY | S_CLIPBOARD)) )
868 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
869 WND *tmpWnd = WIN_FindWndPtr( hWndClipWindow ? hWndClipWindow : AnyPopup() );
870 owner = X11DRV_WND_FindXWindow(tmpWnd );
871 WIN_ReleaseWndPtr(tmpWnd);
873 /* Grab PRIMARY selection if not owned */
874 if ( !(selectionAcquired & S_PRIMARY) )
875 TSXSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
877 /* Grab CLIPBOARD selection if not owned */
878 if ( !(selectionAcquired & S_CLIPBOARD) )
879 TSXSetSelectionOwner(display, xaClipboard, owner, CurrentTime);
881 if( TSXGetSelectionOwner(display,XA_PRIMARY) == owner )
882 selectionAcquired |= S_PRIMARY;
884 if( TSXGetSelectionOwner(display,xaClipboard) == owner)
885 selectionAcquired |= S_CLIPBOARD;
887 if (selectionAcquired)
889 selectionWindow = owner;
890 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
895 /**************************************************************************
896 * IsClipboardFormatAvailable (X11DRV.@)
898 * Checks if the specified format is available in the current selection
899 * Only invoked when WINE is not the selection owner
901 BOOL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
903 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
904 Window ownerPrimary = TSXGetSelectionOwner(display,XA_PRIMARY);
905 Window ownerClipboard = TSXGetSelectionOwner(display,xaClipboard);
907 TRACE("enter for %d\n", wFormat);
910 * If the selection has not been previously cached, or the selection has changed,
911 * try and cache the list of available selection targets from the current selection.
913 if ( !cSelectionTargets || (PrimarySelectionOwner != ownerPrimary)
914 || (ClipboardSelectionOwner != ownerClipboard) )
917 * First try cacheing the CLIPBOARD selection.
918 * If unavailable try PRIMARY.
920 if ( X11DRV_CLIPBOARD_CacheDataFormats(xaClipboard) == 0 )
922 X11DRV_CLIPBOARD_CacheDataFormats(XA_PRIMARY);
925 ClipboardSelectionOwner = ownerClipboard;
926 PrimarySelectionOwner = ownerPrimary;
929 /* Exit if there is no selection */
930 if ( !ownerClipboard && !ownerPrimary )
932 TRACE("There is no selection owner\n");
936 /* Check if the format is available in the clipboard cache */
937 if ( CLIPBOARD_IsPresent(wFormat) )
941 * Many X client apps (such as XTerminal) don't support being queried
942 * for the "TARGETS" target atom. To handle such clients we must actually
943 * try to convert the selection to the requested type.
945 if ( !cSelectionTargets )
946 return X11DRV_GetClipboardData( wFormat );
948 TRACE("There is no selection\n");
952 /**************************************************************************
953 * RegisterClipboardFormat (X11DRV.@)
955 * Registers a custom X clipboard format
956 * Returns: TRUE - success, FALSE - failure
958 BOOL X11DRV_RegisterClipboardFormat( 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 * IsSelectionOwner (X11DRV.@)
981 * Returns: TRUE - We(WINE) own the selection, FALSE - Selection not owned by us
983 BOOL X11DRV_IsSelectionOwner(void)
985 return selectionAcquired;
988 /**************************************************************************
989 * SetClipboardData (X11DRV.@)
991 * We don't need to do anything special here since the clipboard code
992 * maintains the cache.
995 void X11DRV_SetClipboardData(UINT wFormat)
997 /* Make sure we have acquired the X selection */
998 X11DRV_AcquireClipboard();
1001 /**************************************************************************
1002 * GetClipboardData (X11DRV.@)
1004 * This method is invoked only when we DO NOT own the X selection
1006 * NOTE: Clipboard driver get requests only for CF_UNICODETEXT data.
1007 * We always get the data from the selection client each time,
1008 * since we have no way of determining if the data in our cache is stale.
1010 BOOL X11DRV_GetClipboardData(UINT wFormat)
1012 BOOL bRet = selectionAcquired;
1013 HWND hWndClipWindow = GetOpenClipboardWindow();
1014 HWND hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
1016 LPWINE_CLIPFORMAT lpFormat;
1018 TRACE("%d\n", wFormat);
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 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 wine_tsx11_unlock();
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 );
1074 TRACE("Returning %d\n", bRet);
1079 /**************************************************************************
1080 * ResetSelectionOwner (X11DRV.@)
1082 * Called from DestroyWindow() to prevent X selection from being lost when
1083 * a top level window is destroyed, by switching ownership to another top
1085 * Any top level window can own the selection. See X11DRV_CLIPBOARD_Acquire
1086 * for a more detailed description of this.
1088 void X11DRV_ResetSelectionOwner(WND *pWnd, BOOL bFooBar)
1090 HWND hWndClipOwner = 0;
1091 Window XWnd = X11DRV_WND_GetXWindow(pWnd);
1093 BOOL bLostSelection = FALSE;
1095 /* There is nothing to do if we don't own the selection,
1096 * or if the X window which currently owns the selecion is different
1097 * from the one passed in.
1099 if ( !selectionAcquired || XWnd != selectionWindow
1100 || selectionWindow == None )
1103 if ( (bFooBar && XWnd) || (!bFooBar && !XWnd) )
1106 hWndClipOwner = GetClipboardOwner();
1107 xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
1109 TRACE("clipboard owner = %04x, selection window = %08x\n",
1110 hWndClipOwner, (unsigned)selectionWindow);
1112 /* now try to salvage current selection from being destroyed by X */
1114 TRACE("\tchecking %08x\n", (unsigned) XWnd);
1116 selectionPrevWindow = selectionWindow;
1117 selectionWindow = None;
1120 selectionWindow = X11DRV_WND_GetXWindow(pWnd->next);
1121 else if( pWnd->parent )
1122 if( pWnd->parent->child != pWnd )
1123 selectionWindow = X11DRV_WND_GetXWindow(pWnd->parent->child);
1125 if( selectionWindow != None )
1127 /* We must pretend that we don't own the selection while making the switch
1128 * since a SelectionClear event will be sent to the last owner.
1129 * If there is no owner X11DRV_CLIPBOARD_ReleaseSelection will do nothing.
1131 int saveSelectionState = selectionAcquired;
1132 selectionAcquired = False;
1134 TRACE("\tswitching selection from %08x to %08x\n",
1135 (unsigned)selectionPrevWindow, (unsigned)selectionWindow);
1137 /* Assume ownership for the PRIMARY and CLIPBOARD selection */
1138 if ( saveSelectionState & S_PRIMARY )
1139 TSXSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
1141 TSXSetSelectionOwner(display, xaClipboard, selectionWindow, CurrentTime);
1143 /* Restore the selection masks */
1144 selectionAcquired = saveSelectionState;
1146 /* Lose the selection if something went wrong */
1147 if ( ( (saveSelectionState & S_PRIMARY) &&
1148 (TSXGetSelectionOwner(display, XA_PRIMARY) != selectionWindow) )
1149 || (TSXGetSelectionOwner(display, xaClipboard) != selectionWindow) )
1151 bLostSelection = TRUE;
1156 /* Update selection state */
1157 if (saveSelectionState & S_PRIMARY)
1158 PrimarySelectionOwner = selectionWindow;
1160 ClipboardSelectionOwner = selectionWindow;
1165 bLostSelection = TRUE;
1172 /* Launch the clipboard server if the selection can no longer be recyled
1173 * to another top level window. */
1175 if ( !X11DRV_CLIPBOARD_LaunchServer() )
1177 /* Empty the windows clipboard if the server was not launched.
1178 * We should pretend that we still own the selection BEFORE calling
1179 * EmptyClipboard() since otherwise this has the side effect of
1180 * triggering X11DRV_CLIPBOARD_Acquire() and causing the X selection
1181 * to be re-acquired by us!
1184 TRACE("\tLost the selection! Emptying the clipboard...\n");
1187 selectionAcquired = (S_PRIMARY | S_CLIPBOARD);
1192 /* Give up ownership of the windows clipboard */
1193 CLIPBOARD_ReleaseOwner();
1196 selectionAcquired = S_NOSELECTION;
1197 ClipboardSelectionOwner = PrimarySelectionOwner = 0;
1198 selectionWindow = 0;
1202 /**************************************************************************
1203 * X11DRV_CLIPBOARD_RegisterPixmapResource
1204 * Registers a Pixmap resource which is to be associated with a property Atom.
1205 * When the property is destroyed we also destroy the Pixmap through the
1206 * PropertyNotify event.
1208 BOOL X11DRV_CLIPBOARD_RegisterPixmapResource( Atom property, Pixmap pixmap )
1210 PROPERTY *prop = HeapAlloc( GetProcessHeap(), 0, sizeof(*prop) );
1211 if (!prop) return FALSE;
1212 prop->atom = property;
1213 prop->pixmap = pixmap;
1214 prop->next = prop_head;
1219 /**************************************************************************
1220 * X11DRV_CLIPBOARD_FreeResources
1222 * Called from EVENT_PropertyNotify() to give us a chance to destroy
1223 * any resources associated with this property.
1225 void X11DRV_CLIPBOARD_FreeResources( Atom property )
1227 /* Do a simple linear search to see if we have a Pixmap resource
1228 * associated with this property and release it.
1230 PROPERTY **prop = &prop_head;
1234 if ((*prop)->atom == property)
1236 PROPERTY *next = (*prop)->next;
1237 XFreePixmap( display, (*prop)->pixmap );
1238 HeapFree( GetProcessHeap(), 0, *prop );
1241 else prop = &(*prop)->next;