Removed X_DISPLAY_MISSING.
[wine/gsoc_dplay.git] / windows / x11drv / clipboard.c
blob52ce5dc5e2ce311f5ba37287700eb5f0e033a047
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 "config.h"
50 #include <X11/Xatom.h>
52 #include "ts_xlib.h"
54 #include <errno.h>
55 #include <string.h>
56 #include <stdio.h>
57 #include <unistd.h>
58 #include <fcntl.h>
60 #include "windef.h"
61 #include "wingdi.h"
62 #include "wine/winuser16.h"
63 #include "clipboard.h"
64 #include "message.h"
65 #include "win.h"
66 #include "x11drv.h"
67 #include "bitmap.h"
68 #include "heap.h"
69 #include "options.h"
70 #include "debugtools.h"
72 DEFAULT_DEBUG_CHANNEL(clipboard);
74 /* Selection masks */
76 #define S_NOSELECTION 0
77 #define S_PRIMARY 1
78 #define S_CLIPBOARD 2
80 /* X selection context info */
82 static char _CLIPBOARD[] = "CLIPBOARD"; /* CLIPBOARD atom name */
83 static char FMT_PREFIX[] = "<WCF>"; /* Prefix for windows specific formats */
84 static int selectionAcquired = 0; /* Contains the current selection masks */
85 static Window selectionWindow = None; /* The top level X window which owns the selection */
86 static Window selectionPrevWindow = None; /* The last X window that owned the selection */
87 static Window PrimarySelectionOwner = None; /* The window which owns the primary selection */
88 static Window ClipboardSelectionOwner = None; /* The window which owns the clipboard selection */
89 static unsigned long cSelectionTargets = 0; /* Number of target formats reported by TARGETS selection */
90 static Atom selectionCacheSrc = XA_PRIMARY; /* The selection source from which the clipboard cache was filled */
91 static HANDLE selectionClearEvent = 0;/* Synchronization object used to block until server is started */
93 typedef struct tagPROPERTY
95 struct tagPROPERTY *next;
96 Atom atom;
97 Pixmap pixmap;
98 } PROPERTY;
100 static PROPERTY *prop_head;
103 /**************************************************************************
104 * X11DRV_CLIPBOARD_MapPropertyToFormat
106 * Map an X selection property type atom name to a windows clipboard format ID
108 UINT X11DRV_CLIPBOARD_MapPropertyToFormat(char *itemFmtName)
111 * If the property name starts with FMT_PREFIX strip this off and
112 * get the ID for a custom Windows registered format with this name.
113 * We can also understand STRING, PIXMAP and BITMAP.
115 if ( NULL == itemFmtName )
116 return 0;
117 else if ( 0 == strncmp(itemFmtName, FMT_PREFIX, strlen(FMT_PREFIX)) )
118 return RegisterClipboardFormatA(itemFmtName + strlen(FMT_PREFIX));
119 else if ( 0 == strcmp(itemFmtName, "STRING") )
120 return CF_OEMTEXT;
121 else if ( 0 == strcmp(itemFmtName, "PIXMAP")
122 || 0 == strcmp(itemFmtName, "BITMAP") )
125 * Return CF_DIB as first preference, if WINE is the selection owner
126 * and if CF_DIB exists in the cache.
127 * If wine dowsn't own the selection we always return CF_DIB
129 if ( !X11DRV_CLIPBOARD_IsSelectionowner() )
130 return CF_DIB;
131 else if ( CLIPBOARD_IsPresent(CF_DIB) )
132 return CF_DIB;
133 else
134 return CF_BITMAP;
137 WARN("\tNo mapping to Windows clipboard format for property %s\n", itemFmtName);
138 return 0;
141 /**************************************************************************
142 * X11DRV_CLIPBOARD_MapFormatToProperty
144 * Map a windows clipboard format ID to an X selection property atom
146 Atom X11DRV_CLIPBOARD_MapFormatToProperty(UINT wFormat)
148 Atom prop = None;
150 switch (wFormat)
152 case CF_OEMTEXT:
153 case CF_TEXT:
154 prop = XA_STRING;
155 break;
157 case CF_DIB:
158 case CF_BITMAP:
161 * Request a PIXMAP, only if WINE is NOT the selection owner,
162 * AND the requested format is not in the cache.
164 if ( !X11DRV_CLIPBOARD_IsSelectionowner() && !CLIPBOARD_IsPresent(wFormat) )
166 prop = XA_PIXMAP;
167 break;
169 /* Fall thru to the default case in order to use the native format */
172 default:
175 * If an X atom is registered for this format, return that
176 * Otherwise register a new atom.
178 char str[256];
179 char *fmtName = CLIPBOARD_GetFormatName(wFormat);
180 strcpy(str, FMT_PREFIX);
182 if (fmtName)
184 strncat(str, fmtName, sizeof(str) - strlen(FMT_PREFIX));
185 prop = TSXInternAtom(display, str, False);
187 break;
191 if (prop == None)
192 TRACE("\tNo mapping to X property for Windows clipboard format %d(%s)\n",
193 wFormat, CLIPBOARD_GetFormatName(wFormat));
195 return prop;
198 /**************************************************************************
199 * X11DRV_CLIPBOARD_IsNativeProperty
201 * Checks if a property is a native property type
203 BOOL X11DRV_CLIPBOARD_IsNativeProperty(Atom prop)
205 char *itemFmtName = TSXGetAtomName(display, prop);
206 BOOL bRet = FALSE;
208 if ( 0 == strncmp(itemFmtName, FMT_PREFIX, strlen(FMT_PREFIX)) )
209 bRet = TRUE;
211 TSXFree(itemFmtName);
212 return bRet;
216 /**************************************************************************
217 * X11DRV_CLIPBOARD_LaunchServer
218 * Launches the clipboard server. This is called from X11DRV_CLIPBOARD_ResetOwner
219 * when the selection can no longer be recyled to another top level window.
220 * In order to make the selection persist after Wine shuts down a server
221 * process is launched which services subsequent selection requests.
223 BOOL X11DRV_CLIPBOARD_LaunchServer()
225 int iWndsLocks;
227 /* If persistant selection has been disabled in the .winerc Clipboard section,
228 * don't launch the server
230 if ( !PROFILE_GetWineIniInt("Clipboard", "PersistentSelection", 1) )
231 return FALSE;
233 /* Start up persistant WINE X clipboard server process which will
234 * take ownership of the X selection and continue to service selection
235 * requests from other apps.
237 selectionWindow = selectionPrevWindow;
238 if ( !fork() )
240 /* NOTE: This code only executes in the context of the child process
241 * Do note make any Wine specific calls here.
244 int dbgClasses = 0;
245 char selMask[8], dbgClassMask[8], clearSelection[8];
246 int i;
248 /* Don't inherit wine's X sockets to the wineclipsrv, otherwise
249 * windows stay around when you have to kill a hanging wine...
251 for (i = 3; i < 256; ++i)
252 fcntl(i, F_SETFD, 1);
254 sprintf(selMask, "%d", selectionAcquired);
256 /* Build the debug class mask to pass to the server, by inheriting
257 * the settings for the clipboard debug channel.
259 dbgClasses |= FIXME_ON(clipboard) ? 1 : 0;
260 dbgClasses |= ERR_ON(clipboard) ? 2 : 0;
261 dbgClasses |= WARN_ON(clipboard) ? 4 : 0;
262 dbgClasses |= TRACE_ON(clipboard) ? 8 : 0;
263 sprintf(dbgClassMask, "%d", dbgClasses);
265 /* Get the clear selection preference */
266 sprintf(clearSelection, "%d",
267 PROFILE_GetWineIniInt("Clipboard", "ClearAllSelections", 0));
269 /* Exec the clipboard server passing it the selection and debug class masks */
270 execl( BINDIR "/wineclipsrv", "wineclipsrv",
271 selMask, dbgClassMask, clearSelection, NULL );
272 execlp( "wineclipsrv", "wineclipsrv", selMask, dbgClassMask, clearSelection, NULL );
273 execl( "./windows/x11drv/wineclipsrv", "wineclipsrv",
274 selMask, dbgClassMask, clearSelection, NULL );
276 /* Exec Failed! */
277 perror("Could not start Wine clipboard server");
278 exit( 1 ); /* Exit the child process */
281 /* Wait until the clipboard server acquires the selection.
282 * We must release the windows lock to enable Wine to process
283 * selection messages in response to the servers requests.
286 iWndsLocks = WIN_SuspendWndsLock();
288 /* We must wait until the server finishes acquiring the selection,
289 * before proceeding, otherwise the window which owns the selection
290 * will be destroyed prematurely!
291 * Create a non-signalled, auto-reset event which will be set by
292 * X11DRV_CLIPBOARD_ReleaseSelection, and wait until this gets
293 * signalled before proceeding.
296 if ( !(selectionClearEvent = CreateEventA(NULL, FALSE, FALSE, NULL)) )
297 ERR("Could not create wait object. Clipboard server won't start!\n");
298 else
300 /* Make the event object's handle global */
301 selectionClearEvent = ConvertToGlobalHandle(selectionClearEvent);
303 /* Wait until we lose the selection, timing out after a minute */
305 TRACE("Waiting for clipboard server to acquire selection\n");
307 if ( WaitForSingleObject( selectionClearEvent, 60000 ) != WAIT_OBJECT_0 )
308 TRACE("Server could not acquire selection, or a time out occured!\n");
309 else
310 TRACE("Server successfully acquired selection\n");
312 /* Release the event */
313 CloseHandle(selectionClearEvent);
314 selectionClearEvent = 0;
317 WIN_RestoreWndsLock(iWndsLocks);
319 return TRUE;
323 /**************************************************************************
324 * X11DRV_CLIPBOARD_CacheDataFormats
326 * Caches the list of data formats available from the current selection.
327 * This queries the selection owner for the TARGETS property and saves all
328 * reported property types.
330 int X11DRV_CLIPBOARD_CacheDataFormats( Atom SelectionName )
332 HWND hWnd = 0;
333 HWND hWndClipWindow = GetOpenClipboardWindow();
334 WND* wnd = NULL;
335 XEvent xe;
336 Atom aTargets;
337 Atom atype=AnyPropertyType;
338 int aformat;
339 unsigned long remain;
340 Atom* targetList=NULL;
341 Window w;
342 Window ownerSelection = 0;
345 * Empty the clipboard cache
347 CLIPBOARD_EmptyCache(TRUE);
349 cSelectionTargets = 0;
350 selectionCacheSrc = SelectionName;
352 hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
354 ownerSelection = TSXGetSelectionOwner(display, SelectionName);
355 if ( !hWnd || (ownerSelection == None) )
356 return cSelectionTargets;
359 * Query the selection owner for the TARGETS property
361 wnd = WIN_FindWndPtr(hWnd);
362 w = X11DRV_WND_FindXWindow(wnd);
363 WIN_ReleaseWndPtr(wnd);
364 wnd = NULL;
366 aTargets = TSXInternAtom(display, "TARGETS", False);
368 TRACE("Requesting TARGETS selection for '%s' (owner=%08x)...\n",
369 TSXGetAtomName(display, selectionCacheSrc), (unsigned)ownerSelection );
371 EnterCriticalSection( &X11DRV_CritSection );
372 XConvertSelection(display, selectionCacheSrc, aTargets,
373 TSXInternAtom(display, "SELECTION_DATA", False),
374 w, CurrentTime);
377 * Wait until SelectionNotify is received
379 while( TRUE )
381 if( XCheckTypedWindowEvent(display, w, SelectionNotify, &xe) )
382 if( xe.xselection.selection == selectionCacheSrc )
383 break;
385 LeaveCriticalSection( &X11DRV_CritSection );
387 /* Verify that the selection returned a valid TARGETS property */
388 if ( (xe.xselection.target != aTargets)
389 || (xe.xselection.property == None) )
391 TRACE("\tCould not retrieve TARGETS\n");
392 return cSelectionTargets;
395 /* Read the TARGETS property contents */
396 if(TSXGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
397 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat,
398 &cSelectionTargets, &remain, (unsigned char**)&targetList) != Success)
399 TRACE("\tCouldn't read TARGETS property\n");
400 else
402 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
403 TSXGetAtomName(display,atype),aformat,cSelectionTargets, remain);
405 * The TARGETS property should have returned us a list of atoms
406 * corresponding to each selection target format supported.
408 if( (atype == XA_ATOM || atype == aTargets) && aformat == 32 )
410 int i;
411 LPWINE_CLIPFORMAT lpFormat;
413 /* Cache these formats in the clipboard cache */
415 for (i = 0; i < cSelectionTargets; i++)
417 char *itemFmtName = TSXGetAtomName(display, targetList[i]);
418 UINT wFormat = X11DRV_CLIPBOARD_MapPropertyToFormat(itemFmtName);
421 * If the clipboard format maps to a Windows format, simply store
422 * the atom identifier and record its availablity status
423 * in the clipboard cache.
425 if (wFormat)
427 lpFormat = CLIPBOARD_LookupFormat( wFormat );
429 /* Don't replace if the property already cached is a native format,
430 * or if a PIXMAP is being replaced by a BITMAP.
432 if (lpFormat->wDataPresent &&
433 ( X11DRV_CLIPBOARD_IsNativeProperty(lpFormat->drvData)
434 || (lpFormat->drvData == XA_PIXMAP && targetList[i] == XA_BITMAP) )
437 TRACE("\tAtom# %d: '%s' --> FormatID(%d) %s (Skipped)\n",
438 i, itemFmtName, wFormat, lpFormat->Name);
440 else
442 lpFormat->wDataPresent = 1;
443 lpFormat->drvData = targetList[i];
444 TRACE("\tAtom# %d: '%s' --> FormatID(%d) %s\n",
445 i, itemFmtName, wFormat, lpFormat->Name);
449 TSXFree(itemFmtName);
453 /* Free the list of targets */
454 TSXFree(targetList);
457 return cSelectionTargets;
460 /**************************************************************************
461 * X11DRV_CLIPBOARD_ReadSelection
462 * Reads the contents of the X selection property into the WINE clipboard cache
463 * converting the selection into a format compatible with the windows clipboard
464 * if possible.
465 * This method is invoked only to read the contents of a the selection owned
466 * by an external application. i.e. when we do not own the X selection.
468 static BOOL X11DRV_CLIPBOARD_ReadSelection(UINT wFormat, Window w, Atom prop, Atom reqType)
470 Atom atype=AnyPropertyType;
471 int aformat;
472 unsigned long nitems,remain,itemSize;
473 long lRequestLength;
474 unsigned char* val=NULL;
475 LPWINE_CLIPFORMAT lpFormat;
476 BOOL bRet = FALSE;
477 HWND hWndClipWindow = GetOpenClipboardWindow();
480 if(prop == None)
481 return bRet;
483 TRACE("Reading X selection...\n");
485 TRACE("\tretrieving property %s from window %ld into %s\n",
486 TSXGetAtomName(display,reqType), (long)w, TSXGetAtomName(display,prop) );
489 * First request a zero length in order to figure out the request size.
491 if(TSXGetWindowProperty(display,w,prop,0,0,False, AnyPropertyType/*reqType*/,
492 &atype, &aformat, &nitems, &itemSize, &val) != Success)
494 WARN("\tcouldn't get property size\n");
495 return bRet;
498 /* Free zero length return data if any */
499 if ( val )
501 TSXFree(val);
502 val = NULL;
505 TRACE("\tretrieving %ld bytes...\n", itemSize * aformat/8);
506 lRequestLength = (itemSize * aformat/8)/4 + 1;
509 * Retrieve the actual property in the required X format.
511 if(TSXGetWindowProperty(display,w,prop,0,lRequestLength,False,AnyPropertyType/*reqType*/,
512 &atype, &aformat, &nitems, &remain, &val) != Success)
514 WARN("\tcouldn't read property\n");
515 return bRet;
518 TRACE("\tType %s,Format %d,nitems %ld,remain %ld,value %s\n",
519 atype ? TSXGetAtomName(display,atype) : NULL, aformat,nitems,remain,val);
521 if (remain)
523 WARN("\tCouldn't read entire property- selection may be too large! Remain=%ld\n", remain);
524 goto END;
528 * Translate the X property into the appropriate Windows clipboard
529 * format, if possible.
531 if ( (reqType == XA_STRING)
532 && (atype == XA_STRING) && (aformat == 8) ) /* treat Unix text as CF_OEMTEXT */
534 HANDLE16 hText = 0;
535 int i,inlcount = 0;
536 char* lpstr;
538 TRACE("\tselection is '%s'\n",val);
540 for(i=0; i <= nitems; i++)
541 if( val[i] == '\n' ) inlcount++;
543 if( nitems )
545 hText=GlobalAlloc16(GMEM_MOVEABLE, nitems + inlcount + 1);
546 if( (lpstr = (char*)GlobalLock16(hText)) )
548 for(i=0,inlcount=0; i <= nitems; i++)
550 if( val[i] == '\n' ) lpstr[inlcount++]='\r';
551 lpstr[inlcount++]=val[i];
553 GlobalUnlock16(hText);
555 else
556 hText = 0;
559 if( hText )
561 /* delete previous CF_TEXT and CF_OEMTEXT data */
562 lpFormat = CLIPBOARD_LookupFormat(CF_TEXT);
563 if (lpFormat->wDataPresent || lpFormat->hData16 || lpFormat->hData32)
564 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
566 lpFormat = CLIPBOARD_LookupFormat(CF_OEMTEXT);
567 if (lpFormat->wDataPresent || lpFormat->hData16 || lpFormat->hData32)
568 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
570 /* Update the CF_OEMTEXT record */
571 lpFormat->wDataPresent = 1;
572 lpFormat->hData32 = 0;
573 lpFormat->hData16 = hText;
575 bRet = TRUE;
578 else if ( reqType == XA_PIXMAP || reqType == XA_BITMAP ) /* treat PIXMAP as CF_DIB or CF_BITMAP */
580 /* Get the first pixmap handle passed to us */
581 Pixmap *pPixmap = (Pixmap *)val;
582 HANDLE hTargetImage = 0; /* Handle to store the converted bitmap or DIB */
584 if (aformat != 32 || nitems < 1 || atype != XA_PIXMAP
585 || (wFormat != CF_BITMAP && wFormat != CF_DIB))
587 WARN("\tUnimplemented format conversion request\n");
588 goto END;
591 if ( wFormat == CF_BITMAP )
593 /* For CF_BITMAP requests we must return an HBITMAP */
594 hTargetImage = X11DRV_BITMAP_CreateBitmapFromPixmap(*pPixmap, TRUE);
596 else if (wFormat == CF_DIB)
598 HWND hwnd = GetOpenClipboardWindow();
599 HDC hdc = GetDC(hwnd);
601 /* For CF_DIB requests we must return an HGLOBAL storing a packed DIB */
602 hTargetImage = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc, TRUE);
604 ReleaseDC(hdc, hwnd);
607 if (!hTargetImage)
609 WARN("PIXMAP conversion failed!\n" );
610 goto END;
613 /* Delete previous clipboard data */
614 lpFormat = CLIPBOARD_LookupFormat(wFormat);
615 if (lpFormat->wDataPresent && (lpFormat->hData16 || lpFormat->hData32))
616 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
618 /* Update the clipboard record */
619 lpFormat->wDataPresent = 1;
620 lpFormat->hData32 = hTargetImage;
621 lpFormat->hData16 = 0;
623 bRet = TRUE;
626 /* For native properties simply copy the X data without conversion */
627 else if (X11DRV_CLIPBOARD_IsNativeProperty(reqType)) /* <WCF>* */
629 HANDLE hClipData = 0;
630 void* lpClipData;
631 int cBytes = nitems * aformat/8;
633 if( cBytes )
635 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
636 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cBytes );
637 if( (lpClipData = GlobalLock(hClipData)) )
639 memcpy(lpClipData, val, cBytes);
640 GlobalUnlock(hClipData);
642 else
643 hClipData = 0;
646 if( hClipData )
648 /* delete previous clipboard record if any */
649 lpFormat = CLIPBOARD_LookupFormat(wFormat);
650 if (lpFormat->wDataPresent || lpFormat->hData16 || lpFormat->hData32)
651 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
653 /* Update the clipboard record */
654 lpFormat->wDataPresent = 1;
655 lpFormat->hData32 = hClipData;
656 lpFormat->hData16 = 0;
658 bRet = TRUE;
661 else
663 WARN("\tUnimplemented format conversion request\n");
664 goto END;
667 END:
668 /* Delete the property on the window now that we are done
669 * This will send a PropertyNotify event to the selection owner. */
670 TSXDeleteProperty(display,w,prop);
672 /* Free the retrieved property data */
673 if (val)
674 TSXFree(val);
676 return bRet;
679 /**************************************************************************
680 * X11DRV_CLIPBOARD_ReleaseSelection
682 * Release an XA_PRIMARY or XA_CLIPBOARD selection that we own, in response
683 * to a SelectionClear event.
684 * This can occur in response to another client grabbing the X selection.
685 * If the XA_CLIPBOARD selection is lost, we relinquish XA_PRIMARY as well.
687 void X11DRV_CLIPBOARD_ReleaseSelection(Atom selType, Window w, HWND hwnd)
689 Atom xaClipboard = TSXInternAtom(display, "CLIPBOARD", False);
690 int clearAllSelections = PROFILE_GetWineIniInt("Clipboard", "ClearAllSelections", 0);
692 /* w is the window that lost the selection
693 * selectionPrevWindow is nonzero if CheckSelection() was called.
696 TRACE("\tevent->window = %08x (sw = %08x, spw=%08x)\n",
697 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionPrevWindow );
699 if( selectionAcquired )
701 if( w == selectionWindow || selectionPrevWindow == None)
703 /* If we're losing the CLIPBOARD selection, or if the preferences in .winerc
704 * dictate that *all* selections should be cleared on loss of a selection,
705 * we must give up all the selections we own.
707 if ( clearAllSelections || (selType == xaClipboard) )
709 /* completely give up the selection */
710 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
712 /* We are completely giving up the selection.
713 * Make sure we can open the windows clipboard first. */
715 if ( !OpenClipboard(hwnd) )
718 * We can't empty the clipboard if we cant open it so abandon.
719 * Wine will think that it still owns the selection but this is
720 * safer than losing the selection without properly emptying
721 * the clipboard. Perhaps we should forcibly re-assert ownership
722 * of the CLIPBOARD selection in this case...
724 ERR("\tClipboard is busy. Could not give up selection!\n");
725 return;
728 /* We really lost CLIPBOARD but want to voluntarily lose PRIMARY */
729 if ( (selType == xaClipboard)
730 && (selectionAcquired & S_PRIMARY) )
732 XSetSelectionOwner(display, XA_PRIMARY, None, CurrentTime);
735 /* We really lost PRIMARY but want to voluntarily lose CLIPBOARD */
736 if ( (selType == XA_PRIMARY)
737 && (selectionAcquired & S_CLIPBOARD) )
739 XSetSelectionOwner(display, xaClipboard, None, CurrentTime);
742 selectionWindow = None;
743 PrimarySelectionOwner = ClipboardSelectionOwner = 0;
745 /* Empty the windows clipboard.
746 * We should pretend that we still own the selection BEFORE calling
747 * EmptyClipboard() since otherwise this has the side effect of
748 * triggering X11DRV_CLIPBOARD_Acquire() and causing the X selection
749 * to be re-acquired by us!
751 selectionAcquired = (S_PRIMARY | S_CLIPBOARD);
752 EmptyClipboard();
753 CloseClipboard();
755 /* Give up ownership of the windows clipboard */
756 CLIPBOARD_ReleaseOwner();
758 /* Reset the selection flags now that we are done */
759 selectionAcquired = S_NOSELECTION;
761 else if ( selType == XA_PRIMARY ) /* Give up only PRIMARY selection */
763 TRACE("Lost PRIMARY selection\n");
764 PrimarySelectionOwner = 0;
765 selectionAcquired &= ~S_PRIMARY; /* clear S_PRIMARY mask */
768 cSelectionTargets = 0;
770 /* but we'll keep existing data for internal use */
771 else if( w == selectionPrevWindow )
773 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
775 w = TSXGetSelectionOwner(display, XA_PRIMARY);
776 if( w == None )
777 TSXSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
779 w = TSXGetSelectionOwner(display, xaClipboard);
780 if( w == None )
781 TSXSetSelectionOwner(display, xaClipboard, selectionWindow, CurrentTime);
785 /* Signal to a selectionClearEvent listener if the selection is completely lost */
786 if (selectionClearEvent && !selectionAcquired)
788 TRACE("Lost all selections, signalling to selectionClearEvent listener\n");
789 SetEvent(selectionClearEvent);
792 selectionPrevWindow = None;
795 /**************************************************************************
796 * X11DRV_CLIPBOARD_Empty
797 * Voluntarily release all currently owned X selections
799 void X11DRV_CLIPBOARD_Release()
801 if( selectionAcquired )
803 XEvent xe;
804 Window savePrevWindow = selectionWindow;
805 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
806 BOOL bHasPrimarySelection = selectionAcquired & S_PRIMARY;
808 selectionAcquired = S_NOSELECTION;
809 selectionPrevWindow = selectionWindow;
810 selectionWindow = None;
812 TRACE("\tgiving up selection (spw = %08x)\n",
813 (unsigned)selectionPrevWindow);
815 EnterCriticalSection(&X11DRV_CritSection);
817 TRACE("Releasing CLIPBOARD selection\n");
818 XSetSelectionOwner(display, xaClipboard, None, CurrentTime);
819 if( selectionPrevWindow )
820 while( !XCheckTypedWindowEvent( display, selectionPrevWindow,
821 SelectionClear, &xe ) );
823 if ( bHasPrimarySelection )
825 TRACE("Releasing XA_PRIMARY selection\n");
826 selectionPrevWindow = savePrevWindow; /* May be cleared in X11DRV_CLIPBOARD_ReleaseSelection */
827 XSetSelectionOwner(display, XA_PRIMARY, None, CurrentTime);
829 if( selectionPrevWindow )
830 while( !XCheckTypedWindowEvent( display, selectionPrevWindow,
831 SelectionClear, &xe ) );
834 LeaveCriticalSection(&X11DRV_CritSection);
837 /* Get rid of any Pixmap resources we may still have */
838 while (prop_head)
840 PROPERTY *prop = prop_head;
841 prop_head = prop->next;
842 XFreePixmap( display, prop->pixmap );
843 HeapFree( GetProcessHeap(), 0, prop );
847 /**************************************************************************
848 * X11DRV_CLIPBOARD_Acquire()
850 void X11DRV_CLIPBOARD_Acquire()
852 Window owner;
853 HWND hWndClipWindow = GetOpenClipboardWindow();
856 * Acquire X selection if we don't already own it.
857 * Note that we only acquire the selection if it hasn't been already
858 * acquired by us, and ignore the fact that another X window may be
859 * asserting ownership. The reason for this is we need *any* top level
860 * X window to hold selection ownership. The actual clipboard data requests
861 * are made via GetClipboardData from EVENT_SelectionRequest and this
862 * ensures that the real HWND owner services the request.
863 * If the owning X window gets destroyed the selection ownership is
864 * re-cycled to another top level X window in X11DRV_CLIPBOARD_ResetOwner.
868 if ( !(selectionAcquired == (S_PRIMARY | S_CLIPBOARD)) )
870 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
871 WND *tmpWnd = WIN_FindWndPtr( hWndClipWindow ? hWndClipWindow : AnyPopup() );
872 owner = X11DRV_WND_FindXWindow(tmpWnd );
873 WIN_ReleaseWndPtr(tmpWnd);
875 /* Grab PRIMARY selection if not owned */
876 if ( !(selectionAcquired & S_PRIMARY) )
877 TSXSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
879 /* Grab CLIPBOARD selection if not owned */
880 if ( !(selectionAcquired & S_CLIPBOARD) )
881 TSXSetSelectionOwner(display, xaClipboard, owner, CurrentTime);
883 if( TSXGetSelectionOwner(display,XA_PRIMARY) == owner )
884 selectionAcquired |= S_PRIMARY;
886 if( TSXGetSelectionOwner(display,xaClipboard) == owner)
887 selectionAcquired |= S_CLIPBOARD;
889 if (selectionAcquired)
891 selectionWindow = owner;
892 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
897 /**************************************************************************
898 * X11DRV_CLIPBOARD_IsFormatAvailable
900 * Checks if the specified format is available in the current selection
901 * Only invoked when WINE is not the selection owner
903 BOOL X11DRV_CLIPBOARD_IsFormatAvailable(UINT wFormat)
905 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
906 Window ownerPrimary = TSXGetSelectionOwner(display,XA_PRIMARY);
907 Window ownerClipboard = TSXGetSelectionOwner(display,xaClipboard);
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 )
931 return FALSE;
933 if ( wFormat == CF_TEXT )
934 wFormat = CF_OEMTEXT;
936 /* Check if the format is available in the clipboard cache */
937 if ( CLIPBOARD_IsPresent(wFormat) )
938 return TRUE;
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_CLIPBOARD_GetData( wFormat );
948 return FALSE;
951 /**************************************************************************
952 * X11DRV_CLIPBOARD_RegisterFormat
954 * Registers a custom X clipboard format
955 * Returns: TRUE - success, FALSE - failure
957 BOOL X11DRV_CLIPBOARD_RegisterFormat( LPCSTR FormatName )
959 Atom prop = None;
960 char str[256];
963 * If an X atom is registered for this format, return that
964 * Otherwise register a new atom.
966 if (FormatName)
968 /* Add a WINE specific prefix to the format */
969 strcpy(str, FMT_PREFIX);
970 strncat(str, FormatName, sizeof(str) - strlen(FMT_PREFIX));
971 prop = TSXInternAtom(display, str, False);
974 return (prop) ? TRUE : FALSE;
977 /**************************************************************************
978 * X11DRV_CLIPBOARD_IsSelectionowner
980 * Returns: TRUE - We(WINE) own the selection, FALSE - Selection not owned by us
982 BOOL X11DRV_CLIPBOARD_IsSelectionowner()
984 return selectionAcquired;
987 /**************************************************************************
988 * X11DRV_CLIPBOARD_SetData
990 * We don't need to do anything special here since the clipboard code
991 * maintains the cache.
994 void X11DRV_CLIPBOARD_SetData(UINT wFormat)
996 /* Make sure we have acquired the X selection */
997 X11DRV_CLIPBOARD_Acquire();
1000 /**************************************************************************
1001 * X11DRV_CLIPBOARD_GetData
1003 * This method is invoked only when we DO NOT own the X selection
1005 * NOTE: Clipboard driver doesn't get requests for CF_TEXT data, only
1006 * for CF_OEMTEXT.
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_CLIPBOARD_GetData(UINT wFormat)
1012 BOOL bRet = selectionAcquired;
1013 HWND hWndClipWindow = GetOpenClipboardWindow();
1014 HWND hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
1015 WND* wnd = NULL;
1016 LPWINE_CLIPFORMAT lpFormat;
1018 if( !selectionAcquired && (wnd = WIN_FindWndPtr(hWnd)) )
1020 XEvent xe;
1021 Atom propRequest;
1022 Window w = X11DRV_WND_FindXWindow(wnd);
1023 WIN_ReleaseWndPtr(wnd);
1024 wnd = NULL;
1026 /* Map the format ID requested to an X selection property.
1027 * If the format is in the cache, use the atom associated
1028 * with it.
1031 lpFormat = CLIPBOARD_LookupFormat( wFormat );
1032 if (lpFormat && lpFormat->wDataPresent && lpFormat->drvData)
1033 propRequest = (Atom)lpFormat->drvData;
1034 else
1035 propRequest = X11DRV_CLIPBOARD_MapFormatToProperty(wFormat);
1037 if (propRequest)
1039 TRACE("Requesting %s selection from %s...\n",
1040 TSXGetAtomName(display, propRequest),
1041 TSXGetAtomName(display, selectionCacheSrc) );
1043 EnterCriticalSection( &X11DRV_CritSection );
1044 XConvertSelection(display, selectionCacheSrc, propRequest,
1045 TSXInternAtom(display, "SELECTION_DATA", False),
1046 w, CurrentTime);
1048 /* wait until SelectionNotify is received */
1050 while( TRUE )
1052 if( XCheckTypedWindowEvent(display, w, SelectionNotify, &xe) )
1053 if( xe.xselection.selection == selectionCacheSrc )
1054 break;
1056 LeaveCriticalSection( &X11DRV_CritSection );
1059 * Read the contents of the X selection property into WINE's
1060 * clipboard cache converting the selection to be compatible if possible.
1062 bRet = X11DRV_CLIPBOARD_ReadSelection( wFormat,
1063 xe.xselection.requestor,
1064 xe.xselection.property,
1065 xe.xselection.target);
1067 else
1068 bRet = FALSE;
1070 TRACE("\tpresent %s = %i\n", CLIPBOARD_GetFormatName(wFormat), bRet );
1073 return bRet;
1076 /**************************************************************************
1077 * X11DRV_CLIPBOARD_ResetOwner
1079 * Called from DestroyWindow() to prevent X selection from being lost when
1080 * a top level window is destroyed, by switching ownership to another top
1081 * level window.
1082 * Any top level window can own the selection. See X11DRV_CLIPBOARD_Acquire
1083 * for a more detailed description of this.
1085 void X11DRV_CLIPBOARD_ResetOwner(WND *pWnd, BOOL bFooBar)
1087 HWND hWndClipOwner = 0;
1088 Window XWnd = X11DRV_WND_GetXWindow(pWnd);
1089 Atom xaClipboard;
1090 BOOL bLostSelection = FALSE;
1092 /* There is nothing to do if we don't own the selection,
1093 * or if the X window which currently owns the selecion is different
1094 * from the one passed in.
1096 if ( !selectionAcquired || XWnd != selectionWindow
1097 || selectionWindow == None )
1098 return;
1100 if ( (bFooBar && XWnd) || (!bFooBar && !XWnd) )
1101 return;
1103 hWndClipOwner = GetClipboardOwner();
1104 xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
1106 TRACE("clipboard owner = %04x, selection window = %08x\n",
1107 hWndClipOwner, (unsigned)selectionWindow);
1109 /* now try to salvage current selection from being destroyed by X */
1111 TRACE("\tchecking %08x\n", (unsigned) XWnd);
1113 selectionPrevWindow = selectionWindow;
1114 selectionWindow = None;
1116 if( pWnd->next )
1117 selectionWindow = X11DRV_WND_GetXWindow(pWnd->next);
1118 else if( pWnd->parent )
1119 if( pWnd->parent->child != pWnd )
1120 selectionWindow = X11DRV_WND_GetXWindow(pWnd->parent->child);
1122 if( selectionWindow != None )
1124 /* We must pretend that we don't own the selection while making the switch
1125 * since a SelectionClear event will be sent to the last owner.
1126 * If there is no owner X11DRV_CLIPBOARD_ReleaseSelection will do nothing.
1128 int saveSelectionState = selectionAcquired;
1129 selectionAcquired = False;
1131 TRACE("\tswitching selection from %08x to %08x\n",
1132 (unsigned)selectionPrevWindow, (unsigned)selectionWindow);
1134 /* Assume ownership for the PRIMARY and CLIPBOARD selection */
1135 if ( saveSelectionState & S_PRIMARY )
1136 TSXSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
1138 TSXSetSelectionOwner(display, xaClipboard, selectionWindow, CurrentTime);
1140 /* Restore the selection masks */
1141 selectionAcquired = saveSelectionState;
1143 /* Lose the selection if something went wrong */
1144 if ( ( (saveSelectionState & S_PRIMARY) &&
1145 (TSXGetSelectionOwner(display, XA_PRIMARY) != selectionWindow) )
1146 || (TSXGetSelectionOwner(display, xaClipboard) != selectionWindow) )
1148 bLostSelection = TRUE;
1149 goto END;
1151 else
1153 /* Update selection state */
1154 if (saveSelectionState & S_PRIMARY)
1155 PrimarySelectionOwner = selectionWindow;
1157 ClipboardSelectionOwner = selectionWindow;
1160 else
1162 bLostSelection = TRUE;
1163 goto END;
1166 END:
1167 if (bLostSelection)
1169 /* Launch the clipboard server if the selection can no longer be recyled
1170 * to another top level window. */
1172 if ( !X11DRV_CLIPBOARD_LaunchServer() )
1174 /* Empty the windows clipboard if the server was not launched.
1175 * We should pretend that we still own the selection BEFORE calling
1176 * EmptyClipboard() since otherwise this has the side effect of
1177 * triggering X11DRV_CLIPBOARD_Acquire() and causing the X selection
1178 * to be re-acquired by us!
1181 TRACE("\tLost the selection! Emptying the clipboard...\n");
1183 OpenClipboard( 0 );
1184 selectionAcquired = (S_PRIMARY | S_CLIPBOARD);
1185 EmptyClipboard();
1187 CloseClipboard();
1189 /* Give up ownership of the windows clipboard */
1190 CLIPBOARD_ReleaseOwner();
1193 selectionAcquired = S_NOSELECTION;
1194 ClipboardSelectionOwner = PrimarySelectionOwner = 0;
1195 selectionWindow = 0;
1199 /**************************************************************************
1200 * X11DRV_CLIPBOARD_RegisterPixmapResource
1201 * Registers a Pixmap resource which is to be associated with a property Atom.
1202 * When the property is destroyed we also destroy the Pixmap through the
1203 * PropertyNotify event.
1205 BOOL X11DRV_CLIPBOARD_RegisterPixmapResource( Atom property, Pixmap pixmap )
1207 PROPERTY *prop = HeapAlloc( GetProcessHeap(), 0, sizeof(*prop) );
1208 if (!prop) return FALSE;
1209 prop->atom = property;
1210 prop->pixmap = pixmap;
1211 prop->next = prop_head;
1212 prop_head = prop;
1213 return TRUE;
1216 /**************************************************************************
1217 * X11DRV_CLIPBOARD_FreeResources
1219 * Called from EVENT_PropertyNotify() to give us a chance to destroy
1220 * any resources associated with this property.
1222 void X11DRV_CLIPBOARD_FreeResources( Atom property )
1224 /* Do a simple linear search to see if we have a Pixmap resource
1225 * associated with this property and release it.
1227 PROPERTY **prop = &prop_head;
1229 while (*prop)
1231 if ((*prop)->atom == property)
1233 PROPERTY *next = (*prop)->next;
1234 XFreePixmap( display, (*prop)->pixmap );
1235 HeapFree( GetProcessHeap(), 0, *prop );
1236 *prop = next;
1238 else prop = &(*prop)->next;