2 * X11 clipboard windows driver
4 * Copyright 1994 Martin Ayotte
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 * This file contains the X specific implementation for the windows
26 * Wine's internal clipboard is exposed to external apps via the X
27 * selection mechanism.
28 * Currently the driver asserts ownership via two selection atoms:
29 * 1. PRIMARY(XA_PRIMARY)
32 * In our implementation, the CLIPBOARD selection takes precedence over PRIMARY,
33 * i.e. if a CLIPBOARD selection is available, it is used instead of PRIMARY.
34 * When Wine takes ownership of the clipboard, it takes ownership of BOTH selections.
35 * While giving up selection ownership, if the CLIPBOARD selection is lost,
36 * it will lose both PRIMARY and CLIPBOARD and empty the clipboard.
37 * However if only PRIMARY is lost, it will continue to hold the CLIPBOARD selection
38 * (leaving the clipboard cache content unaffected).
40 * Every format exposed via a windows clipboard format is also exposed through
41 * a corresponding X selection target. A selection target atom is synthesized
42 * whenever a new Windows clipboard format is registered via RegisterClipboardFormat,
43 * or when a built-in format is used for the first time.
44 * Windows native format are exposed by prefixing the format name with "<WCF>"
45 * This allows us to uniquely identify windows native formats exposed by other
48 * In order to allow external applications to query WINE for supported formats,
49 * we respond to the "TARGETS" selection target. (See EVENT_SelectionRequest
50 * for implementation) We use the same mechanism to query external clients for
51 * availability of a particular format, by caching the list of available targets
52 * by using the clipboard cache's "delayed render" mechanism. If a selection client
53 * does not support the "TARGETS" selection target, we actually attempt to retrieve
54 * the format requested as a fallback mechanism.
56 * Certain Windows native formats are automatically converted to X native formats
57 * and vice versa. If a native format is available in the selection, it takes
58 * precedence, in order to avoid unnecessary conversions.
72 #include "clipboard.h"
75 #include "wine/debug.h"
77 WINE_DEFAULT_DEBUG_CHANNEL(clipboard);
81 #define S_NOSELECTION 0
85 /* X selection context info */
87 static char _CLIPBOARD[] = "CLIPBOARD"; /* CLIPBOARD atom name */
88 static char FMT_PREFIX[] = "<WCF>"; /* Prefix for windows specific formats */
89 static int selectionAcquired = 0; /* Contains the current selection masks */
90 static Window selectionWindow = None; /* The top level X window which owns the selection */
91 static Window selectionPrevWindow = None; /* The last X window that owned the selection */
92 static Window PrimarySelectionOwner = None; /* The window which owns the primary selection */
93 static Window ClipboardSelectionOwner = None; /* The window which owns the clipboard selection */
94 static unsigned long cSelectionTargets = 0; /* Number of target formats reported by TARGETS selection */
95 static Atom selectionCacheSrc = XA_PRIMARY; /* The selection source from which the clipboard cache was filled */
96 static HANDLE selectionClearEvent = 0;/* Synchronization object used to block until server is started */
98 typedef struct tagPROPERTY
100 struct tagPROPERTY *next;
105 static PROPERTY *prop_head;
108 /**************************************************************************
109 * X11DRV_CLIPBOARD_MapPropertyToFormat
111 * Map an X selection property type atom name to a windows clipboard format ID
113 UINT X11DRV_CLIPBOARD_MapPropertyToFormat(char *itemFmtName)
116 * If the property name starts with FMT_PREFIX strip this off and
117 * get the ID for a custom Windows registered format with this name.
118 * We can also understand STRING, PIXMAP and BITMAP.
120 if ( NULL == itemFmtName )
122 else if ( 0 == strncmp(itemFmtName, FMT_PREFIX, strlen(FMT_PREFIX)) )
123 return RegisterClipboardFormatA(itemFmtName + strlen(FMT_PREFIX));
124 else if ( 0 == strcmp(itemFmtName, "STRING") )
125 return CF_UNICODETEXT;
126 else if ( 0 == strcmp(itemFmtName, "PIXMAP")
127 || 0 == strcmp(itemFmtName, "BITMAP") )
130 * Return CF_DIB as first preference, if WINE is the selection owner
131 * and if CF_DIB exists in the cache.
132 * If wine dowsn't own the selection we always return CF_DIB
134 if ( !X11DRV_IsSelectionOwner() )
136 else if ( CLIPBOARD_IsPresent(CF_DIB) )
142 WARN("\tNo mapping to Windows clipboard format for property %s\n", itemFmtName);
146 /**************************************************************************
147 * X11DRV_CLIPBOARD_MapFormatToProperty
149 * Map a windows clipboard format ID to an X selection property atom
151 Atom X11DRV_CLIPBOARD_MapFormatToProperty(UINT wFormat)
157 /* We support only CF_UNICODETEXT, other formats are synthesized */
170 * Request a PIXMAP, only if WINE is NOT the selection owner,
171 * AND the requested format is not in the cache.
173 if ( !X11DRV_IsSelectionOwner() && !CLIPBOARD_IsPresent(wFormat) )
178 /* Fall through to the default case in order to use the native format */
184 * If an X atom is registered for this format, return that
185 * Otherwise register a new atom.
188 char *fmtName = CLIPBOARD_GetFormatName(wFormat);
189 strcpy(str, FMT_PREFIX);
193 strncat(str, fmtName, sizeof(str) - strlen(FMT_PREFIX));
194 prop = TSXInternAtom(thread_display(), str, False);
201 TRACE("\tNo mapping to X property for Windows clipboard format %d(%s)\n",
202 wFormat, CLIPBOARD_GetFormatName(wFormat));
207 /**************************************************************************
208 * X11DRV_CLIPBOARD_IsNativeProperty
210 * Checks if a property is a native Wine property type
212 BOOL X11DRV_CLIPBOARD_IsNativeProperty(Atom prop)
214 char *itemFmtName = TSXGetAtomName(thread_display(), prop);
217 if ( 0 == strncmp(itemFmtName, FMT_PREFIX, strlen(FMT_PREFIX)) )
220 TSXFree(itemFmtName);
225 /**************************************************************************
226 * X11DRV_CLIPBOARD_LaunchServer
227 * Launches the clipboard server. This is called from X11DRV_CLIPBOARD_ResetOwner
228 * when the selection can no longer be recyled to another top level window.
229 * In order to make the selection persist after Wine shuts down a server
230 * process is launched which services subsequent selection requests.
232 BOOL X11DRV_CLIPBOARD_LaunchServer()
235 char clearSelection[8] = "0";
236 int persistent_selection = 1;
240 /* If persistant selection has been disabled in the .winerc Clipboard section,
241 * don't launch the server
243 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\Clipboard", &hkey))
246 DWORD type, count = sizeof(buffer);
247 if(!RegQueryValueExA(hkey, "PersistentSelection", 0, &type, buffer, &count))
248 persistent_selection = atoi(buffer);
250 /* Get the clear selection preference */
251 count = sizeof(clearSelection);
252 RegQueryValueExA(hkey, "ClearAllSelections", 0, &type, clearSelection, &count);
255 if ( !persistent_selection )
258 /* Start up persistant WINE X clipboard server process which will
259 * take ownership of the X selection and continue to service selection
260 * requests from other apps.
263 if(pipe(fd) == -1) return FALSE;
264 fcntl(fd[1], F_SETFD, 1); /* set close on exec */
266 selectionWindow = selectionPrevWindow;
269 /* NOTE: This code only executes in the context of the child process
270 * Do note make any Wine specific calls here.
273 char selMask[8], dbgClassMask[8];
276 sprintf(selMask, "%d", selectionAcquired);
278 /* Build the debug class mask to pass to the server, by inheriting
279 * the settings for the clipboard debug channel.
281 dbgClasses |= FIXME_ON(clipboard) ? 1 : 0;
282 dbgClasses |= ERR_ON(clipboard) ? 2 : 0;
283 dbgClasses |= WARN_ON(clipboard) ? 4 : 0;
284 dbgClasses |= TRACE_ON(clipboard) ? 8 : 0;
285 sprintf(dbgClassMask, "%d", dbgClasses);
287 /* Exec the clipboard server passing it the selection and debug class masks */
288 execl( BINDIR "/wineclipsrv", "wineclipsrv",
289 selMask, dbgClassMask, clearSelection, NULL );
290 execlp( "wineclipsrv", "wineclipsrv", selMask, dbgClassMask, clearSelection, NULL );
293 perror("Could not start Wine clipboard server");
294 write(fd[1], &err, sizeof(err));
295 _exit( 1 ); /* Exit the child process */
299 if(read(fd[0], &err, sizeof(err)) > 0) { /* exec failed */
305 /* Wait until the clipboard server acquires the selection.
306 * We must release the windows lock to enable Wine to process
307 * selection messages in response to the servers requests.
310 iWndsLocks = WIN_SuspendWndsLock();
312 /* We must wait until the server finishes acquiring the selection,
313 * before proceeding, otherwise the window which owns the selection
314 * will be destroyed prematurely!
315 * Create a non-signalled, auto-reset event which will be set by
316 * X11DRV_CLIPBOARD_ReleaseSelection, and wait until this gets
317 * signalled before proceeding.
320 if ( !(selectionClearEvent = CreateEventA(NULL, FALSE, FALSE, NULL)) )
321 ERR("Could not create wait object. Clipboard server won't start!\n");
324 /* Wait until we lose the selection, timing out after a minute */
325 DWORD start_time, timeout, elapsed, ret;
327 TRACE("Waiting for clipboard server to acquire selection\n");
330 start_time = GetTickCount();
334 ret = MsgWaitForMultipleObjects( 1, &selectionClearEvent, FALSE, timeout - elapsed, QS_ALLINPUT );
335 if (ret != WAIT_OBJECT_0+1)
337 elapsed = GetTickCount() - start_time;
338 if (elapsed > timeout)
342 if ( ret != WAIT_OBJECT_0 )
343 TRACE("Server could not acquire selection, or a timeout occurred!\n");
345 TRACE("Server successfully acquired selection\n");
347 /* Release the event */
348 CloseHandle(selectionClearEvent);
349 selectionClearEvent = 0;
352 WIN_RestoreWndsLock(iWndsLocks);
358 /**************************************************************************
359 * X11DRV_CLIPBOARD_CacheDataFormats
361 * Caches the list of data formats available from the current selection.
362 * This queries the selection owner for the TARGETS property and saves all
363 * reported property types.
365 int X11DRV_CLIPBOARD_CacheDataFormats( Atom SelectionName )
367 Display *display = thread_display();
369 HWND hWndClipWindow = GetOpenClipboardWindow();
372 Atom atype=AnyPropertyType;
374 unsigned long remain;
375 Atom* targetList=NULL;
377 Window ownerSelection = 0;
381 * Empty the clipboard cache
383 CLIPBOARD_EmptyCache(TRUE);
385 cSelectionTargets = 0;
386 selectionCacheSrc = SelectionName;
388 hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
390 ownerSelection = TSXGetSelectionOwner(display, SelectionName);
391 if ( !hWnd || (ownerSelection == None) )
392 return cSelectionTargets;
395 * Query the selection owner for the TARGETS property
397 w = X11DRV_get_whole_window( GetAncestor(hWnd,GA_ROOT) );
399 aTargets = TSXInternAtom(display, "TARGETS", False);
401 TRACE("Requesting TARGETS selection for '%s' (owner=%08x)...\n",
402 TSXGetAtomName(display, selectionCacheSrc), (unsigned)ownerSelection );
404 XConvertSelection(display, selectionCacheSrc, aTargets,
405 TSXInternAtom(display, "SELECTION_DATA", False),
409 * Wait until SelectionNotify is received
413 if( XCheckTypedWindowEvent(display, w, SelectionNotify, &xe) )
414 if( xe.xselection.selection == selectionCacheSrc )
419 /* Verify that the selection returned a valid TARGETS property */
420 if ( (xe.xselection.target != aTargets)
421 || (xe.xselection.property == None) )
423 TRACE("\tExit, could not retrieve TARGETS\n");
424 return cSelectionTargets;
427 /* Read the TARGETS property contents */
428 if(TSXGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
429 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat,
430 &cSelectionTargets, &remain, (unsigned char**)&targetList) != Success)
431 TRACE("\tCouldn't read TARGETS property\n");
434 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
435 TSXGetAtomName(display,atype),aformat,cSelectionTargets, remain);
437 * The TARGETS property should have returned us a list of atoms
438 * corresponding to each selection target format supported.
440 if( (atype == XA_ATOM || atype == aTargets) && aformat == 32 )
443 LPWINE_CLIPFORMAT lpFormat;
445 /* Cache these formats in the clipboard cache */
447 for (i = 0; i < cSelectionTargets; i++)
449 char *itemFmtName = TSXGetAtomName(display, targetList[i]);
450 UINT wFormat = X11DRV_CLIPBOARD_MapPropertyToFormat(itemFmtName);
453 * If the clipboard format maps to a Windows format, simply store
454 * the atom identifier and record its availablity status
455 * in the clipboard cache.
459 lpFormat = CLIPBOARD_LookupFormat( wFormat );
461 /* Don't replace if the property already cached is a native format,
462 * or if a PIXMAP is being replaced by a BITMAP.
464 if (lpFormat->wDataPresent &&
465 ( X11DRV_CLIPBOARD_IsNativeProperty(lpFormat->drvData)
466 || (lpFormat->drvData == XA_PIXMAP && targetList[i] == XA_BITMAP) )
469 TRACE("\tAtom# %d: '%s' --> FormatID(%d) %s (Skipped)\n",
470 i, itemFmtName, wFormat, lpFormat->Name);
474 lpFormat->wDataPresent = 1;
475 lpFormat->drvData = targetList[i];
476 TRACE("\tAtom# %d: '%s' --> FormatID(%d) %s\n",
477 i, itemFmtName, wFormat, lpFormat->Name);
481 TSXFree(itemFmtName);
485 /* Free the list of targets */
489 return cSelectionTargets;
492 /**************************************************************************
493 * X11DRV_CLIPBOARD_ReadSelection
494 * Reads the contents of the X selection property into the WINE clipboard cache
495 * converting the selection into a format compatible with the windows clipboard
497 * This method is invoked only to read the contents of a the selection owned
498 * by an external application. i.e. when we do not own the X selection.
500 static BOOL X11DRV_CLIPBOARD_ReadSelection(UINT wFormat, Window w, Atom prop, Atom reqType)
502 Display *display = thread_display();
503 Atom atype=AnyPropertyType;
505 unsigned long total,nitems,remain,itemSize,val_cnt;
506 long lRequestLength,bwc;
508 unsigned char* buffer;
509 LPWINE_CLIPFORMAT lpFormat;
511 HWND hWndClipWindow = GetOpenClipboardWindow();
517 TRACE("Reading X selection...\n");
519 TRACE("\tretrieving property %s from window %ld into %s\n",
520 TSXGetAtomName(display,reqType), (long)w, TSXGetAtomName(display,prop) );
523 * First request a zero length in order to figure out the request size.
525 if(TSXGetWindowProperty(display,w,prop,0,0,False, AnyPropertyType/*reqType*/,
526 &atype, &aformat, &nitems, &itemSize, &val) != Success)
528 WARN("\tcouldn't get property size\n");
532 /* Free zero length return data if any */
539 TRACE("\tretrieving %ld bytes...\n", itemSize * aformat/8);
540 lRequestLength = (itemSize * aformat/8)/4 + 1;
543 /* we want to read the property, but not it too large of chunks or
544 we could hang the cause problems. Lets go for 4k blocks */
546 if(TSXGetWindowProperty(display,w,prop,0,4096,False,
547 AnyPropertyType/*reqType*/,
548 &atype, &aformat, &nitems, &remain, &buffer)
551 WARN("\tcouldn't read property\n");
554 val = (char*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
556 memcpy(val,buffer,nitems*bwc);
559 for (total = nitems*bwc,val_cnt=0; remain;)
561 val_cnt +=nitems*bwc;
562 TSXGetWindowProperty(display, w, prop,
563 (total / 4), 4096, False,
564 AnyPropertyType, &atype,
565 &aformat, &nitems, &remain,
569 HeapReAlloc(GetProcessHeap(),0,val, total);
570 memcpy(&val[val_cnt], buffer, nitems*(aformat/8));
576 * Translate the X property into the appropriate Windows clipboard
577 * format, if possible.
579 if ( (reqType == XA_STRING)
580 && (atype == XA_STRING) && (aformat == 8) )
581 /* convert Unix text to CF_UNICODETEXT */
586 for(i=0; i <= nitems; i++)
587 if( val[i] == '\n' ) inlcount++;
589 if( (lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, nitems + inlcount + 1)) )
591 static UINT text_cp = (UINT)-1;
595 for(i=0,inlcount=0; i <= nitems; i++)
597 if( val[i] == '\n' ) lpstr[inlcount++]='\r';
598 lpstr[inlcount++]=val[i];
601 if(text_cp == (UINT)-1)
606 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\x11drv", &hkey))
609 DWORD type, count = sizeof(buf);
610 if(!RegQueryValueExA(hkey, "TextCP", 0, &type, buf, &count))
616 count = MultiByteToWideChar(text_cp, 0, lpstr, -1, NULL, 0);
617 hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
620 WCHAR *textW = GlobalLock(hUnicodeText);
621 MultiByteToWideChar(text_cp, 0, lpstr, -1, textW, count);
622 GlobalUnlock(hUnicodeText);
623 if (!SetClipboardData(CF_UNICODETEXT, hUnicodeText))
625 ERR("Not SET! Need to free our own block\n");
626 GlobalFree(hUnicodeText);
630 HeapFree(GetProcessHeap(), 0, lpstr);
633 else if ( reqType == XA_PIXMAP || reqType == XA_BITMAP ) /* treat PIXMAP as CF_DIB or CF_BITMAP */
635 /* Get the first pixmap handle passed to us */
636 Pixmap *pPixmap = (Pixmap *)val;
637 HANDLE hTargetImage = 0; /* Handle to store the converted bitmap or DIB */
639 if (aformat != 32 || nitems < 1 || atype != XA_PIXMAP
640 || (wFormat != CF_BITMAP && wFormat != CF_DIB))
642 WARN("\tUnimplemented format conversion request\n");
646 if ( wFormat == CF_BITMAP )
648 /* For CF_BITMAP requests we must return an HBITMAP */
649 hTargetImage = X11DRV_BITMAP_CreateBitmapFromPixmap(*pPixmap, TRUE);
651 else if (wFormat == CF_DIB)
653 HWND hwnd = GetOpenClipboardWindow();
654 HDC hdc = GetDC(hwnd);
656 /* For CF_DIB requests we must return an HGLOBAL storing a packed DIB */
657 hTargetImage = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc, TRUE);
659 ReleaseDC(hwnd, hdc);
664 WARN("PIXMAP conversion failed!\n" );
668 /* Delete previous clipboard data */
669 lpFormat = CLIPBOARD_LookupFormat(wFormat);
670 if (lpFormat->wDataPresent && (lpFormat->hData16 || lpFormat->hData32))
671 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
673 /* Update the clipboard record */
674 lpFormat->wDataPresent = 1;
675 lpFormat->hData32 = hTargetImage;
676 lpFormat->hData16 = 0;
681 /* For native properties simply copy the X data without conversion */
682 else if (X11DRV_CLIPBOARD_IsNativeProperty(reqType)) /* <WCF>* */
684 HANDLE hClipData = 0;
686 int cBytes = nitems * aformat/8;
690 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
691 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cBytes );
692 if( (lpClipData = GlobalLock(hClipData)) )
694 memcpy(lpClipData, val, cBytes);
695 GlobalUnlock(hClipData);
703 /* delete previous clipboard record if any */
704 lpFormat = CLIPBOARD_LookupFormat(wFormat);
705 if (lpFormat->wDataPresent || lpFormat->hData16 || lpFormat->hData32)
706 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
708 /* Update the clipboard record */
709 lpFormat->wDataPresent = 1;
710 lpFormat->hData32 = hClipData;
711 lpFormat->hData16 = 0;
718 WARN("\tUnimplemented format conversion request\n");
723 /* Delete the property on the window now that we are done
724 * This will send a PropertyNotify event to the selection owner. */
725 TSXDeleteProperty(display,w,prop);
727 /* Free the retrieved property data */
728 HeapFree(GetProcessHeap(),0,val);
732 /**************************************************************************
733 * X11DRV_CLIPBOARD_ReleaseSelection
735 * Release an XA_PRIMARY or XA_CLIPBOARD selection that we own, in response
736 * to a SelectionClear event.
737 * This can occur in response to another client grabbing the X selection.
738 * If the XA_CLIPBOARD selection is lost, we relinquish XA_PRIMARY as well.
740 void X11DRV_CLIPBOARD_ReleaseSelection(Atom selType, Window w, HWND hwnd)
742 Display *display = thread_display();
743 Atom xaClipboard = TSXInternAtom(display, "CLIPBOARD", False);
744 int clearAllSelections = 0;
747 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\Clipboard", &hkey))
750 DWORD type, count = sizeof(buffer);
751 if(!RegQueryValueExA(hkey, "ClearAllSelections", 0, &type, buffer, &count))
752 clearAllSelections = atoi(buffer);
756 /* w is the window that lost the selection
757 * selectionPrevWindow is nonzero if CheckSelection() was called.
760 TRACE("\tevent->window = %08x (sw = %08x, spw=%08x)\n",
761 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionPrevWindow );
763 if( selectionAcquired )
765 if( w == selectionWindow || selectionPrevWindow == None)
767 /* If we're losing the CLIPBOARD selection, or if the preferences in .winerc
768 * dictate that *all* selections should be cleared on loss of a selection,
769 * we must give up all the selections we own.
771 if ( clearAllSelections || (selType == xaClipboard) )
773 /* completely give up the selection */
774 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
776 /* We are completely giving up the selection.
777 * Make sure we can open the windows clipboard first. */
779 if ( !OpenClipboard(hwnd) )
782 * We can't empty the clipboard if we cant open it so abandon.
783 * Wine will think that it still owns the selection but this is
784 * safer than losing the selection without properly emptying
785 * the clipboard. Perhaps we should forcibly re-assert ownership
786 * of the CLIPBOARD selection in this case...
788 ERR("\tClipboard is busy. Could not give up selection!\n");
792 /* We really lost CLIPBOARD but want to voluntarily lose PRIMARY */
793 if ( (selType == xaClipboard)
794 && (selectionAcquired & S_PRIMARY) )
796 XSetSelectionOwner(display, XA_PRIMARY, None, CurrentTime);
799 /* We really lost PRIMARY but want to voluntarily lose CLIPBOARD */
800 if ( (selType == XA_PRIMARY)
801 && (selectionAcquired & S_CLIPBOARD) )
803 XSetSelectionOwner(display, xaClipboard, None, CurrentTime);
806 selectionWindow = None;
807 PrimarySelectionOwner = ClipboardSelectionOwner = 0;
809 /* Empty the windows clipboard.
810 * We should pretend that we still own the selection BEFORE calling
811 * EmptyClipboard() since otherwise this has the side effect of
812 * triggering X11DRV_CLIPBOARD_Acquire() and causing the X selection
813 * to be re-acquired by us!
815 selectionAcquired = (S_PRIMARY | S_CLIPBOARD);
819 /* Give up ownership of the windows clipboard */
820 CLIPBOARD_ReleaseOwner();
822 /* Reset the selection flags now that we are done */
823 selectionAcquired = S_NOSELECTION;
825 else if ( selType == XA_PRIMARY ) /* Give up only PRIMARY selection */
827 TRACE("Lost PRIMARY selection\n");
828 PrimarySelectionOwner = 0;
829 selectionAcquired &= ~S_PRIMARY; /* clear S_PRIMARY mask */
832 cSelectionTargets = 0;
834 /* but we'll keep existing data for internal use */
835 else if( w == selectionPrevWindow )
837 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
839 w = TSXGetSelectionOwner(display, XA_PRIMARY);
841 TSXSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
843 w = TSXGetSelectionOwner(display, xaClipboard);
845 TSXSetSelectionOwner(display, xaClipboard, selectionWindow, CurrentTime);
849 /* Signal to a selectionClearEvent listener if the selection is completely lost */
850 if (selectionClearEvent && !selectionAcquired)
852 TRACE("Lost all selections, signalling to selectionClearEvent listener\n");
853 SetEvent(selectionClearEvent);
856 selectionPrevWindow = None;
859 /**************************************************************************
860 * ReleaseClipboard (X11DRV.@)
861 * Voluntarily release all currently owned X selections
863 void X11DRV_ReleaseClipboard(void)
865 Display *display = thread_display();
866 if( selectionAcquired )
869 Window savePrevWindow = selectionWindow;
870 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
871 BOOL bHasPrimarySelection = selectionAcquired & S_PRIMARY;
873 selectionAcquired = S_NOSELECTION;
874 selectionPrevWindow = selectionWindow;
875 selectionWindow = None;
877 TRACE("\tgiving up selection (spw = %08x)\n",
878 (unsigned)selectionPrevWindow);
882 TRACE("Releasing CLIPBOARD selection\n");
883 XSetSelectionOwner(display, xaClipboard, None, CurrentTime);
884 if( selectionPrevWindow )
885 while( !XCheckTypedWindowEvent( display, selectionPrevWindow,
886 SelectionClear, &xe ) );
888 if ( bHasPrimarySelection )
890 TRACE("Releasing XA_PRIMARY selection\n");
891 selectionPrevWindow = savePrevWindow; /* May be cleared in X11DRV_CLIPBOARD_ReleaseSelection */
892 XSetSelectionOwner(display, XA_PRIMARY, None, CurrentTime);
894 if( selectionPrevWindow )
895 while( !XCheckTypedWindowEvent( display, selectionPrevWindow,
896 SelectionClear, &xe ) );
901 /* Get rid of any Pixmap resources we may still have */
904 PROPERTY *prop = prop_head;
905 prop_head = prop->next;
906 XFreePixmap( gdi_display, prop->pixmap );
907 HeapFree( GetProcessHeap(), 0, prop );
911 /**************************************************************************
912 * AcquireClipboard (X11DRV.@)
914 void X11DRV_AcquireClipboard(void)
916 Display *display = thread_display();
918 HWND hWndClipWindow = GetOpenClipboardWindow();
921 * Acquire X selection if we don't already own it.
922 * Note that we only acquire the selection if it hasn't been already
923 * acquired by us, and ignore the fact that another X window may be
924 * asserting ownership. The reason for this is we need *any* top level
925 * X window to hold selection ownership. The actual clipboard data requests
926 * are made via GetClipboardData from EVENT_SelectionRequest and this
927 * ensures that the real HWND owner services the request.
928 * If the owning X window gets destroyed the selection ownership is
929 * re-cycled to another top level X window in X11DRV_CLIPBOARD_ResetOwner.
933 if ( !(selectionAcquired == (S_PRIMARY | S_CLIPBOARD)) )
935 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
936 owner = X11DRV_get_whole_window( GetAncestor( hWndClipWindow ? hWndClipWindow : AnyPopup(),
939 /* Grab PRIMARY selection if not owned */
940 if ( !(selectionAcquired & S_PRIMARY) )
941 TSXSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
943 /* Grab CLIPBOARD selection if not owned */
944 if ( !(selectionAcquired & S_CLIPBOARD) )
945 TSXSetSelectionOwner(display, xaClipboard, owner, CurrentTime);
947 if( TSXGetSelectionOwner(display,XA_PRIMARY) == owner )
948 selectionAcquired |= S_PRIMARY;
950 if( TSXGetSelectionOwner(display,xaClipboard) == owner)
951 selectionAcquired |= S_CLIPBOARD;
953 if (selectionAcquired)
955 selectionWindow = owner;
956 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
961 /**************************************************************************
962 * IsClipboardFormatAvailable (X11DRV.@)
964 * Checks if the specified format is available in the current selection
965 * Only invoked when WINE is not the selection owner
967 BOOL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
969 Display *display = thread_display();
970 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
971 Window ownerPrimary = TSXGetSelectionOwner(display,XA_PRIMARY);
972 Window ownerClipboard = TSXGetSelectionOwner(display,xaClipboard);
974 TRACE("enter for %d\n", wFormat);
977 * If the selection has not been previously cached, or the selection has changed,
978 * try and cache the list of available selection targets from the current selection.
980 if ( !cSelectionTargets || (PrimarySelectionOwner != ownerPrimary)
981 || (ClipboardSelectionOwner != ownerClipboard) )
984 * First try caching the CLIPBOARD selection.
985 * If unavailable try PRIMARY.
987 if ( X11DRV_CLIPBOARD_CacheDataFormats(xaClipboard) == 0 )
989 X11DRV_CLIPBOARD_CacheDataFormats(XA_PRIMARY);
992 ClipboardSelectionOwner = ownerClipboard;
993 PrimarySelectionOwner = ownerPrimary;
996 /* Exit if there is no selection */
997 if ( !ownerClipboard && !ownerPrimary )
999 TRACE("There is no selection owner\n");
1003 /* Check if the format is available in the clipboard cache */
1004 if ( CLIPBOARD_IsPresent(wFormat) )
1008 * Many X client apps (such as XTerminal) don't support being queried
1009 * for the "TARGETS" target atom. To handle such clients we must actually
1010 * try to convert the selection to the requested type.
1012 if ( !cSelectionTargets )
1013 return X11DRV_GetClipboardData( wFormat );
1015 TRACE("There is no selection\n");
1019 /**************************************************************************
1020 * RegisterClipboardFormat (X11DRV.@)
1022 * Registers a custom X clipboard format
1023 * Returns: TRUE - success, FALSE - failure
1025 BOOL X11DRV_RegisterClipboardFormat( LPCSTR FormatName )
1027 Display *display = thread_display();
1032 * If an X atom is registered for this format, return that
1033 * Otherwise register a new atom.
1037 /* Add a WINE specific prefix to the format */
1038 strcpy(str, FMT_PREFIX);
1039 strncat(str, FormatName, sizeof(str) - strlen(FMT_PREFIX));
1040 prop = TSXInternAtom(display, str, False);
1043 return (prop) ? TRUE : FALSE;
1046 /**************************************************************************
1047 * IsSelectionOwner (X11DRV.@)
1049 * Returns: TRUE - We(WINE) own the selection, FALSE - Selection not owned by us
1051 BOOL X11DRV_IsSelectionOwner(void)
1053 return selectionAcquired;
1056 /**************************************************************************
1057 * SetClipboardData (X11DRV.@)
1059 * We don't need to do anything special here since the clipboard code
1060 * maintains the cache.
1063 void X11DRV_SetClipboardData(UINT wFormat)
1065 /* Make sure we have acquired the X selection */
1066 X11DRV_AcquireClipboard();
1069 /**************************************************************************
1070 * GetClipboardData (X11DRV.@)
1072 * This method is invoked only when we DO NOT own the X selection
1074 * NOTE: Clipboard driver get requests only for CF_UNICODETEXT data.
1075 * We always get the data from the selection client each time,
1076 * since we have no way of determining if the data in our cache is stale.
1078 BOOL X11DRV_GetClipboardData(UINT wFormat)
1080 Display *display = thread_display();
1081 BOOL bRet = selectionAcquired;
1082 HWND hWndClipWindow = GetOpenClipboardWindow();
1083 HWND hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
1084 LPWINE_CLIPFORMAT lpFormat;
1086 TRACE("%d\n", wFormat);
1088 if (!selectionAcquired)
1092 Window w = X11DRV_get_whole_window( GetAncestor( hWnd, GA_ROOT ));
1095 FIXME("No parent win found %x %x\n", hWnd, hWndClipWindow);
1099 /* Map the format ID requested to an X selection property.
1100 * If the format is in the cache, use the atom associated
1104 lpFormat = CLIPBOARD_LookupFormat( wFormat );
1105 if (lpFormat && lpFormat->wDataPresent && lpFormat->drvData)
1106 propRequest = (Atom)lpFormat->drvData;
1108 propRequest = X11DRV_CLIPBOARD_MapFormatToProperty(wFormat);
1112 TRACE("Requesting %s selection from %s...\n",
1113 TSXGetAtomName(display, propRequest),
1114 TSXGetAtomName(display, selectionCacheSrc) );
1116 XConvertSelection(display, selectionCacheSrc, propRequest,
1117 TSXInternAtom(display, "SELECTION_DATA", False),
1120 /* wait until SelectionNotify is received */
1124 if( XCheckTypedWindowEvent(display, w, SelectionNotify, &xe) )
1125 if( xe.xselection.selection == selectionCacheSrc )
1128 wine_tsx11_unlock();
1131 * Read the contents of the X selection property into WINE's
1132 * clipboard cache converting the selection to be compatible if possible.
1134 bRet = X11DRV_CLIPBOARD_ReadSelection( wFormat,
1135 xe.xselection.requestor,
1136 xe.xselection.property,
1137 xe.xselection.target);
1142 TRACE("\tpresent %s = %i\n", CLIPBOARD_GetFormatName(wFormat), bRet );
1145 TRACE("Returning %d\n", bRet);
1150 /**************************************************************************
1151 * ResetSelectionOwner (X11DRV.@)
1153 * Called from DestroyWindow() to prevent X selection from being lost when
1154 * a top level window is destroyed, by switching ownership to another top
1156 * Any top level window can own the selection. See X11DRV_CLIPBOARD_Acquire
1157 * for a more detailed description of this.
1159 void X11DRV_ResetSelectionOwner(HWND hwnd, BOOL bFooBar)
1161 Display *display = thread_display();
1162 HWND hWndClipOwner = 0;
1164 Window XWnd = X11DRV_get_whole_window(hwnd);
1166 BOOL bLostSelection = FALSE;
1168 /* There is nothing to do if we don't own the selection,
1169 * or if the X window which currently owns the selecion is different
1170 * from the one passed in.
1172 if ( !selectionAcquired || XWnd != selectionWindow
1173 || selectionWindow == None )
1176 if ( (bFooBar && XWnd) || (!bFooBar && !XWnd) )
1179 hWndClipOwner = GetClipboardOwner();
1180 xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
1182 TRACE("clipboard owner = %04x, selection window = %08x\n",
1183 hWndClipOwner, (unsigned)selectionWindow);
1185 /* now try to salvage current selection from being destroyed by X */
1187 TRACE("\tchecking %08x\n", (unsigned) XWnd);
1189 selectionPrevWindow = selectionWindow;
1190 selectionWindow = None;
1192 if (!(tmp = GetWindow( hwnd, GW_HWNDNEXT ))) tmp = GetWindow( hwnd, GW_HWNDFIRST );
1193 if (tmp && tmp != hwnd) selectionWindow = X11DRV_get_whole_window(tmp);
1195 if( selectionWindow != None )
1197 /* We must pretend that we don't own the selection while making the switch
1198 * since a SelectionClear event will be sent to the last owner.
1199 * If there is no owner X11DRV_CLIPBOARD_ReleaseSelection will do nothing.
1201 int saveSelectionState = selectionAcquired;
1202 selectionAcquired = False;
1204 TRACE("\tswitching selection from %08x to %08x\n",
1205 (unsigned)selectionPrevWindow, (unsigned)selectionWindow);
1207 /* Assume ownership for the PRIMARY and CLIPBOARD selection */
1208 if ( saveSelectionState & S_PRIMARY )
1209 TSXSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
1211 TSXSetSelectionOwner(display, xaClipboard, selectionWindow, CurrentTime);
1213 /* Restore the selection masks */
1214 selectionAcquired = saveSelectionState;
1216 /* Lose the selection if something went wrong */
1217 if ( ( (saveSelectionState & S_PRIMARY) &&
1218 (TSXGetSelectionOwner(display, XA_PRIMARY) != selectionWindow) )
1219 || (TSXGetSelectionOwner(display, xaClipboard) != selectionWindow) )
1221 bLostSelection = TRUE;
1226 /* Update selection state */
1227 if (saveSelectionState & S_PRIMARY)
1228 PrimarySelectionOwner = selectionWindow;
1230 ClipboardSelectionOwner = selectionWindow;
1235 bLostSelection = TRUE;
1242 /* Launch the clipboard server if the selection can no longer be recyled
1243 * to another top level window. */
1245 if ( !X11DRV_CLIPBOARD_LaunchServer() )
1247 /* Empty the windows clipboard if the server was not launched.
1248 * We should pretend that we still own the selection BEFORE calling
1249 * EmptyClipboard() since otherwise this has the side effect of
1250 * triggering X11DRV_CLIPBOARD_Acquire() and causing the X selection
1251 * to be re-acquired by us!
1254 TRACE("\tLost the selection! Emptying the clipboard...\n");
1257 selectionAcquired = (S_PRIMARY | S_CLIPBOARD);
1262 /* Give up ownership of the windows clipboard */
1263 CLIPBOARD_ReleaseOwner();
1266 selectionAcquired = S_NOSELECTION;
1267 ClipboardSelectionOwner = PrimarySelectionOwner = 0;
1268 selectionWindow = 0;
1272 /**************************************************************************
1273 * X11DRV_CLIPBOARD_RegisterPixmapResource
1274 * Registers a Pixmap resource which is to be associated with a property Atom.
1275 * When the property is destroyed we also destroy the Pixmap through the
1276 * PropertyNotify event.
1278 BOOL X11DRV_CLIPBOARD_RegisterPixmapResource( Atom property, Pixmap pixmap )
1280 PROPERTY *prop = HeapAlloc( GetProcessHeap(), 0, sizeof(*prop) );
1281 if (!prop) return FALSE;
1282 prop->atom = property;
1283 prop->pixmap = pixmap;
1284 prop->next = prop_head;
1289 /**************************************************************************
1290 * X11DRV_CLIPBOARD_FreeResources
1292 * Called from EVENT_PropertyNotify() to give us a chance to destroy
1293 * any resources associated with this property.
1295 void X11DRV_CLIPBOARD_FreeResources( Atom property )
1297 /* Do a simple linear search to see if we have a Pixmap resource
1298 * associated with this property and release it.
1300 PROPERTY **prop = &prop_head;
1304 if ((*prop)->atom == property)
1306 PROPERTY *next = (*prop)->next;
1307 XFreePixmap( gdi_display, (*prop)->pixmap );
1308 HeapFree( GetProcessHeap(), 0, *prop );
1311 else prop = &(*prop)->next;