2 * X11 clipboard windows driver
4 * Copyright 1994 Martin Ayotte
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 * This file contains the X specific implementation for the windows
26 * Wine's internal clipboard is exposed to external apps via the X
27 * selection mechanism.
28 * Currently the driver asserts ownership via two selection atoms:
29 * 1. PRIMARY(XA_PRIMARY)
32 * In our implementation, the CLIPBOARD selection takes precedence over PRIMARY,
33 * i.e. if a CLIPBOARD selection is available, it is used instead of PRIMARY.
34 * When Wine takes ownership of the clipboard, it takes ownership of BOTH selections.
35 * While giving up selection ownership, if the CLIPBOARD selection is lost,
36 * it will lose both PRIMARY and CLIPBOARD and empty the clipboard.
37 * However if only PRIMARY is lost, it will continue to hold the CLIPBOARD selection
38 * (leaving the clipboard cache content unaffected).
40 * Every format exposed via a windows clipboard format is also exposed through
41 * a corresponding X selection target. A selection target atom is synthesized
42 * whenever a new Windows clipboard format is registered via RegisterClipboardFormat,
43 * or when a built-in format is used for the first time.
44 * Windows native format are exposed by prefixing the format name with "<WCF>"
45 * This allows us to uniquely identify windows native formats exposed by other
48 * In order to allow external applications to query WINE for supported formats,
49 * we respond to the "TARGETS" selection target. (See EVENT_SelectionRequest
50 * for implementation) We use the same mechanism to query external clients for
51 * availability of a particular format, by caching the list of available targets
52 * by using the clipboard cache's "delayed render" mechanism. If a selection client
53 * does not support the "TARGETS" selection target, we actually attempt to retrieve
54 * the format requested as a fallback mechanism.
56 * Certain Windows native formats are automatically converted to X native formats
57 * and vice versa. If a native format is available in the selection, it takes
58 * precedence, in order to avoid unnecessary conversions.
75 #include "clipboard.h"
78 #include "wine/debug.h"
80 WINE_DEFAULT_DEBUG_CHANNEL(clipboard
);
82 /* Maximum wait time for slection notify */
83 #define MAXSELECTIONNOTIFYWAIT 5
87 #define S_NOSELECTION 0
91 /* X selection context info */
93 static char _CLIPBOARD
[] = "CLIPBOARD"; /* CLIPBOARD atom name */
94 static char FMT_PREFIX
[] = "<WCF>"; /* Prefix for windows specific formats */
95 static int selectionAcquired
= 0; /* Contains the current selection masks */
96 static Window selectionWindow
= None
; /* The top level X window which owns the selection */
97 static Window selectionPrevWindow
= None
; /* The last X window that owned the selection */
98 static Window PrimarySelectionOwner
= None
; /* The window which owns the primary selection */
99 static Window ClipboardSelectionOwner
= None
; /* The window which owns the clipboard selection */
100 static unsigned long cSelectionTargets
= 0; /* Number of target formats reported by TARGETS selection */
101 static Atom selectionCacheSrc
= XA_PRIMARY
; /* The selection source from which the clipboard cache was filled */
102 static HANDLE selectionClearEvent
= 0;/* Synchronization object used to block until server is started */
104 typedef struct tagPROPERTY
106 struct tagPROPERTY
*next
;
111 static PROPERTY
*prop_head
;
114 /**************************************************************************
115 * X11DRV_CLIPBOARD_MapPropertyToFormat
117 * Map an X selection property type atom name to a windows clipboard format ID
119 UINT
X11DRV_CLIPBOARD_MapPropertyToFormat(char *itemFmtName
)
122 * If the property name starts with FMT_PREFIX strip this off and
123 * get the ID for a custom Windows registered format with this name.
124 * We can also understand STRING, PIXMAP and BITMAP.
126 if ( NULL
== itemFmtName
)
128 else if ( 0 == strncmp(itemFmtName
, FMT_PREFIX
, strlen(FMT_PREFIX
)) )
129 return RegisterClipboardFormatA(itemFmtName
+ strlen(FMT_PREFIX
));
130 else if ( 0 == strcmp(itemFmtName
, "STRING") )
131 return CF_UNICODETEXT
;
132 else if ( 0 == strcmp(itemFmtName
, "PIXMAP")
133 || 0 == strcmp(itemFmtName
, "BITMAP") )
136 * Return CF_DIB as first preference, if WINE is the selection owner
137 * and if CF_DIB exists in the cache.
138 * If wine dowsn't own the selection we always return CF_DIB
140 if ( !X11DRV_IsSelectionOwner() )
142 else if ( CLIPBOARD_IsPresent(CF_DIB
) )
148 WARN("\tNo mapping to Windows clipboard format for property %s\n", itemFmtName
);
152 /**************************************************************************
153 * X11DRV_CLIPBOARD_MapFormatToProperty
155 * Map a windows clipboard format ID to an X selection property atom
157 Atom
X11DRV_CLIPBOARD_MapFormatToProperty(UINT wFormat
)
163 /* We support only CF_UNICODETEXT, other formats are synthesized */
176 * Request a PIXMAP, only if WINE is NOT the selection owner,
177 * AND the requested format is not in the cache.
179 if ( !X11DRV_IsSelectionOwner() && !CLIPBOARD_IsPresent(wFormat
) )
184 /* Fall through to the default case in order to use the native format */
190 * If an X atom is registered for this format, return that
191 * Otherwise register a new atom.
194 int plen
= strlen(FMT_PREFIX
);
196 strcpy(str
, FMT_PREFIX
);
198 if (CLIPBOARD_GetFormatName(wFormat
, str
+ plen
, sizeof(str
) - plen
))
199 prop
= TSXInternAtom(thread_display(), str
, False
);
206 TRACE("\tNo mapping to X property for Windows clipboard format %d(%s)\n",
207 wFormat
, CLIPBOARD_GetFormatName(wFormat
, NULL
, 0));
212 /**************************************************************************
213 * X11DRV_CLIPBOARD_IsNativeProperty
215 * Checks if a property is a native Wine property type
217 BOOL
X11DRV_CLIPBOARD_IsNativeProperty(Atom prop
)
219 char *itemFmtName
= TSXGetAtomName(thread_display(), prop
);
222 if ( 0 == strncmp(itemFmtName
, FMT_PREFIX
, strlen(FMT_PREFIX
)) )
225 TSXFree(itemFmtName
);
230 /**************************************************************************
231 * X11DRV_CLIPBOARD_LaunchServer
232 * Launches the clipboard server. This is called from X11DRV_CLIPBOARD_ResetOwner
233 * when the selection can no longer be recyled to another top level window.
234 * In order to make the selection persist after Wine shuts down a server
235 * process is launched which services subsequent selection requests.
237 BOOL
X11DRV_CLIPBOARD_LaunchServer()
240 char clearSelection
[8] = "0";
241 int persistent_selection
= 1;
245 /* If persistant selection has been disabled in the .winerc Clipboard section,
246 * don't launch the server
248 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE
, "Software\\Wine\\Wine\\Config\\Clipboard", &hkey
))
251 DWORD type
, count
= sizeof(buffer
);
252 if(!RegQueryValueExA(hkey
, "PersistentSelection", 0, &type
, buffer
, &count
))
253 persistent_selection
= atoi(buffer
);
255 /* Get the clear selection preference */
256 count
= sizeof(clearSelection
);
257 RegQueryValueExA(hkey
, "ClearAllSelections", 0, &type
, clearSelection
, &count
);
260 if ( !persistent_selection
)
263 /* Start up persistant WINE X clipboard server process which will
264 * take ownership of the X selection and continue to service selection
265 * requests from other apps.
268 if(pipe(fd
) == -1) return FALSE
;
269 fcntl(fd
[1], F_SETFD
, 1); /* set close on exec */
271 selectionWindow
= selectionPrevWindow
;
274 /* NOTE: This code only executes in the context of the child process
275 * Do note make any Wine specific calls here.
278 char selMask
[8], dbgClassMask
[8];
281 sprintf(selMask
, "%d", selectionAcquired
);
283 /* Build the debug class mask to pass to the server, by inheriting
284 * the settings for the clipboard debug channel.
286 dbgClasses
|= FIXME_ON(clipboard
) ? 1 : 0;
287 dbgClasses
|= ERR_ON(clipboard
) ? 2 : 0;
288 dbgClasses
|= WARN_ON(clipboard
) ? 4 : 0;
289 dbgClasses
|= TRACE_ON(clipboard
) ? 8 : 0;
290 sprintf(dbgClassMask
, "%d", dbgClasses
);
292 /* Exec the clipboard server passing it the selection and debug class masks */
293 execl( BINDIR
"/wineclipsrv", "wineclipsrv",
294 selMask
, dbgClassMask
, clearSelection
, NULL
);
295 execlp( "wineclipsrv", "wineclipsrv", selMask
, dbgClassMask
, clearSelection
, NULL
);
298 perror("Could not start Wine clipboard server");
299 write(fd
[1], &err
, sizeof(err
));
300 _exit( 1 ); /* Exit the child process */
304 if(read(fd
[0], &err
, sizeof(err
)) > 0) { /* exec failed */
310 /* Wait until the clipboard server acquires the selection.
311 * We must release the windows lock to enable Wine to process
312 * selection messages in response to the servers requests.
315 iWndsLocks
= WIN_SuspendWndsLock();
317 /* We must wait until the server finishes acquiring the selection,
318 * before proceeding, otherwise the window which owns the selection
319 * will be destroyed prematurely!
320 * Create a non-signalled, auto-reset event which will be set by
321 * X11DRV_CLIPBOARD_ReleaseSelection, and wait until this gets
322 * signalled before proceeding.
325 if ( !(selectionClearEvent
= CreateEventA(NULL
, FALSE
, FALSE
, NULL
)) )
326 ERR("Could not create wait object. Clipboard server won't start!\n");
329 /* Wait until we lose the selection, timing out after a minute */
330 DWORD start_time
, timeout
, elapsed
, ret
;
332 TRACE("Waiting for clipboard server to acquire selection\n");
335 start_time
= GetTickCount();
339 ret
= MsgWaitForMultipleObjects( 1, &selectionClearEvent
, FALSE
, timeout
- elapsed
, QS_ALLINPUT
);
340 if (ret
!= WAIT_OBJECT_0
+1)
342 elapsed
= GetTickCount() - start_time
;
343 if (elapsed
> timeout
)
347 if ( ret
!= WAIT_OBJECT_0
)
348 TRACE("Server could not acquire selection, or a timeout occurred!\n");
350 TRACE("Server successfully acquired selection\n");
352 /* Release the event */
353 CloseHandle(selectionClearEvent
);
354 selectionClearEvent
= 0;
357 WIN_RestoreWndsLock(iWndsLocks
);
363 /**************************************************************************
364 * X11DRV_CLIPBOARD_CacheDataFormats
366 * Caches the list of data formats available from the current selection.
367 * This queries the selection owner for the TARGETS property and saves all
368 * reported property types.
370 int X11DRV_CLIPBOARD_CacheDataFormats( Atom SelectionName
)
372 Display
*display
= thread_display();
374 HWND hWndClipWindow
= GetOpenClipboardWindow();
377 Atom atype
=AnyPropertyType
;
379 unsigned long remain
;
380 Atom
* targetList
=NULL
;
382 Window ownerSelection
= 0;
387 * Empty the clipboard cache
389 CLIPBOARD_EmptyCache(TRUE
);
391 cSelectionTargets
= 0;
392 selectionCacheSrc
= SelectionName
;
394 hWnd
= (hWndClipWindow
) ? hWndClipWindow
: GetActiveWindow();
396 ownerSelection
= TSXGetSelectionOwner(display
, SelectionName
);
397 if ( !hWnd
|| (ownerSelection
== None
) )
398 return cSelectionTargets
;
401 * Query the selection owner for the TARGETS property
403 w
= X11DRV_get_whole_window( GetAncestor(hWnd
,GA_ROOT
) );
405 aTargets
= TSXInternAtom(display
, "TARGETS", False
);
407 TRACE("Requesting TARGETS selection for '%s' (owner=%08x)...\n",
408 TSXGetAtomName(display
, selectionCacheSrc
), (unsigned)ownerSelection
);
410 XConvertSelection(display
, selectionCacheSrc
, aTargets
,
411 TSXInternAtom(display
, "SELECTION_DATA", False
),
415 * Wait until SelectionNotify is received
417 maxtm
= time(NULL
) + MAXSELECTIONNOTIFYWAIT
; /* Timeout after a maximum wait */
418 while( maxtm
- time(NULL
) > 0 )
420 if( XCheckTypedWindowEvent(display
, w
, SelectionNotify
, &xe
) )
421 if( xe
.xselection
.selection
== selectionCacheSrc
)
426 /* Verify that the selection returned a valid TARGETS property */
427 if ( (xe
.xselection
.target
!= aTargets
)
428 || (xe
.xselection
.property
== None
) )
430 TRACE("\tExit, could not retrieve TARGETS\n");
431 return cSelectionTargets
;
434 /* Read the TARGETS property contents */
435 if(TSXGetWindowProperty(display
, xe
.xselection
.requestor
, xe
.xselection
.property
,
436 0, 0x3FFF, True
, AnyPropertyType
/*XA_ATOM*/, &atype
, &aformat
,
437 &cSelectionTargets
, &remain
, (unsigned char**)&targetList
) != Success
)
438 TRACE("\tCouldn't read TARGETS property\n");
441 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
442 TSXGetAtomName(display
,atype
),aformat
,cSelectionTargets
, remain
);
444 * The TARGETS property should have returned us a list of atoms
445 * corresponding to each selection target format supported.
447 if( (atype
== XA_ATOM
|| atype
== aTargets
) && aformat
== 32 )
450 LPWINE_CLIPFORMAT lpFormat
;
452 /* Cache these formats in the clipboard cache */
454 for (i
= 0; i
< cSelectionTargets
; i
++)
456 char *itemFmtName
= TSXGetAtomName(display
, targetList
[i
]);
457 UINT wFormat
= X11DRV_CLIPBOARD_MapPropertyToFormat(itemFmtName
);
460 * If the clipboard format maps to a Windows format, simply store
461 * the atom identifier and record its availablity status
462 * in the clipboard cache.
466 lpFormat
= CLIPBOARD_LookupFormat( wFormat
);
468 /* Don't replace if the property already cached is a native format,
469 * or if a PIXMAP is being replaced by a BITMAP.
471 if (lpFormat
->wDataPresent
&&
472 ( X11DRV_CLIPBOARD_IsNativeProperty(lpFormat
->drvData
)
473 || (lpFormat
->drvData
== XA_PIXMAP
&& targetList
[i
] == XA_BITMAP
) )
476 TRACE("\tAtom# %d: '%s' --> FormatID(%d) %s (Skipped)\n",
477 i
, itemFmtName
, wFormat
, lpFormat
->Name
);
481 lpFormat
->wDataPresent
= 1;
482 lpFormat
->drvData
= targetList
[i
];
483 TRACE("\tAtom# %d: '%s' --> FormatID(%d) %s\n",
484 i
, itemFmtName
, wFormat
, lpFormat
->Name
);
488 TSXFree(itemFmtName
);
492 /* Free the list of targets */
496 return cSelectionTargets
;
499 /**************************************************************************
500 * X11DRV_CLIPBOARD_ReadSelection
501 * Reads the contents of the X selection property into the WINE clipboard cache
502 * converting the selection into a format compatible with the windows clipboard
504 * This method is invoked only to read the contents of a the selection owned
505 * by an external application. i.e. when we do not own the X selection.
507 static BOOL
X11DRV_CLIPBOARD_ReadSelection(UINT wFormat
, Window w
, Atom prop
, Atom reqType
)
509 Display
*display
= thread_display();
510 Atom atype
=AnyPropertyType
;
512 unsigned long total
,nitems
,remain
,itemSize
,val_cnt
;
513 long lRequestLength
,bwc
;
515 unsigned char* buffer
;
516 LPWINE_CLIPFORMAT lpFormat
;
518 HWND hWndClipWindow
= GetOpenClipboardWindow();
524 TRACE("Reading X selection...\n");
526 TRACE("\tretrieving property %s from window %ld into %s\n",
527 TSXGetAtomName(display
,reqType
), (long)w
, TSXGetAtomName(display
,prop
) );
530 * First request a zero length in order to figure out the request size.
532 if(TSXGetWindowProperty(display
,w
,prop
,0,0,False
, AnyPropertyType
/*reqType*/,
533 &atype
, &aformat
, &nitems
, &itemSize
, &val
) != Success
)
535 WARN("\tcouldn't get property size\n");
539 /* Free zero length return data if any */
546 TRACE("\tretrieving %ld bytes...\n", itemSize
* aformat
/8);
547 lRequestLength
= (itemSize
* aformat
/8)/4 + 1;
550 /* we want to read the property, but not it too large of chunks or
551 we could hang the cause problems. Lets go for 4k blocks */
553 if(TSXGetWindowProperty(display
,w
,prop
,0,4096,False
,
554 AnyPropertyType
/*reqType*/,
555 &atype
, &aformat
, &nitems
, &remain
, &buffer
)
558 WARN("\tcouldn't read property\n");
561 val
= (char*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY
,
563 memcpy(val
,buffer
,nitems
*bwc
);
566 for (total
= nitems
*bwc
,val_cnt
=0; remain
;)
568 val_cnt
+=nitems
*bwc
;
569 TSXGetWindowProperty(display
, w
, prop
,
570 (total
/ 4), 4096, False
,
571 AnyPropertyType
, &atype
,
572 &aformat
, &nitems
, &remain
,
576 HeapReAlloc(GetProcessHeap(),0,val
, total
);
577 memcpy(&val
[val_cnt
], buffer
, nitems
*(aformat
/8));
583 * Translate the X property into the appropriate Windows clipboard
584 * format, if possible.
586 if ( (reqType
== XA_STRING
)
587 && (atype
== XA_STRING
) && (aformat
== 8) )
588 /* convert Unix text to CF_UNICODETEXT */
593 for(i
=0; i
<= nitems
; i
++)
594 if( val
[i
] == '\n' ) inlcount
++;
596 if( (lpstr
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, nitems
+ inlcount
+ 1)) )
598 static UINT text_cp
= (UINT
)-1;
602 for(i
=0,inlcount
=0; i
<= nitems
; i
++)
604 if( val
[i
] == '\n' ) lpstr
[inlcount
++]='\r';
605 lpstr
[inlcount
++]=val
[i
];
608 if(text_cp
== (UINT
)-1)
613 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE
, "Software\\Wine\\Wine\\Config\\x11drv", &hkey
))
616 DWORD type
, count
= sizeof(buf
);
617 if(!RegQueryValueExA(hkey
, "TextCP", 0, &type
, buf
, &count
))
623 count
= MultiByteToWideChar(text_cp
, 0, lpstr
, -1, NULL
, 0);
624 hUnicodeText
= GlobalAlloc(GMEM_MOVEABLE
| GMEM_DDESHARE
, count
* sizeof(WCHAR
));
627 WCHAR
*textW
= GlobalLock(hUnicodeText
);
628 MultiByteToWideChar(text_cp
, 0, lpstr
, -1, textW
, count
);
629 GlobalUnlock(hUnicodeText
);
630 if (!SetClipboardData(CF_UNICODETEXT
, hUnicodeText
))
632 ERR("Not SET! Need to free our own block\n");
633 GlobalFree(hUnicodeText
);
637 HeapFree(GetProcessHeap(), 0, lpstr
);
640 else if ( reqType
== XA_PIXMAP
|| reqType
== XA_BITMAP
) /* treat PIXMAP as CF_DIB or CF_BITMAP */
642 /* Get the first pixmap handle passed to us */
643 Pixmap
*pPixmap
= (Pixmap
*)val
;
644 HANDLE hTargetImage
= 0; /* Handle to store the converted bitmap or DIB */
646 if (aformat
!= 32 || nitems
< 1 || atype
!= XA_PIXMAP
647 || (wFormat
!= CF_BITMAP
&& wFormat
!= CF_DIB
))
649 WARN("\tUnimplemented format conversion request\n");
653 if ( wFormat
== CF_BITMAP
)
655 /* For CF_BITMAP requests we must return an HBITMAP */
656 hTargetImage
= X11DRV_BITMAP_CreateBitmapFromPixmap(*pPixmap
, TRUE
);
658 else if (wFormat
== CF_DIB
)
660 HWND hwnd
= GetOpenClipboardWindow();
661 HDC hdc
= GetDC(hwnd
);
663 /* For CF_DIB requests we must return an HGLOBAL storing a packed DIB */
664 hTargetImage
= X11DRV_DIB_CreateDIBFromPixmap(*pPixmap
, hdc
, TRUE
);
666 ReleaseDC(hwnd
, hdc
);
671 WARN("PIXMAP conversion failed!\n" );
675 /* Delete previous clipboard data */
676 lpFormat
= CLIPBOARD_LookupFormat(wFormat
);
677 if (lpFormat
->wDataPresent
&& (lpFormat
->hData16
|| lpFormat
->hData32
))
678 CLIPBOARD_DeleteRecord(lpFormat
, !(hWndClipWindow
));
680 /* Update the clipboard record */
681 lpFormat
->wDataPresent
= 1;
682 lpFormat
->hData32
= hTargetImage
;
683 lpFormat
->hData16
= 0;
688 /* For native properties simply copy the X data without conversion */
689 else if (X11DRV_CLIPBOARD_IsNativeProperty(reqType
)) /* <WCF>* */
691 HANDLE hClipData
= 0;
693 int cBytes
= nitems
* aformat
/8;
697 if (wFormat
== CF_METAFILEPICT
|| wFormat
== CF_ENHMETAFILE
)
699 hClipData
= X11DRV_CLIPBOARD_SerializeMetafile(wFormat
, (HANDLE
)val
, cBytes
, FALSE
);
703 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
704 hClipData
= GlobalAlloc(GMEM_MOVEABLE
| GMEM_DDESHARE
, cBytes
);
705 if( (lpClipData
= GlobalLock(hClipData
)) )
707 memcpy(lpClipData
, val
, cBytes
);
708 GlobalUnlock(hClipData
);
717 /* delete previous clipboard record if any */
718 lpFormat
= CLIPBOARD_LookupFormat(wFormat
);
719 if (lpFormat
->wDataPresent
|| lpFormat
->hData16
|| lpFormat
->hData32
)
720 CLIPBOARD_DeleteRecord(lpFormat
, !(hWndClipWindow
));
722 /* Update the clipboard record */
723 lpFormat
->wDataPresent
= 1;
724 lpFormat
->hData32
= hClipData
;
725 lpFormat
->hData16
= 0;
732 WARN("\tUnimplemented format conversion request\n");
737 /* Delete the property on the window now that we are done
738 * This will send a PropertyNotify event to the selection owner. */
739 TSXDeleteProperty(display
,w
,prop
);
741 /* Free the retrieved property data */
742 HeapFree(GetProcessHeap(),0,val
);
746 /**************************************************************************
747 * X11DRV_CLIPBOARD_ReleaseSelection
749 * Release an XA_PRIMARY or XA_CLIPBOARD selection that we own, in response
750 * to a SelectionClear event.
751 * This can occur in response to another client grabbing the X selection.
752 * If the XA_CLIPBOARD selection is lost, we relinquish XA_PRIMARY as well.
754 void X11DRV_CLIPBOARD_ReleaseSelection(Atom selType
, Window w
, HWND hwnd
)
756 Display
*display
= thread_display();
757 Atom xaClipboard
= TSXInternAtom(display
, "CLIPBOARD", False
);
758 int clearAllSelections
= 0;
761 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE
, "Software\\Wine\\Wine\\Config\\Clipboard", &hkey
))
764 DWORD type
, count
= sizeof(buffer
);
765 if(!RegQueryValueExA(hkey
, "ClearAllSelections", 0, &type
, buffer
, &count
))
766 clearAllSelections
= atoi(buffer
);
770 /* w is the window that lost the selection
771 * selectionPrevWindow is nonzero if CheckSelection() was called.
774 TRACE("\tevent->window = %08x (sw = %08x, spw=%08x)\n",
775 (unsigned)w
, (unsigned)selectionWindow
, (unsigned)selectionPrevWindow
);
777 if( selectionAcquired
)
779 if( w
== selectionWindow
|| selectionPrevWindow
== None
)
781 /* If we're losing the CLIPBOARD selection, or if the preferences in .winerc
782 * dictate that *all* selections should be cleared on loss of a selection,
783 * we must give up all the selections we own.
785 if ( clearAllSelections
|| (selType
== xaClipboard
) )
787 /* completely give up the selection */
788 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
790 /* We are completely giving up the selection.
791 * Make sure we can open the windows clipboard first. */
793 if ( !OpenClipboard(hwnd
) )
796 * We can't empty the clipboard if we cant open it so abandon.
797 * Wine will think that it still owns the selection but this is
798 * safer than losing the selection without properly emptying
799 * the clipboard. Perhaps we should forcibly re-assert ownership
800 * of the CLIPBOARD selection in this case...
802 ERR("\tClipboard is busy. Could not give up selection!\n");
806 /* We really lost CLIPBOARD but want to voluntarily lose PRIMARY */
807 if ( (selType
== xaClipboard
)
808 && (selectionAcquired
& S_PRIMARY
) )
810 XSetSelectionOwner(display
, XA_PRIMARY
, None
, CurrentTime
);
813 /* We really lost PRIMARY but want to voluntarily lose CLIPBOARD */
814 if ( (selType
== XA_PRIMARY
)
815 && (selectionAcquired
& S_CLIPBOARD
) )
817 XSetSelectionOwner(display
, xaClipboard
, None
, CurrentTime
);
820 selectionWindow
= None
;
821 PrimarySelectionOwner
= ClipboardSelectionOwner
= 0;
823 /* Empty the windows clipboard.
824 * We should pretend that we still own the selection BEFORE calling
825 * EmptyClipboard() since otherwise this has the side effect of
826 * triggering X11DRV_CLIPBOARD_Acquire() and causing the X selection
827 * to be re-acquired by us!
829 selectionAcquired
= (S_PRIMARY
| S_CLIPBOARD
);
833 /* Give up ownership of the windows clipboard */
834 CLIPBOARD_ReleaseOwner();
836 /* Reset the selection flags now that we are done */
837 selectionAcquired
= S_NOSELECTION
;
839 else if ( selType
== XA_PRIMARY
) /* Give up only PRIMARY selection */
841 TRACE("Lost PRIMARY selection\n");
842 PrimarySelectionOwner
= 0;
843 selectionAcquired
&= ~S_PRIMARY
; /* clear S_PRIMARY mask */
846 cSelectionTargets
= 0;
848 /* but we'll keep existing data for internal use */
849 else if( w
== selectionPrevWindow
)
851 Atom xaClipboard
= TSXInternAtom(display
, _CLIPBOARD
, False
);
853 w
= TSXGetSelectionOwner(display
, XA_PRIMARY
);
855 TSXSetSelectionOwner(display
, XA_PRIMARY
, selectionWindow
, CurrentTime
);
857 w
= TSXGetSelectionOwner(display
, xaClipboard
);
859 TSXSetSelectionOwner(display
, xaClipboard
, selectionWindow
, CurrentTime
);
863 /* Signal to a selectionClearEvent listener if the selection is completely lost */
864 if (selectionClearEvent
&& !selectionAcquired
)
866 TRACE("Lost all selections, signalling to selectionClearEvent listener\n");
867 SetEvent(selectionClearEvent
);
870 selectionPrevWindow
= None
;
873 /**************************************************************************
874 * ReleaseClipboard (X11DRV.@)
875 * Voluntarily release all currently owned X selections
877 void X11DRV_ReleaseClipboard(void)
879 Display
*display
= thread_display();
880 if( selectionAcquired
)
883 Window savePrevWindow
= selectionWindow
;
884 Atom xaClipboard
= TSXInternAtom(display
, _CLIPBOARD
, False
);
885 BOOL bHasPrimarySelection
= selectionAcquired
& S_PRIMARY
;
887 selectionAcquired
= S_NOSELECTION
;
888 selectionPrevWindow
= selectionWindow
;
889 selectionWindow
= None
;
891 TRACE("\tgiving up selection (spw = %08x)\n",
892 (unsigned)selectionPrevWindow
);
896 TRACE("Releasing CLIPBOARD selection\n");
897 XSetSelectionOwner(display
, xaClipboard
, None
, CurrentTime
);
898 if( selectionPrevWindow
)
899 while( !XCheckTypedWindowEvent( display
, selectionPrevWindow
,
900 SelectionClear
, &xe
) );
902 if ( bHasPrimarySelection
)
904 TRACE("Releasing XA_PRIMARY selection\n");
905 selectionPrevWindow
= savePrevWindow
; /* May be cleared in X11DRV_CLIPBOARD_ReleaseSelection */
906 XSetSelectionOwner(display
, XA_PRIMARY
, None
, CurrentTime
);
908 if( selectionPrevWindow
)
909 while( !XCheckTypedWindowEvent( display
, selectionPrevWindow
,
910 SelectionClear
, &xe
) );
915 /* Get rid of any Pixmap resources we may still have */
918 PROPERTY
*prop
= prop_head
;
919 prop_head
= prop
->next
;
920 XFreePixmap( gdi_display
, prop
->pixmap
);
921 HeapFree( GetProcessHeap(), 0, prop
);
925 /**************************************************************************
926 * AcquireClipboard (X11DRV.@)
928 void X11DRV_AcquireClipboard(void)
930 Display
*display
= thread_display();
932 HWND hWndClipWindow
= GetOpenClipboardWindow();
935 * Acquire X selection if we don't already own it.
936 * Note that we only acquire the selection if it hasn't been already
937 * acquired by us, and ignore the fact that another X window may be
938 * asserting ownership. The reason for this is we need *any* top level
939 * X window to hold selection ownership. The actual clipboard data requests
940 * are made via GetClipboardData from EVENT_SelectionRequest and this
941 * ensures that the real HWND owner services the request.
942 * If the owning X window gets destroyed the selection ownership is
943 * re-cycled to another top level X window in X11DRV_CLIPBOARD_ResetOwner.
947 if ( !(selectionAcquired
== (S_PRIMARY
| S_CLIPBOARD
)) )
949 Atom xaClipboard
= TSXInternAtom(display
, _CLIPBOARD
, False
);
950 owner
= X11DRV_get_whole_window( GetAncestor( hWndClipWindow
, GA_ROOT
) );
952 /* Grab PRIMARY selection if not owned */
953 if ( !(selectionAcquired
& S_PRIMARY
) )
954 TSXSetSelectionOwner(display
, XA_PRIMARY
, owner
, CurrentTime
);
956 /* Grab CLIPBOARD selection if not owned */
957 if ( !(selectionAcquired
& S_CLIPBOARD
) )
958 TSXSetSelectionOwner(display
, xaClipboard
, owner
, CurrentTime
);
960 if( TSXGetSelectionOwner(display
,XA_PRIMARY
) == owner
)
961 selectionAcquired
|= S_PRIMARY
;
963 if( TSXGetSelectionOwner(display
,xaClipboard
) == owner
)
964 selectionAcquired
|= S_CLIPBOARD
;
966 if (selectionAcquired
)
968 selectionWindow
= owner
;
969 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner
);
974 /**************************************************************************
975 * IsClipboardFormatAvailable (X11DRV.@)
977 * Checks if the specified format is available in the current selection
978 * Only invoked when WINE is not the selection owner
980 BOOL
X11DRV_IsClipboardFormatAvailable(UINT wFormat
)
982 Display
*display
= thread_display();
983 Atom xaClipboard
= TSXInternAtom(display
, _CLIPBOARD
, False
);
984 Window ownerPrimary
= TSXGetSelectionOwner(display
,XA_PRIMARY
);
985 Window ownerClipboard
= TSXGetSelectionOwner(display
,xaClipboard
);
987 TRACE("enter for %d\n", wFormat
);
990 * If the selection has not been previously cached, or the selection has changed,
991 * try and cache the list of available selection targets from the current selection.
993 if ( !cSelectionTargets
|| (PrimarySelectionOwner
!= ownerPrimary
)
994 || (ClipboardSelectionOwner
!= ownerClipboard
) )
997 * First try caching the CLIPBOARD selection.
998 * If unavailable try PRIMARY.
1000 if ( X11DRV_CLIPBOARD_CacheDataFormats(xaClipboard
) == 0 )
1002 X11DRV_CLIPBOARD_CacheDataFormats(XA_PRIMARY
);
1005 ClipboardSelectionOwner
= ownerClipboard
;
1006 PrimarySelectionOwner
= ownerPrimary
;
1009 /* Exit if there is no selection */
1010 if ( !ownerClipboard
&& !ownerPrimary
)
1012 TRACE("There is no selection owner\n");
1016 /* Check if the format is available in the clipboard cache */
1017 if ( CLIPBOARD_IsPresent(wFormat
) )
1021 * Many X client apps (such as XTerminal) don't support being queried
1022 * for the "TARGETS" target atom. To handle such clients we must actually
1023 * try to convert the selection to the requested type.
1025 if ( !cSelectionTargets
)
1026 return X11DRV_GetClipboardData( wFormat
);
1028 TRACE("There is no selection\n");
1032 /**************************************************************************
1033 * RegisterClipboardFormat (X11DRV.@)
1035 * Registers a custom X clipboard format
1036 * Returns: Format id or 0 on failure
1038 INT
X11DRV_RegisterClipboardFormat( LPCSTR FormatName
)
1040 Display
*display
= thread_display();
1045 * If an X atom is registered for this format, return that
1046 * Otherwise register a new atom.
1050 /* Add a WINE specific prefix to the format */
1051 strcpy(str
, FMT_PREFIX
);
1052 strncat(str
, FormatName
, sizeof(str
) - strlen(FMT_PREFIX
));
1053 prop
= TSXInternAtom(display
, str
, False
);
1059 /**************************************************************************
1060 * IsSelectionOwner (X11DRV.@)
1062 * Returns: TRUE - We(WINE) own the selection, FALSE - Selection not owned by us
1064 BOOL
X11DRV_IsSelectionOwner(void)
1066 return selectionAcquired
;
1069 /**************************************************************************
1070 * SetClipboardData (X11DRV.@)
1072 * We don't need to do anything special here since the clipboard code
1073 * maintains the cache.
1076 void X11DRV_SetClipboardData(UINT wFormat
)
1078 /* Make sure we have acquired the X selection */
1079 X11DRV_AcquireClipboard();
1082 /**************************************************************************
1083 * GetClipboardData (X11DRV.@)
1085 * This method is invoked only when we DO NOT own the X selection
1087 * NOTE: Clipboard driver get requests only for CF_UNICODETEXT data.
1088 * We always get the data from the selection client each time,
1089 * since we have no way of determining if the data in our cache is stale.
1091 BOOL
X11DRV_GetClipboardData(UINT wFormat
)
1093 Display
*display
= thread_display();
1094 BOOL bRet
= selectionAcquired
;
1095 HWND hWndClipWindow
= GetOpenClipboardWindow();
1096 HWND hWnd
= (hWndClipWindow
) ? hWndClipWindow
: GetActiveWindow();
1097 LPWINE_CLIPFORMAT lpFormat
;
1099 TRACE("%d\n", wFormat
);
1101 if (!selectionAcquired
)
1105 Window w
= X11DRV_get_whole_window( GetAncestor( hWnd
, GA_ROOT
));
1108 FIXME("No parent win found %p %p\n", hWnd
, hWndClipWindow
);
1112 /* Map the format ID requested to an X selection property.
1113 * If the format is in the cache, use the atom associated
1117 lpFormat
= CLIPBOARD_LookupFormat( wFormat
);
1118 if (lpFormat
&& lpFormat
->wDataPresent
&& lpFormat
->drvData
)
1119 propRequest
= (Atom
)lpFormat
->drvData
;
1121 propRequest
= X11DRV_CLIPBOARD_MapFormatToProperty(wFormat
);
1125 TRACE("Requesting %s selection from %s...\n",
1126 TSXGetAtomName(display
, propRequest
),
1127 TSXGetAtomName(display
, selectionCacheSrc
) );
1129 XConvertSelection(display
, selectionCacheSrc
, propRequest
,
1130 TSXInternAtom(display
, "SELECTION_DATA", False
),
1133 /* wait until SelectionNotify is received */
1137 if( XCheckTypedWindowEvent(display
, w
, SelectionNotify
, &xe
) )
1138 if( xe
.xselection
.selection
== selectionCacheSrc
)
1141 wine_tsx11_unlock();
1144 * Read the contents of the X selection property into WINE's
1145 * clipboard cache converting the selection to be compatible if possible.
1147 bRet
= X11DRV_CLIPBOARD_ReadSelection( wFormat
,
1148 xe
.xselection
.requestor
,
1149 xe
.xselection
.property
,
1150 xe
.xselection
.target
);
1155 TRACE("\tpresent %s = %i\n", CLIPBOARD_GetFormatName(wFormat
, NULL
, 0), bRet
);
1158 TRACE("Returning %d\n", bRet
);
1163 /**************************************************************************
1164 * ResetSelectionOwner (X11DRV.@)
1166 * Called from DestroyWindow() to prevent X selection from being lost when
1167 * a top level window is destroyed, by switching ownership to another top
1169 * Any top level window can own the selection. See X11DRV_CLIPBOARD_Acquire
1170 * for a more detailed description of this.
1172 void X11DRV_ResetSelectionOwner(HWND hwnd
, BOOL bFooBar
)
1174 Display
*display
= thread_display();
1175 HWND hWndClipOwner
= 0;
1177 Window XWnd
= X11DRV_get_whole_window(hwnd
);
1179 BOOL bLostSelection
= FALSE
;
1181 /* There is nothing to do if we don't own the selection,
1182 * or if the X window which currently owns the selecion is different
1183 * from the one passed in.
1185 if ( !selectionAcquired
|| XWnd
!= selectionWindow
1186 || selectionWindow
== None
)
1189 if ( (bFooBar
&& XWnd
) || (!bFooBar
&& !XWnd
) )
1192 hWndClipOwner
= GetClipboardOwner();
1193 xaClipboard
= TSXInternAtom(display
, _CLIPBOARD
, False
);
1195 TRACE("clipboard owner = %p, selection window = %08x\n",
1196 hWndClipOwner
, (unsigned)selectionWindow
);
1198 /* now try to salvage current selection from being destroyed by X */
1200 TRACE("\tchecking %08x\n", (unsigned) XWnd
);
1202 selectionPrevWindow
= selectionWindow
;
1203 selectionWindow
= None
;
1205 if (!(tmp
= GetWindow( hwnd
, GW_HWNDNEXT
))) tmp
= GetWindow( hwnd
, GW_HWNDFIRST
);
1206 if (tmp
&& tmp
!= hwnd
) selectionWindow
= X11DRV_get_whole_window(tmp
);
1208 if( selectionWindow
!= None
)
1210 /* We must pretend that we don't own the selection while making the switch
1211 * since a SelectionClear event will be sent to the last owner.
1212 * If there is no owner X11DRV_CLIPBOARD_ReleaseSelection will do nothing.
1214 int saveSelectionState
= selectionAcquired
;
1215 selectionAcquired
= False
;
1217 TRACE("\tswitching selection from %08x to %08x\n",
1218 (unsigned)selectionPrevWindow
, (unsigned)selectionWindow
);
1220 /* Assume ownership for the PRIMARY and CLIPBOARD selection */
1221 if ( saveSelectionState
& S_PRIMARY
)
1222 TSXSetSelectionOwner(display
, XA_PRIMARY
, selectionWindow
, CurrentTime
);
1224 TSXSetSelectionOwner(display
, xaClipboard
, selectionWindow
, CurrentTime
);
1226 /* Restore the selection masks */
1227 selectionAcquired
= saveSelectionState
;
1229 /* Lose the selection if something went wrong */
1230 if ( ( (saveSelectionState
& S_PRIMARY
) &&
1231 (TSXGetSelectionOwner(display
, XA_PRIMARY
) != selectionWindow
) )
1232 || (TSXGetSelectionOwner(display
, xaClipboard
) != selectionWindow
) )
1234 bLostSelection
= TRUE
;
1239 /* Update selection state */
1240 if (saveSelectionState
& S_PRIMARY
)
1241 PrimarySelectionOwner
= selectionWindow
;
1243 ClipboardSelectionOwner
= selectionWindow
;
1248 bLostSelection
= TRUE
;
1255 /* Launch the clipboard server if the selection can no longer be recyled
1256 * to another top level window. */
1258 if ( !X11DRV_CLIPBOARD_LaunchServer() )
1260 /* Empty the windows clipboard if the server was not launched.
1261 * We should pretend that we still own the selection BEFORE calling
1262 * EmptyClipboard() since otherwise this has the side effect of
1263 * triggering X11DRV_CLIPBOARD_Acquire() and causing the X selection
1264 * to be re-acquired by us!
1267 TRACE("\tLost the selection! Emptying the clipboard...\n");
1270 selectionAcquired
= (S_PRIMARY
| S_CLIPBOARD
);
1275 /* Give up ownership of the windows clipboard */
1276 CLIPBOARD_ReleaseOwner();
1279 selectionAcquired
= S_NOSELECTION
;
1280 ClipboardSelectionOwner
= PrimarySelectionOwner
= 0;
1281 selectionWindow
= 0;
1285 /**************************************************************************
1286 * X11DRV_CLIPBOARD_RegisterPixmapResource
1287 * Registers a Pixmap resource which is to be associated with a property Atom.
1288 * When the property is destroyed we also destroy the Pixmap through the
1289 * PropertyNotify event.
1291 BOOL
X11DRV_CLIPBOARD_RegisterPixmapResource( Atom property
, Pixmap pixmap
)
1293 PROPERTY
*prop
= HeapAlloc( GetProcessHeap(), 0, sizeof(*prop
) );
1294 if (!prop
) return FALSE
;
1295 prop
->atom
= property
;
1296 prop
->pixmap
= pixmap
;
1297 prop
->next
= prop_head
;
1302 /**************************************************************************
1303 * X11DRV_CLIPBOARD_FreeResources
1305 * Called from EVENT_PropertyNotify() to give us a chance to destroy
1306 * any resources associated with this property.
1308 void X11DRV_CLIPBOARD_FreeResources( Atom property
)
1310 /* Do a simple linear search to see if we have a Pixmap resource
1311 * associated with this property and release it.
1313 PROPERTY
**prop
= &prop_head
;
1317 if ((*prop
)->atom
== property
)
1319 PROPERTY
*next
= (*prop
)->next
;
1320 XFreePixmap( gdi_display
, (*prop
)->pixmap
);
1321 HeapFree( GetProcessHeap(), 0, *prop
);
1324 else prop
= &(*prop
)->next
;
1328 /**************************************************************************
1329 * X11DRV_GetClipboardFormatName
1331 BOOL
X11DRV_GetClipboardFormatName( UINT wFormat
, LPSTR retStr
, UINT maxlen
)
1334 char *itemFmtName
= TSXGetAtomName(thread_display(), wFormat
);
1335 INT prefixlen
= strlen(FMT_PREFIX
);
1337 if ( 0 == strncmp(itemFmtName
, FMT_PREFIX
, prefixlen
) )
1339 strncpy(retStr
, itemFmtName
+ prefixlen
, maxlen
);
1343 TSXFree(itemFmtName
);
1349 /**************************************************************************
1350 * CLIPBOARD_SerializeMetafile
1352 HANDLE
X11DRV_CLIPBOARD_SerializeMetafile(INT wformat
, HANDLE hdata
, INT cbytes
, BOOL out
)
1356 if (out
) /* Serialize out, caller should free memory */
1358 if (wformat
== CF_METAFILEPICT
)
1360 LPMETAFILEPICT lpmfp
= (LPMETAFILEPICT
) GlobalLock(hdata
);
1361 int size
= GetMetaFileBitsEx(lpmfp
->hMF
, 0, NULL
);
1363 h
= GlobalAlloc(0, size
+ sizeof(METAFILEPICT
));
1366 METAFILEPICT
*pdata
= GlobalLock(h
);
1368 memcpy(pdata
, lpmfp
, sizeof(METAFILEPICT
));
1369 GetMetaFileBitsEx(lpmfp
->hMF
, size
, pdata
+ 1);
1374 GlobalUnlock(hdata
);
1376 else if (wformat
== CF_ENHMETAFILE
)
1378 int size
= GetEnhMetaFileBits(hdata
, 0, NULL
);
1380 h
= GlobalAlloc(0, size
);
1383 LPVOID pdata
= GlobalLock(h
);
1384 GetEnhMetaFileBits(hdata
, size
, pdata
);
1391 if (wformat
== CF_METAFILEPICT
)
1393 h
= GlobalAlloc(0, sizeof(METAFILEPICT
));
1396 LPMETAFILEPICT pmfp
= (LPMETAFILEPICT
) GlobalLock(h
);
1398 memcpy(pmfp
, (LPVOID
)hdata
, sizeof(METAFILEPICT
));
1399 pmfp
->hMF
= SetMetaFileBitsEx(cbytes
- sizeof(METAFILEPICT
),
1400 (char *)hdata
+ sizeof(METAFILEPICT
));
1405 else if (wformat
== CF_ENHMETAFILE
)
1407 h
= SetEnhMetaFileBits(cbytes
, (LPVOID
)hdata
);