Allow for zero-length string selections.
[wine.git] / windows / x11drv / clipboard.c
blob8434793dcff15221a85471b619b712b34ccf219a
1 /*
2 * X11 clipboard windows driver
4 * Copyright 1994 Martin Ayotte
5 * 1996 Alex Korobka
6 * 1999 Noel Borthwick
8 * NOTES:
9 * This file contains the X specific implementation for the windows
10 * Clipboard API.
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)
16 * 2. CLIPBOARD
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
32 * running WINE apps.
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.
48 #include "ts_xlib.h"
50 #include <string.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <unistd.h>
54 #include <fcntl.h>
56 #include "clipboard.h"
57 #include "win.h"
58 #include "x11drv.h"
59 #include "options.h"
60 #include "debugtools.h"
62 DEFAULT_DEBUG_CHANNEL(clipboard);
64 /* Selection masks */
66 #define S_NOSELECTION 0
67 #define S_PRIMARY 1
68 #define S_CLIPBOARD 2
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;
86 Atom atom;
87 Pixmap pixmap;
88 } PROPERTY;
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 )
106 return 0;
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_OEMTEXT;
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() )
120 return CF_DIB;
121 else if ( CLIPBOARD_IsPresent(CF_DIB) )
122 return CF_DIB;
123 else
124 return CF_BITMAP;
127 WARN("\tNo mapping to Windows clipboard format for property %s\n", itemFmtName);
128 return 0;
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)
138 Atom prop = None;
140 switch (wFormat)
142 case CF_OEMTEXT:
143 case CF_TEXT:
144 prop = XA_STRING;
145 break;
147 case CF_DIB:
148 case CF_BITMAP:
151 * Request a PIXMAP, only if WINE is NOT the selection owner,
152 * AND the requested format is not in the cache.
154 if ( !X11DRV_IsSelectionOwner() && !CLIPBOARD_IsPresent(wFormat) )
156 prop = XA_PIXMAP;
157 break;
159 /* Fall thru to the default case in order to use the native format */
162 default:
165 * If an X atom is registered for this format, return that
166 * Otherwise register a new atom.
168 char str[256];
169 char *fmtName = CLIPBOARD_GetFormatName(wFormat);
170 strcpy(str, FMT_PREFIX);
172 if (fmtName)
174 strncat(str, fmtName, sizeof(str) - strlen(FMT_PREFIX));
175 prop = TSXInternAtom(display, str, False);
177 break;
181 if (prop == None)
182 TRACE("\tNo mapping to X property for Windows clipboard format %d(%s)\n",
183 wFormat, CLIPBOARD_GetFormatName(wFormat));
185 return prop;
188 /**************************************************************************
189 * X11DRV_CLIPBOARD_IsNativeProperty
191 * Checks if a property is a native property type
193 BOOL X11DRV_CLIPBOARD_IsNativeProperty(Atom prop)
195 char *itemFmtName = TSXGetAtomName(display, prop);
196 BOOL bRet = FALSE;
198 if ( 0 == strncmp(itemFmtName, FMT_PREFIX, strlen(FMT_PREFIX)) )
199 bRet = TRUE;
201 TSXFree(itemFmtName);
202 return bRet;
206 /**************************************************************************
207 * X11DRV_CLIPBOARD_LaunchServer
208 * Launches the clipboard server. This is called from X11DRV_CLIPBOARD_ResetOwner
209 * when the selection can no longer be recyled to another top level window.
210 * In order to make the selection persist after Wine shuts down a server
211 * process is launched which services subsequent selection requests.
213 BOOL X11DRV_CLIPBOARD_LaunchServer()
215 int iWndsLocks;
217 /* If persistant selection has been disabled in the .winerc Clipboard section,
218 * don't launch the server
220 if ( !PROFILE_GetWineIniInt("Clipboard", "PersistentSelection", 1) )
221 return FALSE;
223 /* Start up persistant WINE X clipboard server process which will
224 * take ownership of the X selection and continue to service selection
225 * requests from other apps.
227 selectionWindow = selectionPrevWindow;
228 if ( !fork() )
230 /* NOTE: This code only executes in the context of the child process
231 * Do note make any Wine specific calls here.
234 int dbgClasses = 0;
235 char selMask[8], dbgClassMask[8], clearSelection[8];
236 int i;
238 /* Don't inherit wine's X sockets to the wineclipsrv, otherwise
239 * windows stay around when you have to kill a hanging wine...
241 for (i = 3; i < 256; ++i)
242 fcntl(i, F_SETFD, 1);
244 sprintf(selMask, "%d", selectionAcquired);
246 /* Build the debug class mask to pass to the server, by inheriting
247 * the settings for the clipboard debug channel.
249 dbgClasses |= FIXME_ON(clipboard) ? 1 : 0;
250 dbgClasses |= ERR_ON(clipboard) ? 2 : 0;
251 dbgClasses |= WARN_ON(clipboard) ? 4 : 0;
252 dbgClasses |= TRACE_ON(clipboard) ? 8 : 0;
253 sprintf(dbgClassMask, "%d", dbgClasses);
255 /* Get the clear selection preference */
256 sprintf(clearSelection, "%d",
257 PROFILE_GetWineIniInt("Clipboard", "ClearAllSelections", 0));
259 /* Exec the clipboard server passing it the selection and debug class masks */
260 execl( BINDIR "/wineclipsrv", "wineclipsrv",
261 selMask, dbgClassMask, clearSelection, NULL );
262 execlp( "wineclipsrv", "wineclipsrv", selMask, dbgClassMask, clearSelection, NULL );
263 execl( "./windows/x11drv/wineclipsrv", "wineclipsrv",
264 selMask, dbgClassMask, clearSelection, NULL );
266 /* Exec Failed! */
267 perror("Could not start Wine clipboard server");
268 exit( 1 ); /* Exit the child process */
271 /* Wait until the clipboard server acquires the selection.
272 * We must release the windows lock to enable Wine to process
273 * selection messages in response to the servers requests.
276 iWndsLocks = WIN_SuspendWndsLock();
278 /* We must wait until the server finishes acquiring the selection,
279 * before proceeding, otherwise the window which owns the selection
280 * will be destroyed prematurely!
281 * Create a non-signalled, auto-reset event which will be set by
282 * X11DRV_CLIPBOARD_ReleaseSelection, and wait until this gets
283 * signalled before proceeding.
286 if ( !(selectionClearEvent = CreateEventA(NULL, FALSE, FALSE, NULL)) )
287 ERR("Could not create wait object. Clipboard server won't start!\n");
288 else
290 /* Wait until we lose the selection, timing out after a minute */
292 TRACE("Waiting for clipboard server to acquire selection\n");
294 if ( WaitForSingleObject( selectionClearEvent, 60000 ) != WAIT_OBJECT_0 )
295 TRACE("Server could not acquire selection, or a timeout occurred!\n");
296 else
297 TRACE("Server successfully acquired selection\n");
299 /* Release the event */
300 CloseHandle(selectionClearEvent);
301 selectionClearEvent = 0;
304 WIN_RestoreWndsLock(iWndsLocks);
306 return TRUE;
310 /**************************************************************************
311 * X11DRV_CLIPBOARD_CacheDataFormats
313 * Caches the list of data formats available from the current selection.
314 * This queries the selection owner for the TARGETS property and saves all
315 * reported property types.
317 int X11DRV_CLIPBOARD_CacheDataFormats( Atom SelectionName )
319 HWND hWnd = 0;
320 HWND hWndClipWindow = GetOpenClipboardWindow();
321 WND* wnd = NULL;
322 XEvent xe;
323 Atom aTargets;
324 Atom atype=AnyPropertyType;
325 int aformat;
326 unsigned long remain;
327 Atom* targetList=NULL;
328 Window w;
329 Window ownerSelection = 0;
332 * Empty the clipboard cache
334 CLIPBOARD_EmptyCache(TRUE);
336 cSelectionTargets = 0;
337 selectionCacheSrc = SelectionName;
339 hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
341 ownerSelection = TSXGetSelectionOwner(display, SelectionName);
342 if ( !hWnd || (ownerSelection == None) )
343 return cSelectionTargets;
346 * Query the selection owner for the TARGETS property
348 wnd = WIN_FindWndPtr(hWnd);
349 w = X11DRV_WND_FindXWindow(wnd);
350 WIN_ReleaseWndPtr(wnd);
351 wnd = NULL;
353 aTargets = TSXInternAtom(display, "TARGETS", False);
355 TRACE("Requesting TARGETS selection for '%s' (owner=%08x)...\n",
356 TSXGetAtomName(display, selectionCacheSrc), (unsigned)ownerSelection );
358 EnterCriticalSection( &X11DRV_CritSection );
359 XConvertSelection(display, selectionCacheSrc, aTargets,
360 TSXInternAtom(display, "SELECTION_DATA", False),
361 w, CurrentTime);
364 * Wait until SelectionNotify is received
366 while( TRUE )
368 if( XCheckTypedWindowEvent(display, w, SelectionNotify, &xe) )
369 if( xe.xselection.selection == selectionCacheSrc )
370 break;
372 LeaveCriticalSection( &X11DRV_CritSection );
374 /* Verify that the selection returned a valid TARGETS property */
375 if ( (xe.xselection.target != aTargets)
376 || (xe.xselection.property == None) )
378 TRACE("\tCould not retrieve TARGETS\n");
379 return cSelectionTargets;
382 /* Read the TARGETS property contents */
383 if(TSXGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
384 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat,
385 &cSelectionTargets, &remain, (unsigned char**)&targetList) != Success)
386 TRACE("\tCouldn't read TARGETS property\n");
387 else
389 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
390 TSXGetAtomName(display,atype),aformat,cSelectionTargets, remain);
392 * The TARGETS property should have returned us a list of atoms
393 * corresponding to each selection target format supported.
395 if( (atype == XA_ATOM || atype == aTargets) && aformat == 32 )
397 int i;
398 LPWINE_CLIPFORMAT lpFormat;
400 /* Cache these formats in the clipboard cache */
402 for (i = 0; i < cSelectionTargets; i++)
404 char *itemFmtName = TSXGetAtomName(display, targetList[i]);
405 UINT wFormat = X11DRV_CLIPBOARD_MapPropertyToFormat(itemFmtName);
408 * If the clipboard format maps to a Windows format, simply store
409 * the atom identifier and record its availablity status
410 * in the clipboard cache.
412 if (wFormat)
414 lpFormat = CLIPBOARD_LookupFormat( wFormat );
416 /* Don't replace if the property already cached is a native format,
417 * or if a PIXMAP is being replaced by a BITMAP.
419 if (lpFormat->wDataPresent &&
420 ( X11DRV_CLIPBOARD_IsNativeProperty(lpFormat->drvData)
421 || (lpFormat->drvData == XA_PIXMAP && targetList[i] == XA_BITMAP) )
424 TRACE("\tAtom# %d: '%s' --> FormatID(%d) %s (Skipped)\n",
425 i, itemFmtName, wFormat, lpFormat->Name);
427 else
429 lpFormat->wDataPresent = 1;
430 lpFormat->drvData = targetList[i];
431 TRACE("\tAtom# %d: '%s' --> FormatID(%d) %s\n",
432 i, itemFmtName, wFormat, lpFormat->Name);
436 TSXFree(itemFmtName);
440 /* Free the list of targets */
441 TSXFree(targetList);
444 return cSelectionTargets;
447 /**************************************************************************
448 * X11DRV_CLIPBOARD_ReadSelection
449 * Reads the contents of the X selection property into the WINE clipboard cache
450 * converting the selection into a format compatible with the windows clipboard
451 * if possible.
452 * This method is invoked only to read the contents of a the selection owned
453 * by an external application. i.e. when we do not own the X selection.
455 static BOOL X11DRV_CLIPBOARD_ReadSelection(UINT wFormat, Window w, Atom prop, Atom reqType)
457 Atom atype=AnyPropertyType;
458 int aformat;
459 unsigned long nitems,remain,itemSize;
460 long lRequestLength;
461 unsigned char* val=NULL;
462 LPWINE_CLIPFORMAT lpFormat;
463 BOOL bRet = FALSE;
464 HWND hWndClipWindow = GetOpenClipboardWindow();
467 if(prop == None)
468 return bRet;
470 TRACE("Reading X selection...\n");
472 TRACE("\tretrieving property %s from window %ld into %s\n",
473 TSXGetAtomName(display,reqType), (long)w, TSXGetAtomName(display,prop) );
476 * First request a zero length in order to figure out the request size.
478 if(TSXGetWindowProperty(display,w,prop,0,0,False, AnyPropertyType/*reqType*/,
479 &atype, &aformat, &nitems, &itemSize, &val) != Success)
481 WARN("\tcouldn't get property size\n");
482 return bRet;
485 /* Free zero length return data if any */
486 if ( val )
488 TSXFree(val);
489 val = NULL;
492 TRACE("\tretrieving %ld bytes...\n", itemSize * aformat/8);
493 lRequestLength = (itemSize * aformat/8)/4 + 1;
496 * Retrieve the actual property in the required X format.
498 if(TSXGetWindowProperty(display,w,prop,0,lRequestLength,False,AnyPropertyType/*reqType*/,
499 &atype, &aformat, &nitems, &remain, &val) != Success)
501 WARN("\tcouldn't read property\n");
502 return bRet;
505 TRACE("\tType %s,Format %d,nitems %ld,remain %ld,value %s\n",
506 atype ? TSXGetAtomName(display,atype) : NULL, aformat,nitems,remain,val);
508 if (remain)
510 WARN("\tCouldn't read entire property- selection may be too large! Remain=%ld\n", remain);
511 goto END;
515 * Translate the X property into the appropriate Windows clipboard
516 * format, if possible.
518 if ( (reqType == XA_STRING)
519 && (atype == XA_STRING) && (aformat == 8) ) /* treat Unix text as CF_OEMTEXT */
521 HANDLE16 hText = 0;
522 int i,inlcount = 0;
523 char* lpstr;
525 TRACE("\tselection is '%s'\n",val);
527 for(i=0; i <= nitems; i++)
528 if( val[i] == '\n' ) inlcount++;
530 hText=GlobalAlloc16(GMEM_MOVEABLE, nitems + inlcount + 1);
531 if( (lpstr = (char*)GlobalLock16(hText)) )
533 ZeroMemory(lpstr, nitems + inlcount + 1);
534 for(i=0,inlcount=0; i <= nitems; i++)
536 if( val[i] == '\n' ) lpstr[inlcount++]='\r';
537 lpstr[inlcount++]=val[i];
539 GlobalUnlock16(hText);
541 else
542 hText = 0;
544 if( hText )
546 /* delete previous CF_TEXT and CF_OEMTEXT data */
547 lpFormat = CLIPBOARD_LookupFormat(CF_TEXT);
548 if (lpFormat->wDataPresent || lpFormat->hData16 || lpFormat->hData32)
549 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
551 lpFormat = CLIPBOARD_LookupFormat(CF_OEMTEXT);
552 if (lpFormat->wDataPresent || lpFormat->hData16 || lpFormat->hData32)
553 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
555 /* Update the CF_OEMTEXT record */
556 lpFormat->wDataPresent = 1;
557 lpFormat->hData32 = 0;
558 lpFormat->hData16 = hText;
560 bRet = TRUE;
563 else if ( reqType == XA_PIXMAP || reqType == XA_BITMAP ) /* treat PIXMAP as CF_DIB or CF_BITMAP */
565 /* Get the first pixmap handle passed to us */
566 Pixmap *pPixmap = (Pixmap *)val;
567 HANDLE hTargetImage = 0; /* Handle to store the converted bitmap or DIB */
569 if (aformat != 32 || nitems < 1 || atype != XA_PIXMAP
570 || (wFormat != CF_BITMAP && wFormat != CF_DIB))
572 WARN("\tUnimplemented format conversion request\n");
573 goto END;
576 if ( wFormat == CF_BITMAP )
578 /* For CF_BITMAP requests we must return an HBITMAP */
579 hTargetImage = X11DRV_BITMAP_CreateBitmapFromPixmap(*pPixmap, TRUE);
581 else if (wFormat == CF_DIB)
583 HWND hwnd = GetOpenClipboardWindow();
584 HDC hdc = GetDC(hwnd);
586 /* For CF_DIB requests we must return an HGLOBAL storing a packed DIB */
587 hTargetImage = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc, TRUE);
589 ReleaseDC(hdc, hwnd);
592 if (!hTargetImage)
594 WARN("PIXMAP conversion failed!\n" );
595 goto END;
598 /* Delete previous clipboard data */
599 lpFormat = CLIPBOARD_LookupFormat(wFormat);
600 if (lpFormat->wDataPresent && (lpFormat->hData16 || lpFormat->hData32))
601 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
603 /* Update the clipboard record */
604 lpFormat->wDataPresent = 1;
605 lpFormat->hData32 = hTargetImage;
606 lpFormat->hData16 = 0;
608 bRet = TRUE;
611 /* For native properties simply copy the X data without conversion */
612 else if (X11DRV_CLIPBOARD_IsNativeProperty(reqType)) /* <WCF>* */
614 HANDLE hClipData = 0;
615 void* lpClipData;
616 int cBytes = nitems * aformat/8;
618 if( cBytes )
620 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
621 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cBytes );
622 if( (lpClipData = GlobalLock(hClipData)) )
624 memcpy(lpClipData, val, cBytes);
625 GlobalUnlock(hClipData);
627 else
628 hClipData = 0;
631 if( hClipData )
633 /* delete previous clipboard record if any */
634 lpFormat = CLIPBOARD_LookupFormat(wFormat);
635 if (lpFormat->wDataPresent || lpFormat->hData16 || lpFormat->hData32)
636 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
638 /* Update the clipboard record */
639 lpFormat->wDataPresent = 1;
640 lpFormat->hData32 = hClipData;
641 lpFormat->hData16 = 0;
643 bRet = TRUE;
646 else
648 WARN("\tUnimplemented format conversion request\n");
649 goto END;
652 END:
653 /* Delete the property on the window now that we are done
654 * This will send a PropertyNotify event to the selection owner. */
655 TSXDeleteProperty(display,w,prop);
657 /* Free the retrieved property data */
658 if (val)
659 TSXFree(val);
661 return bRet;
664 /**************************************************************************
665 * X11DRV_CLIPBOARD_ReleaseSelection
667 * Release an XA_PRIMARY or XA_CLIPBOARD selection that we own, in response
668 * to a SelectionClear event.
669 * This can occur in response to another client grabbing the X selection.
670 * If the XA_CLIPBOARD selection is lost, we relinquish XA_PRIMARY as well.
672 void X11DRV_CLIPBOARD_ReleaseSelection(Atom selType, Window w, HWND hwnd)
674 Atom xaClipboard = TSXInternAtom(display, "CLIPBOARD", False);
675 int clearAllSelections = PROFILE_GetWineIniInt("Clipboard", "ClearAllSelections", 0);
677 /* w is the window that lost the selection
678 * selectionPrevWindow is nonzero if CheckSelection() was called.
681 TRACE("\tevent->window = %08x (sw = %08x, spw=%08x)\n",
682 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionPrevWindow );
684 if( selectionAcquired )
686 if( w == selectionWindow || selectionPrevWindow == None)
688 /* If we're losing the CLIPBOARD selection, or if the preferences in .winerc
689 * dictate that *all* selections should be cleared on loss of a selection,
690 * we must give up all the selections we own.
692 if ( clearAllSelections || (selType == xaClipboard) )
694 /* completely give up the selection */
695 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
697 /* We are completely giving up the selection.
698 * Make sure we can open the windows clipboard first. */
700 if ( !OpenClipboard(hwnd) )
703 * We can't empty the clipboard if we cant open it so abandon.
704 * Wine will think that it still owns the selection but this is
705 * safer than losing the selection without properly emptying
706 * the clipboard. Perhaps we should forcibly re-assert ownership
707 * of the CLIPBOARD selection in this case...
709 ERR("\tClipboard is busy. Could not give up selection!\n");
710 return;
713 /* We really lost CLIPBOARD but want to voluntarily lose PRIMARY */
714 if ( (selType == xaClipboard)
715 && (selectionAcquired & S_PRIMARY) )
717 XSetSelectionOwner(display, XA_PRIMARY, None, CurrentTime);
720 /* We really lost PRIMARY but want to voluntarily lose CLIPBOARD */
721 if ( (selType == XA_PRIMARY)
722 && (selectionAcquired & S_CLIPBOARD) )
724 XSetSelectionOwner(display, xaClipboard, None, CurrentTime);
727 selectionWindow = None;
728 PrimarySelectionOwner = ClipboardSelectionOwner = 0;
730 /* Empty the windows clipboard.
731 * We should pretend that we still own the selection BEFORE calling
732 * EmptyClipboard() since otherwise this has the side effect of
733 * triggering X11DRV_CLIPBOARD_Acquire() and causing the X selection
734 * to be re-acquired by us!
736 selectionAcquired = (S_PRIMARY | S_CLIPBOARD);
737 EmptyClipboard();
738 CloseClipboard();
740 /* Give up ownership of the windows clipboard */
741 CLIPBOARD_ReleaseOwner();
743 /* Reset the selection flags now that we are done */
744 selectionAcquired = S_NOSELECTION;
746 else if ( selType == XA_PRIMARY ) /* Give up only PRIMARY selection */
748 TRACE("Lost PRIMARY selection\n");
749 PrimarySelectionOwner = 0;
750 selectionAcquired &= ~S_PRIMARY; /* clear S_PRIMARY mask */
753 cSelectionTargets = 0;
755 /* but we'll keep existing data for internal use */
756 else if( w == selectionPrevWindow )
758 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
760 w = TSXGetSelectionOwner(display, XA_PRIMARY);
761 if( w == None )
762 TSXSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
764 w = TSXGetSelectionOwner(display, xaClipboard);
765 if( w == None )
766 TSXSetSelectionOwner(display, xaClipboard, selectionWindow, CurrentTime);
770 /* Signal to a selectionClearEvent listener if the selection is completely lost */
771 if (selectionClearEvent && !selectionAcquired)
773 TRACE("Lost all selections, signalling to selectionClearEvent listener\n");
774 SetEvent(selectionClearEvent);
777 selectionPrevWindow = None;
780 /**************************************************************************
781 * X11DRV_ReleaseClipboard
782 * Voluntarily release all currently owned X selections
784 void X11DRV_ReleaseClipboard(void)
786 if( selectionAcquired )
788 XEvent xe;
789 Window savePrevWindow = selectionWindow;
790 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
791 BOOL bHasPrimarySelection = selectionAcquired & S_PRIMARY;
793 selectionAcquired = S_NOSELECTION;
794 selectionPrevWindow = selectionWindow;
795 selectionWindow = None;
797 TRACE("\tgiving up selection (spw = %08x)\n",
798 (unsigned)selectionPrevWindow);
800 EnterCriticalSection(&X11DRV_CritSection);
802 TRACE("Releasing CLIPBOARD selection\n");
803 XSetSelectionOwner(display, xaClipboard, None, CurrentTime);
804 if( selectionPrevWindow )
805 while( !XCheckTypedWindowEvent( display, selectionPrevWindow,
806 SelectionClear, &xe ) );
808 if ( bHasPrimarySelection )
810 TRACE("Releasing XA_PRIMARY selection\n");
811 selectionPrevWindow = savePrevWindow; /* May be cleared in X11DRV_CLIPBOARD_ReleaseSelection */
812 XSetSelectionOwner(display, XA_PRIMARY, None, CurrentTime);
814 if( selectionPrevWindow )
815 while( !XCheckTypedWindowEvent( display, selectionPrevWindow,
816 SelectionClear, &xe ) );
819 LeaveCriticalSection(&X11DRV_CritSection);
822 /* Get rid of any Pixmap resources we may still have */
823 while (prop_head)
825 PROPERTY *prop = prop_head;
826 prop_head = prop->next;
827 XFreePixmap( display, prop->pixmap );
828 HeapFree( GetProcessHeap(), 0, prop );
832 /**************************************************************************
833 * X11DRV_AcquireClipboard
835 void X11DRV_AcquireClipboard(void)
837 Window owner;
838 HWND hWndClipWindow = GetOpenClipboardWindow();
841 * Acquire X selection if we don't already own it.
842 * Note that we only acquire the selection if it hasn't been already
843 * acquired by us, and ignore the fact that another X window may be
844 * asserting ownership. The reason for this is we need *any* top level
845 * X window to hold selection ownership. The actual clipboard data requests
846 * are made via GetClipboardData from EVENT_SelectionRequest and this
847 * ensures that the real HWND owner services the request.
848 * If the owning X window gets destroyed the selection ownership is
849 * re-cycled to another top level X window in X11DRV_CLIPBOARD_ResetOwner.
853 if ( !(selectionAcquired == (S_PRIMARY | S_CLIPBOARD)) )
855 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
856 WND *tmpWnd = WIN_FindWndPtr( hWndClipWindow ? hWndClipWindow : AnyPopup() );
857 owner = X11DRV_WND_FindXWindow(tmpWnd );
858 WIN_ReleaseWndPtr(tmpWnd);
860 /* Grab PRIMARY selection if not owned */
861 if ( !(selectionAcquired & S_PRIMARY) )
862 TSXSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
864 /* Grab CLIPBOARD selection if not owned */
865 if ( !(selectionAcquired & S_CLIPBOARD) )
866 TSXSetSelectionOwner(display, xaClipboard, owner, CurrentTime);
868 if( TSXGetSelectionOwner(display,XA_PRIMARY) == owner )
869 selectionAcquired |= S_PRIMARY;
871 if( TSXGetSelectionOwner(display,xaClipboard) == owner)
872 selectionAcquired |= S_CLIPBOARD;
874 if (selectionAcquired)
876 selectionWindow = owner;
877 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
882 /**************************************************************************
883 * X11DRV_IsClipboardFormatAvailable
885 * Checks if the specified format is available in the current selection
886 * Only invoked when WINE is not the selection owner
888 BOOL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
890 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
891 Window ownerPrimary = TSXGetSelectionOwner(display,XA_PRIMARY);
892 Window ownerClipboard = TSXGetSelectionOwner(display,xaClipboard);
895 * If the selection has not been previously cached, or the selection has changed,
896 * try and cache the list of available selection targets from the current selection.
898 if ( !cSelectionTargets || (PrimarySelectionOwner != ownerPrimary)
899 || (ClipboardSelectionOwner != ownerClipboard) )
902 * First try cacheing the CLIPBOARD selection.
903 * If unavailable try PRIMARY.
905 if ( X11DRV_CLIPBOARD_CacheDataFormats(xaClipboard) == 0 )
907 X11DRV_CLIPBOARD_CacheDataFormats(XA_PRIMARY);
910 ClipboardSelectionOwner = ownerClipboard;
911 PrimarySelectionOwner = ownerPrimary;
914 /* Exit if there is no selection */
915 if ( !ownerClipboard && !ownerPrimary )
916 return FALSE;
918 if ( wFormat == CF_TEXT )
919 wFormat = CF_OEMTEXT;
921 /* Check if the format is available in the clipboard cache */
922 if ( CLIPBOARD_IsPresent(wFormat) )
923 return TRUE;
926 * Many X client apps (such as XTerminal) don't support being queried
927 * for the "TARGETS" target atom. To handle such clients we must actually
928 * try to convert the selection to the requested type.
930 if ( !cSelectionTargets )
931 return X11DRV_GetClipboardData( wFormat );
933 return FALSE;
936 /**************************************************************************
937 * X11DRV_RegisterClipboardFormat
939 * Registers a custom X clipboard format
940 * Returns: TRUE - success, FALSE - failure
942 BOOL X11DRV_RegisterClipboardFormat( LPCSTR FormatName )
944 Atom prop = None;
945 char str[256];
948 * If an X atom is registered for this format, return that
949 * Otherwise register a new atom.
951 if (FormatName)
953 /* Add a WINE specific prefix to the format */
954 strcpy(str, FMT_PREFIX);
955 strncat(str, FormatName, sizeof(str) - strlen(FMT_PREFIX));
956 prop = TSXInternAtom(display, str, False);
959 return (prop) ? TRUE : FALSE;
962 /**************************************************************************
963 * X11DRV_IsSelectionOwner
965 * Returns: TRUE - We(WINE) own the selection, FALSE - Selection not owned by us
967 BOOL X11DRV_IsSelectionOwner(void)
969 return selectionAcquired;
972 /**************************************************************************
973 * X11DRV_SetClipboardData
975 * We don't need to do anything special here since the clipboard code
976 * maintains the cache.
979 void X11DRV_SetClipboardData(UINT wFormat)
981 /* Make sure we have acquired the X selection */
982 X11DRV_AcquireClipboard();
985 /**************************************************************************
986 * X11DRV_GetClipboardData
988 * This method is invoked only when we DO NOT own the X selection
990 * NOTE: Clipboard driver doesn't get requests for CF_TEXT data, only
991 * for CF_OEMTEXT.
992 * We always get the data from the selection client each time,
993 * since we have no way of determining if the data in our cache is stale.
995 BOOL X11DRV_GetClipboardData(UINT wFormat)
997 BOOL bRet = selectionAcquired;
998 HWND hWndClipWindow = GetOpenClipboardWindow();
999 HWND hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
1000 WND* wnd = NULL;
1001 LPWINE_CLIPFORMAT lpFormat;
1003 if( !selectionAcquired && (wnd = WIN_FindWndPtr(hWnd)) )
1005 XEvent xe;
1006 Atom propRequest;
1007 Window w = X11DRV_WND_FindXWindow(wnd);
1008 WIN_ReleaseWndPtr(wnd);
1009 wnd = NULL;
1011 /* Map the format ID requested to an X selection property.
1012 * If the format is in the cache, use the atom associated
1013 * with it.
1016 lpFormat = CLIPBOARD_LookupFormat( wFormat );
1017 if (lpFormat && lpFormat->wDataPresent && lpFormat->drvData)
1018 propRequest = (Atom)lpFormat->drvData;
1019 else
1020 propRequest = X11DRV_CLIPBOARD_MapFormatToProperty(wFormat);
1022 if (propRequest)
1024 TRACE("Requesting %s selection from %s...\n",
1025 TSXGetAtomName(display, propRequest),
1026 TSXGetAtomName(display, selectionCacheSrc) );
1028 EnterCriticalSection( &X11DRV_CritSection );
1029 XConvertSelection(display, selectionCacheSrc, propRequest,
1030 TSXInternAtom(display, "SELECTION_DATA", False),
1031 w, CurrentTime);
1033 /* wait until SelectionNotify is received */
1035 while( TRUE )
1037 if( XCheckTypedWindowEvent(display, w, SelectionNotify, &xe) )
1038 if( xe.xselection.selection == selectionCacheSrc )
1039 break;
1041 LeaveCriticalSection( &X11DRV_CritSection );
1044 * Read the contents of the X selection property into WINE's
1045 * clipboard cache converting the selection to be compatible if possible.
1047 bRet = X11DRV_CLIPBOARD_ReadSelection( wFormat,
1048 xe.xselection.requestor,
1049 xe.xselection.property,
1050 xe.xselection.target);
1052 else
1053 bRet = FALSE;
1055 TRACE("\tpresent %s = %i\n", CLIPBOARD_GetFormatName(wFormat), bRet );
1058 return bRet;
1061 /**************************************************************************
1062 * X11DRV_ResetSelectionOwner
1064 * Called from DestroyWindow() to prevent X selection from being lost when
1065 * a top level window is destroyed, by switching ownership to another top
1066 * level window.
1067 * Any top level window can own the selection. See X11DRV_CLIPBOARD_Acquire
1068 * for a more detailed description of this.
1070 void X11DRV_ResetSelectionOwner(WND *pWnd, BOOL bFooBar)
1072 HWND hWndClipOwner = 0;
1073 Window XWnd = X11DRV_WND_GetXWindow(pWnd);
1074 Atom xaClipboard;
1075 BOOL bLostSelection = FALSE;
1077 /* There is nothing to do if we don't own the selection,
1078 * or if the X window which currently owns the selecion is different
1079 * from the one passed in.
1081 if ( !selectionAcquired || XWnd != selectionWindow
1082 || selectionWindow == None )
1083 return;
1085 if ( (bFooBar && XWnd) || (!bFooBar && !XWnd) )
1086 return;
1088 hWndClipOwner = GetClipboardOwner();
1089 xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
1091 TRACE("clipboard owner = %04x, selection window = %08x\n",
1092 hWndClipOwner, (unsigned)selectionWindow);
1094 /* now try to salvage current selection from being destroyed by X */
1096 TRACE("\tchecking %08x\n", (unsigned) XWnd);
1098 selectionPrevWindow = selectionWindow;
1099 selectionWindow = None;
1101 if( pWnd->next )
1102 selectionWindow = X11DRV_WND_GetXWindow(pWnd->next);
1103 else if( pWnd->parent )
1104 if( pWnd->parent->child != pWnd )
1105 selectionWindow = X11DRV_WND_GetXWindow(pWnd->parent->child);
1107 if( selectionWindow != None )
1109 /* We must pretend that we don't own the selection while making the switch
1110 * since a SelectionClear event will be sent to the last owner.
1111 * If there is no owner X11DRV_CLIPBOARD_ReleaseSelection will do nothing.
1113 int saveSelectionState = selectionAcquired;
1114 selectionAcquired = False;
1116 TRACE("\tswitching selection from %08x to %08x\n",
1117 (unsigned)selectionPrevWindow, (unsigned)selectionWindow);
1119 /* Assume ownership for the PRIMARY and CLIPBOARD selection */
1120 if ( saveSelectionState & S_PRIMARY )
1121 TSXSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
1123 TSXSetSelectionOwner(display, xaClipboard, selectionWindow, CurrentTime);
1125 /* Restore the selection masks */
1126 selectionAcquired = saveSelectionState;
1128 /* Lose the selection if something went wrong */
1129 if ( ( (saveSelectionState & S_PRIMARY) &&
1130 (TSXGetSelectionOwner(display, XA_PRIMARY) != selectionWindow) )
1131 || (TSXGetSelectionOwner(display, xaClipboard) != selectionWindow) )
1133 bLostSelection = TRUE;
1134 goto END;
1136 else
1138 /* Update selection state */
1139 if (saveSelectionState & S_PRIMARY)
1140 PrimarySelectionOwner = selectionWindow;
1142 ClipboardSelectionOwner = selectionWindow;
1145 else
1147 bLostSelection = TRUE;
1148 goto END;
1151 END:
1152 if (bLostSelection)
1154 /* Launch the clipboard server if the selection can no longer be recyled
1155 * to another top level window. */
1157 if ( !X11DRV_CLIPBOARD_LaunchServer() )
1159 /* Empty the windows clipboard if the server was not launched.
1160 * We should pretend that we still own the selection BEFORE calling
1161 * EmptyClipboard() since otherwise this has the side effect of
1162 * triggering X11DRV_CLIPBOARD_Acquire() and causing the X selection
1163 * to be re-acquired by us!
1166 TRACE("\tLost the selection! Emptying the clipboard...\n");
1168 OpenClipboard( 0 );
1169 selectionAcquired = (S_PRIMARY | S_CLIPBOARD);
1170 EmptyClipboard();
1172 CloseClipboard();
1174 /* Give up ownership of the windows clipboard */
1175 CLIPBOARD_ReleaseOwner();
1178 selectionAcquired = S_NOSELECTION;
1179 ClipboardSelectionOwner = PrimarySelectionOwner = 0;
1180 selectionWindow = 0;
1184 /**************************************************************************
1185 * X11DRV_CLIPBOARD_RegisterPixmapResource
1186 * Registers a Pixmap resource which is to be associated with a property Atom.
1187 * When the property is destroyed we also destroy the Pixmap through the
1188 * PropertyNotify event.
1190 BOOL X11DRV_CLIPBOARD_RegisterPixmapResource( Atom property, Pixmap pixmap )
1192 PROPERTY *prop = HeapAlloc( GetProcessHeap(), 0, sizeof(*prop) );
1193 if (!prop) return FALSE;
1194 prop->atom = property;
1195 prop->pixmap = pixmap;
1196 prop->next = prop_head;
1197 prop_head = prop;
1198 return TRUE;
1201 /**************************************************************************
1202 * X11DRV_CLIPBOARD_FreeResources
1204 * Called from EVENT_PropertyNotify() to give us a chance to destroy
1205 * any resources associated with this property.
1207 void X11DRV_CLIPBOARD_FreeResources( Atom property )
1209 /* Do a simple linear search to see if we have a Pixmap resource
1210 * associated with this property and release it.
1212 PROPERTY **prop = &prop_head;
1214 while (*prop)
1216 if ((*prop)->atom == property)
1218 PROPERTY *next = (*prop)->next;
1219 XFreePixmap( display, (*prop)->pixmap );
1220 HeapFree( GetProcessHeap(), 0, *prop );
1221 *prop = next;
1223 else prop = &(*prop)->next;