Add option to use the primary selection in addition to the clipboard
[wine.git] / dlls / x11drv / clipboard.c
blob55dbb5c17cc4725c607777efe22c6e47173e3ed2
1 /*
2 * X11 clipboard windows driver
4 * Copyright 1994 Martin Ayotte
5 * 1996 Alex Korobka
6 * 1999 Noel Borthwick
7 * 2003 Ulrich Czekalla for CodeWeavers
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 * NOTES:
24 * This file contains the X specific implementation for the windows
25 * Clipboard API.
27 * Wine's internal clipboard is exposed to external apps via the X
28 * selection mechanism.
29 * Currently the driver asserts ownership via two selection atoms:
30 * 1. PRIMARY(XA_PRIMARY)
31 * 2. CLIPBOARD
33 * In our implementation, the CLIPBOARD selection takes precedence over PRIMARY,
34 * i.e. if a CLIPBOARD selection is available, it is used instead of PRIMARY.
35 * When Wine takes ownership of the clipboard, it takes ownership of BOTH selections.
36 * While giving up selection ownership, if the CLIPBOARD selection is lost,
37 * it will lose both PRIMARY and CLIPBOARD and empty the clipboard.
38 * However if only PRIMARY is lost, it will continue to hold the CLIPBOARD selection
39 * (leaving the clipboard cache content unaffected).
41 * Every format exposed via a windows clipboard format is also exposed through
42 * a corresponding X selection target. A selection target atom is synthesized
43 * whenever a new Windows clipboard format is registered via RegisterClipboardFormat,
44 * or when a built-in format is used for the first time.
45 * Windows native format are exposed by prefixing the format name with "<WCF>"
46 * This allows us to uniquely identify windows native formats exposed by other
47 * running WINE apps.
49 * In order to allow external applications to query WINE for supported formats,
50 * we respond to the "TARGETS" selection target. (See EVENT_SelectionRequest
51 * for implementation) We use the same mechanism to query external clients for
52 * availability of a particular format, by caching the list of available targets
53 * by using the clipboard cache's "delayed render" mechanism. If a selection client
54 * does not support the "TARGETS" selection target, we actually attempt to retrieve
55 * the format requested as a fallback mechanism.
57 * Certain Windows native formats are automatically converted to X native formats
58 * and vice versa. If a native format is available in the selection, it takes
59 * precedence, in order to avoid unnecessary conversions.
61 * FIXME: global format list needs a critical section
64 #include "config.h"
65 #include "wine/port.h"
67 #include <string.h>
68 #include <stdarg.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #ifdef HAVE_UNISTD_H
72 # include <unistd.h>
73 #endif
74 #include <fcntl.h>
75 #include <time.h>
77 #include "windef.h"
78 #include "winbase.h"
79 #include "winreg.h"
80 #include "win.h"
81 #include "x11drv.h"
82 #include "wine/debug.h"
83 #include "wine/unicode.h"
84 #include "wine/server.h"
86 WINE_DEFAULT_DEBUG_CHANNEL(clipboard);
88 #define HGDIOBJ_32(handle16) ((HGDIOBJ)(ULONG_PTR)(handle16))
90 /* Maximum wait time for selection notify */
91 #define SELECTION_RETRIES 500 /* wait for .1 seconds */
92 #define SELECTION_WAIT 1000 /* us */
93 /* Minimum seconds that must lapse between owner queries */
94 #define OWNERQUERYLAPSETIME 1
96 /* Selection masks */
97 #define S_NOSELECTION 0
98 #define S_PRIMARY 1
99 #define S_CLIPBOARD 2
101 typedef struct
103 HWND hWndOpen;
104 HWND hWndOwner;
105 HWND hWndViewer;
106 UINT seqno;
107 UINT flags;
108 } CLIPBOARDINFO, *LPCLIPBOARDINFO;
110 static int selectionAcquired = 0; /* Contains the current selection masks */
111 static Window selectionWindow = None; /* The top level X window which owns the selection */
112 static BOOL clearAllSelections = FALSE; /* Always lose all selections */
113 static BOOL usePrimary = FALSE; /* Use primary selection in additon to the clipboard selection */
114 static Atom selectionCacheSrc = XA_PRIMARY; /* The selection source from which the clipboard cache was filled */
115 static Window PrimarySelectionOwner = None; /* The window which owns the primary selection */
116 static Window ClipboardSelectionOwner = None; /* The window which owns the clipboard selection */
118 INT X11DRV_RegisterClipboardFormat(LPCSTR FormatName);
119 void X11DRV_EmptyClipboard(void);
120 void X11DRV_EndClipboardUpdate(void);
121 HANDLE X11DRV_CLIPBOARD_ImportClipboardData(LPBYTE lpdata, UINT cBytes);
122 HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(LPBYTE lpdata, UINT cBytes);
123 HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(LPBYTE lpdata, UINT cBytes);
124 HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(LPBYTE lpdata, UINT cBytes);
125 HANDLE X11DRV_CLIPBOARD_ImportXAString(LPBYTE lpdata, UINT cBytes);
126 HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Window requestor, Atom aTarget,
127 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
128 HANDLE X11DRV_CLIPBOARD_ExportString(Window requestor, Atom aTarget,
129 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
130 HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Window requestor, Atom aTarget,
131 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
132 HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Window requestor, Atom aTarget,
133 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
134 HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Window requestor, Atom aTarget,
135 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
136 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCSTR FormatName, Atom prop);
137 static BOOL X11DRV_CLIPBOARD_ReadSelection(LPWINE_CLIPFORMAT lpData, Window w, Atom prop);
138 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(UINT wFormatID);
139 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData);
140 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void);
141 static int X11DRV_CLIPBOARD_QueryAvailableData(LPCLIPBOARDINFO lpcbinfo);
142 static BOOL X11DRV_CLIPBOARD_ReadClipboardData(UINT wFormat);
143 static BOOL X11DRV_CLIPBOARD_RenderFormat(LPWINE_CLIPDATA lpData);
144 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out);
145 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID);
146 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(LPWINE_CLIPDATA lpData);
148 /* Clipboard formats
149 * WARNING: This data ordering is dependent on the WINE_CLIPFORMAT structure
150 * declared in clipboard.h
152 static WINE_CLIPFORMAT ClipFormats[] =
154 { CF_TEXT, "WCF_TEXT", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
155 X11DRV_CLIPBOARD_ExportClipboardData, NULL, &ClipFormats[1]},
157 { CF_BITMAP, "WCF_BITMAP", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
158 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[0], &ClipFormats[2]},
160 { CF_METAFILEPICT, "WCF_METAFILEPICT", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportMetaFilePict,
161 X11DRV_CLIPBOARD_ExportMetaFilePict, &ClipFormats[1], &ClipFormats[3]},
163 { CF_SYLK, "WCF_SYLK", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
164 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[2], &ClipFormats[4]},
166 { CF_DIF, "WCF_DIF", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
167 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[3], &ClipFormats[5]},
169 { CF_TIFF, "WCF_TIFF", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
170 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[4], &ClipFormats[6]},
172 { CF_OEMTEXT, "WCF_OEMTEXT", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
173 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[5], &ClipFormats[7]},
175 { CF_DIB, "WCF_DIB", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAPIXMAP,
176 X11DRV_CLIPBOARD_ExportXAPIXMAP, &ClipFormats[6], &ClipFormats[8]},
178 { CF_PALETTE, "WCF_PALETTE", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
179 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[7], &ClipFormats[9]},
181 { CF_PENDATA, "WCF_PENDATA", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
182 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[8], &ClipFormats[10]},
184 { CF_RIFF, "WCF_RIFF", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
185 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[9], &ClipFormats[11]},
187 { CF_WAVE, "WCF_WAVE", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
188 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[10], &ClipFormats[12]},
190 { CF_UNICODETEXT, "WCF_UNICODETEXT", XA_STRING, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAString,
191 X11DRV_CLIPBOARD_ExportString, &ClipFormats[11], &ClipFormats[13]},
193 { CF_ENHMETAFILE, "WCF_ENHMETAFILE", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportEnhMetaFile,
194 X11DRV_CLIPBOARD_ExportEnhMetaFile, &ClipFormats[12], &ClipFormats[14]},
196 { CF_HDROP, "WCF_HDROP", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
197 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[13], &ClipFormats[15]},
199 { CF_LOCALE, "WCF_LOCALE", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
200 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[14], &ClipFormats[16]},
202 { CF_DIBV5, "WCF_DIBV5", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
203 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[15], &ClipFormats[17]},
205 { CF_OWNERDISPLAY, "WCF_OWNERDISPLAY", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
206 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[16], &ClipFormats[18]},
208 { CF_DSPTEXT, "WCF_DSPTEXT", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
209 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[17], &ClipFormats[19]},
211 { CF_DSPBITMAP, "WCF_DSPBITMAP", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
212 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[18], &ClipFormats[20]},
214 { CF_DSPMETAFILEPICT, "WCF_DSPMETAFILEPICT", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
215 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[19], &ClipFormats[21]},
217 { CF_DSPENHMETAFILE, "WCF_DSPENHMETAFILE", 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
218 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[20], NULL}
221 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
223 /* Maps X properties to Windows formats */
224 static const struct
226 LPCSTR lpszFormat;
227 UINT prop;
228 } PropertyFormatMap[] =
230 { "Rich Text Format", XATOM_text_rtf },
231 /* Temporarily disable text/html because Evolution incorrectly pastes strings with extra nulls */
232 /*{ "text/html", "HTML Format" },*/
233 { "GIF", XATOM_image_gif }
237 /* Maps equivalent X properties. It is assumed that lpszProperty must already
238 be in ClipFormats or PropertyFormatMap. */
239 static const struct
241 UINT drvDataProperty;
242 UINT drvDataAlias;
243 } PropertyAliasMap[] =
245 /* DataProperty, DataAlias */
246 { XATOM_text_rtf, XATOM_text_richtext },
247 { XA_STRING, XATOM_COMPOUND_TEXT },
248 { XA_STRING, XATOM_TEXT },
253 * Cached clipboard data.
255 static LPWINE_CLIPDATA ClipData = NULL;
256 static UINT ClipDataCount = 0;
259 * Clipboard sequence number
261 static UINT wSeqNo = 0;
263 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
265 /**************************************************************************
266 * Internal Clipboard implementation methods
267 **************************************************************************/
269 /**************************************************************************
270 * X11DRV_InitClipboard
272 void X11DRV_InitClipboard(void)
274 INT i;
275 HKEY hkey;
277 if(!RegOpenKeyA(HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\Clipboard", &hkey))
279 char buffer[20];
280 DWORD type, count = sizeof(buffer);
281 if(!RegQueryValueExA(hkey, "ClearAllSelections", 0, &type, buffer, &count))
282 clearAllSelections = IS_OPTION_TRUE( buffer[0] );
283 count = sizeof(buffer);
284 if(!RegQueryValueExA(hkey, "UsePrimary", 0, &type, buffer, &count))
285 usePrimary = IS_OPTION_TRUE( buffer[0] );
286 RegCloseKey(hkey);
289 /* Register known mapping between window formats and X properties */
290 for (i = 0; i < sizeof(PropertyFormatMap)/sizeof(PropertyFormatMap[0]); i++)
291 X11DRV_CLIPBOARD_InsertClipboardFormat(PropertyFormatMap[i].lpszFormat,
292 GET_ATOM(PropertyFormatMap[i].prop));
296 /**************************************************************************
297 * intern_atoms
299 * Intern atoms for formats that don't have one yet.
301 static void intern_atoms(void)
303 LPWINE_CLIPFORMAT format;
304 int i, count;
305 char **names;
306 Atom *atoms;
308 for (format = ClipFormats, count = 0; format; format = format->NextFormat)
309 if (!format->drvData) count++;
310 if (!count) return;
312 names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
313 atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
315 for (format = ClipFormats, i = 0; format; format = format->NextFormat)
316 if (!format->drvData) names[i++] = format->Name;
318 wine_tsx11_lock();
319 XInternAtoms( thread_display(), names, count, False, atoms );
320 wine_tsx11_unlock();
322 for (format = ClipFormats, i = 0; format; format = format->NextFormat)
323 if (!format->drvData) format->drvData = atoms[i];
325 HeapFree( GetProcessHeap(), 0, names );
326 HeapFree( GetProcessHeap(), 0, atoms );
330 /**************************************************************************
331 * register_format
333 * Register a custom X clipboard format.
335 static WINE_CLIPFORMAT *register_format( LPCSTR FormatName, Atom prop )
337 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
339 TRACE("'%s'\n", FormatName);
341 /* walk format chain to see if it's already registered */
342 while (lpFormat)
344 if ( !strcasecmp(lpFormat->Name, FormatName) &&
345 (lpFormat->wFlags & CF_FLAG_BUILTINFMT) == 0)
346 return lpFormat;
347 lpFormat = lpFormat->NextFormat;
350 return X11DRV_CLIPBOARD_InsertClipboardFormat(FormatName, prop);
354 /**************************************************************************
355 * X11DRV_CLIPBOARD_LookupFormat
357 LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupFormat(WORD wID)
359 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
361 while(lpFormat)
363 if (lpFormat->wFormatID == wID)
364 break;
366 lpFormat = lpFormat->NextFormat;
368 if (!lpFormat->drvData) intern_atoms();
369 return lpFormat;
373 /**************************************************************************
374 * X11DRV_CLIPBOARD_LookupProperty
376 LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupProperty(UINT drvData)
378 for (;;)
380 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
381 BOOL need_intern = FALSE;
383 while(lpFormat)
385 if (lpFormat->drvData == drvData) return lpFormat;
386 if (!lpFormat->drvData) need_intern = TRUE;
387 lpFormat = lpFormat->NextFormat;
389 if (!need_intern) return NULL;
390 intern_atoms();
391 /* restart the search for the new atoms */
396 /**************************************************************************
397 * X11DRV_CLIPBOARD_LookupAliasProperty
399 LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupAliasProperty(UINT drvDataAlias)
401 unsigned int i;
402 LPWINE_CLIPFORMAT lpFormat = NULL;
404 for (i = 0; i < sizeof(PropertyAliasMap)/sizeof(PropertyAliasMap[0]); i++)
406 if (GET_ATOM(PropertyAliasMap[i].drvDataAlias) == drvDataAlias)
408 lpFormat = X11DRV_CLIPBOARD_LookupProperty(GET_ATOM(PropertyAliasMap[i].drvDataProperty));
409 break;
413 return lpFormat;
417 /**************************************************************************
418 * X11DRV_CLIPBOARD_LookupPropertyAlias
420 UINT X11DRV_CLIPBOARD_LookupPropertyAlias(UINT drvDataProperty)
422 unsigned int i;
423 UINT alias = 0;
425 for (i = 0; i < sizeof(PropertyAliasMap)/sizeof(PropertyAliasMap[0]); i++)
427 if (GET_ATOM(PropertyAliasMap[i].drvDataProperty) == drvDataProperty)
429 alias = GET_ATOM(PropertyAliasMap[i].drvDataAlias);
430 break;
434 return alias;
438 /**************************************************************************
439 * X11DRV_CLIPBOARD_LookupData
441 LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
443 LPWINE_CLIPDATA lpData = ClipData;
445 if (lpData)
449 if (lpData->wFormatID == wID)
450 break;
452 lpData = lpData->NextData;
454 while(lpData != ClipData);
456 if (lpData->wFormatID != wID)
457 lpData = NULL;
460 return lpData;
464 /**************************************************************************
465 * InsertClipboardFormat
467 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCSTR FormatName, Atom prop)
469 LPWINE_CLIPFORMAT lpFormat;
470 LPWINE_CLIPFORMAT lpNewFormat;
472 /* allocate storage for new format entry */
473 lpNewFormat = (LPWINE_CLIPFORMAT) HeapAlloc(GetProcessHeap(),
474 0, sizeof(WINE_CLIPFORMAT));
476 if(lpNewFormat == NULL)
478 WARN("No more memory for a new format!\n");
479 return NULL;
482 if (!(lpNewFormat->Name = HeapAlloc(GetProcessHeap(), 0, strlen(FormatName)+1)))
484 WARN("No more memory for the new format name!\n");
485 HeapFree(GetProcessHeap(), 0, lpNewFormat);
486 return NULL;
489 strcpy(lpNewFormat->Name, FormatName);
490 lpNewFormat->wFlags = 0;
491 lpNewFormat->wFormatID = GlobalAddAtomA(lpNewFormat->Name);
492 lpNewFormat->drvData = prop;
493 lpNewFormat->lpDrvImportFunc = X11DRV_CLIPBOARD_ImportClipboardData;
494 lpNewFormat->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportClipboardData;
496 /* Link Format */
497 lpFormat = ClipFormats;
499 while(lpFormat->NextFormat) /* Move to last entry */
500 lpFormat = lpFormat->NextFormat;
502 lpNewFormat->NextFormat = NULL;
503 lpFormat->NextFormat = lpNewFormat;
504 lpNewFormat->PrevFormat = lpFormat;
506 TRACE("Registering format(%d): %s drvData %d\n",
507 lpNewFormat->wFormatID, FormatName, lpNewFormat->drvData);
509 return lpNewFormat;
515 /**************************************************************************
516 * X11DRV_CLIPBOARD_GetClipboardInfo
518 static BOOL X11DRV_CLIPBOARD_GetClipboardInfo(LPCLIPBOARDINFO cbInfo)
520 BOOL bRet = FALSE;
522 SERVER_START_REQ( set_clipboard_info )
524 req->flags = 0;
526 if (wine_server_call_err( req ))
528 ERR("Failed to get clipboard owner.\n");
530 else
532 cbInfo->hWndOpen = reply->old_clipboard;
533 cbInfo->hWndOwner = reply->old_owner;
534 cbInfo->hWndViewer = reply->old_viewer;
535 cbInfo->seqno = reply->seqno;
536 cbInfo->flags = reply->flags;
538 bRet = TRUE;
541 SERVER_END_REQ;
543 return bRet;
547 /**************************************************************************
548 * X11DRV_CLIPBOARD_ReleaseOwnership
550 static BOOL X11DRV_CLIPBOARD_ReleaseOwnership(void)
552 BOOL bRet = FALSE;
554 SERVER_START_REQ( set_clipboard_info )
556 req->flags = SET_CB_RELOWNER | SET_CB_SEQNO;
558 if (wine_server_call_err( req ))
560 ERR("Failed to set clipboard.\n");
562 else
564 bRet = TRUE;
567 SERVER_END_REQ;
569 return bRet;
574 /**************************************************************************
575 * X11DRV_CLIPBOARD_InsertClipboardData
577 * Caller *must* have the clipboard open and be the owner.
579 static BOOL X11DRV_CLIPBOARD_InsertClipboardData(UINT wFormat, HANDLE16 hData16, HANDLE hData32, DWORD flags)
581 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
583 TRACE("format=%d lpData=%p hData16=%08x hData32=%08x flags=0x%08lx\n",
584 wFormat, lpData, hData16, (unsigned int)hData32, flags);
586 if (lpData)
588 X11DRV_CLIPBOARD_FreeData(lpData);
590 lpData->hData16 = hData16; /* 0 is legal, see WM_RENDERFORMAT */
591 lpData->hData32 = hData32;
593 else
595 lpData = (LPWINE_CLIPDATA) HeapAlloc(GetProcessHeap(),
596 0, sizeof(WINE_CLIPDATA));
598 lpData->wFormatID = wFormat;
599 lpData->hData16 = hData16; /* 0 is legal, see WM_RENDERFORMAT */
600 lpData->hData32 = hData32;
602 if (ClipData)
604 LPWINE_CLIPDATA lpPrevData = ClipData->PrevData;
606 lpData->PrevData = lpPrevData;
607 lpData->NextData = ClipData;
609 lpPrevData->NextData = lpData;
610 ClipData->PrevData = lpData;
612 else
614 lpData->NextData = lpData;
615 lpData->PrevData = lpData;
616 ClipData = lpData;
619 ClipDataCount++;
622 lpData->wFlags = flags;
624 return TRUE;
628 /**************************************************************************
629 * X11DRV_CLIPBOARD_FreeData
631 * Free clipboard data handle.
633 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData)
635 TRACE("%d\n", lpData->wFormatID);
637 if ((lpData->wFormatID >= CF_GDIOBJFIRST &&
638 lpData->wFormatID <= CF_GDIOBJLAST) ||
639 lpData->wFormatID == CF_BITMAP ||
640 lpData->wFormatID == CF_DIB ||
641 lpData->wFormatID == CF_PALETTE)
643 if (lpData->hData32)
644 DeleteObject(lpData->hData32);
646 if (lpData->hData16)
647 DeleteObject(HGDIOBJ_32(lpData->hData16));
649 else if (lpData->wFormatID == CF_METAFILEPICT)
651 if (lpData->hData32)
653 DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData32 ))->hMF );
654 GlobalFree(lpData->hData32);
656 if (lpData->hData16)
657 /* HMETAFILE16 and HMETAFILE32 are apparently the same thing,
658 and a shallow copy is enough to share a METAFILEPICT
659 structure between 16bit and 32bit clipboards. The MetaFile
660 should of course only be deleted once. */
661 GlobalFree16(lpData->hData16);
664 if (lpData->hData16)
666 METAFILEPICT16* lpMetaPict = (METAFILEPICT16 *) GlobalLock16(lpData->hData16);
668 if (lpMetaPict)
670 DeleteMetaFile16(lpMetaPict->hMF);
671 lpMetaPict->hMF = 0;
674 GlobalFree16(lpData->hData16);
677 else if (lpData->wFormatID == CF_ENHMETAFILE)
679 if (lpData->hData32)
680 DeleteEnhMetaFile(lpData->hData32);
682 else if (lpData->wFormatID < CF_PRIVATEFIRST ||
683 lpData->wFormatID > CF_PRIVATELAST)
685 if (lpData->hData32)
686 GlobalFree(lpData->hData32);
688 if (lpData->hData16)
689 GlobalFree16(lpData->hData16);
692 lpData->hData16 = 0;
693 lpData->hData32 = 0;
697 /**************************************************************************
698 * X11DRV_CLIPBOARD_UpdateCache
700 static BOOL X11DRV_CLIPBOARD_UpdateCache(LPCLIPBOARDINFO lpcbinfo)
702 BOOL bret = TRUE;
704 if (!X11DRV_CLIPBOARD_IsSelectionOwner())
706 if (!X11DRV_CLIPBOARD_GetClipboardInfo(lpcbinfo))
708 ERR("Failed to retrieve clipboard information.\n");
709 bret = FALSE;
711 else if (wSeqNo < lpcbinfo->seqno)
713 X11DRV_EmptyClipboard();
715 if (X11DRV_CLIPBOARD_QueryAvailableData(lpcbinfo) < 0)
717 ERR("Failed to cache clipboard data owned by another process.\n");
718 bret = FALSE;
720 else
722 X11DRV_EndClipboardUpdate();
725 wSeqNo = lpcbinfo->seqno;
729 return bret;
733 /**************************************************************************
734 * X11DRV_CLIPBOARD_RenderFormat
736 static BOOL X11DRV_CLIPBOARD_RenderFormat(LPWINE_CLIPDATA lpData)
738 BOOL bret = TRUE;
740 TRACE(" 0x%04x hData32(0x%08x) hData16(0x%08x)\n",
741 lpData->wFormatID, (unsigned int)lpData->hData32, lpData->hData16);
743 if (lpData->hData32 || lpData->hData16)
744 return bret; /* Already rendered */
746 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
747 bret = X11DRV_CLIPBOARD_RenderSynthesizedFormat(lpData);
748 else if (!X11DRV_CLIPBOARD_IsSelectionOwner())
750 if (!X11DRV_CLIPBOARD_ReadClipboardData(lpData->wFormatID))
752 ERR("Failed to cache clipboard data owned by another process. Format=%d\n",
753 lpData->wFormatID);
754 bret = FALSE;
757 else
759 CLIPBOARDINFO cbInfo;
761 if (X11DRV_CLIPBOARD_GetClipboardInfo(&cbInfo) && cbInfo.hWndOwner)
763 /* Send a WM_RENDERFORMAT message to notify the owner to render the
764 * data requested into the clipboard.
766 TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", cbInfo.hWndOwner);
767 SendMessageW(cbInfo.hWndOwner, WM_RENDERFORMAT, (WPARAM)lpData->wFormatID, 0);
769 if (!lpData->hData32 && !lpData->hData16)
770 bret = FALSE;
772 else
774 ERR("hWndClipOwner is lost!\n");
775 bret = FALSE;
779 return bret;
783 /**************************************************************************
784 * CLIPBOARD_ConvertText
785 * Returns number of required/converted characters - not bytes!
787 static INT CLIPBOARD_ConvertText(WORD src_fmt, void const *src, INT src_size,
788 WORD dst_fmt, void *dst, INT dst_size)
790 UINT cp;
792 if(src_fmt == CF_UNICODETEXT)
794 switch(dst_fmt)
796 case CF_TEXT:
797 cp = CP_ACP;
798 break;
799 case CF_OEMTEXT:
800 cp = CP_OEMCP;
801 break;
802 default:
803 return 0;
805 return WideCharToMultiByte(cp, 0, src, src_size, dst, dst_size, NULL, NULL);
808 if(dst_fmt == CF_UNICODETEXT)
810 switch(src_fmt)
812 case CF_TEXT:
813 cp = CP_ACP;
814 break;
815 case CF_OEMTEXT:
816 cp = CP_OEMCP;
817 break;
818 default:
819 return 0;
821 return MultiByteToWideChar(cp, 0, src, src_size, dst, dst_size);
824 if(!dst_size) return src_size;
826 if(dst_size > src_size) dst_size = src_size;
828 if(src_fmt == CF_TEXT )
829 CharToOemBuffA(src, dst, dst_size);
830 else
831 OemToCharBuffA(src, dst, dst_size);
833 return dst_size;
837 /**************************************************************************
838 * X11DRV_CLIPBOARD_RenderSynthesizedFormat
840 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(LPWINE_CLIPDATA lpData)
842 BOOL bret = FALSE;
844 TRACE("\n");
846 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
848 UINT wFormatID = lpData->wFormatID;
850 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
851 bret = X11DRV_CLIPBOARD_RenderSynthesizedText(wFormatID);
852 else
854 switch (wFormatID)
856 case CF_ENHMETAFILE:
857 case CF_METAFILEPICT:
858 case CF_DIB:
859 case CF_BITMAP:
860 FIXME("Synthesizing wFormatID(0x%08x) not implemented\n", wFormatID);
861 break;
863 default:
864 FIXME("Called to synthesize unknown format\n");
865 break;
869 lpData->wFlags &= ~CF_FLAG_SYNTHESIZED;
872 return bret;
876 /**************************************************************************
877 * X11DRV_CLIPBOARD_RenderSynthesizedText
879 * Renders synthesized text
881 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(UINT wFormatID)
883 LPCSTR lpstrS;
884 LPSTR lpstrT;
885 HANDLE hData32;
886 INT src_chars, dst_chars, alloc_size;
887 LPWINE_CLIPDATA lpSource = NULL;
889 TRACE(" %d\n", wFormatID);
891 if ((lpSource = X11DRV_CLIPBOARD_LookupData(wFormatID)) &&
892 lpSource->hData32)
893 return TRUE;
895 /* Look for rendered source or non-synthesized source */
896 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
897 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
899 TRACE("UNICODETEXT -> %d\n", wFormatID);
901 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
902 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
904 TRACE("TEXT -> %d\n", wFormatID);
906 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
907 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
909 TRACE("OEMTEXT -> %d\n", wFormatID);
912 if (!lpSource || (lpSource->wFlags & CF_FLAG_SYNTHESIZED &&
913 !lpSource->hData32))
914 return FALSE;
916 /* Ask the clipboard owner to render the source text if necessary */
917 if (!lpSource->hData32 && !X11DRV_CLIPBOARD_RenderFormat(lpSource))
918 return FALSE;
920 if (lpSource->hData32)
922 lpstrS = (LPSTR)GlobalLock(lpSource->hData32);
924 else
926 lpstrS = (LPSTR)GlobalLock16(lpSource->hData16);
929 if (!lpstrS)
930 return FALSE;
932 /* Text always NULL terminated */
933 if(lpSource->wFormatID == CF_UNICODETEXT)
934 src_chars = strlenW((LPCWSTR)lpstrS) + 1;
935 else
936 src_chars = strlen(lpstrS) + 1;
938 /* Calculate number of characters in the destination buffer */
939 dst_chars = CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS,
940 src_chars, wFormatID, NULL, 0);
942 if (!dst_chars)
943 return FALSE;
945 TRACE("Converting from '%d' to '%d', %i chars\n",
946 lpSource->wFormatID, wFormatID, src_chars);
948 /* Convert characters to bytes */
949 if(wFormatID == CF_UNICODETEXT)
950 alloc_size = dst_chars * sizeof(WCHAR);
951 else
952 alloc_size = dst_chars;
954 hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
955 GMEM_DDESHARE, alloc_size);
957 lpstrT = (LPSTR)GlobalLock(hData32);
959 if (lpstrT)
961 CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS, src_chars,
962 wFormatID, lpstrT, dst_chars);
963 GlobalUnlock(hData32);
966 /* Unlock source */
967 if (lpSource->hData32)
968 GlobalUnlock(lpSource->hData32);
969 else
970 GlobalUnlock16(lpSource->hData16);
972 return X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, hData32, 0);
976 /**************************************************************************
977 * X11DRV_CLIPBOARD_ImportXAString
979 * Import XA_STRING, converting the string to CF_UNICODE.
981 HANDLE X11DRV_CLIPBOARD_ImportXAString(LPBYTE lpdata, UINT cBytes)
983 LPSTR lpstr;
984 UINT i, inlcount = 0;
985 HANDLE hUnicodeText = 0;
987 for (i = 0; i <= cBytes; i++)
989 if (lpdata[i] == '\n')
990 inlcount++;
993 if ((lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cBytes + inlcount + 1)))
995 UINT count;
997 for (i = 0, inlcount = 0; i <= cBytes; i++)
999 if (lpdata[i] == '\n')
1000 lpstr[inlcount++] = '\r';
1002 lpstr[inlcount++] = lpdata[i];
1005 count = MultiByteToWideChar(CP_UNIXCP, 0, lpstr, -1, NULL, 0);
1006 hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
1008 if(hUnicodeText)
1010 WCHAR *textW = GlobalLock(hUnicodeText);
1011 MultiByteToWideChar(CP_UNIXCP, 0, lpstr, -1, textW, count);
1012 GlobalUnlock(hUnicodeText);
1015 HeapFree(GetProcessHeap(), 0, lpstr);
1018 return hUnicodeText;
1022 /**************************************************************************
1023 * X11DRV_CLIPBOARD_ImportXAPIXMAP
1025 * Import XA_PIXMAP, converting the image to CF_DIB.
1027 HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(LPBYTE lpdata, UINT cBytes)
1029 HANDLE hTargetImage = 0; /* Handle to store the converted DIB */
1030 Pixmap *pPixmap = (Pixmap *) lpdata;
1031 HWND hwnd = GetOpenClipboardWindow();
1032 HDC hdc = GetDC(hwnd);
1034 hTargetImage = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc, TRUE);
1036 ReleaseDC(hwnd, hdc);
1038 return hTargetImage;
1042 /**************************************************************************
1043 * X11DRV_CLIPBOARD_ImportMetaFilePict
1045 * Import MetaFilePict.
1047 HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(LPBYTE lpdata, UINT cBytes)
1049 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, (HANDLE)lpdata, (LPDWORD)&cBytes, FALSE);
1053 /**************************************************************************
1054 * X11DRV_ImportEnhMetaFile
1056 * Import EnhMetaFile.
1058 HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(LPBYTE lpdata, UINT cBytes)
1060 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, (HANDLE)lpdata, (LPDWORD)&cBytes, FALSE);
1064 /**************************************************************************
1065 * X11DRV_ImportClipbordaData
1067 * Generic import clipboard data routine.
1069 HANDLE X11DRV_CLIPBOARD_ImportClipboardData(LPBYTE lpdata, UINT cBytes)
1071 LPVOID lpClipData;
1072 HANDLE hClipData = 0;
1074 if (cBytes)
1076 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
1077 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cBytes);
1078 if ((lpClipData = GlobalLock(hClipData)))
1080 memcpy(lpClipData, lpdata, cBytes);
1081 GlobalUnlock(hClipData);
1083 else
1084 hClipData = 0;
1087 return hClipData;
1091 /**************************************************************************
1092 X11DRV_CLIPBOARD_ExportClipboardData
1094 * Generic export clipboard data routine.
1096 HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Window requestor, Atom aTarget,
1097 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1099 LPVOID lpClipData;
1100 UINT cBytes = 0;
1101 HANDLE hClipData = 0;
1103 *lpBytes = 0; /* Assume failure */
1105 if (!X11DRV_CLIPBOARD_RenderFormat(lpData))
1106 ERR("Failed to export %d format\n", lpData->wFormatID);
1107 else
1109 cBytes = GlobalSize(lpData->hData32);
1111 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cBytes);
1113 if ((lpClipData = GlobalLock(hClipData)))
1115 LPVOID lpdata = GlobalLock(lpData->hData32);
1117 memcpy(lpClipData, lpdata, cBytes);
1118 *lpBytes = cBytes;
1120 GlobalUnlock(lpData->hData32);
1121 GlobalUnlock(hClipData);
1125 return hClipData;
1129 /**************************************************************************
1130 * X11DRV_CLIPBOARD_ExportXAString
1132 * Export CF_UNICODE converting the string to XA_STRING.
1133 * Helper function for X11DRV_CLIPBOARD_ExportString.
1135 HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1137 INT i, j;
1138 UINT size;
1139 LPWSTR uni_text;
1140 LPSTR text, lpstr;
1142 *lpBytes = 0; /* Assume return has zero bytes */
1144 uni_text = GlobalLock(lpData->hData32);
1146 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1148 text = HeapAlloc(GetProcessHeap(), 0, size);
1149 if (!text)
1150 return None;
1151 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, text, size, NULL, NULL);
1153 /* remove carriage returns */
1155 lpstr = (char*)HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size-- );
1156 if(lpstr == NULL) return None;
1157 for(i = 0,j = 0; i < size && text[i]; i++ )
1159 if( text[i] == '\r' &&
1160 (text[i+1] == '\n' || text[i+1] == '\0') ) continue;
1161 lpstr[j++] = text[i];
1163 lpstr[j]='\0';
1165 *lpBytes = j; /* Number of bytes in string */
1167 HeapFree(GetProcessHeap(), 0, text);
1168 GlobalUnlock(lpData->hData32);
1170 return lpstr;
1174 /**************************************************************************
1175 * X11DRV_CLIPBOARD_ExportCompoundText
1177 * Export CF_UNICODE to COMPOUND_TEXT or TEXT
1178 * Helper function for X11DRV_CLIPBOARD_ExportString.
1180 HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Window requestor, Atom aTarget, Atom rprop,
1181 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1183 Display *display = thread_display();
1184 char* lpstr = 0;
1185 XTextProperty prop;
1186 XICCEncodingStyle style;
1188 lpstr = (char*) X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1190 if (lpstr)
1192 if (aTarget == x11drv_atom(COMPOUND_TEXT))
1193 style = XCompoundTextStyle;
1194 else
1195 style = XStdICCTextStyle;
1197 /* Update the X property */
1198 wine_tsx11_lock();
1199 if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1201 XSetTextProperty(display, requestor, &prop, rprop);
1202 XFree(prop.value);
1204 wine_tsx11_unlock();
1206 HeapFree( GetProcessHeap(), 0, lpstr );
1209 return 0;
1212 /**************************************************************************
1213 * X11DRV_CLIPBOARD_ExportString
1215 * Export CF_UNICODE string
1217 HANDLE X11DRV_CLIPBOARD_ExportString(Window requestor, Atom aTarget, Atom rprop,
1218 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1220 if (X11DRV_CLIPBOARD_RenderFormat(lpData))
1222 if (aTarget == XA_STRING)
1223 return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1224 else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1225 return X11DRV_CLIPBOARD_ExportCompoundText(requestor, aTarget,
1226 rprop, lpData, lpBytes);
1227 else
1228 ERR("Unknown target %ld to %d format\n", aTarget, lpData->wFormatID);
1230 else
1231 ERR("Failed to render %d format\n", lpData->wFormatID);
1233 return 0;
1237 /**************************************************************************
1238 * X11DRV_CLIPBOARD_ExportXAPIXMAP
1240 * Export CF_DIB to XA_PIXMAP.
1242 HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Window requestor, Atom aTarget, Atom rprop,
1243 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1245 HDC hdc;
1246 Pixmap pixmap;
1248 if (!X11DRV_CLIPBOARD_RenderFormat(lpdata))
1250 ERR("Failed to export %d format\n", lpdata->wFormatID);
1251 return 0;
1254 hdc = GetDC(0);
1256 /* For convert from packed DIB to Pixmap */
1257 pixmap = X11DRV_DIB_CreatePixmapFromDIB(lpdata, hdc);
1258 *lpBytes = 4; /* pixmap is a 32bit value */
1260 ReleaseDC(0, hdc);
1262 return (HANDLE) pixmap;
1266 /**************************************************************************
1267 * X11DRV_CLIPBOARD_ExportMetaFilePict
1269 * Export MetaFilePict.
1271 HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Window requestor, Atom aTarget, Atom rprop,
1272 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1274 if (!X11DRV_CLIPBOARD_RenderFormat(lpdata))
1276 ERR("Failed to export %d format\n", lpdata->wFormatID);
1277 return 0;
1280 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, (HANDLE)lpdata->hData32,
1281 lpBytes, TRUE);
1285 /**************************************************************************
1286 * X11DRV_CLIPBOARD_ExportEnhMetaFile
1288 * Export EnhMetaFile.
1290 HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Window requestor, Atom aTarget, Atom rprop,
1291 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1293 if (!X11DRV_CLIPBOARD_RenderFormat(lpdata))
1295 ERR("Failed to export %d format\n", lpdata->wFormatID);
1296 return 0;
1299 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, (HANDLE)lpdata->hData32,
1300 lpBytes, TRUE);
1304 /**************************************************************************
1305 * X11DRV_CLIPBOARD_QueryTargets
1307 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection, XEvent *xe)
1309 INT i;
1310 Bool res;
1312 wine_tsx11_lock();
1313 XConvertSelection(display, selection, x11drv_atom(TARGETS),
1314 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1315 wine_tsx11_unlock();
1318 * Wait until SelectionNotify is received
1320 for (i = 0; i < SELECTION_RETRIES; i++)
1322 wine_tsx11_lock();
1323 res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
1324 wine_tsx11_unlock();
1325 if (res && xe->xselection.selection == selection) break;
1327 usleep(SELECTION_WAIT);
1330 /* Verify that the selection returned a valid TARGETS property */
1331 if ((xe->xselection.target != x11drv_atom(TARGETS)) || (xe->xselection.property == None))
1333 /* Selection owner failed to respond or we missed the SelectionNotify */
1334 WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
1335 return FALSE;
1338 return TRUE;
1342 /**************************************************************************
1343 * X11DRV_CLIPBOARD_QueryAvailableData
1345 * Caches the list of data formats available from the current selection.
1346 * This queries the selection owner for the TARGETS property and saves all
1347 * reported property types.
1349 static int X11DRV_CLIPBOARD_QueryAvailableData(LPCLIPBOARDINFO lpcbinfo)
1351 Display *display = thread_display();
1352 XEvent xe;
1353 Atom atype=AnyPropertyType;
1354 int aformat;
1355 unsigned long remain;
1356 Atom* targetList=NULL;
1357 Window w;
1358 HWND hWndClipWindow;
1359 unsigned long cSelectionTargets = 0;
1361 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
1363 ERR("Received request to cache selection but process is owner=(%08x)\n",
1364 (unsigned) selectionWindow);
1366 selectionAcquired = S_NOSELECTION;
1368 wine_tsx11_lock();
1369 if (XGetSelectionOwner(display,XA_PRIMARY) == selectionWindow)
1370 selectionAcquired |= S_PRIMARY;
1372 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == selectionWindow)
1373 selectionAcquired |= S_CLIPBOARD;
1374 wine_tsx11_unlock();
1376 if (!(selectionAcquired == (S_PRIMARY | S_CLIPBOARD)))
1378 WARN("Lost selection but process didn't process SelectClear\n");
1379 selectionWindow = None;
1381 else
1383 return -1; /* Prevent self request */
1387 if (lpcbinfo->flags & CB_OWNER)
1388 hWndClipWindow = lpcbinfo->hWndOwner;
1389 else if (lpcbinfo->flags & CB_OPEN)
1390 hWndClipWindow = lpcbinfo->hWndOpen;
1391 else
1392 hWndClipWindow = GetActiveWindow();
1394 if (!hWndClipWindow)
1396 WARN("No window available to retrieve selection!\n");
1397 return -1;
1400 w = X11DRV_get_whole_window(GetAncestor(hWndClipWindow, GA_ROOT));
1403 * Query the selection owner for the TARGETS property
1405 wine_tsx11_lock();
1406 if ((usePrimary && XGetSelectionOwner(display,XA_PRIMARY)) ||
1407 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
1409 wine_tsx11_unlock();
1410 if (usePrimary && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, &xe)))
1411 selectionCacheSrc = XA_PRIMARY;
1412 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), &xe))
1413 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1414 else
1415 return -1;
1417 else /* No selection owner so report 0 targets available */
1419 wine_tsx11_unlock();
1420 return 0;
1423 /* Read the TARGETS property contents */
1424 wine_tsx11_lock();
1425 if(XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
1426 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
1427 &remain, (unsigned char**)&targetList) != Success)
1429 wine_tsx11_unlock();
1430 WARN("Failed to read TARGETS property\n");
1432 else
1434 wine_tsx11_unlock();
1435 TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
1436 atype, aformat, cSelectionTargets, remain);
1438 * The TARGETS property should have returned us a list of atoms
1439 * corresponding to each selection target format supported.
1441 if ((atype == XA_ATOM || atype == x11drv_atom(TARGETS)) && aformat == 32)
1443 INT i, nb_atoms = 0;
1444 Atom *atoms = NULL;
1446 /* Cache these formats in the clipboard cache */
1447 for (i = 0; i < cSelectionTargets; i++)
1449 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(targetList[i]);
1451 if (!lpFormat)
1452 lpFormat = X11DRV_CLIPBOARD_LookupAliasProperty(targetList[i]);
1454 if (!lpFormat)
1456 /* add it to the list of atoms that we don't know about yet */
1457 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
1458 (cSelectionTargets - i) * sizeof(*atoms) );
1459 if (atoms) atoms[nb_atoms++] = targetList[i];
1461 else
1463 TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1464 i, lpFormat->drvData, lpFormat->wFormatID, lpFormat->Name);
1465 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0);
1469 /* query all unknown atoms in one go */
1470 if (atoms)
1472 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
1473 if (names)
1475 wine_tsx11_lock();
1476 XGetAtomNames( display, atoms, nb_atoms, names );
1477 wine_tsx11_unlock();
1478 for (i = 0; i < nb_atoms; i++)
1480 WINE_CLIPFORMAT *lpFormat = register_format( names[i], atoms[i] );
1481 if (!lpFormat)
1483 ERR("Failed to cache %s property\n", names[i]);
1484 continue;
1486 TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1487 i, lpFormat->drvData, lpFormat->wFormatID, lpFormat->Name);
1488 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0);
1490 wine_tsx11_lock();
1491 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
1492 wine_tsx11_unlock();
1493 HeapFree( GetProcessHeap(), 0, names );
1498 /* Free the list of targets */
1499 wine_tsx11_lock();
1500 XFree(targetList);
1501 wine_tsx11_unlock();
1504 return cSelectionTargets;
1508 /**************************************************************************
1509 * X11DRV_CLIPBOARD_ReadClipboardData
1511 * This method is invoked only when we DO NOT own the X selection
1513 * We always get the data from the selection client each time,
1514 * since we have no way of determining if the data in our cache is stale.
1516 static BOOL X11DRV_CLIPBOARD_ReadClipboardData(UINT wFormat)
1518 Display *display = thread_display();
1519 BOOL bRet = FALSE;
1520 Bool res;
1522 HWND hWndClipWindow = GetOpenClipboardWindow();
1523 HWND hWnd = (hWndClipWindow) ? hWndClipWindow : GetActiveWindow();
1525 LPWINE_CLIPFORMAT lpFormat;
1527 TRACE("%d\n", wFormat);
1529 if (!selectionAcquired)
1531 Window w = X11DRV_get_whole_window(GetAncestor(hWnd, GA_ROOT));
1532 if(!w)
1534 FIXME("No parent win found %p %p\n", hWnd, hWndClipWindow);
1535 return FALSE;
1538 lpFormat = X11DRV_CLIPBOARD_LookupFormat(wFormat);
1540 if (lpFormat->drvData)
1542 DWORD i;
1543 UINT alias;
1544 XEvent xe;
1546 TRACE("Requesting %s selection (%d) from win(%08x)\n",
1547 lpFormat->Name, lpFormat->drvData, (UINT)selectionCacheSrc);
1549 wine_tsx11_lock();
1550 XConvertSelection(display, selectionCacheSrc, lpFormat->drvData,
1551 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1552 wine_tsx11_unlock();
1554 /* wait until SelectionNotify is received */
1555 for (i = 0; i < SELECTION_RETRIES; i++)
1557 wine_tsx11_lock();
1558 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
1559 wine_tsx11_unlock();
1560 if (res && xe.xselection.selection == selectionCacheSrc) break;
1562 usleep(SELECTION_WAIT);
1565 /* If the property wasn't available check for aliases */
1566 if (xe.xselection.property == None &&
1567 (alias = X11DRV_CLIPBOARD_LookupPropertyAlias(lpFormat->drvData)))
1569 wine_tsx11_lock();
1570 XConvertSelection(display, selectionCacheSrc, alias,
1571 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1572 wine_tsx11_unlock();
1574 /* wait until SelectionNotify is received */
1575 for (i = 0; i < SELECTION_RETRIES; i++)
1577 wine_tsx11_lock();
1578 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
1579 wine_tsx11_unlock();
1580 if (res && xe.xselection.selection == selectionCacheSrc) break;
1582 usleep(SELECTION_WAIT);
1586 /* Verify that the selection returned a valid TARGETS property */
1587 if (xe.xselection.property != None)
1590 * Read the contents of the X selection property
1591 * into WINE's clipboard cache converting the
1592 * selection to be compatible if possible.
1594 bRet = X11DRV_CLIPBOARD_ReadSelection(lpFormat, xe.xselection.requestor,
1595 xe.xselection.property);
1599 else
1601 ERR("Received request to cache selection data but process is owner\n");
1604 TRACE("Returning %d\n", bRet);
1606 return bRet;
1610 /**************************************************************************
1611 * X11DRV_CLIPBOARD_ReadSelection
1612 * Reads the contents of the X selection property into the WINE clipboard cache
1613 * converting the selection into a format compatible with the windows clipboard
1614 * if possible.
1615 * This method is invoked only to read the contents of a the selection owned
1616 * by an external application. i.e. when we do not own the X selection.
1618 static BOOL X11DRV_CLIPBOARD_ReadSelection(LPWINE_CLIPFORMAT lpData, Window w, Atom prop)
1620 Display *display = thread_display();
1621 Atom atype=AnyPropertyType;
1622 int aformat;
1623 unsigned long total,nitems,remain,itemSize,val_cnt;
1624 long lRequestLength,bwc;
1625 unsigned char* val;
1626 unsigned char* buffer;
1627 BOOL bRet = FALSE;
1629 if(prop == None)
1630 return bRet;
1632 TRACE("Reading X selection type %s\n", lpData->Name);
1635 * First request a zero length in order to figure out the request size.
1637 wine_tsx11_lock();
1638 if(XGetWindowProperty(display,w,prop,0,0,False, AnyPropertyType,
1639 &atype, &aformat, &nitems, &itemSize, &val) != Success)
1641 wine_tsx11_unlock();
1642 WARN("Failed to get property size\n");
1643 return bRet;
1646 /* Free zero length return data if any */
1647 if (val)
1649 XFree(val);
1650 val = NULL;
1653 TRACE("Retrieving %ld bytes\n", itemSize * aformat/8);
1655 lRequestLength = (itemSize * aformat/8)/4 + 1;
1656 bwc = aformat/8;
1658 /* Read property in 4K blocks */
1659 if (XGetWindowProperty(display,w,prop,0,4096,False, AnyPropertyType/*reqType*/,
1660 &atype, &aformat, &nitems, &remain, &buffer) != Success)
1662 wine_tsx11_unlock();
1663 WARN("Failed to read property\n");
1664 return bRet;
1667 val = (char*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, nitems*bwc);
1668 memcpy(val,buffer,nitems*bwc);
1670 XFree(buffer);
1672 for (total = nitems*bwc, val_cnt = 0; remain;)
1674 val_cnt +=nitems*bwc;
1675 if (XGetWindowProperty(display, w, prop, (total / 4), 4096, False,
1676 AnyPropertyType, &atype, &aformat, &nitems, &remain, &buffer) != Success)
1678 wine_tsx11_unlock();
1679 WARN("Failed to read property\n");
1680 HeapFree(GetProcessHeap(), 0, val);
1681 return bRet;
1684 total += nitems*bwc;
1685 HeapReAlloc(GetProcessHeap(),0,val, total);
1686 memcpy(&val[val_cnt], buffer, nitems*(aformat/8));
1687 XFree(buffer);
1689 wine_tsx11_unlock();
1691 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, 0, lpData->lpDrvImportFunc(val, total), 0);
1693 /* Delete the property on the window now that we are done
1694 * This will send a PropertyNotify event to the selection owner. */
1695 wine_tsx11_lock();
1696 XDeleteProperty(display,w,prop);
1697 wine_tsx11_unlock();
1699 /* Free the retrieved property data */
1700 HeapFree(GetProcessHeap(),0,val);
1702 return bRet;
1706 /**************************************************************************
1707 * CLIPBOARD_SerializeMetafile
1709 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
1711 HANDLE h = 0;
1713 TRACE(" wFormat=%d hdata=%08x out=%d\n", wformat, (unsigned int) hdata, out);
1715 if (out) /* Serialize out, caller should free memory */
1717 *lpcbytes = 0; /* Assume failure */
1719 if (wformat == CF_METAFILEPICT)
1721 LPMETAFILEPICT lpmfp = (LPMETAFILEPICT) GlobalLock(hdata);
1722 int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
1724 h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
1725 if (h)
1727 char *pdata = GlobalLock(h);
1729 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
1730 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
1732 *lpcbytes = size + sizeof(METAFILEPICT);
1734 GlobalUnlock(h);
1737 GlobalUnlock(hdata);
1739 else if (wformat == CF_ENHMETAFILE)
1741 int size = GetEnhMetaFileBits(hdata, 0, NULL);
1743 h = GlobalAlloc(0, size);
1744 if (h)
1746 LPVOID pdata = GlobalLock(h);
1748 GetEnhMetaFileBits(hdata, size, pdata);
1749 *lpcbytes = size;
1751 GlobalUnlock(h);
1755 else
1757 if (wformat == CF_METAFILEPICT)
1759 h = GlobalAlloc(0, sizeof(METAFILEPICT));
1760 if (h)
1762 LPMETAFILEPICT pmfp = (LPMETAFILEPICT) GlobalLock(h);
1764 memcpy(pmfp, (LPVOID)hdata, sizeof(METAFILEPICT));
1765 pmfp->hMF = SetMetaFileBitsEx(*lpcbytes - sizeof(METAFILEPICT),
1766 (char *)hdata + sizeof(METAFILEPICT));
1768 GlobalUnlock(h);
1771 else if (wformat == CF_ENHMETAFILE)
1773 h = SetEnhMetaFileBits(*lpcbytes, (LPVOID)hdata);
1777 return h;
1781 /**************************************************************************
1782 * X11DRV_CLIPBOARD_ReleaseSelection
1784 * Release an XA_PRIMARY or XA_CLIPBOARD selection that we own, in response
1785 * to a SelectionClear event.
1786 * This can occur in response to another client grabbing the X selection.
1787 * If the XA_CLIPBOARD selection is lost, we relinquish XA_PRIMARY as well.
1789 void X11DRV_CLIPBOARD_ReleaseSelection(Atom selType, Window w, HWND hwnd)
1791 Display *display = thread_display();
1793 /* w is the window that lost the selection
1795 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
1796 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
1798 if (selectionAcquired)
1800 if (w == selectionWindow)
1802 /* If we're losing the CLIPBOARD selection, or if the preferences in .winerc
1803 * dictate that *all* selections should be cleared on loss of a selection,
1804 * we must give up all the selections we own.
1806 if (clearAllSelections || (selType == x11drv_atom(CLIPBOARD)))
1808 CLIPBOARDINFO cbinfo;
1810 /* completely give up the selection */
1811 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
1813 /* We are completely giving up the selection. There is a
1814 * potential race condition where the apps that now owns
1815 * the selection has already grabbed both selections. In
1816 * this case, if we clear any selection we may clear the
1817 * new owners selection. To prevent this common case we
1818 * try to open the clipboard. If we can't, we assume it
1819 * was a wine apps that took it and has taken both selections.
1820 * In this case, don't bother releasing the other selection.
1821 * Otherwise only release the selection if we still own it.
1823 X11DRV_CLIPBOARD_GetClipboardInfo(&cbinfo);
1825 if (cbinfo.flags & CB_OWNER)
1827 /* Since we're still the owner, this wasn't initiated by
1828 another Wine process */
1829 if (OpenClipboard(hwnd))
1831 /* We really lost CLIPBOARD but want to voluntarily lose PRIMARY */
1832 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
1834 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
1835 wine_tsx11_lock();
1836 if (selectionWindow == XGetSelectionOwner(display,XA_PRIMARY))
1838 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
1839 XSetSelectionOwner(display, XA_PRIMARY, None, CurrentTime);
1841 else
1842 TRACE("We no longer own PRIMARY\n");
1843 wine_tsx11_unlock();
1846 /* We really lost PRIMARY but want to voluntarily lose CLIPBOARD */
1847 if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
1849 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
1850 wine_tsx11_lock();
1851 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
1853 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
1854 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, CurrentTime);
1856 else
1857 TRACE("We no longer own CLIPBOARD\n");
1858 wine_tsx11_unlock();
1861 /* Destroy private objects */
1862 SendMessageW(cbinfo.hWndOwner, WM_DESTROYCLIPBOARD, 0, 0);
1864 /* Give up ownership of the windows clipboard */
1865 X11DRV_CLIPBOARD_ReleaseOwnership();
1867 CloseClipboard();
1870 else
1872 TRACE("Lost selection to other Wine process.\n");
1875 selectionWindow = None;
1876 PrimarySelectionOwner = ClipboardSelectionOwner = 0;
1878 X11DRV_EmptyClipboard();
1880 /* Reset the selection flags now that we are done */
1881 selectionAcquired = S_NOSELECTION;
1883 else if ( selType == XA_PRIMARY ) /* Give up only PRIMARY selection */
1885 TRACE("Lost PRIMARY selection\n");
1886 PrimarySelectionOwner = 0;
1887 selectionAcquired &= ~S_PRIMARY; /* clear S_PRIMARY mask */
1894 /**************************************************************************
1895 * IsSelectionOwner (X11DRV.@)
1897 * Returns: TRUE if the selection is owned by this process, FALSE otherwise
1899 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void)
1901 return selectionAcquired;
1905 /**************************************************************************
1906 * X11DRV Clipboard Exports
1907 **************************************************************************/
1910 /**************************************************************************
1911 * RegisterClipboardFormat (X11DRV.@)
1913 * Registers a custom X clipboard format
1914 * Returns: Format id or 0 on failure
1916 INT X11DRV_RegisterClipboardFormat(LPCSTR FormatName)
1918 LPWINE_CLIPFORMAT lpFormat;
1920 if (FormatName == NULL) return 0;
1921 if (!(lpFormat = register_format( FormatName, 0 ))) return 0;
1922 return lpFormat->wFormatID;
1926 /**************************************************************************
1927 * X11DRV_GetClipboardFormatName
1929 INT X11DRV_GetClipboardFormatName(UINT wFormat, LPSTR retStr, INT maxlen)
1931 INT len = 0;
1932 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupFormat(wFormat);
1934 TRACE("(%04X, %p, %d) !\n", wFormat, retStr, maxlen);
1936 if (!lpFormat || (lpFormat->wFlags & CF_FLAG_BUILTINFMT))
1938 TRACE("Unknown format 0x%08x!\n", wFormat);
1939 SetLastError(ERROR_INVALID_PARAMETER);
1941 else
1943 strncpy(retStr, lpFormat->Name, maxlen - 1);
1944 retStr[maxlen - 1] = 0;
1946 len = strlen(retStr);
1949 return len;
1953 /**************************************************************************
1954 * AcquireClipboard (X11DRV.@)
1956 void X11DRV_AcquireClipboard(HWND hWndClipWindow)
1958 Display *display = thread_display();
1961 * Acquire X selection if we don't already own it.
1962 * Note that we only acquire the selection if it hasn't been already
1963 * acquired by us, and ignore the fact that another X window may be
1964 * asserting ownership. The reason for this is we need *any* top level
1965 * X window to hold selection ownership. The actual clipboard data requests
1966 * are made via GetClipboardData from EVENT_SelectionRequest and this
1967 * ensures that the real HWND owner services the request.
1968 * If the owning X window gets destroyed the selection ownership is
1969 * re-cycled to another top level X window in X11DRV_CLIPBOARD_ResetOwner.
1972 if (!(selectionAcquired == (S_PRIMARY | S_CLIPBOARD)))
1974 Window owner;
1976 if (!hWndClipWindow)
1977 hWndClipWindow = GetActiveWindow();
1979 owner = X11DRV_get_whole_window(GetAncestor(hWndClipWindow, GA_ROOT));
1981 wine_tsx11_lock();
1982 /* Grab PRIMARY selection if not owned */
1983 if (usePrimary && !(selectionAcquired & S_PRIMARY))
1984 XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
1986 /* Grab CLIPBOARD selection if not owned */
1987 if (!(selectionAcquired & S_CLIPBOARD))
1988 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
1990 if (usePrimary && XGetSelectionOwner(display,XA_PRIMARY) == owner)
1991 selectionAcquired |= S_PRIMARY;
1993 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
1994 selectionAcquired |= S_CLIPBOARD;
1995 wine_tsx11_unlock();
1997 if (selectionAcquired)
1999 selectionWindow = owner;
2000 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2003 else
2005 WARN("Received request to acquire selection but process is already owner=(%08x)\n", (unsigned) selectionWindow);
2007 selectionAcquired = S_NOSELECTION;
2009 wine_tsx11_lock();
2010 if (XGetSelectionOwner(display,XA_PRIMARY) == selectionWindow)
2011 selectionAcquired |= S_PRIMARY;
2013 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == selectionWindow)
2014 selectionAcquired |= S_CLIPBOARD;
2015 wine_tsx11_unlock();
2017 if (!(selectionAcquired == (S_PRIMARY | S_CLIPBOARD)))
2019 WARN("Lost selection but process didn't process SelectClear\n");
2020 selectionWindow = None;
2026 /**************************************************************************
2027 * X11DRV_EmptyClipboard
2029 void X11DRV_EmptyClipboard(void)
2031 if (ClipData)
2033 LPWINE_CLIPDATA lpData;
2034 LPWINE_CLIPDATA lpNext = ClipData;
2038 lpData = lpNext;
2039 lpNext = lpData->NextData;
2040 lpData->PrevData->NextData = lpData->NextData;
2041 lpData->NextData->PrevData = lpData->PrevData;
2042 X11DRV_CLIPBOARD_FreeData(lpData);
2043 HeapFree(GetProcessHeap(), 0, lpData);
2044 } while (lpNext != lpData);
2047 TRACE(" %d entries deleted from cache.\n", ClipDataCount);
2049 ClipData = NULL;
2050 ClipDataCount = 0;
2055 /**************************************************************************
2056 * X11DRV_SetClipboardData
2058 BOOL X11DRV_SetClipboardData(UINT wFormat, HANDLE16 hData16, HANDLE hData32)
2060 BOOL bResult = FALSE;
2062 if (X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData16, hData32, 0))
2063 bResult = TRUE;
2065 return bResult;
2069 /**************************************************************************
2070 * CountClipboardFormats
2072 INT X11DRV_CountClipboardFormats(void)
2074 CLIPBOARDINFO cbinfo;
2076 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2078 TRACE(" count=%d\n", ClipDataCount);
2080 return ClipDataCount;
2084 /**************************************************************************
2085 * X11DRV_EnumClipboardFormats
2087 UINT X11DRV_EnumClipboardFormats(UINT wFormat)
2089 CLIPBOARDINFO cbinfo;
2090 UINT wNextFormat = 0;
2092 TRACE("(%04X)\n", wFormat);
2094 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2096 if (!wFormat)
2098 if (ClipData)
2099 wNextFormat = ClipData->wFormatID;
2101 else
2103 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
2105 if (lpData && lpData->NextData != ClipData)
2106 wNextFormat = lpData->NextData->wFormatID;
2109 return wNextFormat;
2113 /**************************************************************************
2114 * X11DRV_IsClipboardFormatAvailable
2116 BOOL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
2118 BOOL bRet = FALSE;
2119 CLIPBOARDINFO cbinfo;
2121 TRACE("(%04X)\n", wFormat);
2123 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2125 if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
2126 bRet = TRUE;
2128 TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
2130 return bRet;
2134 /**************************************************************************
2135 * GetClipboardData (USER.142)
2137 BOOL X11DRV_GetClipboardData(UINT wFormat, HANDLE16* phData16, HANDLE* phData32)
2139 CLIPBOARDINFO cbinfo;
2140 LPWINE_CLIPDATA lpRender;
2142 TRACE("(%04X)\n", wFormat);
2144 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2146 if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
2148 if ( !lpRender->hData32 )
2149 X11DRV_CLIPBOARD_RenderFormat(lpRender);
2151 /* Convert between 32 -> 16 bit data, if necessary */
2152 if (lpRender->hData32 && !lpRender->hData16)
2154 int size;
2156 if (lpRender->wFormatID == CF_METAFILEPICT)
2157 size = sizeof(METAFILEPICT16);
2158 else
2159 size = GlobalSize(lpRender->hData32);
2161 lpRender->hData16 = GlobalAlloc16(GMEM_ZEROINIT, size);
2163 if (!lpRender->hData16)
2164 ERR("(%04X) -- not enough memory in 16b heap\n", wFormat);
2165 else
2167 if (lpRender->wFormatID == CF_METAFILEPICT)
2169 FIXME("\timplement function CopyMetaFilePict32to16\n");
2170 FIXME("\tin the appropriate file.\n");
2171 #ifdef SOMEONE_IMPLEMENTED_ME
2172 CopyMetaFilePict32to16(GlobalLock16(lpRender->hData16),
2173 GlobalLock(lpRender->hData32));
2174 #endif
2176 else
2178 memcpy(GlobalLock16(lpRender->hData16),
2179 GlobalLock(lpRender->hData32), size);
2182 GlobalUnlock16(lpRender->hData16);
2183 GlobalUnlock(lpRender->hData32);
2187 /* Convert between 32 -> 16 bit data, if necessary */
2188 if (lpRender->hData16 && !lpRender->hData32)
2190 int size;
2192 if (lpRender->wFormatID == CF_METAFILEPICT)
2193 size = sizeof(METAFILEPICT16);
2194 else
2195 size = GlobalSize(lpRender->hData32);
2197 lpRender->hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
2198 GMEM_DDESHARE, size);
2200 if (lpRender->wFormatID == CF_METAFILEPICT)
2202 FIXME("\timplement function CopyMetaFilePict16to32\n");
2203 FIXME("\tin the appropriate file.\n");
2204 #ifdef SOMEONE_IMPLEMENTED_ME
2205 CopyMetaFilePict16to32(GlobalLock16(lpRender->hData32),
2206 GlobalLock(lpRender->hData16));
2207 #endif
2209 else
2211 memcpy(GlobalLock(lpRender->hData32),
2212 GlobalLock16(lpRender->hData16), size);
2215 GlobalUnlock(lpRender->hData32);
2216 GlobalUnlock16(lpRender->hData16);
2219 if (phData16)
2220 *phData16 = lpRender->hData16;
2222 if (phData32)
2223 *phData32 = lpRender->hData32;
2225 TRACE(" returning hData16(%04x) hData32(%04x) (type %d)\n",
2226 lpRender->hData16, (unsigned int) lpRender->hData32, lpRender->wFormatID);
2228 return lpRender->hData16 || lpRender->hData32;
2231 return 0;
2235 /**************************************************************************
2236 * ResetSelectionOwner (X11DRV.@)
2238 * Called from DestroyWindow() to prevent X selection from being lost when
2239 * a top level window is destroyed, by switching ownership to another top
2240 * level window.
2241 * Any top level window can own the selection. See X11DRV_CLIPBOARD_Acquire
2242 * for a more detailed description of this.
2244 void X11DRV_ResetSelectionOwner(HWND hwnd, BOOL bFooBar)
2246 Display *display = thread_display();
2247 HWND hWndClipOwner = 0;
2248 HWND tmp;
2249 Window XWnd = X11DRV_get_whole_window(hwnd);
2250 BOOL bLostSelection = FALSE;
2251 Window selectionPrevWindow;
2253 /* There is nothing to do if we don't own the selection,
2254 * or if the X window which currently owns the selection is different
2255 * from the one passed in.
2257 if (!selectionAcquired || XWnd != selectionWindow
2258 || selectionWindow == None )
2259 return;
2261 if ((bFooBar && XWnd) || (!bFooBar && !XWnd))
2262 return;
2264 hWndClipOwner = GetClipboardOwner();
2266 TRACE("clipboard owner = %p, selection window = %08x\n",
2267 hWndClipOwner, (unsigned)selectionWindow);
2269 /* now try to salvage current selection from being destroyed by X */
2270 TRACE("checking %08x\n", (unsigned) XWnd);
2272 selectionPrevWindow = selectionWindow;
2273 selectionWindow = None;
2275 if (!(tmp = GetWindow(hwnd, GW_HWNDNEXT)))
2276 tmp = GetWindow(hwnd, GW_HWNDFIRST);
2278 if (tmp && tmp != hwnd)
2279 selectionWindow = X11DRV_get_whole_window(tmp);
2281 if (selectionWindow != None)
2283 /* We must pretend that we don't own the selection while making the switch
2284 * since a SelectionClear event will be sent to the last owner.
2285 * If there is no owner X11DRV_CLIPBOARD_ReleaseSelection will do nothing.
2287 int saveSelectionState = selectionAcquired;
2288 selectionAcquired = S_NOSELECTION;
2290 TRACE("\tswitching selection from %08x to %08x\n",
2291 (unsigned)selectionPrevWindow, (unsigned)selectionWindow);
2293 wine_tsx11_lock();
2295 /* Assume ownership for the PRIMARY and CLIPBOARD selection */
2296 if (saveSelectionState & S_PRIMARY)
2297 XSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
2299 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), selectionWindow, CurrentTime);
2301 /* Restore the selection masks */
2302 selectionAcquired = saveSelectionState;
2304 /* Lose the selection if something went wrong */
2305 if (((saveSelectionState & S_PRIMARY) &&
2306 (XGetSelectionOwner(display, XA_PRIMARY) != selectionWindow)) ||
2307 (XGetSelectionOwner(display, x11drv_atom(CLIPBOARD)) != selectionWindow))
2309 bLostSelection = TRUE;
2311 else
2313 /* Update selection state */
2314 if (saveSelectionState & S_PRIMARY)
2315 PrimarySelectionOwner = selectionWindow;
2317 ClipboardSelectionOwner = selectionWindow;
2319 wine_tsx11_unlock();
2321 else
2323 bLostSelection = TRUE;
2326 if (bLostSelection)
2328 TRACE("Lost the selection!\n");
2330 X11DRV_CLIPBOARD_ReleaseOwnership();
2331 selectionAcquired = S_NOSELECTION;
2332 ClipboardSelectionOwner = PrimarySelectionOwner = 0;
2333 selectionWindow = 0;
2338 /**************************************************************************
2339 * X11DRV_CLIPBOARD_SynthesizeData
2341 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID)
2343 BOOL bsyn = TRUE;
2344 LPWINE_CLIPDATA lpSource = NULL;
2346 TRACE(" %d\n", wFormatID);
2348 /* Don't need to synthesize if it already exists */
2349 if (X11DRV_CLIPBOARD_LookupData(wFormatID))
2350 return TRUE;
2352 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
2354 bsyn = ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
2355 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2356 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
2357 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2358 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
2359 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED);
2361 else if (wFormatID == CF_ENHMETAFILE)
2363 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2364 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2366 else if (wFormatID == CF_METAFILEPICT)
2368 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2369 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2371 else if (wFormatID == CF_DIB)
2373 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
2374 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2376 else if (wFormatID == CF_BITMAP)
2378 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
2379 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2382 if (bsyn)
2383 X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, 0, CF_FLAG_SYNTHESIZED);
2385 return bsyn;
2390 /**************************************************************************
2391 * X11DRV_EndClipboardUpdate
2392 * TODO:
2393 * Add locale if it hasn't already been added
2395 void X11DRV_EndClipboardUpdate(void)
2397 INT count = ClipDataCount;
2399 /* Do Unicode <-> Text <-> OEM mapping */
2400 X11DRV_CLIPBOARD_SynthesizeData(CF_UNICODETEXT);
2401 X11DRV_CLIPBOARD_SynthesizeData(CF_TEXT);
2402 X11DRV_CLIPBOARD_SynthesizeData(CF_OEMTEXT);
2404 /* Enhmetafile <-> MetafilePict mapping */
2405 X11DRV_CLIPBOARD_SynthesizeData(CF_ENHMETAFILE);
2406 X11DRV_CLIPBOARD_SynthesizeData(CF_METAFILEPICT);
2408 /* DIB <-> Bitmap mapping */
2409 X11DRV_CLIPBOARD_SynthesizeData(CF_DIB);
2410 X11DRV_CLIPBOARD_SynthesizeData(CF_BITMAP);
2412 TRACE("%d formats added to cached data\n", ClipDataCount - count);