2 * X11 clipboard windows driver
4 * Copyright 1994 Martin Ayotte
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
24 * This file contains the X specific implementation for the windows
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)
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
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
65 #include "wine/port.h"
80 #include "wine/wingdi16.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
97 #define S_NOSELECTION 0
108 } CLIPBOARDINFO, *LPCLIPBOARDINFO;
110 typedef struct tagWINE_CLIPDATA {
116 struct tagWINE_CLIPDATA *PrevData;
117 struct tagWINE_CLIPDATA *NextData;
118 } WINE_CLIPDATA, *LPWINE_CLIPDATA;
120 typedef HANDLE (*DRVEXPORTFUNC)(Window requestor, Atom aTarget, Atom rprop,
121 LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
122 typedef HANDLE (*DRVIMPORTFUNC)(LPBYTE hData, UINT cBytes);
124 typedef struct tagWINE_CLIPFORMAT {
129 DRVIMPORTFUNC lpDrvImportFunc;
130 DRVEXPORTFUNC lpDrvExportFunc;
131 struct tagWINE_CLIPFORMAT *PrevFormat;
132 struct tagWINE_CLIPFORMAT *NextFormat;
133 } WINE_CLIPFORMAT, *LPWINE_CLIPFORMAT;
135 #define CF_FLAG_BUILTINFMT 1 /* Built-in windows format */
136 #define CF_FLAG_UNOWNED 2 /* cached data is not owned */
137 #define CF_FLAG_SYNTHESIZED 8 /* Implicitly converted data */
139 static int selectionAcquired = 0; /* Contains the current selection masks */
140 static Window selectionWindow = None; /* The top level X window which owns the selection */
141 static Atom selectionCacheSrc = XA_PRIMARY; /* The selection source from which the clipboard cache was filled */
143 void X11DRV_EmptyClipboard(BOOL keepunowned);
144 void X11DRV_EndClipboardUpdate(void);
145 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(LPBYTE lpdata, UINT cBytes);
146 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(LPBYTE lpdata, UINT cBytes);
147 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(LPBYTE lpdata, UINT cBytes);
148 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(LPBYTE lpdata, UINT cBytes);
149 static HANDLE X11DRV_CLIPBOARD_ImportXAString(LPBYTE lpdata, UINT cBytes);
150 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Window requestor, Atom aTarget,
151 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
152 static HANDLE X11DRV_CLIPBOARD_ExportString(Window requestor, Atom aTarget,
153 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
154 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Window requestor, Atom aTarget,
155 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
156 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Window requestor, Atom aTarget,
157 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
158 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Window requestor, Atom aTarget,
159 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
160 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCWSTR FormatName, Atom prop);
161 static BOOL X11DRV_CLIPBOARD_ReadSelection(LPWINE_CLIPFORMAT lpData, Window w, Atom prop);
162 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(UINT wFormatID);
163 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData);
164 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void);
165 static int X11DRV_CLIPBOARD_QueryAvailableData(LPCLIPBOARDINFO lpcbinfo);
166 static BOOL X11DRV_CLIPBOARD_ReadClipboardData(UINT wFormat);
167 static BOOL X11DRV_CLIPBOARD_RenderFormat(LPWINE_CLIPDATA lpData);
168 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out);
169 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID);
170 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(LPWINE_CLIPDATA lpData);
171 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(void);
172 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(void);
173 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple );
176 * WARNING: This data ordering is dependent on the WINE_CLIPFORMAT structure
177 * declared in clipboard.h
179 static const WCHAR wszCF_TEXT[] = {'W','C','F','_','T','E','X','T',0};
180 static const WCHAR wszCF_BITMAP[] = {'W','C','F','_','B','I','T','M','A','P',0};
181 static const WCHAR wszCF_METAFILEPICT[] = {'W','C','F','_','M','E','T','A','F','I','L','E','P','I','C','T',0};
182 static const WCHAR wszCF_SYLK[] = {'W','C','F','_','S','Y','L','K',0};
183 static const WCHAR wszCF_DIF[] = {'W','C','F','_','D','I','F',0};
184 static const WCHAR wszCF_TIFF[] = {'W','C','F','_','T','I','F','F',0};
185 static const WCHAR wszCF_OEMTEXT[] = {'W','C','F','_','O','E','M','T','E','X','T',0};
186 static const WCHAR wszCF_DIB[] = {'W','C','F','_','D','I','B',0};
187 static const WCHAR wszCF_PALETTE[] = {'W','C','F','_','P','A','L','E','T','T','E',0};
188 static const WCHAR wszCF_PENDATA[] = {'W','C','F','_','P','E','N','D','A','T','A',0};
189 static const WCHAR wszCF_RIFF[] = {'W','C','F','_','R','I','F','F',0};
190 static const WCHAR wszCF_WAVE[] = {'W','C','F','_','W','A','V','E',0};
191 static const WCHAR wszCF_UNICODETEXT[] = {'W','C','F','_','U','N','I','C','O','D','E','T','E','X','T',0};
192 static const WCHAR wszCF_ENHMETAFILE[] = {'W','C','F','_','E','N','H','M','E','T','A','F','I','L','E',0};
193 static const WCHAR wszCF_HDROP[] = {'W','C','F','_','H','D','R','O','P',0};
194 static const WCHAR wszCF_LOCALE[] = {'W','C','F','_','L','O','C','A','L','E',0};
195 static const WCHAR wszCF_DIBV5[] = {'W','C','F','_','D','I','B','V','5',0};
196 static const WCHAR wszCF_OWNERDISPLAY[] = {'W','C','F','_','O','W','N','E','R','D','I','S','P','L','A','Y',0};
197 static const WCHAR wszCF_DSPTEXT[] = {'W','C','F','_','D','S','P','T','E','X','T',0};
198 static const WCHAR wszCF_DSPBITMAP[] = {'W','C','F','_','D','S','P','B','I','T','M','A','P',0};
199 static const WCHAR wszCF_DSPMETAFILEPICT[] = {'W','C','F','_','D','S','P','M','E','T','A','F','I','L','E','P','I','C','T',0};
200 static const WCHAR wszCF_DSPENHMETAFILE[] = {'W','C','F','_','D','S','P','E','N','H','M','E','T','A','F','I','L','E',0};
202 static WINE_CLIPFORMAT ClipFormats[] =
204 { CF_TEXT, wszCF_TEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
205 X11DRV_CLIPBOARD_ExportClipboardData, NULL, &ClipFormats[1]},
207 { CF_BITMAP, wszCF_BITMAP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
208 NULL, &ClipFormats[0], &ClipFormats[2]},
210 { CF_METAFILEPICT, wszCF_METAFILEPICT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportMetaFilePict,
211 X11DRV_CLIPBOARD_ExportMetaFilePict, &ClipFormats[1], &ClipFormats[3]},
213 { CF_SYLK, wszCF_SYLK, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
214 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[2], &ClipFormats[4]},
216 { CF_DIF, wszCF_DIF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
217 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[3], &ClipFormats[5]},
219 { CF_TIFF, wszCF_TIFF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
220 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[4], &ClipFormats[6]},
222 { CF_OEMTEXT, wszCF_OEMTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
223 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[5], &ClipFormats[7]},
225 { CF_DIB, wszCF_DIB, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAPIXMAP,
226 X11DRV_CLIPBOARD_ExportXAPIXMAP, &ClipFormats[6], &ClipFormats[8]},
228 { CF_PALETTE, wszCF_PALETTE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
229 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[7], &ClipFormats[9]},
231 { CF_PENDATA, wszCF_PENDATA, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
232 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[8], &ClipFormats[10]},
234 { CF_RIFF, wszCF_RIFF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
235 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[9], &ClipFormats[11]},
237 { CF_WAVE, wszCF_WAVE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
238 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[10], &ClipFormats[12]},
240 { CF_UNICODETEXT, wszCF_UNICODETEXT, XA_STRING, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAString,
241 X11DRV_CLIPBOARD_ExportString, &ClipFormats[11], &ClipFormats[13]},
243 { CF_ENHMETAFILE, wszCF_ENHMETAFILE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportEnhMetaFile,
244 X11DRV_CLIPBOARD_ExportEnhMetaFile, &ClipFormats[12], &ClipFormats[14]},
246 { CF_HDROP, wszCF_HDROP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
247 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[13], &ClipFormats[15]},
249 { CF_LOCALE, wszCF_LOCALE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
250 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[14], &ClipFormats[16]},
252 { CF_DIBV5, wszCF_DIBV5, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
253 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[15], &ClipFormats[17]},
255 { CF_OWNERDISPLAY, wszCF_OWNERDISPLAY, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
256 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[16], &ClipFormats[18]},
258 { CF_DSPTEXT, wszCF_DSPTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
259 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[17], &ClipFormats[19]},
261 { CF_DSPBITMAP, wszCF_DSPBITMAP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
262 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[18], &ClipFormats[20]},
264 { CF_DSPMETAFILEPICT, wszCF_DSPMETAFILEPICT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
265 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[19], &ClipFormats[21]},
267 { CF_DSPENHMETAFILE, wszCF_DSPENHMETAFILE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
268 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[20], NULL}
271 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
273 /* Maps X properties to Windows formats */
274 static const WCHAR wszRichTextFormat[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
275 static const WCHAR wszGIF[] = {'G','I','F',0};
280 } PropertyFormatMap[] =
282 { wszRichTextFormat, XATOM_text_rtf },
283 /* Temporarily disable text/html because Evolution incorrectly pastes strings with extra nulls */
284 /*{ "text/html", "HTML Format" },*/
285 { wszGIF, XATOM_image_gif }
289 /* Maps equivalent X properties. It is assumed that lpszProperty must already
290 be in ClipFormats or PropertyFormatMap. */
293 UINT drvDataProperty;
295 } PropertyAliasMap[] =
297 /* DataProperty, DataAlias */
298 { XATOM_text_rtf, XATOM_text_richtext },
299 { XA_STRING, XATOM_COMPOUND_TEXT },
300 { XA_STRING, XATOM_TEXT },
301 { XATOM_WCF_DIB, XA_PIXMAP },
306 * Cached clipboard data.
308 static LPWINE_CLIPDATA ClipData = NULL;
309 static UINT ClipDataCount = 0;
312 * Clipboard sequence number
314 static UINT wSeqNo = 0;
316 /**************************************************************************
317 * Internal Clipboard implementation methods
318 **************************************************************************/
320 static Window thread_selection_wnd(void)
322 Window w = x11drv_thread_data()->selection_wnd;
327 w = XCreateWindow(thread_display(), root_window, 0, 0, 1, 1, 0, screen_depth,
328 InputOutput, CopyFromParent, 0, NULL);
332 x11drv_thread_data()->selection_wnd = w;
334 FIXME("Failed to create window. Fetching selection data will fail.\n");
340 /**************************************************************************
341 * X11DRV_InitClipboard
343 void X11DRV_InitClipboard(void)
347 /* Register known mapping between window formats and X properties */
348 for (i = 0; i < sizeof(PropertyFormatMap)/sizeof(PropertyFormatMap[0]); i++)
349 X11DRV_CLIPBOARD_InsertClipboardFormat(PropertyFormatMap[i].lpszFormat,
350 GET_ATOM(PropertyFormatMap[i].prop));
354 /**************************************************************************
357 * Intern atoms for formats that don't have one yet.
359 static void intern_atoms(void)
361 LPWINE_CLIPFORMAT format;
366 for (format = ClipFormats, count = 0; format; format = format->NextFormat)
367 if (!format->drvData) count++;
370 names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
371 atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
373 for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
374 if (!format->drvData) {
375 len = WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, NULL, 0, NULL, NULL);
376 names[i] = HeapAlloc(GetProcessHeap(), 0, len);
377 WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, names[i++], len, NULL, NULL);
382 XInternAtoms( thread_display(), names, count, False, atoms );
385 for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
386 if (!format->drvData) {
387 HeapFree(GetProcessHeap(), 0, names[i]);
388 format->drvData = atoms[i++];
392 HeapFree( GetProcessHeap(), 0, names );
393 HeapFree( GetProcessHeap(), 0, atoms );
397 /**************************************************************************
400 * Register a custom X clipboard format.
402 static WINE_CLIPFORMAT *register_format( LPCWSTR FormatName, Atom prop )
404 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
406 TRACE("%s\n", debugstr_w(FormatName));
408 /* walk format chain to see if it's already registered */
411 if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE, lpFormat->Name, -1, FormatName, -1) == CSTR_EQUAL
412 && (lpFormat->wFlags & CF_FLAG_BUILTINFMT) == 0)
414 lpFormat = lpFormat->NextFormat;
417 return X11DRV_CLIPBOARD_InsertClipboardFormat(FormatName, prop);
421 /**************************************************************************
422 * X11DRV_CLIPBOARD_LookupFormat
424 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupFormat(WORD wID)
426 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
430 if (lpFormat->wFormatID == wID)
433 lpFormat = lpFormat->NextFormat;
435 if (lpFormat && !lpFormat->drvData) intern_atoms();
440 /**************************************************************************
441 * X11DRV_CLIPBOARD_LookupProperty
443 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupProperty(UINT drvData)
447 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
448 BOOL need_intern = FALSE;
452 if (lpFormat->drvData == drvData) return lpFormat;
453 if (!lpFormat->drvData) need_intern = TRUE;
454 lpFormat = lpFormat->NextFormat;
456 if (!need_intern) return NULL;
458 /* restart the search for the new atoms */
463 /**************************************************************************
464 * X11DRV_CLIPBOARD_LookupAliasProperty
466 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupAliasProperty(UINT drvDataAlias)
469 LPWINE_CLIPFORMAT lpFormat = NULL;
471 for (i = 0; i < sizeof(PropertyAliasMap)/sizeof(PropertyAliasMap[0]); i++)
473 if (GET_ATOM(PropertyAliasMap[i].drvDataAlias) == drvDataAlias)
475 lpFormat = X11DRV_CLIPBOARD_LookupProperty(GET_ATOM(PropertyAliasMap[i].drvDataProperty));
484 /**************************************************************************
485 * X11DRV_CLIPBOARD_LookupPropertyAlias
487 static UINT X11DRV_CLIPBOARD_LookupPropertyAlias(UINT drvDataProperty)
492 for (i = 0; i < sizeof(PropertyAliasMap)/sizeof(PropertyAliasMap[0]); i++)
494 if (GET_ATOM(PropertyAliasMap[i].drvDataProperty) == drvDataProperty)
496 alias = GET_ATOM(PropertyAliasMap[i].drvDataAlias);
505 /**************************************************************************
506 * X11DRV_CLIPBOARD_LookupData
508 static LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
510 LPWINE_CLIPDATA lpData = ClipData;
516 if (lpData->wFormatID == wID)
519 lpData = lpData->NextData;
521 while(lpData != ClipData);
523 if (lpData->wFormatID != wID)
531 /**************************************************************************
532 * InsertClipboardFormat
534 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCWSTR FormatName, Atom prop)
536 LPWINE_CLIPFORMAT lpFormat;
537 LPWINE_CLIPFORMAT lpNewFormat;
539 /* allocate storage for new format entry */
540 lpNewFormat = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPFORMAT));
542 if(lpNewFormat == NULL)
544 WARN("No more memory for a new format!\n");
548 if (!(lpNewFormat->Name = HeapAlloc(GetProcessHeap(), 0, (strlenW(FormatName)+1)*sizeof(WCHAR))))
550 WARN("No more memory for the new format name!\n");
551 HeapFree(GetProcessHeap(), 0, lpNewFormat);
555 strcpyW((LPWSTR)lpNewFormat->Name, FormatName);
556 lpNewFormat->wFlags = 0;
557 lpNewFormat->wFormatID = GlobalAddAtomW(lpNewFormat->Name);
558 lpNewFormat->drvData = prop;
559 lpNewFormat->lpDrvImportFunc = X11DRV_CLIPBOARD_ImportClipboardData;
560 lpNewFormat->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportClipboardData;
563 lpFormat = ClipFormats;
565 while(lpFormat->NextFormat) /* Move to last entry */
566 lpFormat = lpFormat->NextFormat;
568 lpNewFormat->NextFormat = NULL;
569 lpFormat->NextFormat = lpNewFormat;
570 lpNewFormat->PrevFormat = lpFormat;
572 TRACE("Registering format(%d): %s drvData %d\n",
573 lpNewFormat->wFormatID, debugstr_w(FormatName), lpNewFormat->drvData);
581 /**************************************************************************
582 * X11DRV_CLIPBOARD_GetClipboardInfo
584 static BOOL X11DRV_CLIPBOARD_GetClipboardInfo(LPCLIPBOARDINFO cbInfo)
588 SERVER_START_REQ( set_clipboard_info )
592 if (wine_server_call_err( req ))
594 ERR("Failed to get clipboard owner.\n");
598 cbInfo->hWndOpen = reply->old_clipboard;
599 cbInfo->hWndOwner = reply->old_owner;
600 cbInfo->hWndViewer = reply->old_viewer;
601 cbInfo->seqno = reply->seqno;
602 cbInfo->flags = reply->flags;
613 /**************************************************************************
614 * X11DRV_CLIPBOARD_ReleaseOwnership
616 static BOOL X11DRV_CLIPBOARD_ReleaseOwnership(void)
620 SERVER_START_REQ( set_clipboard_info )
622 req->flags = SET_CB_RELOWNER | SET_CB_SEQNO;
624 if (wine_server_call_err( req ))
626 ERR("Failed to set clipboard.\n");
640 /**************************************************************************
641 * X11DRV_CLIPBOARD_InsertClipboardData
643 * Caller *must* have the clipboard open and be the owner.
645 static BOOL X11DRV_CLIPBOARD_InsertClipboardData(UINT wFormat, HANDLE16 hData16, HANDLE hData32, DWORD flags)
647 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
649 TRACE("format=%d lpData=%p hData16=%08x hData32=%08x flags=0x%08lx\n",
650 wFormat, lpData, hData16, (unsigned int)hData32, flags);
654 X11DRV_CLIPBOARD_FreeData(lpData);
656 lpData->hData16 = hData16; /* 0 is legal, see WM_RENDERFORMAT */
657 lpData->hData32 = hData32;
661 lpData = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPDATA));
663 lpData->wFormatID = wFormat;
664 lpData->hData16 = hData16; /* 0 is legal, see WM_RENDERFORMAT */
665 lpData->hData32 = hData32;
670 LPWINE_CLIPDATA lpPrevData = ClipData->PrevData;
672 lpData->PrevData = lpPrevData;
673 lpData->NextData = ClipData;
675 lpPrevData->NextData = lpData;
676 ClipData->PrevData = lpData;
680 lpData->NextData = lpData;
681 lpData->PrevData = lpData;
688 lpData->wFlags = flags;
694 /**************************************************************************
695 * X11DRV_CLIPBOARD_FreeData
697 * Free clipboard data handle.
699 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData)
701 TRACE("%d\n", lpData->wFormatID);
703 if ((lpData->wFormatID >= CF_GDIOBJFIRST &&
704 lpData->wFormatID <= CF_GDIOBJLAST) ||
705 lpData->wFormatID == CF_BITMAP ||
706 lpData->wFormatID == CF_DIB ||
707 lpData->wFormatID == CF_PALETTE)
710 DeleteObject(lpData->hData32);
713 DeleteObject(HGDIOBJ_32(lpData->hData16));
715 if ((lpData->wFormatID == CF_DIB) && lpData->drvData)
716 XFreePixmap(gdi_display, lpData->drvData);
718 else if (lpData->wFormatID == CF_METAFILEPICT)
722 DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData32 ))->hMF );
723 GlobalFree(lpData->hData32);
726 /* HMETAFILE16 and HMETAFILE32 are apparently the same thing,
727 and a shallow copy is enough to share a METAFILEPICT
728 structure between 16bit and 32bit clipboards. The MetaFile
729 should of course only be deleted once. */
730 GlobalFree16(lpData->hData16);
735 METAFILEPICT16* lpMetaPict = (METAFILEPICT16 *) GlobalLock16(lpData->hData16);
739 /* To delete 16-bit meta file, we just need to free the associated
740 handle. See DeleteMetaFile16() in dlls/gdi/metafile.c. */
741 GlobalFree16(lpMetaPict->hMF);
745 GlobalFree16(lpData->hData16);
748 else if (lpData->wFormatID == CF_ENHMETAFILE)
751 DeleteEnhMetaFile(lpData->hData32);
753 else if (lpData->wFormatID < CF_PRIVATEFIRST ||
754 lpData->wFormatID > CF_PRIVATELAST)
757 GlobalFree(lpData->hData32);
760 GlobalFree16(lpData->hData16);
769 /**************************************************************************
770 * X11DRV_CLIPBOARD_UpdateCache
772 static BOOL X11DRV_CLIPBOARD_UpdateCache(LPCLIPBOARDINFO lpcbinfo)
776 if (!X11DRV_CLIPBOARD_IsSelectionOwner())
778 if (!X11DRV_CLIPBOARD_GetClipboardInfo(lpcbinfo))
780 ERR("Failed to retrieve clipboard information.\n");
783 else if (wSeqNo < lpcbinfo->seqno)
785 X11DRV_EmptyClipboard(TRUE);
787 if (X11DRV_CLIPBOARD_QueryAvailableData(lpcbinfo) < 0)
789 ERR("Failed to cache clipboard data owned by another process.\n");
794 X11DRV_EndClipboardUpdate();
797 wSeqNo = lpcbinfo->seqno;
805 /**************************************************************************
806 * X11DRV_CLIPBOARD_RenderFormat
808 static BOOL X11DRV_CLIPBOARD_RenderFormat(LPWINE_CLIPDATA lpData)
812 TRACE(" 0x%04x hData32(0x%08x) hData16(0x%08x)\n",
813 lpData->wFormatID, (unsigned int)lpData->hData32, lpData->hData16);
815 if (lpData->hData32 || lpData->hData16)
816 return bret; /* Already rendered */
818 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
819 bret = X11DRV_CLIPBOARD_RenderSynthesizedFormat(lpData);
820 else if (!X11DRV_CLIPBOARD_IsSelectionOwner())
822 if (!X11DRV_CLIPBOARD_ReadClipboardData(lpData->wFormatID))
824 ERR("Failed to cache clipboard data owned by another process. Format=%d\n",
831 CLIPBOARDINFO cbInfo;
833 if (X11DRV_CLIPBOARD_GetClipboardInfo(&cbInfo) && cbInfo.hWndOwner)
835 /* Send a WM_RENDERFORMAT message to notify the owner to render the
836 * data requested into the clipboard.
838 TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", cbInfo.hWndOwner);
839 SendMessageW(cbInfo.hWndOwner, WM_RENDERFORMAT, (WPARAM)lpData->wFormatID, 0);
841 if (!lpData->hData32 && !lpData->hData16)
846 ERR("hWndClipOwner is lost!\n");
855 /**************************************************************************
856 * CLIPBOARD_ConvertText
857 * Returns number of required/converted characters - not bytes!
859 static INT CLIPBOARD_ConvertText(WORD src_fmt, void const *src, INT src_size,
860 WORD dst_fmt, void *dst, INT dst_size)
864 if(src_fmt == CF_UNICODETEXT)
877 return WideCharToMultiByte(cp, 0, src, src_size, dst, dst_size, NULL, NULL);
880 if(dst_fmt == CF_UNICODETEXT)
893 return MultiByteToWideChar(cp, 0, src, src_size, dst, dst_size);
896 if(!dst_size) return src_size;
898 if(dst_size > src_size) dst_size = src_size;
900 if(src_fmt == CF_TEXT )
901 CharToOemBuffA(src, dst, dst_size);
903 OemToCharBuffA(src, dst, dst_size);
909 /**************************************************************************
910 * X11DRV_CLIPBOARD_RenderSynthesizedFormat
912 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(LPWINE_CLIPDATA lpData)
918 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
920 UINT wFormatID = lpData->wFormatID;
922 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
923 bret = X11DRV_CLIPBOARD_RenderSynthesizedText(wFormatID);
929 bret = X11DRV_CLIPBOARD_RenderSynthesizedDIB();
933 bret = X11DRV_CLIPBOARD_RenderSynthesizedBitmap();
937 case CF_METAFILEPICT:
938 FIXME("Synthesizing wFormatID(0x%08x) not implemented\n", wFormatID);
942 FIXME("Called to synthesize unknown format\n");
947 lpData->wFlags &= ~CF_FLAG_SYNTHESIZED;
954 /**************************************************************************
955 * X11DRV_CLIPBOARD_RenderSynthesizedText
957 * Renders synthesized text
959 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(UINT wFormatID)
964 INT src_chars, dst_chars, alloc_size;
965 LPWINE_CLIPDATA lpSource = NULL;
967 TRACE(" %d\n", wFormatID);
969 if ((lpSource = X11DRV_CLIPBOARD_LookupData(wFormatID)) &&
973 /* Look for rendered source or non-synthesized source */
974 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
975 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
977 TRACE("UNICODETEXT -> %d\n", wFormatID);
979 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
980 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
982 TRACE("TEXT -> %d\n", wFormatID);
984 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
985 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
987 TRACE("OEMTEXT -> %d\n", wFormatID);
990 if (!lpSource || (lpSource->wFlags & CF_FLAG_SYNTHESIZED &&
994 /* Ask the clipboard owner to render the source text if necessary */
995 if (!lpSource->hData32 && !X11DRV_CLIPBOARD_RenderFormat(lpSource))
998 if (lpSource->hData32)
1000 lpstrS = (LPSTR)GlobalLock(lpSource->hData32);
1004 lpstrS = (LPSTR)GlobalLock16(lpSource->hData16);
1010 /* Text always NULL terminated */
1011 if(lpSource->wFormatID == CF_UNICODETEXT)
1012 src_chars = strlenW((LPCWSTR)lpstrS) + 1;
1014 src_chars = strlen(lpstrS) + 1;
1016 /* Calculate number of characters in the destination buffer */
1017 dst_chars = CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS,
1018 src_chars, wFormatID, NULL, 0);
1023 TRACE("Converting from '%d' to '%d', %i chars\n",
1024 lpSource->wFormatID, wFormatID, src_chars);
1026 /* Convert characters to bytes */
1027 if(wFormatID == CF_UNICODETEXT)
1028 alloc_size = dst_chars * sizeof(WCHAR);
1030 alloc_size = dst_chars;
1032 hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
1033 GMEM_DDESHARE, alloc_size);
1035 lpstrT = (LPSTR)GlobalLock(hData32);
1039 CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS, src_chars,
1040 wFormatID, lpstrT, dst_chars);
1041 GlobalUnlock(hData32);
1045 if (lpSource->hData32)
1046 GlobalUnlock(lpSource->hData32);
1048 GlobalUnlock16(lpSource->hData16);
1050 return X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, hData32, 0);
1054 /**************************************************************************
1055 * X11DRV_CLIPBOARD_RenderSynthesizedDIB
1057 * Renders synthesized DIB
1059 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB()
1062 LPWINE_CLIPDATA lpSource = NULL;
1066 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) && lpSource->hData32)
1070 /* If we have a bitmap and it's not synthesized or it has been rendered */
1071 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
1072 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
1074 /* Render source if required */
1075 if (lpSource->hData32 || X11DRV_CLIPBOARD_RenderFormat(lpSource))
1081 hData32 = X11DRV_DIB_CreateDIBFromBitmap(hdc, lpSource->hData32);
1082 ReleaseDC(NULL, hdc);
1086 X11DRV_CLIPBOARD_InsertClipboardData(CF_DIB, 0, hData32, 0);
1096 /**************************************************************************
1097 * X11DRV_CLIPBOARD_RenderSynthesizedBitmap
1099 * Renders synthesized bitmap
1101 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap()
1104 LPWINE_CLIPDATA lpSource = NULL;
1108 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) && lpSource->hData32)
1112 /* If we have a dib and it's not synthesized or it has been rendered */
1113 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
1114 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
1116 /* Render source if required */
1117 if (lpSource->hData32 || X11DRV_CLIPBOARD_RenderFormat(lpSource))
1121 unsigned int offset;
1122 LPBITMAPINFOHEADER lpbmih;
1125 lpbmih = (LPBITMAPINFOHEADER) GlobalLock(lpSource->hData32);
1127 offset = sizeof(BITMAPINFOHEADER)
1128 + ((lpbmih->biBitCount <= 8) ? (sizeof(RGBQUAD) *
1129 (1 << lpbmih->biBitCount)) : 0);
1131 hData32 = CreateDIBitmap(hdc, lpbmih, CBM_INIT, (LPBYTE)lpbmih +
1132 offset, (LPBITMAPINFO) lpbmih, DIB_RGB_COLORS);
1134 GlobalUnlock(lpSource->hData32);
1135 ReleaseDC(NULL, hdc);
1139 X11DRV_CLIPBOARD_InsertClipboardData(CF_BITMAP, 0, hData32, 0);
1149 /**************************************************************************
1150 * X11DRV_CLIPBOARD_ImportXAString
1152 * Import XA_STRING, converting the string to CF_UNICODE.
1154 HANDLE X11DRV_CLIPBOARD_ImportXAString(LPBYTE lpdata, UINT cBytes)
1157 UINT i, inlcount = 0;
1158 HANDLE hUnicodeText = 0;
1160 for (i = 0; i <= cBytes; i++)
1162 if (lpdata[i] == '\n')
1166 if ((lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cBytes + inlcount + 1)))
1170 for (i = 0, inlcount = 0; i <= cBytes; i++)
1172 if (lpdata[i] == '\n')
1173 lpstr[inlcount++] = '\r';
1175 lpstr[inlcount++] = lpdata[i];
1178 count = MultiByteToWideChar(CP_UNIXCP, 0, lpstr, -1, NULL, 0);
1179 hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
1183 WCHAR *textW = GlobalLock(hUnicodeText);
1184 MultiByteToWideChar(CP_UNIXCP, 0, lpstr, -1, textW, count);
1185 GlobalUnlock(hUnicodeText);
1188 HeapFree(GetProcessHeap(), 0, lpstr);
1191 return hUnicodeText;
1195 /**************************************************************************
1196 * X11DRV_CLIPBOARD_ImportXAPIXMAP
1198 * Import XA_PIXMAP, converting the image to CF_DIB.
1200 HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(LPBYTE lpdata, UINT cBytes)
1202 HANDLE hTargetImage = 0; /* Handle to store the converted DIB */
1203 Pixmap *pPixmap = (Pixmap *) lpdata;
1204 HWND hwnd = GetOpenClipboardWindow();
1205 HDC hdc = GetDC(hwnd);
1207 hTargetImage = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc);
1209 ReleaseDC(hwnd, hdc);
1211 return hTargetImage;
1215 /**************************************************************************
1216 * X11DRV_CLIPBOARD_ImportMetaFilePict
1218 * Import MetaFilePict.
1220 HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(LPBYTE lpdata, UINT cBytes)
1222 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, (HANDLE)lpdata, (LPDWORD)&cBytes, FALSE);
1226 /**************************************************************************
1227 * X11DRV_ImportEnhMetaFile
1229 * Import EnhMetaFile.
1231 HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(LPBYTE lpdata, UINT cBytes)
1233 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, (HANDLE)lpdata, (LPDWORD)&cBytes, FALSE);
1237 /**************************************************************************
1238 * X11DRV_ImportClipbordaData
1240 * Generic import clipboard data routine.
1242 HANDLE X11DRV_CLIPBOARD_ImportClipboardData(LPBYTE lpdata, UINT cBytes)
1245 HANDLE hClipData = 0;
1249 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
1250 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cBytes);
1251 if (hClipData == 0) return NULL;
1253 if ((lpClipData = GlobalLock(hClipData)))
1255 memcpy(lpClipData, lpdata, cBytes);
1256 GlobalUnlock(hClipData);
1259 GlobalFree(hClipData);
1268 /**************************************************************************
1269 X11DRV_CLIPBOARD_ExportClipboardData
1271 * Generic export clipboard data routine.
1273 HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Window requestor, Atom aTarget,
1274 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1278 HANDLE hClipData = 0;
1280 *lpBytes = 0; /* Assume failure */
1282 if (!X11DRV_CLIPBOARD_RenderFormat(lpData))
1283 ERR("Failed to export %d format\n", lpData->wFormatID);
1286 cBytes = GlobalSize(lpData->hData32);
1288 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cBytes);
1289 if (hClipData == 0) return NULL;
1291 if ((lpClipData = GlobalLock(hClipData)))
1293 LPVOID lpdata = GlobalLock(lpData->hData32);
1295 memcpy(lpClipData, lpdata, cBytes);
1298 GlobalUnlock(lpData->hData32);
1299 GlobalUnlock(hClipData);
1301 GlobalFree(hClipData);
1310 /**************************************************************************
1311 * X11DRV_CLIPBOARD_ExportXAString
1313 * Export CF_UNICODE converting the string to XA_STRING.
1314 * Helper function for X11DRV_CLIPBOARD_ExportString.
1316 static HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1321 LPSTR text, lpstr = NULL;
1323 *lpBytes = 0; /* Assume return has zero bytes */
1325 uni_text = GlobalLock(lpData->hData32);
1327 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1329 text = HeapAlloc(GetProcessHeap(), 0, size);
1330 if (!text) goto done;
1331 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, text, size, NULL, NULL);
1333 /* remove carriage returns */
1335 lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size-- );
1336 if(lpstr == NULL) goto done;
1338 for(i = 0,j = 0; i < size && text[i]; i++ )
1340 if( text[i] == '\r' &&
1341 (text[i+1] == '\n' || text[i+1] == '\0') ) continue;
1342 lpstr[j++] = text[i];
1346 *lpBytes = j; /* Number of bytes in string */
1349 HeapFree(GetProcessHeap(), 0, text);
1350 GlobalUnlock(lpData->hData32);
1356 /**************************************************************************
1357 * X11DRV_CLIPBOARD_ExportCompoundText
1359 * Export CF_UNICODE to COMPOUND_TEXT or TEXT
1360 * Helper function for X11DRV_CLIPBOARD_ExportString.
1362 static HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Window requestor, Atom aTarget, Atom rprop,
1363 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1365 Display *display = thread_display();
1368 XICCEncodingStyle style;
1370 lpstr = (char*) X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1374 if (aTarget == x11drv_atom(COMPOUND_TEXT))
1375 style = XCompoundTextStyle;
1377 style = XStdICCTextStyle;
1379 /* Update the X property */
1381 if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1383 XSetTextProperty(display, requestor, &prop, rprop);
1386 wine_tsx11_unlock();
1388 HeapFree( GetProcessHeap(), 0, lpstr );
1394 /**************************************************************************
1395 * X11DRV_CLIPBOARD_ExportString
1397 * Export CF_UNICODE string
1399 HANDLE X11DRV_CLIPBOARD_ExportString(Window requestor, Atom aTarget, Atom rprop,
1400 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1402 if (X11DRV_CLIPBOARD_RenderFormat(lpData))
1404 if (aTarget == XA_STRING)
1405 return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1406 else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1407 return X11DRV_CLIPBOARD_ExportCompoundText(requestor, aTarget,
1408 rprop, lpData, lpBytes);
1410 ERR("Unknown target %ld to %d format\n", aTarget, lpData->wFormatID);
1413 ERR("Failed to render %d format\n", lpData->wFormatID);
1419 /**************************************************************************
1420 * X11DRV_CLIPBOARD_ExportXAPIXMAP
1422 * Export CF_DIB to XA_PIXMAP.
1424 HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Window requestor, Atom aTarget, Atom rprop,
1425 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1429 unsigned char* lpData;
1431 if (!X11DRV_CLIPBOARD_RenderFormat(lpdata))
1433 ERR("Failed to export %d format\n", lpdata->wFormatID);
1437 if (!lpdata->drvData) /* If not already rendered */
1439 /* For convert from packed DIB to Pixmap */
1441 lpdata->drvData = (UINT) X11DRV_DIB_CreatePixmapFromDIB(lpdata->hData32, hdc);
1445 *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1447 /* Wrap pixmap so we can return a handle */
1448 hData = GlobalAlloc(0, *lpBytes);
1449 lpData = GlobalLock(hData);
1450 memcpy(lpData, &lpdata->drvData, *lpBytes);
1451 GlobalUnlock(hData);
1453 return (HANDLE) hData;
1457 /**************************************************************************
1458 * X11DRV_CLIPBOARD_ExportMetaFilePict
1460 * Export MetaFilePict.
1462 HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Window requestor, Atom aTarget, Atom rprop,
1463 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1465 if (!X11DRV_CLIPBOARD_RenderFormat(lpdata))
1467 ERR("Failed to export %d format\n", lpdata->wFormatID);
1471 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, (HANDLE)lpdata->hData32,
1476 /**************************************************************************
1477 * X11DRV_CLIPBOARD_ExportEnhMetaFile
1479 * Export EnhMetaFile.
1481 HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Window requestor, Atom aTarget, Atom rprop,
1482 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1484 if (!X11DRV_CLIPBOARD_RenderFormat(lpdata))
1486 ERR("Failed to export %d format\n", lpdata->wFormatID);
1490 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, (HANDLE)lpdata->hData32,
1495 /**************************************************************************
1496 * X11DRV_CLIPBOARD_QueryTargets
1498 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection,
1499 Atom target, XEvent *xe)
1505 XConvertSelection(display, selection, target,
1506 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1507 wine_tsx11_unlock();
1510 * Wait until SelectionNotify is received
1512 for (i = 0; i < SELECTION_RETRIES; i++)
1515 res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
1516 wine_tsx11_unlock();
1517 if (res && xe->xselection.selection == selection) break;
1519 usleep(SELECTION_WAIT);
1522 /* Verify that the selection returned a valid TARGETS property */
1523 if ((xe->xselection.target != target) || (xe->xselection.property == None))
1525 /* Selection owner failed to respond or we missed the SelectionNotify */
1526 WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
1534 /**************************************************************************
1535 * X11DRV_CLIPBOARD_InsertSelectionProperties
1537 * Mark property available for future retrieval.
1539 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
1541 UINT i, nb_atoms = 0;
1544 /* Cache these formats in the clipboard cache */
1545 for (i = 0; i < count; i++)
1547 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(properties[i]);
1550 lpFormat = X11DRV_CLIPBOARD_LookupAliasProperty(properties[i]);
1554 /* add it to the list of atoms that we don't know about yet */
1555 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
1556 (count - i) * sizeof(*atoms) );
1557 if (atoms) atoms[nb_atoms++] = properties[i];
1561 TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1562 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
1563 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0);
1567 /* query all unknown atoms in one go */
1570 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
1574 XGetAtomNames( display, atoms, nb_atoms, names );
1575 wine_tsx11_unlock();
1576 for (i = 0; i < nb_atoms; i++)
1578 WINE_CLIPFORMAT *lpFormat;
1580 int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
1581 wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1582 MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
1584 lpFormat = register_format( wname, atoms[i] );
1585 HeapFree(GetProcessHeap(), 0, wname);
1588 ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
1591 TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1592 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
1593 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0);
1596 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
1597 wine_tsx11_unlock();
1598 HeapFree( GetProcessHeap(), 0, names );
1600 HeapFree( GetProcessHeap(), 0, atoms );
1605 /**************************************************************************
1606 * X11DRV_CLIPBOARD_QueryAvailableData
1608 * Caches the list of data formats available from the current selection.
1609 * This queries the selection owner for the TARGETS property and saves all
1610 * reported property types.
1612 static int X11DRV_CLIPBOARD_QueryAvailableData(LPCLIPBOARDINFO lpcbinfo)
1614 Display *display = thread_display();
1616 Atom atype=AnyPropertyType;
1618 unsigned long remain;
1619 Atom* targetList=NULL;
1621 unsigned long cSelectionTargets = 0;
1623 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
1625 ERR("Received request to cache selection but process is owner=(%08x)\n",
1626 (unsigned) selectionWindow);
1627 return -1; /* Prevent self request */
1630 w = thread_selection_wnd();
1633 ERR("No window available to retrieve selection!\n");
1638 * Query the selection owner for the TARGETS property
1641 if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
1642 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
1644 wine_tsx11_unlock();
1645 if (use_primary_selection && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
1646 selectionCacheSrc = XA_PRIMARY;
1647 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
1648 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1651 Atom xstr = XA_PRIMARY;
1653 /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
1654 if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
1656 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1657 selectionCacheSrc = XA_PRIMARY;
1660 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
1662 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1663 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1668 WARN("Failed to query selection owner for available data.\n");
1673 else /* No selection owner so report 0 targets available */
1675 wine_tsx11_unlock();
1679 /* Read the TARGETS property contents */
1681 if(XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
1682 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
1683 &remain, (unsigned char**)&targetList) != Success)
1685 wine_tsx11_unlock();
1686 WARN("Failed to read TARGETS property\n");
1690 wine_tsx11_unlock();
1691 TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
1692 atype, aformat, cSelectionTargets, remain);
1694 * The TARGETS property should have returned us a list of atoms
1695 * corresponding to each selection target format supported.
1697 if ((atype == XA_ATOM || atype == x11drv_atom(TARGETS)) && aformat == 32)
1698 X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, cSelectionTargets);
1700 /* Free the list of targets */
1703 wine_tsx11_unlock();
1706 return cSelectionTargets;
1710 /**************************************************************************
1711 * X11DRV_CLIPBOARD_ReadClipboardData
1713 * This method is invoked only when we DO NOT own the X selection
1715 * We always get the data from the selection client each time,
1716 * since we have no way of determining if the data in our cache is stale.
1718 static BOOL X11DRV_CLIPBOARD_ReadClipboardData(UINT wFormat)
1720 Display *display = thread_display();
1723 LPWINE_CLIPFORMAT lpFormat;
1725 TRACE("%d\n", wFormat);
1727 if (!selectionAcquired)
1729 Window w = thread_selection_wnd();
1732 ERR("No window available to read selection data!\n");
1736 lpFormat = X11DRV_CLIPBOARD_LookupFormat(wFormat);
1738 if (lpFormat && lpFormat->drvData)
1744 TRACE("Requesting %s selection (%d) from win(%08x)\n",
1745 debugstr_w(lpFormat->Name), lpFormat->drvData, (UINT)selectionCacheSrc);
1748 XConvertSelection(display, selectionCacheSrc, lpFormat->drvData,
1749 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1750 wine_tsx11_unlock();
1752 /* wait until SelectionNotify is received */
1753 for (i = 0; i < SELECTION_RETRIES; i++)
1756 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
1757 wine_tsx11_unlock();
1758 if (res && xe.xselection.selection == selectionCacheSrc) break;
1760 usleep(SELECTION_WAIT);
1763 /* If the property wasn't available check for aliases */
1764 if (xe.xselection.property == None &&
1765 (alias = X11DRV_CLIPBOARD_LookupPropertyAlias(lpFormat->drvData)))
1768 XConvertSelection(display, selectionCacheSrc, alias,
1769 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1770 wine_tsx11_unlock();
1772 /* wait until SelectionNotify is received */
1773 for (i = 0; i < SELECTION_RETRIES; i++)
1776 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
1777 wine_tsx11_unlock();
1778 if (res && xe.xselection.selection == selectionCacheSrc) break;
1780 usleep(SELECTION_WAIT);
1784 /* Verify that the selection returned a valid TARGETS property */
1785 if (xe.xselection.property != None)
1788 * Read the contents of the X selection property
1789 * into WINE's clipboard cache converting the
1790 * selection to be compatible if possible.
1792 bRet = X11DRV_CLIPBOARD_ReadSelection(lpFormat, xe.xselection.requestor,
1793 xe.xselection.property);
1799 ERR("Received request to cache selection data but process is owner\n");
1802 TRACE("Returning %d\n", bRet);
1808 /**************************************************************************
1809 * X11DRV_CLIPBOARD_ReadSelection
1810 * Reads the contents of the X selection property into the WINE clipboard cache
1811 * converting the selection into a format compatible with the windows clipboard
1813 * This method is invoked only to read the contents of a the selection owned
1814 * by an external application. i.e. when we do not own the X selection.
1816 static BOOL X11DRV_CLIPBOARD_ReadSelection(LPWINE_CLIPFORMAT lpData, Window w, Atom prop)
1818 Display *display = thread_display();
1819 Atom atype=AnyPropertyType;
1821 unsigned long total,nitems,remain,val_cnt;
1824 unsigned char* buffer;
1830 TRACE("Reading X selection type %s\n", debugstr_w(lpData->Name));
1833 * First request a zero length in order to figure out the request size.
1836 if(XGetWindowProperty(display,w,prop,0,0,False, AnyPropertyType,
1837 &atype, &aformat, &nitems, &remain, &buffer) != Success)
1839 wine_tsx11_unlock();
1840 WARN("Failed to get property size\n");
1844 /* Free zero length return data if any */
1852 reqlen = remain * bwc;
1854 TRACE("Retrieving %ld bytes\n", reqlen);
1856 val = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, reqlen);
1858 /* Read property in 4K blocks */
1859 for (total = 0, val_cnt = 0; remain;)
1861 if (XGetWindowProperty(display, w, prop, (total / 4), 4096, False,
1862 AnyPropertyType, &atype, &aformat, &nitems, &remain, &buffer) != Success)
1864 wine_tsx11_unlock();
1865 WARN("Failed to read property\n");
1866 HeapFree(GetProcessHeap(), 0, val);
1871 memcpy(&val[val_cnt], buffer, nitems * bwc);
1872 val_cnt += nitems * bwc;
1873 total += nitems*bwc;
1876 wine_tsx11_unlock();
1878 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, 0, lpData->lpDrvImportFunc(val, total), 0);
1880 /* Delete the property on the window now that we are done
1881 * This will send a PropertyNotify event to the selection owner. */
1883 XDeleteProperty(display,w,prop);
1884 wine_tsx11_unlock();
1886 /* Free the retrieved property data */
1887 HeapFree(GetProcessHeap(),0,val);
1893 /**************************************************************************
1894 * CLIPBOARD_SerializeMetafile
1896 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
1900 TRACE(" wFormat=%d hdata=%08x out=%d\n", wformat, (unsigned int) hdata, out);
1902 if (out) /* Serialize out, caller should free memory */
1904 *lpcbytes = 0; /* Assume failure */
1906 if (wformat == CF_METAFILEPICT)
1908 LPMETAFILEPICT lpmfp = (LPMETAFILEPICT) GlobalLock(hdata);
1909 unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
1911 h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
1914 char *pdata = GlobalLock(h);
1916 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
1917 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
1919 *lpcbytes = size + sizeof(METAFILEPICT);
1924 GlobalUnlock(hdata);
1926 else if (wformat == CF_ENHMETAFILE)
1928 int size = GetEnhMetaFileBits(hdata, 0, NULL);
1930 h = GlobalAlloc(0, size);
1933 LPVOID pdata = GlobalLock(h);
1935 GetEnhMetaFileBits(hdata, size, pdata);
1944 if (wformat == CF_METAFILEPICT)
1946 h = GlobalAlloc(0, sizeof(METAFILEPICT));
1949 unsigned int wiresize, size;
1950 LPMETAFILEPICT lpmfp = (LPMETAFILEPICT) GlobalLock(h);
1952 memcpy(lpmfp, (LPVOID)hdata, sizeof(METAFILEPICT));
1953 wiresize = *lpcbytes - sizeof(METAFILEPICT);
1954 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
1955 ((const char *)hdata) + sizeof(METAFILEPICT));
1956 size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
1960 else if (wformat == CF_ENHMETAFILE)
1962 h = SetEnhMetaFileBits(*lpcbytes, (LPVOID)hdata);
1970 /**************************************************************************
1971 * X11DRV_CLIPBOARD_ReleaseSelection
1973 * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
1975 static void X11DRV_CLIPBOARD_ReleaseSelection(Atom selType, Window w, HWND hwnd, Time time)
1977 Display *display = thread_display();
1979 /* w is the window that lost the selection
1981 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
1982 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
1984 if (selectionAcquired && (w == selectionWindow))
1986 CLIPBOARDINFO cbinfo;
1988 /* completely give up the selection */
1989 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
1991 X11DRV_CLIPBOARD_GetClipboardInfo(&cbinfo);
1993 if (cbinfo.flags & CB_PROCESS)
1995 /* Since we're still the owner, this wasn't initiated by
1996 another Wine process */
1997 if (OpenClipboard(hwnd))
1999 /* Destroy private objects */
2000 SendMessageW(cbinfo.hWndOwner, WM_DESTROYCLIPBOARD, 0, 0);
2002 /* Give up ownership of the windows clipboard */
2003 X11DRV_CLIPBOARD_ReleaseOwnership();
2008 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2010 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2013 if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2015 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2016 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2019 TRACE("We no longer own PRIMARY\n");
2020 wine_tsx11_unlock();
2022 else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2024 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2027 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2029 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2030 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2033 TRACE("We no longer own CLIPBOARD\n");
2034 wine_tsx11_unlock();
2037 selectionWindow = None;
2039 X11DRV_EmptyClipboard(FALSE);
2041 /* Reset the selection flags now that we are done */
2042 selectionAcquired = S_NOSELECTION;
2047 /**************************************************************************
2048 * IsSelectionOwner (X11DRV.@)
2050 * Returns: TRUE if the selection is owned by this process, FALSE otherwise
2052 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void)
2054 return selectionAcquired;
2058 /**************************************************************************
2059 * X11DRV Clipboard Exports
2060 **************************************************************************/
2063 /**************************************************************************
2064 * RegisterClipboardFormat (X11DRV.@)
2066 * Registers a custom X clipboard format
2067 * Returns: Format id or 0 on failure
2069 UINT X11DRV_RegisterClipboardFormat(LPCWSTR FormatName)
2071 LPWINE_CLIPFORMAT lpFormat;
2073 if (FormatName == NULL) return 0;
2074 if (!(lpFormat = register_format( FormatName, 0 ))) return 0;
2075 return lpFormat->wFormatID;
2079 /**************************************************************************
2080 * X11DRV_GetClipboardFormatName
2082 INT X11DRV_GetClipboardFormatName(UINT wFormat, LPWSTR retStr, INT maxlen)
2084 LPWINE_CLIPFORMAT lpFormat;
2086 TRACE("(%04X, %p, %d) !\n", wFormat, retStr, maxlen);
2088 if (wFormat < 0xc000)
2090 SetLastError(ERROR_INVALID_PARAMETER);
2094 lpFormat = X11DRV_CLIPBOARD_LookupFormat(wFormat);
2096 if (!lpFormat || (lpFormat->wFlags & CF_FLAG_BUILTINFMT))
2098 TRACE("Unknown format 0x%08x!\n", wFormat);
2099 SetLastError(ERROR_INVALID_HANDLE);
2103 lstrcpynW(retStr, lpFormat->Name, maxlen);
2105 return strlenW(retStr);
2109 /**************************************************************************
2110 * AcquireClipboard (X11DRV.@)
2112 void X11DRV_AcquireClipboard(HWND hWndClipWindow)
2114 Display *display = thread_display();
2117 * Acquire X selection if we don't already own it.
2118 * Note that we only acquire the selection if it hasn't been already
2119 * acquired by us, and ignore the fact that another X window may be
2120 * asserting ownership. The reason for this is we need *any* top level
2121 * X window to hold selection ownership. The actual clipboard data requests
2122 * are made via GetClipboardData from EVENT_SelectionRequest and this
2123 * ensures that the real HWND owner services the request.
2124 * If the owning X window gets destroyed the selection ownership is
2125 * re-cycled to another top level X window in X11DRV_CLIPBOARD_ResetOwner.
2128 if (!(selectionAcquired == (S_PRIMARY | S_CLIPBOARD)))
2132 if (!hWndClipWindow)
2133 hWndClipWindow = GetActiveWindow();
2135 hWndClipWindow = GetAncestor(hWndClipWindow, GA_ROOT);
2137 if (GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, NULL))
2139 TRACE("Thread %lx is acquiring selection with thread %lx's window %p\n",
2140 GetCurrentThreadId(),
2141 GetWindowThreadProcessId(hWndClipWindow, NULL),
2143 if (!SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0))
2144 ERR("Failed to acquire selection\n");
2148 owner = X11DRV_get_whole_window(hWndClipWindow);
2151 /* Grab PRIMARY selection if not owned */
2152 if (use_primary_selection && !(selectionAcquired & S_PRIMARY))
2153 XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2155 /* Grab CLIPBOARD selection if not owned */
2156 if (!(selectionAcquired & S_CLIPBOARD))
2157 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2159 if (use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY) == owner)
2160 selectionAcquired |= S_PRIMARY;
2162 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2163 selectionAcquired |= S_CLIPBOARD;
2164 wine_tsx11_unlock();
2166 if (selectionAcquired)
2168 selectionWindow = owner;
2169 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2174 ERR("Received request to acquire selection but process is already owner=(%08x)\n", (unsigned) selectionWindow);
2179 /**************************************************************************
2180 * X11DRV_EmptyClipboard
2182 * Empty cached clipboard data.
2184 void X11DRV_EmptyClipboard(BOOL keepunowned)
2188 LPWINE_CLIPDATA lpData, lpStart;
2189 LPWINE_CLIPDATA lpNext = ClipData;
2191 TRACE(" called with %d entries in cache.\n", ClipDataCount);
2197 lpNext = lpData->NextData;
2199 if (!keepunowned || !(lpData->wFlags & CF_FLAG_UNOWNED))
2201 lpData->PrevData->NextData = lpData->NextData;
2202 lpData->NextData->PrevData = lpData->PrevData;
2204 if (lpData == ClipData)
2205 ClipData = lpNext != lpData ? lpNext : NULL;
2207 X11DRV_CLIPBOARD_FreeData(lpData);
2208 HeapFree(GetProcessHeap(), 0, lpData);
2212 } while (lpNext != lpStart);
2215 TRACE(" %d entries remaining in cache.\n", ClipDataCount);
2220 /**************************************************************************
2221 * X11DRV_SetClipboardData
2223 BOOL X11DRV_SetClipboardData(UINT wFormat, HANDLE16 hData16, HANDLE hData32, BOOL owner)
2226 BOOL bResult = TRUE;
2228 /* If it's not owned, data can only be set if the format data is not already owned
2229 and its rendering is not delayed */
2232 CLIPBOARDINFO cbinfo;
2233 LPWINE_CLIPDATA lpRender;
2235 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2237 if ((!hData16 && !hData32) ||
2238 ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)) &&
2239 !(lpRender->wFlags & CF_FLAG_UNOWNED)))
2242 flags = CF_FLAG_UNOWNED;
2245 bResult &= X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData16, hData32, flags);
2251 /**************************************************************************
2252 * CountClipboardFormats
2254 INT X11DRV_CountClipboardFormats(void)
2256 CLIPBOARDINFO cbinfo;
2258 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2260 TRACE(" count=%d\n", ClipDataCount);
2262 return ClipDataCount;
2266 /**************************************************************************
2267 * X11DRV_EnumClipboardFormats
2269 UINT X11DRV_EnumClipboardFormats(UINT wFormat)
2271 CLIPBOARDINFO cbinfo;
2272 UINT wNextFormat = 0;
2274 TRACE("(%04X)\n", wFormat);
2276 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2281 wNextFormat = ClipData->wFormatID;
2285 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
2287 if (lpData && lpData->NextData != ClipData)
2288 wNextFormat = lpData->NextData->wFormatID;
2295 /**************************************************************************
2296 * X11DRV_IsClipboardFormatAvailable
2298 BOOL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
2301 CLIPBOARDINFO cbinfo;
2303 TRACE("(%04X)\n", wFormat);
2305 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2307 if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
2310 TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
2316 /**************************************************************************
2317 * GetClipboardData (USER.142)
2319 BOOL X11DRV_GetClipboardData(UINT wFormat, HANDLE16* phData16, HANDLE* phData32)
2321 CLIPBOARDINFO cbinfo;
2322 LPWINE_CLIPDATA lpRender;
2324 TRACE("(%04X)\n", wFormat);
2326 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2328 if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
2330 if ( !lpRender->hData32 )
2331 X11DRV_CLIPBOARD_RenderFormat(lpRender);
2333 /* Convert between 32 -> 16 bit data, if necessary */
2334 if (lpRender->hData32 && !lpRender->hData16)
2338 if (lpRender->wFormatID == CF_METAFILEPICT)
2339 size = sizeof(METAFILEPICT16);
2341 size = GlobalSize(lpRender->hData32);
2343 lpRender->hData16 = GlobalAlloc16(GMEM_ZEROINIT, size);
2345 if (!lpRender->hData16)
2346 ERR("(%04X) -- not enough memory in 16b heap\n", wFormat);
2349 if (lpRender->wFormatID == CF_METAFILEPICT)
2351 FIXME("\timplement function CopyMetaFilePict32to16\n");
2352 FIXME("\tin the appropriate file.\n");
2353 #ifdef SOMEONE_IMPLEMENTED_ME
2354 CopyMetaFilePict32to16(GlobalLock16(lpRender->hData16),
2355 GlobalLock(lpRender->hData32));
2360 memcpy(GlobalLock16(lpRender->hData16),
2361 GlobalLock(lpRender->hData32), size);
2364 GlobalUnlock16(lpRender->hData16);
2365 GlobalUnlock(lpRender->hData32);
2369 /* Convert between 32 -> 16 bit data, if necessary */
2370 if (lpRender->hData16 && !lpRender->hData32)
2374 if (lpRender->wFormatID == CF_METAFILEPICT)
2375 size = sizeof(METAFILEPICT16);
2377 size = GlobalSize(lpRender->hData32);
2379 lpRender->hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
2380 GMEM_DDESHARE, size);
2382 if (lpRender->wFormatID == CF_METAFILEPICT)
2384 FIXME("\timplement function CopyMetaFilePict16to32\n");
2385 FIXME("\tin the appropriate file.\n");
2386 #ifdef SOMEONE_IMPLEMENTED_ME
2387 CopyMetaFilePict16to32(GlobalLock16(lpRender->hData32),
2388 GlobalLock(lpRender->hData16));
2393 memcpy(GlobalLock(lpRender->hData32),
2394 GlobalLock16(lpRender->hData16), size);
2397 GlobalUnlock(lpRender->hData32);
2398 GlobalUnlock16(lpRender->hData16);
2402 *phData16 = lpRender->hData16;
2405 *phData32 = lpRender->hData32;
2407 TRACE(" returning hData16(%04x) hData32(%04x) (type %d)\n",
2408 lpRender->hData16, (unsigned int) lpRender->hData32, lpRender->wFormatID);
2410 return lpRender->hData16 || lpRender->hData32;
2417 /**************************************************************************
2418 * ResetSelectionOwner (X11DRV.@)
2420 * Called from DestroyWindow() to prevent X selection from being lost when
2421 * a top level window is destroyed, by switching ownership to another top
2423 * Any top level window can own the selection. See X11DRV_CLIPBOARD_Acquire
2424 * for a more detailed description of this.
2426 void X11DRV_ResetSelectionOwner(HWND hwnd, BOOL bFooBar)
2428 Display *display = thread_display();
2429 HWND hWndClipOwner = 0;
2431 Window XWnd = X11DRV_get_whole_window(hwnd);
2432 BOOL bLostSelection = FALSE;
2433 Window selectionPrevWindow;
2435 /* There is nothing to do if we don't own the selection,
2436 * or if the X window which currently owns the selection is different
2437 * from the one passed in.
2439 if (!selectionAcquired || XWnd != selectionWindow
2440 || selectionWindow == None )
2443 if ((bFooBar && XWnd) || (!bFooBar && !XWnd))
2446 hWndClipOwner = GetClipboardOwner();
2448 TRACE("clipboard owner = %p, selection window = %08x\n",
2449 hWndClipOwner, (unsigned)selectionWindow);
2451 /* now try to salvage current selection from being destroyed by X */
2452 TRACE("checking %08x\n", (unsigned) XWnd);
2454 selectionPrevWindow = selectionWindow;
2455 selectionWindow = None;
2457 if (!(tmp = GetWindow(hwnd, GW_HWNDNEXT)))
2458 tmp = GetWindow(hwnd, GW_HWNDFIRST);
2460 if (tmp && tmp != hwnd)
2461 selectionWindow = X11DRV_get_whole_window(tmp);
2463 if (selectionWindow != None)
2465 /* We must pretend that we don't own the selection while making the switch
2466 * since a SelectionClear event will be sent to the last owner.
2467 * If there is no owner X11DRV_CLIPBOARD_ReleaseSelection will do nothing.
2469 int saveSelectionState = selectionAcquired;
2470 selectionAcquired = S_NOSELECTION;
2472 TRACE("\tswitching selection from %08x to %08x\n",
2473 (unsigned)selectionPrevWindow, (unsigned)selectionWindow);
2477 /* Assume ownership for the PRIMARY and CLIPBOARD selection */
2478 if (saveSelectionState & S_PRIMARY)
2479 XSetSelectionOwner(display, XA_PRIMARY, selectionWindow, CurrentTime);
2481 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), selectionWindow, CurrentTime);
2483 /* Restore the selection masks */
2484 selectionAcquired = saveSelectionState;
2486 /* Lose the selection if something went wrong */
2487 if (((saveSelectionState & S_PRIMARY) &&
2488 (XGetSelectionOwner(display, XA_PRIMARY) != selectionWindow)) ||
2489 (XGetSelectionOwner(display, x11drv_atom(CLIPBOARD)) != selectionWindow))
2491 bLostSelection = TRUE;
2493 wine_tsx11_unlock();
2497 bLostSelection = TRUE;
2502 TRACE("Lost the selection!\n");
2504 X11DRV_CLIPBOARD_ReleaseOwnership();
2505 selectionAcquired = S_NOSELECTION;
2506 selectionWindow = 0;
2511 /**************************************************************************
2512 * X11DRV_CLIPBOARD_SynthesizeData
2514 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID)
2517 LPWINE_CLIPDATA lpSource = NULL;
2519 TRACE(" %d\n", wFormatID);
2521 /* Don't need to synthesize if it already exists */
2522 if (X11DRV_CLIPBOARD_LookupData(wFormatID))
2525 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
2527 bsyn = ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
2528 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2529 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
2530 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2531 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
2532 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED);
2534 else if (wFormatID == CF_ENHMETAFILE)
2536 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2537 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2539 else if (wFormatID == CF_METAFILEPICT)
2541 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2542 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2544 else if (wFormatID == CF_DIB)
2546 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
2547 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2549 else if (wFormatID == CF_BITMAP)
2551 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
2552 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2556 X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, 0, CF_FLAG_SYNTHESIZED);
2563 /**************************************************************************
2564 * X11DRV_EndClipboardUpdate
2566 * Add locale if it hasn't already been added
2568 void X11DRV_EndClipboardUpdate(void)
2570 INT count = ClipDataCount;
2572 /* Do Unicode <-> Text <-> OEM mapping */
2573 X11DRV_CLIPBOARD_SynthesizeData(CF_UNICODETEXT);
2574 X11DRV_CLIPBOARD_SynthesizeData(CF_TEXT);
2575 X11DRV_CLIPBOARD_SynthesizeData(CF_OEMTEXT);
2577 /* Enhmetafile <-> MetafilePict mapping */
2578 X11DRV_CLIPBOARD_SynthesizeData(CF_ENHMETAFILE);
2579 X11DRV_CLIPBOARD_SynthesizeData(CF_METAFILEPICT);
2581 /* DIB <-> Bitmap mapping */
2582 X11DRV_CLIPBOARD_SynthesizeData(CF_DIB);
2583 X11DRV_CLIPBOARD_SynthesizeData(CF_BITMAP);
2585 TRACE("%d formats added to cached data\n", ClipDataCount - count);
2589 /***********************************************************************
2592 * Utility function for X11DRV_SelectionRequest_TARGETS.
2594 static BOOL add_targets(Atom* targets, unsigned long cTargets, Atom prop)
2599 /* Scan through what we have so far to avoid duplicates */
2600 for (i = 0, bExists = FALSE; i < cTargets; i++)
2602 if (targets[i] == prop)
2610 targets[cTargets] = prop;
2616 /***********************************************************************
2617 * X11DRV_SelectionRequest_TARGETS
2618 * Service a TARGETS selection request event
2620 static Atom X11DRV_SelectionRequest_TARGETS( Display *display, Window requestor,
2621 Atom target, Atom rprop )
2627 LPWINE_CLIPFORMAT lpFormat;
2630 * Count the number of items we wish to expose as selection targets.
2631 * We include the TARGETS item, and property aliases
2633 cTargets = X11DRV_CountClipboardFormats() + 1;
2635 for (wFormat = 0; (wFormat = X11DRV_EnumClipboardFormats(wFormat));)
2637 lpFormat = X11DRV_CLIPBOARD_LookupFormat(wFormat);
2641 if (!lpFormat->lpDrvExportFunc)
2644 if (X11DRV_CLIPBOARD_LookupPropertyAlias(lpFormat->drvData))
2647 /* else most likely unregistered format such as CF_PRIVATE or CF_GDIOBJ */
2650 TRACE(" found %ld formats\n", cTargets);
2652 /* Allocate temp buffer */
2653 targets = HeapAlloc( GetProcessHeap(), 0, cTargets * sizeof(Atom));
2657 /* Create TARGETS property list (First item in list is TARGETS itself) */
2658 for (targets[0] = x11drv_atom(TARGETS), cTargets = 1, wFormat = 0;
2659 (wFormat = X11DRV_EnumClipboardFormats(wFormat));)
2661 lpFormat = X11DRV_CLIPBOARD_LookupFormat(wFormat);
2665 if (lpFormat->lpDrvExportFunc)
2667 if (add_targets(targets, cTargets, lpFormat->drvData))
2671 /* Check if any alias should be listed */
2672 alias = X11DRV_CLIPBOARD_LookupPropertyAlias(lpFormat->drvData);
2675 if (add_targets(targets, cTargets, alias))
2683 if (TRACE_ON(clipboard))
2686 for ( i = 0; i < cTargets; i++)
2690 char *itemFmtName = XGetAtomName(display, targets[i]);
2691 TRACE("\tAtom# %d: Property %ld Type %s\n", i, targets[i], itemFmtName);
2697 /* We may want to consider setting the type to xaTargets instead,
2698 * in case some apps expect this instead of XA_ATOM */
2699 XChangeProperty(display, requestor, rprop, XA_ATOM, 32,
2700 PropModeReplace, (unsigned char *)targets, cTargets);
2701 wine_tsx11_unlock();
2703 HeapFree(GetProcessHeap(), 0, targets);
2709 /***********************************************************************
2710 * X11DRV_SelectionRequest_MULTIPLE
2711 * Service a MULTIPLE selection request event
2712 * rprop contains a list of (target,property) atom pairs.
2713 * The first atom names a target and the second names a property.
2714 * The effect is as if we have received a sequence of SelectionRequest events
2715 * (one for each atom pair) except that:
2716 * 1. We reply with a SelectionNotify only when all the requested conversions
2717 * have been performed.
2718 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
2719 * we replace the atom in the property by None.
2721 static Atom X11DRV_SelectionRequest_MULTIPLE( HWND hWnd, XSelectionRequestEvent *pevent )
2723 Display *display = pevent->display;
2725 Atom atype=AnyPropertyType;
2727 unsigned long remain;
2728 Atom* targetPropList=NULL;
2729 unsigned long cTargetPropList = 0;
2731 /* If the specified property is None the requestor is an obsolete client.
2732 * We support these by using the specified target atom as the reply property.
2734 rprop = pevent->property;
2736 rprop = pevent->target;
2740 /* Read the MULTIPLE property contents. This should contain a list of
2741 * (target,property) atom pairs.
2744 if(XGetWindowProperty(display, pevent->requestor, rprop,
2745 0, 0x3FFF, False, AnyPropertyType, &atype,&aformat,
2746 &cTargetPropList, &remain,
2747 (unsigned char**)&targetPropList) != Success)
2749 wine_tsx11_unlock();
2750 TRACE("\tCouldn't read MULTIPLE property\n");
2754 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
2755 XGetAtomName(display, atype), aformat, cTargetPropList, remain);
2756 wine_tsx11_unlock();
2759 * Make sure we got what we expect.
2760 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
2761 * in a MULTIPLE selection request should be of type ATOM_PAIR.
2762 * However some X apps(such as XPaint) are not compliant with this and return
2763 * a user defined atom in atype when XGetWindowProperty is called.
2764 * The data *is* an atom pair but is not denoted as such.
2766 if(aformat == 32 /* atype == xAtomPair */ )
2770 /* Iterate through the ATOM_PAIR list and execute a SelectionRequest
2771 * for each (target,property) pair */
2773 for (i = 0; i < cTargetPropList; i+=2)
2775 XSelectionRequestEvent event;
2777 if (TRACE_ON(clipboard))
2779 char *targetName, *propName;
2781 targetName = XGetAtomName(display, targetPropList[i]);
2782 propName = XGetAtomName(display, targetPropList[i+1]);
2783 TRACE("MULTIPLE(%d): Target='%s' Prop='%s'\n",
2784 i/2, targetName, propName);
2787 wine_tsx11_unlock();
2790 /* We must have a non "None" property to service a MULTIPLE target atom */
2791 if ( !targetPropList[i+1] )
2793 TRACE("\tMULTIPLE(%d): Skipping target with empty property!\n", i);
2797 /* Set up an XSelectionRequestEvent for this (target,property) pair */
2798 memcpy( &event, pevent, sizeof(XSelectionRequestEvent) );
2799 event.target = targetPropList[i];
2800 event.property = targetPropList[i+1];
2802 /* Fire a SelectionRequest, informing the handler that we are processing
2803 * a MULTIPLE selection request event.
2805 X11DRV_HandleSelectionRequest( hWnd, &event, TRUE );
2809 /* Free the list of targets/properties */
2811 XFree(targetPropList);
2812 wine_tsx11_unlock();
2819 /***********************************************************************
2820 * X11DRV_HandleSelectionRequest
2821 * Process an event selection request event.
2822 * The bIsMultiple flag is used to signal when EVENT_SelectionRequest is called
2823 * recursively while servicing a "MULTIPLE" selection target.
2825 * Note: We only receive this event when WINE owns the X selection
2827 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple )
2829 Display *display = event->display;
2830 XSelectionEvent result;
2832 Window request = event->requestor;
2837 * We can only handle the selection request if :
2838 * The selection is PRIMARY or CLIPBOARD, AND we can successfully open the clipboard.
2839 * Don't do these checks or open the clipboard while recursively processing MULTIPLE,
2840 * since this has been already done.
2844 if (((event->selection != XA_PRIMARY) && (event->selection != x11drv_atom(CLIPBOARD))))
2848 /* If the specified property is None the requestor is an obsolete client.
2849 * We support these by using the specified target atom as the reply property.
2851 rprop = event->property;
2853 rprop = event->target;
2855 if(event->target == x11drv_atom(TARGETS)) /* Return a list of all supported targets */
2857 /* TARGETS selection request */
2858 rprop = X11DRV_SelectionRequest_TARGETS( display, request, event->target, rprop );
2860 else if(event->target == x11drv_atom(MULTIPLE)) /* rprop contains a list of (target, property) atom pairs */
2862 /* MULTIPLE selection request */
2863 rprop = X11DRV_SelectionRequest_MULTIPLE( hWnd, event );
2867 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(event->target);
2870 lpFormat = X11DRV_CLIPBOARD_LookupAliasProperty(event->target);
2872 if (lpFormat && lpFormat->lpDrvExportFunc)
2874 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(lpFormat->wFormatID);
2878 unsigned char* lpClipData;
2880 HANDLE hClipData = lpFormat->lpDrvExportFunc(request, event->target,
2881 rprop, lpData, &cBytes);
2883 if (hClipData && (lpClipData = GlobalLock(hClipData)))
2885 TRACE("\tUpdating property %s, %ld bytes\n", debugstr_w(lpFormat->Name), cBytes);
2888 XChangeProperty(display, request, rprop, event->target,
2889 8, PropModeReplace, (unsigned char *)lpClipData, cBytes);
2890 wine_tsx11_unlock();
2892 GlobalUnlock(hClipData);
2893 GlobalFree(hClipData);
2901 * SelectionNotify should be sent only at the end of a MULTIPLE request
2905 result.type = SelectionNotify;
2906 result.display = display;
2907 result.requestor = request;
2908 result.selection = event->selection;
2909 result.property = rprop;
2910 result.target = event->target;
2911 result.time = event->time;
2912 TRACE("Sending SelectionNotify event...\n");
2914 XSendEvent(display,event->requestor,False,NoEventMask,(XEvent*)&result);
2915 wine_tsx11_unlock();
2920 /***********************************************************************
2921 * X11DRV_SelectionRequest
2923 void X11DRV_SelectionRequest( HWND hWnd, XEvent *event )
2926 X11DRV_HandleSelectionRequest( hWnd, &event->xselectionrequest, FALSE );
2930 /***********************************************************************
2931 * X11DRV_SelectionClear
2933 void X11DRV_SelectionClear( HWND hWnd, XEvent *xev )
2935 XSelectionClearEvent *event = &xev->xselectionclear;
2937 if (event->selection == XA_PRIMARY || event->selection == x11drv_atom(CLIPBOARD))
2938 X11DRV_CLIPBOARD_ReleaseSelection( event->selection, event->window, hWnd, event->time );