Implemented GetAncestor and removed WIN_GetTopParent.
[wine/multimedia.git] / windows / x11drv / clipboard.c
blob83e72054ca86ff76a58219730412d45da2486adf
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 takes 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 caching 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 "winreg.h"
57 #include "clipboard.h"
58 #include "win.h"
59 #include "x11drv.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_UNICODETEXT;
111 else if ( 0 == strcmp(itemFmtName, "PIXMAP")
112 || 0 == strcmp(itemFmtName, "BITMAP") )
115 * Return CF_DIB as first preference, if WINE is the selection owner
116 * and if CF_DIB exists in the cache.
117 * If wine dowsn't own the selection we always return CF_DIB
119 if ( !X11DRV_IsSelectionOwner() )
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 /* We support only CF_UNICODETEXT, other formats are synthesized */
143 case CF_OEMTEXT:
144 case CF_TEXT:
145 return None;
147 case CF_UNICODETEXT:
148 prop = XA_STRING;
149 break;
151 case CF_DIB:
152 case CF_BITMAP:
155 * Request a PIXMAP, only if WINE is NOT the selection owner,
156 * AND the requested format is not in the cache.
158 if ( !X11DRV_IsSelectionOwner() && !CLIPBOARD_IsPresent(wFormat) )
160 prop = XA_PIXMAP;
161 break;
163 /* Fall through to the default case in order to use the native format */
166 default:
169 * If an X atom is registered for this format, return that
170 * Otherwise register a new atom.
172 char str[256];
173 char *fmtName = CLIPBOARD_GetFormatName(wFormat);
174 strcpy(str, FMT_PREFIX);
176 if (fmtName)
178 strncat(str, fmtName, sizeof(str) - strlen(FMT_PREFIX));
179 prop = TSXInternAtom(thread_display(), str, False);
181 break;
185 if (prop == None)
186 TRACE("\tNo mapping to X property for Windows clipboard format %d(%s)\n",
187 wFormat, CLIPBOARD_GetFormatName(wFormat));
189 return prop;
192 /**************************************************************************
193 * X11DRV_CLIPBOARD_IsNativeProperty
195 * Checks if a property is a native Wine property type
197 BOOL X11DRV_CLIPBOARD_IsNativeProperty(Atom prop)
199 char *itemFmtName = TSXGetAtomName(thread_display(), prop);
200 BOOL bRet = FALSE;
202 if ( 0 == strncmp(itemFmtName, FMT_PREFIX, strlen(FMT_PREFIX)) )
203 bRet = TRUE;
205 TSXFree(itemFmtName);
206 return bRet;
210 /**************************************************************************
211 * X11DRV_CLIPBOARD_LaunchServer
212 * Launches the clipboard server. This is called from X11DRV_CLIPBOARD_ResetOwner
213 * when the selection can no longer be recyled to another top level window.
214 * In order to make the selection persist after Wine shuts down a server
215 * process is launched which services subsequent selection requests.
217 BOOL X11DRV_CLIPBOARD_LaunchServer()
219 int iWndsLocks;
220 char clearSelection[8] = "0";
221 int persistent_selection = 1;
222 HKEY hkey;
224 /* If persistant selection has been disabled in the .winerc Clipboard section,
225 * don't launch the server
227 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\Clipboard", &hkey))
229 char buffer[20];
230 DWORD type, count = sizeof(buffer);
231 if(!RegQueryValueExA(hkey, "PersistentSelection", 0, &type, buffer, &count))
232 persistent_selection = atoi(buffer);
234 /* Get the clear selection preference */
235 count = sizeof(clearSelection);
236 RegQueryValueExA(hkey, "ClearAllSelections", 0, &type, clearSelection, &count);
237 RegCloseKey(hkey);
239 if ( !persistent_selection )
240 return FALSE;
242 /* Start up persistant WINE X clipboard server process which will
243 * take ownership of the X selection and continue to service selection
244 * requests from other apps.
246 selectionWindow = selectionPrevWindow;
247 if ( !fork() )
249 /* NOTE: This code only executes in the context of the child process
250 * Do note make any Wine specific calls here.
252 int dbgClasses = 0;
253 char selMask[8], dbgClassMask[8];
255 sprintf(selMask, "%d", selectionAcquired);
257 /* Build the debug class mask to pass to the server, by inheriting
258 * the settings for the clipboard debug channel.
260 dbgClasses |= FIXME_ON(clipboard) ? 1 : 0;
261 dbgClasses |= ERR_ON(clipboard) ? 2 : 0;
262 dbgClasses |= WARN_ON(clipboard) ? 4 : 0;
263 dbgClasses |= TRACE_ON(clipboard) ? 8 : 0;
264 sprintf(dbgClassMask, "%d", dbgClasses);
266 /* Exec the clipboard server passing it the selection and debug class masks */
267 execl( BINDIR "/wineclipsrv", "wineclipsrv",
268 selMask, dbgClassMask, clearSelection, NULL );
269 execlp( "wineclipsrv", "wineclipsrv", selMask, dbgClassMask, clearSelection, NULL );
270 execl( "./windows/x11drv/wineclipsrv", "wineclipsrv",
271 selMask, dbgClassMask, clearSelection, NULL );
273 /* Exec Failed! */
274 perror("Could not start Wine clipboard server");
275 exit( 1 ); /* Exit the child process */
278 /* Wait until the clipboard server acquires the selection.
279 * We must release the windows lock to enable Wine to process
280 * selection messages in response to the servers requests.
283 iWndsLocks = WIN_SuspendWndsLock();
285 /* We must wait until the server finishes acquiring the selection,
286 * before proceeding, otherwise the window which owns the selection
287 * will be destroyed prematurely!
288 * Create a non-signalled, auto-reset event which will be set by
289 * X11DRV_CLIPBOARD_ReleaseSelection, and wait until this gets
290 * signalled before proceeding.
293 if ( !(selectionClearEvent = CreateEventA(NULL, FALSE, FALSE, NULL)) )
294 ERR("Could not create wait object. Clipboard server won't start!\n");
295 else
297 /* Wait until we lose the selection, timing out after a minute */
299 TRACE("Waiting for clipboard server to acquire selection\n");
301 if ( MsgWaitForMultipleObjects( 1, &selectionClearEvent, FALSE, 60000, QS_ALLINPUT ) != WAIT_OBJECT_0 )
302 TRACE("Server could not acquire selection, or a timeout occurred!\n");
303 else
304 TRACE("Server successfully acquired selection\n");
306 /* Release the event */
307 CloseHandle(selectionClearEvent);
308 selectionClearEvent = 0;
311 WIN_RestoreWndsLock(iWndsLocks);
313 return TRUE;
317 /**************************************************************************
318 * X11DRV_CLIPBOARD_CacheDataFormats
320 * Caches the list of data formats available from the current selection.
321 * This queries the selection owner for the TARGETS property and saves all
322 * reported property types.
324 int X11DRV_CLIPBOARD_CacheDataFormats( Atom SelectionName )
326 Display *display = thread_display();
327 HWND hWnd = 0;
328 HWND hWndClipWindow = GetOpenClipboardWindow();
329 XEvent xe;
330 Atom aTargets;
331 Atom atype=AnyPropertyType;
332 int aformat;
333 unsigned long remain;
334 Atom* targetList=NULL;
335 Window w;
336 Window ownerSelection = 0;
338 TRACE("enter\n");
340 * Empty the clipboard cache
342 CLIPBOARD_EmptyCache(TRUE);
344 cSelectionTargets = 0;
345 selectionCacheSrc = SelectionName;
347 hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
349 ownerSelection = TSXGetSelectionOwner(display, SelectionName);
350 if ( !hWnd || (ownerSelection == None) )
351 return cSelectionTargets;
354 * Query the selection owner for the TARGETS property
356 w = X11DRV_get_whole_window( GetAncestor(hWnd,GA_ROOT) );
358 aTargets = TSXInternAtom(display, "TARGETS", False);
360 TRACE("Requesting TARGETS selection for '%s' (owner=%08x)...\n",
361 TSXGetAtomName(display, selectionCacheSrc), (unsigned)ownerSelection );
362 wine_tsx11_lock();
363 XConvertSelection(display, selectionCacheSrc, aTargets,
364 TSXInternAtom(display, "SELECTION_DATA", False),
365 w, CurrentTime);
368 * Wait until SelectionNotify is received
370 while( TRUE )
372 if( XCheckTypedWindowEvent(display, w, SelectionNotify, &xe) )
373 if( xe.xselection.selection == selectionCacheSrc )
374 break;
376 wine_tsx11_unlock();
378 /* Verify that the selection returned a valid TARGETS property */
379 if ( (xe.xselection.target != aTargets)
380 || (xe.xselection.property == None) )
382 TRACE("\tExit, could not retrieve TARGETS\n");
383 return cSelectionTargets;
386 /* Read the TARGETS property contents */
387 if(TSXGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
388 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat,
389 &cSelectionTargets, &remain, (unsigned char**)&targetList) != Success)
390 TRACE("\tCouldn't read TARGETS property\n");
391 else
393 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
394 TSXGetAtomName(display,atype),aformat,cSelectionTargets, remain);
396 * The TARGETS property should have returned us a list of atoms
397 * corresponding to each selection target format supported.
399 if( (atype == XA_ATOM || atype == aTargets) && aformat == 32 )
401 int i;
402 LPWINE_CLIPFORMAT lpFormat;
404 /* Cache these formats in the clipboard cache */
406 for (i = 0; i < cSelectionTargets; i++)
408 char *itemFmtName = TSXGetAtomName(display, targetList[i]);
409 UINT wFormat = X11DRV_CLIPBOARD_MapPropertyToFormat(itemFmtName);
412 * If the clipboard format maps to a Windows format, simply store
413 * the atom identifier and record its availablity status
414 * in the clipboard cache.
416 if (wFormat)
418 lpFormat = CLIPBOARD_LookupFormat( wFormat );
420 /* Don't replace if the property already cached is a native format,
421 * or if a PIXMAP is being replaced by a BITMAP.
423 if (lpFormat->wDataPresent &&
424 ( X11DRV_CLIPBOARD_IsNativeProperty(lpFormat->drvData)
425 || (lpFormat->drvData == XA_PIXMAP && targetList[i] == XA_BITMAP) )
428 TRACE("\tAtom# %d: '%s' --> FormatID(%d) %s (Skipped)\n",
429 i, itemFmtName, wFormat, lpFormat->Name);
431 else
433 lpFormat->wDataPresent = 1;
434 lpFormat->drvData = targetList[i];
435 TRACE("\tAtom# %d: '%s' --> FormatID(%d) %s\n",
436 i, itemFmtName, wFormat, lpFormat->Name);
440 TSXFree(itemFmtName);
444 /* Free the list of targets */
445 TSXFree(targetList);
448 return cSelectionTargets;
451 /**************************************************************************
452 * X11DRV_CLIPBOARD_ReadSelection
453 * Reads the contents of the X selection property into the WINE clipboard cache
454 * converting the selection into a format compatible with the windows clipboard
455 * if possible.
456 * This method is invoked only to read the contents of a the selection owned
457 * by an external application. i.e. when we do not own the X selection.
459 static BOOL X11DRV_CLIPBOARD_ReadSelection(UINT wFormat, Window w, Atom prop, Atom reqType)
461 Display *display = thread_display();
462 Atom atype=AnyPropertyType;
463 int aformat;
464 unsigned long total,nitems,remain,itemSize,val_cnt;
465 long lRequestLength,bwc;
466 unsigned char* val;
467 unsigned char* buffer;
468 LPWINE_CLIPFORMAT lpFormat;
469 BOOL bRet = FALSE;
470 HWND hWndClipWindow = GetOpenClipboardWindow();
473 if(prop == None)
474 return bRet;
476 TRACE("Reading X selection...\n");
478 TRACE("\tretrieving property %s from window %ld into %s\n",
479 TSXGetAtomName(display,reqType), (long)w, TSXGetAtomName(display,prop) );
482 * First request a zero length in order to figure out the request size.
484 if(TSXGetWindowProperty(display,w,prop,0,0,False, AnyPropertyType/*reqType*/,
485 &atype, &aformat, &nitems, &itemSize, &val) != Success)
487 WARN("\tcouldn't get property size\n");
488 return bRet;
491 /* Free zero length return data if any */
492 if ( val )
494 TSXFree(val);
495 val = NULL;
498 TRACE("\tretrieving %ld bytes...\n", itemSize * aformat/8);
499 lRequestLength = (itemSize * aformat/8)/4 + 1;
501 bwc = aformat/8;
502 /* we want to read the property, but not it too large of chunks or
503 we could hang the cause problems. Lets go for 4k blocks */
505 if(TSXGetWindowProperty(display,w,prop,0,4096,False,
506 AnyPropertyType/*reqType*/,
507 &atype, &aformat, &nitems, &remain, &buffer)
508 != Success)
510 WARN("\tcouldn't read property\n");
511 return bRet;
513 val = (char*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,
514 nitems*bwc);
515 memcpy(val,buffer,nitems*bwc);
516 TSXFree(buffer);
518 for (total = nitems*bwc,val_cnt=0; remain;)
520 val_cnt +=nitems*bwc;
521 TSXGetWindowProperty(display, w, prop,
522 (total / 4), 4096, False,
523 AnyPropertyType, &atype,
524 &aformat, &nitems, &remain,
525 &buffer);
527 total += nitems*bwc;
528 HeapReAlloc(GetProcessHeap(),0,val, total);
529 memcpy(&val[val_cnt], buffer, nitems*(aformat/8));
530 TSXFree(buffer);
532 nitems = total;
535 * Translate the X property into the appropriate Windows clipboard
536 * format, if possible.
538 if ( (reqType == XA_STRING)
539 && (atype == XA_STRING) && (aformat == 8) )
540 /* convert Unix text to CF_UNICODETEXT */
542 int i,inlcount = 0;
543 char* lpstr;
545 for(i=0; i <= nitems; i++)
546 if( val[i] == '\n' ) inlcount++;
548 if( (lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, nitems + inlcount + 1)) )
550 static UINT text_cp = (UINT)-1;
551 UINT count;
552 HANDLE hUnicodeText;
554 for(i=0,inlcount=0; i <= nitems; i++)
556 if( val[i] == '\n' ) lpstr[inlcount++]='\r';
557 lpstr[inlcount++]=val[i];
560 if(text_cp == (UINT)-1)
562 HKEY hkey;
563 /* default value */
564 text_cp = CP_ACP;
565 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\x11drv", &hkey))
567 char buf[20];
568 DWORD type, count = sizeof(buf);
569 if(!RegQueryValueExA(hkey, "TextCP", 0, &type, buf, &count))
570 text_cp = atoi(buf);
571 RegCloseKey(hkey);
575 count = MultiByteToWideChar(text_cp, 0, lpstr, -1, NULL, 0);
576 hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
577 if(hUnicodeText)
579 WCHAR *textW = GlobalLock(hUnicodeText);
580 MultiByteToWideChar(text_cp, 0, lpstr, -1, textW, count);
581 GlobalUnlock(hUnicodeText);
582 if (!SetClipboardData(CF_UNICODETEXT, hUnicodeText))
584 ERR("Not SET! Need to free our own block\n");
585 GlobalFree(hUnicodeText);
587 bRet = TRUE;
589 HeapFree(GetProcessHeap(), 0, lpstr);
592 else if ( reqType == XA_PIXMAP || reqType == XA_BITMAP ) /* treat PIXMAP as CF_DIB or CF_BITMAP */
594 /* Get the first pixmap handle passed to us */
595 Pixmap *pPixmap = (Pixmap *)val;
596 HANDLE hTargetImage = 0; /* Handle to store the converted bitmap or DIB */
598 if (aformat != 32 || nitems < 1 || atype != XA_PIXMAP
599 || (wFormat != CF_BITMAP && wFormat != CF_DIB))
601 WARN("\tUnimplemented format conversion request\n");
602 goto END;
605 if ( wFormat == CF_BITMAP )
607 /* For CF_BITMAP requests we must return an HBITMAP */
608 hTargetImage = X11DRV_BITMAP_CreateBitmapFromPixmap(*pPixmap, TRUE);
610 else if (wFormat == CF_DIB)
612 HWND hwnd = GetOpenClipboardWindow();
613 HDC hdc = GetDC(hwnd);
615 /* For CF_DIB requests we must return an HGLOBAL storing a packed DIB */
616 hTargetImage = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc, TRUE);
618 ReleaseDC(hdc, hwnd);
621 if (!hTargetImage)
623 WARN("PIXMAP conversion failed!\n" );
624 goto END;
627 /* Delete previous clipboard data */
628 lpFormat = CLIPBOARD_LookupFormat(wFormat);
629 if (lpFormat->wDataPresent && (lpFormat->hData16 || lpFormat->hData32))
630 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
632 /* Update the clipboard record */
633 lpFormat->wDataPresent = 1;
634 lpFormat->hData32 = hTargetImage;
635 lpFormat->hData16 = 0;
637 bRet = TRUE;
640 /* For native properties simply copy the X data without conversion */
641 else if (X11DRV_CLIPBOARD_IsNativeProperty(reqType)) /* <WCF>* */
643 HANDLE hClipData = 0;
644 void* lpClipData;
645 int cBytes = nitems * aformat/8;
647 if( cBytes )
649 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
650 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cBytes );
651 if( (lpClipData = GlobalLock(hClipData)) )
653 memcpy(lpClipData, val, cBytes);
654 GlobalUnlock(hClipData);
656 else
657 hClipData = 0;
660 if( hClipData )
662 /* delete previous clipboard record if any */
663 lpFormat = CLIPBOARD_LookupFormat(wFormat);
664 if (lpFormat->wDataPresent || lpFormat->hData16 || lpFormat->hData32)
665 CLIPBOARD_DeleteRecord(lpFormat, !(hWndClipWindow));
667 /* Update the clipboard record */
668 lpFormat->wDataPresent = 1;
669 lpFormat->hData32 = hClipData;
670 lpFormat->hData16 = 0;
672 bRet = TRUE;
675 else
677 WARN("\tUnimplemented format conversion request\n");
678 goto END;
681 END:
682 /* Delete the property on the window now that we are done
683 * This will send a PropertyNotify event to the selection owner. */
684 TSXDeleteProperty(display,w,prop);
686 /* Free the retrieved property data */
687 HeapFree(GetProcessHeap(),0,val);
688 return bRet;
691 /**************************************************************************
692 * X11DRV_CLIPBOARD_ReleaseSelection
694 * Release an XA_PRIMARY or XA_CLIPBOARD selection that we own, in response
695 * to a SelectionClear event.
696 * This can occur in response to another client grabbing the X selection.
697 * If the XA_CLIPBOARD selection is lost, we relinquish XA_PRIMARY as well.
699 void X11DRV_CLIPBOARD_ReleaseSelection(Atom selType, Window w, HWND hwnd)
701 Display *display = thread_display();
702 Atom xaClipboard = TSXInternAtom(display, "CLIPBOARD", False);
703 int clearAllSelections = 0;
704 HKEY hkey;
706 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\Clipboard", &hkey))
708 char buffer[20];
709 DWORD type, count = sizeof(buffer);
710 if(!RegQueryValueExA(hkey, "ClearAllSelections", 0, &type, buffer, &count))
711 clearAllSelections = atoi(buffer);
712 RegCloseKey(hkey);
715 /* w is the window that lost the selection
716 * selectionPrevWindow is nonzero if CheckSelection() was called.
719 TRACE("\tevent->window = %08x (sw = %08x, spw=%08x)\n",
720 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionPrevWindow );
722 if( selectionAcquired )
724 if( w == selectionWindow || selectionPrevWindow == None)
726 /* If we're losing the CLIPBOARD selection, or if the preferences in .winerc
727 * dictate that *all* selections should be cleared on loss of a selection,
728 * we must give up all the selections we own.
730 if ( clearAllSelections || (selType == xaClipboard) )
732 /* completely give up the selection */
733 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
735 /* We are completely giving up the selection.
736 * Make sure we can open the windows clipboard first. */
738 if ( !OpenClipboard(hwnd) )
741 * We can't empty the clipboard if we cant open it so abandon.
742 * Wine will think that it still owns the selection but this is
743 * safer than losing the selection without properly emptying
744 * the clipboard. Perhaps we should forcibly re-assert ownership
745 * of the CLIPBOARD selection in this case...
747 ERR("\tClipboard is busy. Could not give up selection!\n");
748 return;
751 /* We really lost CLIPBOARD but want to voluntarily lose PRIMARY */
752 if ( (selType == xaClipboard)
753 && (selectionAcquired & S_PRIMARY) )
755 XSetSelectionOwner(display, XA_PRIMARY, None, CurrentTime);
758 /* We really lost PRIMARY but want to voluntarily lose CLIPBOARD */
759 if ( (selType == XA_PRIMARY)
760 && (selectionAcquired & S_CLIPBOARD) )
762 XSetSelectionOwner(display, xaClipboard, None, CurrentTime);
765 selectionWindow = None;
766 PrimarySelectionOwner = ClipboardSelectionOwner = 0;
768 /* Empty the windows clipboard.
769 * We should pretend that we still own the selection BEFORE calling
770 * EmptyClipboard() since otherwise this has the side effect of
771 * triggering X11DRV_CLIPBOARD_Acquire() and causing the X selection
772 * to be re-acquired by us!
774 selectionAcquired = (S_PRIMARY | S_CLIPBOARD);
775 EmptyClipboard();
776 CloseClipboard();
778 /* Give up ownership of the windows clipboard */
779 CLIPBOARD_ReleaseOwner();
781 /* Reset the selection flags now that we are done */
782 selectionAcquired = S_NOSELECTION;
784 else if ( selType == XA_PRIMARY ) /* Give up only PRIMARY selection */
786 TRACE("Lost PRIMARY selection\n");
787 PrimarySelectionOwner = 0;
788 selectionAcquired &= ~S_PRIMARY; /* clear S_PRIMARY mask */
791 cSelectionTargets = 0;
793 /* but we'll keep existing data for internal use */
794 else if( w == selectionPrevWindow )
796 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
798 w = TSXGetSelectionOwner(display, XA_PRIMARY);
799 if( w == None )
800 TSXSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
802 w = TSXGetSelectionOwner(display, xaClipboard);
803 if( w == None )
804 TSXSetSelectionOwner(display, xaClipboard, selectionWindow, CurrentTime);
808 /* Signal to a selectionClearEvent listener if the selection is completely lost */
809 if (selectionClearEvent && !selectionAcquired)
811 TRACE("Lost all selections, signalling to selectionClearEvent listener\n");
812 SetEvent(selectionClearEvent);
815 selectionPrevWindow = None;
818 /**************************************************************************
819 * ReleaseClipboard (X11DRV.@)
820 * Voluntarily release all currently owned X selections
822 void X11DRV_ReleaseClipboard(void)
824 Display *display = thread_display();
825 if( selectionAcquired )
827 XEvent xe;
828 Window savePrevWindow = selectionWindow;
829 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
830 BOOL bHasPrimarySelection = selectionAcquired & S_PRIMARY;
832 selectionAcquired = S_NOSELECTION;
833 selectionPrevWindow = selectionWindow;
834 selectionWindow = None;
836 TRACE("\tgiving up selection (spw = %08x)\n",
837 (unsigned)selectionPrevWindow);
839 wine_tsx11_lock();
841 TRACE("Releasing CLIPBOARD selection\n");
842 XSetSelectionOwner(display, xaClipboard, None, CurrentTime);
843 if( selectionPrevWindow )
844 while( !XCheckTypedWindowEvent( display, selectionPrevWindow,
845 SelectionClear, &xe ) );
847 if ( bHasPrimarySelection )
849 TRACE("Releasing XA_PRIMARY selection\n");
850 selectionPrevWindow = savePrevWindow; /* May be cleared in X11DRV_CLIPBOARD_ReleaseSelection */
851 XSetSelectionOwner(display, XA_PRIMARY, None, CurrentTime);
853 if( selectionPrevWindow )
854 while( !XCheckTypedWindowEvent( display, selectionPrevWindow,
855 SelectionClear, &xe ) );
857 wine_tsx11_unlock();
860 /* Get rid of any Pixmap resources we may still have */
861 while (prop_head)
863 PROPERTY *prop = prop_head;
864 prop_head = prop->next;
865 XFreePixmap( gdi_display, prop->pixmap );
866 HeapFree( GetProcessHeap(), 0, prop );
870 /**************************************************************************
871 * AcquireClipboard (X11DRV.@)
873 void X11DRV_AcquireClipboard(void)
875 Display *display = thread_display();
876 Window owner;
877 HWND hWndClipWindow = GetOpenClipboardWindow();
880 * Acquire X selection if we don't already own it.
881 * Note that we only acquire the selection if it hasn't been already
882 * acquired by us, and ignore the fact that another X window may be
883 * asserting ownership. The reason for this is we need *any* top level
884 * X window to hold selection ownership. The actual clipboard data requests
885 * are made via GetClipboardData from EVENT_SelectionRequest and this
886 * ensures that the real HWND owner services the request.
887 * If the owning X window gets destroyed the selection ownership is
888 * re-cycled to another top level X window in X11DRV_CLIPBOARD_ResetOwner.
892 if ( !(selectionAcquired == (S_PRIMARY | S_CLIPBOARD)) )
894 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
895 owner = X11DRV_get_whole_window( GetAncestor( hWndClipWindow ? hWndClipWindow : AnyPopup(),
896 GA_ROOT ) );
898 /* Grab PRIMARY selection if not owned */
899 if ( !(selectionAcquired & S_PRIMARY) )
900 TSXSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
902 /* Grab CLIPBOARD selection if not owned */
903 if ( !(selectionAcquired & S_CLIPBOARD) )
904 TSXSetSelectionOwner(display, xaClipboard, owner, CurrentTime);
906 if( TSXGetSelectionOwner(display,XA_PRIMARY) == owner )
907 selectionAcquired |= S_PRIMARY;
909 if( TSXGetSelectionOwner(display,xaClipboard) == owner)
910 selectionAcquired |= S_CLIPBOARD;
912 if (selectionAcquired)
914 selectionWindow = owner;
915 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
920 /**************************************************************************
921 * IsClipboardFormatAvailable (X11DRV.@)
923 * Checks if the specified format is available in the current selection
924 * Only invoked when WINE is not the selection owner
926 BOOL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
928 Display *display = thread_display();
929 Atom xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
930 Window ownerPrimary = TSXGetSelectionOwner(display,XA_PRIMARY);
931 Window ownerClipboard = TSXGetSelectionOwner(display,xaClipboard);
933 TRACE("enter for %d\n", wFormat);
936 * If the selection has not been previously cached, or the selection has changed,
937 * try and cache the list of available selection targets from the current selection.
939 if ( !cSelectionTargets || (PrimarySelectionOwner != ownerPrimary)
940 || (ClipboardSelectionOwner != ownerClipboard) )
943 * First try caching the CLIPBOARD selection.
944 * If unavailable try PRIMARY.
946 if ( X11DRV_CLIPBOARD_CacheDataFormats(xaClipboard) == 0 )
948 X11DRV_CLIPBOARD_CacheDataFormats(XA_PRIMARY);
951 ClipboardSelectionOwner = ownerClipboard;
952 PrimarySelectionOwner = ownerPrimary;
955 /* Exit if there is no selection */
956 if ( !ownerClipboard && !ownerPrimary )
958 TRACE("There is no selection owner\n");
959 return FALSE;
962 /* Check if the format is available in the clipboard cache */
963 if ( CLIPBOARD_IsPresent(wFormat) )
964 return TRUE;
967 * Many X client apps (such as XTerminal) don't support being queried
968 * for the "TARGETS" target atom. To handle such clients we must actually
969 * try to convert the selection to the requested type.
971 if ( !cSelectionTargets )
972 return X11DRV_GetClipboardData( wFormat );
974 TRACE("There is no selection\n");
975 return FALSE;
978 /**************************************************************************
979 * RegisterClipboardFormat (X11DRV.@)
981 * Registers a custom X clipboard format
982 * Returns: TRUE - success, FALSE - failure
984 BOOL X11DRV_RegisterClipboardFormat( LPCSTR FormatName )
986 Display *display = thread_display();
987 Atom prop = None;
988 char str[256];
991 * If an X atom is registered for this format, return that
992 * Otherwise register a new atom.
994 if (FormatName)
996 /* Add a WINE specific prefix to the format */
997 strcpy(str, FMT_PREFIX);
998 strncat(str, FormatName, sizeof(str) - strlen(FMT_PREFIX));
999 prop = TSXInternAtom(display, str, False);
1002 return (prop) ? TRUE : FALSE;
1005 /**************************************************************************
1006 * IsSelectionOwner (X11DRV.@)
1008 * Returns: TRUE - We(WINE) own the selection, FALSE - Selection not owned by us
1010 BOOL X11DRV_IsSelectionOwner(void)
1012 return selectionAcquired;
1015 /**************************************************************************
1016 * SetClipboardData (X11DRV.@)
1018 * We don't need to do anything special here since the clipboard code
1019 * maintains the cache.
1022 void X11DRV_SetClipboardData(UINT wFormat)
1024 /* Make sure we have acquired the X selection */
1025 X11DRV_AcquireClipboard();
1028 /**************************************************************************
1029 * GetClipboardData (X11DRV.@)
1031 * This method is invoked only when we DO NOT own the X selection
1033 * NOTE: Clipboard driver get requests only for CF_UNICODETEXT data.
1034 * We always get the data from the selection client each time,
1035 * since we have no way of determining if the data in our cache is stale.
1037 BOOL X11DRV_GetClipboardData(UINT wFormat)
1039 Display *display = thread_display();
1040 BOOL bRet = selectionAcquired;
1041 HWND hWndClipWindow = GetOpenClipboardWindow();
1042 HWND hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
1043 LPWINE_CLIPFORMAT lpFormat;
1045 TRACE("%d\n", wFormat);
1047 if (!selectionAcquired)
1049 XEvent xe;
1050 Atom propRequest;
1051 Window w = X11DRV_get_whole_window( GetAncestor( hWnd, GA_ROOT ));
1053 /* Map the format ID requested to an X selection property.
1054 * If the format is in the cache, use the atom associated
1055 * with it.
1058 lpFormat = CLIPBOARD_LookupFormat( wFormat );
1059 if (lpFormat && lpFormat->wDataPresent && lpFormat->drvData)
1060 propRequest = (Atom)lpFormat->drvData;
1061 else
1062 propRequest = X11DRV_CLIPBOARD_MapFormatToProperty(wFormat);
1064 if (propRequest)
1066 TRACE("Requesting %s selection from %s...\n",
1067 TSXGetAtomName(display, propRequest),
1068 TSXGetAtomName(display, selectionCacheSrc) );
1069 wine_tsx11_lock();
1070 XConvertSelection(display, selectionCacheSrc, propRequest,
1071 TSXInternAtom(display, "SELECTION_DATA", False),
1072 w, CurrentTime);
1074 /* wait until SelectionNotify is received */
1076 while( TRUE )
1078 if( XCheckTypedWindowEvent(display, w, SelectionNotify, &xe) )
1079 if( xe.xselection.selection == selectionCacheSrc )
1080 break;
1082 wine_tsx11_unlock();
1085 * Read the contents of the X selection property into WINE's
1086 * clipboard cache converting the selection to be compatible if possible.
1088 bRet = X11DRV_CLIPBOARD_ReadSelection( wFormat,
1089 xe.xselection.requestor,
1090 xe.xselection.property,
1091 xe.xselection.target);
1093 else
1094 bRet = FALSE;
1096 TRACE("\tpresent %s = %i\n", CLIPBOARD_GetFormatName(wFormat), bRet );
1099 TRACE("Returning %d\n", bRet);
1101 return bRet;
1104 /**************************************************************************
1105 * ResetSelectionOwner (X11DRV.@)
1107 * Called from DestroyWindow() to prevent X selection from being lost when
1108 * a top level window is destroyed, by switching ownership to another top
1109 * level window.
1110 * Any top level window can own the selection. See X11DRV_CLIPBOARD_Acquire
1111 * for a more detailed description of this.
1113 void X11DRV_ResetSelectionOwner(HWND hwnd, BOOL bFooBar)
1115 Display *display = thread_display();
1116 HWND hWndClipOwner = 0;
1117 HWND tmp;
1118 Window XWnd = X11DRV_get_whole_window(hwnd);
1119 Atom xaClipboard;
1120 BOOL bLostSelection = FALSE;
1122 /* There is nothing to do if we don't own the selection,
1123 * or if the X window which currently owns the selecion is different
1124 * from the one passed in.
1126 if ( !selectionAcquired || XWnd != selectionWindow
1127 || selectionWindow == None )
1128 return;
1130 if ( (bFooBar && XWnd) || (!bFooBar && !XWnd) )
1131 return;
1133 hWndClipOwner = GetClipboardOwner();
1134 xaClipboard = TSXInternAtom(display, _CLIPBOARD, False);
1136 TRACE("clipboard owner = %04x, selection window = %08x\n",
1137 hWndClipOwner, (unsigned)selectionWindow);
1139 /* now try to salvage current selection from being destroyed by X */
1141 TRACE("\tchecking %08x\n", (unsigned) XWnd);
1143 selectionPrevWindow = selectionWindow;
1144 selectionWindow = None;
1146 if (!(tmp = GetWindow( hwnd, GW_HWNDNEXT ))) tmp = GetWindow( hwnd, GW_HWNDFIRST );
1147 if (tmp && tmp != hwnd) selectionWindow = X11DRV_get_whole_window(tmp);
1149 if( selectionWindow != None )
1151 /* We must pretend that we don't own the selection while making the switch
1152 * since a SelectionClear event will be sent to the last owner.
1153 * If there is no owner X11DRV_CLIPBOARD_ReleaseSelection will do nothing.
1155 int saveSelectionState = selectionAcquired;
1156 selectionAcquired = False;
1158 TRACE("\tswitching selection from %08x to %08x\n",
1159 (unsigned)selectionPrevWindow, (unsigned)selectionWindow);
1161 /* Assume ownership for the PRIMARY and CLIPBOARD selection */
1162 if ( saveSelectionState & S_PRIMARY )
1163 TSXSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
1165 TSXSetSelectionOwner(display, xaClipboard, selectionWindow, CurrentTime);
1167 /* Restore the selection masks */
1168 selectionAcquired = saveSelectionState;
1170 /* Lose the selection if something went wrong */
1171 if ( ( (saveSelectionState & S_PRIMARY) &&
1172 (TSXGetSelectionOwner(display, XA_PRIMARY) != selectionWindow) )
1173 || (TSXGetSelectionOwner(display, xaClipboard) != selectionWindow) )
1175 bLostSelection = TRUE;
1176 goto END;
1178 else
1180 /* Update selection state */
1181 if (saveSelectionState & S_PRIMARY)
1182 PrimarySelectionOwner = selectionWindow;
1184 ClipboardSelectionOwner = selectionWindow;
1187 else
1189 bLostSelection = TRUE;
1190 goto END;
1193 END:
1194 if (bLostSelection)
1196 /* Launch the clipboard server if the selection can no longer be recyled
1197 * to another top level window. */
1199 if ( !X11DRV_CLIPBOARD_LaunchServer() )
1201 /* Empty the windows clipboard if the server was not launched.
1202 * We should pretend that we still own the selection BEFORE calling
1203 * EmptyClipboard() since otherwise this has the side effect of
1204 * triggering X11DRV_CLIPBOARD_Acquire() and causing the X selection
1205 * to be re-acquired by us!
1208 TRACE("\tLost the selection! Emptying the clipboard...\n");
1210 OpenClipboard( 0 );
1211 selectionAcquired = (S_PRIMARY | S_CLIPBOARD);
1212 EmptyClipboard();
1214 CloseClipboard();
1216 /* Give up ownership of the windows clipboard */
1217 CLIPBOARD_ReleaseOwner();
1220 selectionAcquired = S_NOSELECTION;
1221 ClipboardSelectionOwner = PrimarySelectionOwner = 0;
1222 selectionWindow = 0;
1226 /**************************************************************************
1227 * X11DRV_CLIPBOARD_RegisterPixmapResource
1228 * Registers a Pixmap resource which is to be associated with a property Atom.
1229 * When the property is destroyed we also destroy the Pixmap through the
1230 * PropertyNotify event.
1232 BOOL X11DRV_CLIPBOARD_RegisterPixmapResource( Atom property, Pixmap pixmap )
1234 PROPERTY *prop = HeapAlloc( GetProcessHeap(), 0, sizeof(*prop) );
1235 if (!prop) return FALSE;
1236 prop->atom = property;
1237 prop->pixmap = pixmap;
1238 prop->next = prop_head;
1239 prop_head = prop;
1240 return TRUE;
1243 /**************************************************************************
1244 * X11DRV_CLIPBOARD_FreeResources
1246 * Called from EVENT_PropertyNotify() to give us a chance to destroy
1247 * any resources associated with this property.
1249 void X11DRV_CLIPBOARD_FreeResources( Atom property )
1251 /* Do a simple linear search to see if we have a Pixmap resource
1252 * associated with this property and release it.
1254 PROPERTY **prop = &prop_head;
1256 while (*prop)
1258 if ((*prop)->atom == property)
1260 PROPERTY *next = (*prop)->next;
1261 XFreePixmap( gdi_display, (*prop)->pixmap );
1262 HeapFree( GetProcessHeap(), 0, *prop );
1263 *prop = next;
1265 else prop = &(*prop)->next;