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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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 struct tagWINE_CLIPDATA; /* Forward */
112 typedef HANDLE (*DRVEXPORTFUNC)(Window requestor, Atom aTarget, Atom rprop,
113 struct tagWINE_CLIPDATA* lpData, LPDWORD lpBytes);
114 typedef HANDLE (*DRVIMPORTFUNC)(Window w, Atom prop);
116 typedef struct tagWINE_CLIPFORMAT {
121 DRVIMPORTFUNC lpDrvImportFunc;
122 DRVEXPORTFUNC lpDrvExportFunc;
123 struct tagWINE_CLIPFORMAT *PrevFormat;
124 struct tagWINE_CLIPFORMAT *NextFormat;
125 } WINE_CLIPFORMAT, *LPWINE_CLIPFORMAT;
127 typedef struct tagWINE_CLIPDATA {
133 LPWINE_CLIPFORMAT lpFormat;
134 struct tagWINE_CLIPDATA *PrevData;
135 struct tagWINE_CLIPDATA *NextData;
136 } WINE_CLIPDATA, *LPWINE_CLIPDATA;
138 #define CF_FLAG_BUILTINFMT 0x0001 /* Built-in windows format */
139 #define CF_FLAG_UNOWNED 0x0002 /* cached data is not owned */
140 #define CF_FLAG_SYNTHESIZED 0x0004 /* Implicitly converted data */
141 #define CF_FLAG_UNICODE 0x0008 /* Data is in unicode */
143 static int selectionAcquired = 0; /* Contains the current selection masks */
144 static Window selectionWindow = None; /* The top level X window which owns the selection */
145 static Atom selectionCacheSrc = XA_PRIMARY; /* The selection source from which the clipboard cache was filled */
147 void X11DRV_EmptyClipboard(BOOL keepunowned);
148 void X11DRV_EndClipboardUpdate(void);
149 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Window w, Atom prop);
150 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Window w, Atom prop);
151 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Window w, Atom prop);
152 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Window w, Atom prop);
153 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Window w, Atom prop);
154 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Window w, Atom prop);
155 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Window w, Atom prop);
156 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Window requestor, Atom aTarget,
157 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
158 static HANDLE X11DRV_CLIPBOARD_ExportString(Window requestor, Atom aTarget,
159 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
160 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Window requestor, Atom aTarget,
161 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
162 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Window requestor, Atom aTarget,
163 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
164 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Window requestor, Atom aTarget,
165 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
166 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCWSTR FormatName, Atom prop);
167 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(UINT wFormatID);
168 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData);
169 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void);
170 static int X11DRV_CLIPBOARD_QueryAvailableData(LPCLIPBOARDINFO lpcbinfo);
171 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(LPWINE_CLIPDATA lpData);
172 static BOOL X11DRV_CLIPBOARD_ReadProperty(Window w, Atom prop,
173 unsigned char** data, unsigned long* datasize);
174 static BOOL X11DRV_CLIPBOARD_RenderFormat(LPWINE_CLIPDATA lpData);
175 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out);
176 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID);
177 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(LPWINE_CLIPDATA lpData);
178 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(void);
179 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(void);
180 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple );
183 * WARNING: This data ordering is dependent on the WINE_CLIPFORMAT structure
184 * declared in clipboard.h
186 static const WCHAR wszCF_TEXT[] = {'W','C','F','_','T','E','X','T',0};
187 static const WCHAR wszCF_BITMAP[] = {'W','C','F','_','B','I','T','M','A','P',0};
188 static const WCHAR wszCF_METAFILEPICT[] = {'W','C','F','_','M','E','T','A','F','I','L','E','P','I','C','T',0};
189 static const WCHAR wszCF_SYLK[] = {'W','C','F','_','S','Y','L','K',0};
190 static const WCHAR wszCF_DIF[] = {'W','C','F','_','D','I','F',0};
191 static const WCHAR wszCF_TIFF[] = {'W','C','F','_','T','I','F','F',0};
192 static const WCHAR wszCF_OEMTEXT[] = {'W','C','F','_','O','E','M','T','E','X','T',0};
193 static const WCHAR wszCF_DIB[] = {'W','C','F','_','D','I','B',0};
194 static const WCHAR wszCF_PALETTE[] = {'W','C','F','_','P','A','L','E','T','T','E',0};
195 static const WCHAR wszCF_PENDATA[] = {'W','C','F','_','P','E','N','D','A','T','A',0};
196 static const WCHAR wszCF_RIFF[] = {'W','C','F','_','R','I','F','F',0};
197 static const WCHAR wszCF_WAVE[] = {'W','C','F','_','W','A','V','E',0};
198 static const WCHAR wszCOMPOUNDTEXT[] = {'C','O','M','P','O','U','N','D','_','T','E','X','T',0};
199 static const WCHAR wszUTF8STRING[] = {'U','T','F','8','_','S','T','R','I','N','G',0};
200 static const WCHAR wszCF_ENHMETAFILE[] = {'W','C','F','_','E','N','H','M','E','T','A','F','I','L','E',0};
201 static const WCHAR wszCF_HDROP[] = {'W','C','F','_','H','D','R','O','P',0};
202 static const WCHAR wszCF_LOCALE[] = {'W','C','F','_','L','O','C','A','L','E',0};
203 static const WCHAR wszCF_DIBV5[] = {'W','C','F','_','D','I','B','V','5',0};
204 static const WCHAR wszCF_OWNERDISPLAY[] = {'W','C','F','_','O','W','N','E','R','D','I','S','P','L','A','Y',0};
205 static const WCHAR wszCF_DSPTEXT[] = {'W','C','F','_','D','S','P','T','E','X','T',0};
206 static const WCHAR wszCF_DSPBITMAP[] = {'W','C','F','_','D','S','P','B','I','T','M','A','P',0};
207 static const WCHAR wszCF_DSPMETAFILEPICT[] = {'W','C','F','_','D','S','P','M','E','T','A','F','I','L','E','P','I','C','T',0};
208 static const WCHAR wszCF_DSPENHMETAFILE[] = {'W','C','F','_','D','S','P','E','N','H','M','E','T','A','F','I','L','E',0};
210 static WINE_CLIPFORMAT ClipFormats[] =
212 { CF_TEXT, wszCF_TEXT, XA_STRING, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAString,
213 X11DRV_CLIPBOARD_ExportString, NULL, &ClipFormats[1]},
215 { CF_BITMAP, wszCF_BITMAP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
216 NULL, &ClipFormats[0], &ClipFormats[2]},
218 { CF_METAFILEPICT, wszCF_METAFILEPICT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportMetaFilePict,
219 X11DRV_CLIPBOARD_ExportMetaFilePict, &ClipFormats[1], &ClipFormats[3]},
221 { CF_SYLK, wszCF_SYLK, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
222 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[2], &ClipFormats[4]},
224 { CF_DIF, wszCF_DIF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
225 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[3], &ClipFormats[5]},
227 { CF_TIFF, wszCF_TIFF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
228 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[4], &ClipFormats[6]},
230 { CF_OEMTEXT, wszCF_OEMTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
231 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[5], &ClipFormats[7]},
233 { CF_DIB, wszCF_DIB, XA_PIXMAP, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAPIXMAP,
234 X11DRV_CLIPBOARD_ExportXAPIXMAP, &ClipFormats[6], &ClipFormats[8]},
236 { CF_PALETTE, wszCF_PALETTE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
237 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[7], &ClipFormats[9]},
239 { CF_PENDATA, wszCF_PENDATA, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
240 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[8], &ClipFormats[10]},
242 { CF_RIFF, wszCF_RIFF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
243 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[9], &ClipFormats[11]},
245 { CF_WAVE, wszCF_WAVE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
246 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[10], &ClipFormats[12]},
248 { CF_UNICODETEXT, wszUTF8STRING, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportUTF8,
249 X11DRV_CLIPBOARD_ExportString, &ClipFormats[11], &ClipFormats[13]},
251 /* If UTF8_STRING is not available, attempt COMPUND_TEXT */
252 { CF_UNICODETEXT, wszCOMPOUNDTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportCompoundText,
253 X11DRV_CLIPBOARD_ExportString, &ClipFormats[12], &ClipFormats[14]},
255 { CF_ENHMETAFILE, wszCF_ENHMETAFILE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportEnhMetaFile,
256 X11DRV_CLIPBOARD_ExportEnhMetaFile, &ClipFormats[13], &ClipFormats[15]},
258 { CF_HDROP, wszCF_HDROP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
259 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[14], &ClipFormats[16]},
261 { CF_LOCALE, wszCF_LOCALE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
262 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[15], &ClipFormats[17]},
264 { CF_DIBV5, wszCF_DIBV5, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
265 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[16], &ClipFormats[18]},
267 { CF_OWNERDISPLAY, wszCF_OWNERDISPLAY, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
268 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[17], &ClipFormats[19]},
270 { CF_DSPTEXT, wszCF_DSPTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
271 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[18], &ClipFormats[20]},
273 { CF_DSPBITMAP, wszCF_DSPBITMAP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
274 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[19], &ClipFormats[21]},
276 { CF_DSPMETAFILEPICT, wszCF_DSPMETAFILEPICT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
277 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[20], &ClipFormats[22]},
279 { CF_DSPENHMETAFILE, wszCF_DSPENHMETAFILE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
280 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[21], NULL}
283 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
285 /* Maps X properties to Windows formats */
286 static const WCHAR wszRichTextFormat[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
287 static const WCHAR wszGIF[] = {'G','I','F',0};
288 static const WCHAR wszHTMLFormat[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
293 } PropertyFormatMap[] =
295 { wszRichTextFormat, XATOM_text_rtf },
296 { wszRichTextFormat, XATOM_text_richtext },
297 { wszGIF, XATOM_image_gif },
298 { wszHTMLFormat, XATOM_text_html },
303 * Cached clipboard data.
305 static LPWINE_CLIPDATA ClipData = NULL;
306 static UINT ClipDataCount = 0;
309 * Clipboard sequence number
311 static UINT wSeqNo = 0;
313 /**************************************************************************
314 * Internal Clipboard implementation methods
315 **************************************************************************/
317 static Window thread_selection_wnd(void)
319 Window w = x11drv_thread_data()->selection_wnd;
323 XSetWindowAttributes attr;
325 attr.event_mask = (ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
326 ButtonPressMask | ButtonReleaseMask | EnterWindowMask);
329 w = XCreateWindow(thread_display(), root_window, 0, 0, 1, 1, 0, screen_depth,
330 InputOutput, CopyFromParent, CWEventMask, &attr);
334 x11drv_thread_data()->selection_wnd = w;
336 FIXME("Failed to create window. Fetching selection data will fail.\n");
342 /**************************************************************************
343 * X11DRV_InitClipboard
345 void X11DRV_InitClipboard(void)
349 /* Register known mapping between window formats and X properties */
350 for (i = 0; i < sizeof(PropertyFormatMap)/sizeof(PropertyFormatMap[0]); i++)
351 X11DRV_CLIPBOARD_InsertClipboardFormat(PropertyFormatMap[i].lpszFormat, GET_ATOM(PropertyFormatMap[i].prop));
355 /**************************************************************************
358 * Intern atoms for formats that don't have one yet.
360 static void intern_atoms(void)
362 LPWINE_CLIPFORMAT format;
367 for (format = ClipFormats, count = 0; format; format = format->NextFormat)
368 if (!format->drvData) count++;
371 names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
372 atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
374 for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
375 if (!format->drvData) {
376 len = WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, NULL, 0, NULL, NULL);
377 names[i] = HeapAlloc(GetProcessHeap(), 0, len);
378 WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, names[i++], len, NULL, NULL);
383 XInternAtoms( thread_display(), names, count, False, atoms );
386 for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
387 if (!format->drvData) {
388 HeapFree(GetProcessHeap(), 0, names[i]);
389 format->drvData = atoms[i++];
393 HeapFree( GetProcessHeap(), 0, names );
394 HeapFree( GetProcessHeap(), 0, atoms );
398 /**************************************************************************
401 * Register a custom X clipboard format.
403 static WINE_CLIPFORMAT *register_format( LPCWSTR FormatName, Atom prop )
405 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
407 TRACE("%s\n", debugstr_w(FormatName));
409 /* walk format chain to see if it's already registered */
412 if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE, lpFormat->Name, -1, FormatName, -1) == CSTR_EQUAL
413 && (lpFormat->wFlags & CF_FLAG_BUILTINFMT) == 0)
415 lpFormat = lpFormat->NextFormat;
418 return X11DRV_CLIPBOARD_InsertClipboardFormat(FormatName, prop);
422 /**************************************************************************
423 * X11DRV_CLIPBOARD_LookupFormat
425 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupFormat(WORD wID)
427 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
431 if (lpFormat->wFormatID == wID)
434 lpFormat = lpFormat->NextFormat;
436 if (lpFormat && !lpFormat->drvData) intern_atoms();
441 /**************************************************************************
442 * X11DRV_CLIPBOARD_LookupProperty
444 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupProperty(LPWINE_CLIPFORMAT current, UINT drvData)
448 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
449 BOOL need_intern = FALSE;
452 lpFormat = current->NextFormat;
456 if (lpFormat->drvData == drvData) return lpFormat;
457 if (!lpFormat->drvData) need_intern = TRUE;
458 lpFormat = lpFormat->NextFormat;
460 if (!need_intern) return NULL;
462 /* restart the search for the new atoms */
467 /**************************************************************************
468 * X11DRV_CLIPBOARD_LookupData
470 static LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
472 LPWINE_CLIPDATA lpData = ClipData;
478 if (lpData->wFormatID == wID)
481 lpData = lpData->NextData;
483 while(lpData != ClipData);
485 if (lpData->wFormatID != wID)
493 /**************************************************************************
494 * InsertClipboardFormat
496 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCWSTR FormatName, Atom prop)
498 LPWINE_CLIPFORMAT lpFormat;
499 LPWINE_CLIPFORMAT lpNewFormat;
502 /* allocate storage for new format entry */
503 lpNewFormat = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPFORMAT));
505 if(lpNewFormat == NULL)
507 WARN("No more memory for a new format!\n");
511 if (!(new_name = HeapAlloc(GetProcessHeap(), 0, (strlenW(FormatName)+1)*sizeof(WCHAR))))
513 WARN("No more memory for the new format name!\n");
514 HeapFree(GetProcessHeap(), 0, lpNewFormat);
518 lpNewFormat->Name = strcpyW(new_name, FormatName);
519 lpNewFormat->wFlags = 0;
520 lpNewFormat->wFormatID = GlobalAddAtomW(lpNewFormat->Name);
521 lpNewFormat->drvData = prop;
522 lpNewFormat->lpDrvImportFunc = X11DRV_CLIPBOARD_ImportClipboardData;
523 lpNewFormat->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportClipboardData;
526 lpFormat = ClipFormats;
528 while(lpFormat->NextFormat) /* Move to last entry */
529 lpFormat = lpFormat->NextFormat;
531 lpNewFormat->NextFormat = NULL;
532 lpFormat->NextFormat = lpNewFormat;
533 lpNewFormat->PrevFormat = lpFormat;
535 TRACE("Registering format(%d): %s drvData %d\n",
536 lpNewFormat->wFormatID, debugstr_w(FormatName), lpNewFormat->drvData);
544 /**************************************************************************
545 * X11DRV_CLIPBOARD_GetClipboardInfo
547 static BOOL X11DRV_CLIPBOARD_GetClipboardInfo(LPCLIPBOARDINFO cbInfo)
551 SERVER_START_REQ( set_clipboard_info )
555 if (wine_server_call_err( req ))
557 ERR("Failed to get clipboard owner.\n");
561 cbInfo->hWndOpen = reply->old_clipboard;
562 cbInfo->hWndOwner = reply->old_owner;
563 cbInfo->hWndViewer = reply->old_viewer;
564 cbInfo->seqno = reply->seqno;
565 cbInfo->flags = reply->flags;
576 /**************************************************************************
577 * X11DRV_CLIPBOARD_ReleaseOwnership
579 static BOOL X11DRV_CLIPBOARD_ReleaseOwnership(void)
583 SERVER_START_REQ( set_clipboard_info )
585 req->flags = SET_CB_RELOWNER | SET_CB_SEQNO;
587 if (wine_server_call_err( req ))
589 ERR("Failed to set clipboard.\n");
603 /**************************************************************************
604 * X11DRV_CLIPBOARD_InsertClipboardData
606 * Caller *must* have the clipboard open and be the owner.
608 static BOOL X11DRV_CLIPBOARD_InsertClipboardData(UINT wFormatID, HANDLE16 hData16,
609 HANDLE hData32, DWORD flags, LPWINE_CLIPFORMAT lpFormat, BOOL override)
611 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormatID);
613 TRACE("format=%d lpData=%p hData16=%08x hData32=%p flags=0x%08x lpFormat=%p override=%d\n",
614 wFormatID, lpData, hData16, hData32, flags, lpFormat, override);
616 if (lpData && !override)
621 X11DRV_CLIPBOARD_FreeData(lpData);
623 lpData->hData16 = hData16; /* 0 is legal, see WM_RENDERFORMAT */
624 lpData->hData32 = hData32;
628 lpData = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPDATA));
630 lpData->wFormatID = wFormatID;
631 lpData->hData16 = hData16; /* 0 is legal, see WM_RENDERFORMAT */
632 lpData->hData32 = hData32;
633 lpData->lpFormat = lpFormat;
638 LPWINE_CLIPDATA lpPrevData = ClipData->PrevData;
640 lpData->PrevData = lpPrevData;
641 lpData->NextData = ClipData;
643 lpPrevData->NextData = lpData;
644 ClipData->PrevData = lpData;
648 lpData->NextData = lpData;
649 lpData->PrevData = lpData;
656 lpData->wFlags = flags;
662 /**************************************************************************
663 * X11DRV_CLIPBOARD_FreeData
665 * Free clipboard data handle.
667 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData)
669 TRACE("%d\n", lpData->wFormatID);
671 if ((lpData->wFormatID >= CF_GDIOBJFIRST &&
672 lpData->wFormatID <= CF_GDIOBJLAST) ||
673 lpData->wFormatID == CF_BITMAP ||
674 lpData->wFormatID == CF_DIB ||
675 lpData->wFormatID == CF_PALETTE)
678 DeleteObject(lpData->hData32);
681 DeleteObject(HGDIOBJ_32(lpData->hData16));
683 if ((lpData->wFormatID == CF_DIB) && lpData->drvData)
684 XFreePixmap(gdi_display, lpData->drvData);
686 else if (lpData->wFormatID == CF_METAFILEPICT)
690 DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData32 ))->hMF );
691 GlobalFree(lpData->hData32);
694 /* HMETAFILE16 and HMETAFILE32 are apparently the same thing,
695 and a shallow copy is enough to share a METAFILEPICT
696 structure between 16bit and 32bit clipboards. The MetaFile
697 should of course only be deleted once. */
698 GlobalFree16(lpData->hData16);
703 METAFILEPICT16* lpMetaPict = (METAFILEPICT16 *) GlobalLock16(lpData->hData16);
707 /* To delete 16-bit meta file, we just need to free the associated
708 handle. See DeleteMetaFile16() in dlls/gdi/metafile.c. */
709 GlobalFree16(lpMetaPict->hMF);
713 GlobalFree16(lpData->hData16);
716 else if (lpData->wFormatID == CF_ENHMETAFILE)
719 DeleteEnhMetaFile(lpData->hData32);
721 else if (lpData->wFormatID < CF_PRIVATEFIRST ||
722 lpData->wFormatID > CF_PRIVATELAST)
725 GlobalFree(lpData->hData32);
728 GlobalFree16(lpData->hData16);
737 /**************************************************************************
738 * X11DRV_CLIPBOARD_UpdateCache
740 static BOOL X11DRV_CLIPBOARD_UpdateCache(LPCLIPBOARDINFO lpcbinfo)
744 if (!X11DRV_CLIPBOARD_IsSelectionOwner())
746 if (!X11DRV_CLIPBOARD_GetClipboardInfo(lpcbinfo))
748 ERR("Failed to retrieve clipboard information.\n");
751 else if (wSeqNo < lpcbinfo->seqno)
753 X11DRV_EmptyClipboard(TRUE);
755 if (X11DRV_CLIPBOARD_QueryAvailableData(lpcbinfo) < 0)
757 ERR("Failed to cache clipboard data owned by another process.\n");
762 X11DRV_EndClipboardUpdate();
765 wSeqNo = lpcbinfo->seqno;
773 /**************************************************************************
774 * X11DRV_CLIPBOARD_RenderFormat
776 static BOOL X11DRV_CLIPBOARD_RenderFormat(LPWINE_CLIPDATA lpData)
780 TRACE(" 0x%04x hData32(%p) hData16(0x%08x)\n",
781 lpData->wFormatID, lpData->hData32, lpData->hData16);
783 if (lpData->hData32 || lpData->hData16)
784 return bret; /* Already rendered */
786 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
787 bret = X11DRV_CLIPBOARD_RenderSynthesizedFormat(lpData);
788 else if (!X11DRV_CLIPBOARD_IsSelectionOwner())
790 if (!X11DRV_CLIPBOARD_ReadSelectionData(lpData))
792 ERR("Failed to cache clipboard data owned by another process. Format=%d\n",
799 CLIPBOARDINFO cbInfo;
801 if (X11DRV_CLIPBOARD_GetClipboardInfo(&cbInfo) && cbInfo.hWndOwner)
803 /* Send a WM_RENDERFORMAT message to notify the owner to render the
804 * data requested into the clipboard.
806 TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", cbInfo.hWndOwner);
807 SendMessageW(cbInfo.hWndOwner, WM_RENDERFORMAT, (WPARAM)lpData->wFormatID, 0);
809 if (!lpData->hData32 && !lpData->hData16)
814 ERR("hWndClipOwner is lost!\n");
823 /**************************************************************************
824 * CLIPBOARD_ConvertText
825 * Returns number of required/converted characters - not bytes!
827 static INT CLIPBOARD_ConvertText(WORD src_fmt, void const *src, INT src_size,
828 WORD dst_fmt, void *dst, INT dst_size)
832 if(src_fmt == CF_UNICODETEXT)
845 return WideCharToMultiByte(cp, 0, src, src_size, dst, dst_size, NULL, NULL);
848 if(dst_fmt == CF_UNICODETEXT)
861 return MultiByteToWideChar(cp, 0, src, src_size, dst, dst_size);
864 if(!dst_size) return src_size;
866 if(dst_size > src_size) dst_size = src_size;
868 if(src_fmt == CF_TEXT )
869 CharToOemBuffA(src, dst, dst_size);
871 OemToCharBuffA(src, dst, dst_size);
877 /**************************************************************************
878 * X11DRV_CLIPBOARD_RenderSynthesizedFormat
880 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(LPWINE_CLIPDATA lpData)
886 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
888 UINT wFormatID = lpData->wFormatID;
890 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
891 bret = X11DRV_CLIPBOARD_RenderSynthesizedText(wFormatID);
897 bret = X11DRV_CLIPBOARD_RenderSynthesizedDIB();
901 bret = X11DRV_CLIPBOARD_RenderSynthesizedBitmap();
905 case CF_METAFILEPICT:
906 FIXME("Synthesizing wFormatID(0x%08x) not implemented\n", wFormatID);
910 FIXME("Called to synthesize unknown format\n");
915 lpData->wFlags &= ~CF_FLAG_SYNTHESIZED;
922 /**************************************************************************
923 * X11DRV_CLIPBOARD_RenderSynthesizedText
925 * Renders synthesized text
927 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(UINT wFormatID)
932 INT src_chars, dst_chars, alloc_size;
933 LPWINE_CLIPDATA lpSource = NULL;
935 TRACE(" %d\n", wFormatID);
937 if ((lpSource = X11DRV_CLIPBOARD_LookupData(wFormatID)) &&
941 /* Look for rendered source or non-synthesized source */
942 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
943 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
945 TRACE("UNICODETEXT -> %d\n", wFormatID);
947 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
948 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
950 TRACE("TEXT -> %d\n", wFormatID);
952 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
953 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
955 TRACE("OEMTEXT -> %d\n", wFormatID);
958 if (!lpSource || (lpSource->wFlags & CF_FLAG_SYNTHESIZED &&
962 /* Ask the clipboard owner to render the source text if necessary */
963 if (!lpSource->hData32 && !X11DRV_CLIPBOARD_RenderFormat(lpSource))
966 if (lpSource->hData32)
968 lpstrS = (LPSTR)GlobalLock(lpSource->hData32);
972 lpstrS = (LPSTR)GlobalLock16(lpSource->hData16);
978 /* Text always NULL terminated */
979 if(lpSource->wFormatID == CF_UNICODETEXT)
980 src_chars = strlenW((LPCWSTR)lpstrS) + 1;
982 src_chars = strlen(lpstrS) + 1;
984 /* Calculate number of characters in the destination buffer */
985 dst_chars = CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS,
986 src_chars, wFormatID, NULL, 0);
991 TRACE("Converting from '%d' to '%d', %i chars\n",
992 lpSource->wFormatID, wFormatID, src_chars);
994 /* Convert characters to bytes */
995 if(wFormatID == CF_UNICODETEXT)
996 alloc_size = dst_chars * sizeof(WCHAR);
998 alloc_size = dst_chars;
1000 hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
1001 GMEM_DDESHARE, alloc_size);
1003 lpstrT = (LPSTR)GlobalLock(hData32);
1007 CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS, src_chars,
1008 wFormatID, lpstrT, dst_chars);
1009 GlobalUnlock(hData32);
1013 if (lpSource->hData32)
1014 GlobalUnlock(lpSource->hData32);
1016 GlobalUnlock16(lpSource->hData16);
1018 return X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, hData32, 0, NULL, TRUE);
1022 /**************************************************************************
1023 * X11DRV_CLIPBOARD_RenderSynthesizedDIB
1025 * Renders synthesized DIB
1027 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(void)
1030 LPWINE_CLIPDATA lpSource = NULL;
1034 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) && lpSource->hData32)
1038 /* If we have a bitmap and it's not synthesized or it has been rendered */
1039 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
1040 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
1042 /* Render source if required */
1043 if (lpSource->hData32 || X11DRV_CLIPBOARD_RenderFormat(lpSource))
1049 hData32 = X11DRV_DIB_CreateDIBFromBitmap(hdc, lpSource->hData32);
1050 ReleaseDC(NULL, hdc);
1054 X11DRV_CLIPBOARD_InsertClipboardData(CF_DIB, 0, hData32, 0, NULL, TRUE);
1064 /**************************************************************************
1065 * X11DRV_CLIPBOARD_RenderSynthesizedBitmap
1067 * Renders synthesized bitmap
1069 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(void)
1072 LPWINE_CLIPDATA lpSource = NULL;
1076 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) && lpSource->hData32)
1080 /* If we have a dib and it's not synthesized or it has been rendered */
1081 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
1082 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
1084 /* Render source if required */
1085 if (lpSource->hData32 || X11DRV_CLIPBOARD_RenderFormat(lpSource))
1089 unsigned int offset;
1090 LPBITMAPINFOHEADER lpbmih;
1093 lpbmih = (LPBITMAPINFOHEADER) GlobalLock(lpSource->hData32);
1095 offset = sizeof(BITMAPINFOHEADER)
1096 + ((lpbmih->biBitCount <= 8) ? (sizeof(RGBQUAD) *
1097 (1 << lpbmih->biBitCount)) : 0);
1099 hData32 = CreateDIBitmap(hdc, lpbmih, CBM_INIT, (LPBYTE)lpbmih +
1100 offset, (LPBITMAPINFO) lpbmih, DIB_RGB_COLORS);
1102 GlobalUnlock(lpSource->hData32);
1103 ReleaseDC(NULL, hdc);
1107 X11DRV_CLIPBOARD_InsertClipboardData(CF_BITMAP, 0, hData32, 0, NULL, TRUE);
1117 /**************************************************************************
1118 * X11DRV_CLIPBOARD_ImportXAString
1120 * Import XA_STRING, converting the string to CF_TEXT.
1122 HANDLE X11DRV_CLIPBOARD_ImportXAString(Window w, Atom prop)
1125 unsigned long cbytes;
1127 unsigned long i, inlcount = 0;
1130 if (!X11DRV_CLIPBOARD_ReadProperty(w, prop, &lpdata, &cbytes))
1133 for (i = 0; i <= cbytes; i++)
1135 if (lpdata[i] == '\n')
1139 if ((hText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes + inlcount + 1)))
1141 lpstr = GlobalLock(hText);
1143 for (i = 0, inlcount = 0; i <= cbytes; i++)
1145 if (lpdata[i] == '\n')
1146 lpstr[inlcount++] = '\r';
1148 lpstr[inlcount++] = lpdata[i];
1151 GlobalUnlock(hText);
1154 /* Free the retrieved property data */
1155 HeapFree(GetProcessHeap(), 0, lpdata);
1161 /**************************************************************************
1162 * X11DRV_CLIPBOARD_ImportUTF8
1164 * Import XA_STRING, converting the string to CF_UNICODE.
1166 HANDLE X11DRV_CLIPBOARD_ImportUTF8(Window w, Atom prop)
1169 unsigned long cbytes;
1171 unsigned long i, inlcount = 0;
1172 HANDLE hUnicodeText = 0;
1174 if (!X11DRV_CLIPBOARD_ReadProperty(w, prop, &lpdata, &cbytes))
1177 for (i = 0; i <= cbytes; i++)
1179 if (lpdata[i] == '\n')
1183 if ((lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbytes + inlcount + 1)))
1187 for (i = 0, inlcount = 0; i <= cbytes; i++)
1189 if (lpdata[i] == '\n')
1190 lpstr[inlcount++] = '\r';
1192 lpstr[inlcount++] = lpdata[i];
1195 count = MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, NULL, 0);
1196 hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
1200 WCHAR *textW = GlobalLock(hUnicodeText);
1201 MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, textW, count);
1202 GlobalUnlock(hUnicodeText);
1205 HeapFree(GetProcessHeap(), 0, lpstr);
1208 /* Free the retrieved property data */
1209 HeapFree(GetProcessHeap(), 0, lpdata);
1211 return hUnicodeText;
1215 /**************************************************************************
1216 * X11DRV_CLIPBOARD_ImportCompoundText
1218 * Import COMPOUND_TEXT to CF_UNICODE
1220 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Window w, Atom prop)
1222 Display *display = thread_display();
1226 int srclen, destlen;
1227 HANDLE hUnicodeText;
1228 XTextProperty txtprop;
1231 if (!XGetTextProperty(display, w, &txtprop, prop))
1233 wine_tsx11_unlock();
1237 XmbTextPropertyToTextList(display, &txtprop, &srcstr, &count);
1238 wine_tsx11_unlock();
1240 TRACE("Importing %d line(s)\n", count);
1242 /* Compute number of lines */
1243 srclen = strlen(srcstr[0]);
1244 for (i = 0, lcount = 0; i <= srclen; i++)
1246 if (srcstr[0][i] == '\n')
1250 destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
1252 TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
1254 if ((hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (destlen + lcount + 1) * sizeof(WCHAR))))
1256 WCHAR *deststr = GlobalLock(hUnicodeText);
1257 MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1261 for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1263 deststr[j] = deststr[i];
1265 if (deststr[i] == '\n')
1266 deststr[--j] = '\r';
1270 GlobalUnlock(hUnicodeText);
1274 XFreeStringList(srcstr);
1275 XFree(txtprop.value);
1276 wine_tsx11_unlock();
1278 return hUnicodeText;
1282 /**************************************************************************
1283 * X11DRV_CLIPBOARD_ImportXAPIXMAP
1285 * Import XA_PIXMAP, converting the image to CF_DIB.
1287 HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Window w, Atom prop)
1292 unsigned long cbytes;
1294 HANDLE hClipData = 0;
1296 if (X11DRV_CLIPBOARD_ReadProperty(w, prop, &lpdata, &cbytes))
1298 pPixmap = (Pixmap *) lpdata;
1300 hwnd = GetOpenClipboardWindow();
1303 hClipData = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc);
1304 ReleaseDC(hwnd, hdc);
1306 /* Free the retrieved property data */
1307 HeapFree(GetProcessHeap(), 0, lpdata);
1314 /**************************************************************************
1315 * X11DRV_CLIPBOARD_ImportMetaFilePict
1317 * Import MetaFilePict.
1319 HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Window w, Atom prop)
1322 unsigned long cbytes;
1323 HANDLE hClipData = 0;
1325 if (X11DRV_CLIPBOARD_ReadProperty(w, prop, &lpdata, &cbytes))
1328 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, (HANDLE)lpdata, (LPDWORD)&cbytes, FALSE);
1330 /* Free the retrieved property data */
1331 HeapFree(GetProcessHeap(), 0, lpdata);
1338 /**************************************************************************
1339 * X11DRV_ImportEnhMetaFile
1341 * Import EnhMetaFile.
1343 HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Window w, Atom prop)
1346 unsigned long cbytes;
1347 HANDLE hClipData = 0;
1349 if (X11DRV_CLIPBOARD_ReadProperty(w, prop, &lpdata, &cbytes))
1352 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, (HANDLE)lpdata, (LPDWORD)&cbytes, FALSE);
1354 /* Free the retrieved property data */
1355 HeapFree(GetProcessHeap(), 0, lpdata);
1362 /**************************************************************************
1363 * X11DRV_ImportClipbordaData
1365 * Generic import clipboard data routine.
1367 HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Window w, Atom prop)
1371 unsigned long cbytes;
1372 HANDLE hClipData = 0;
1374 if (X11DRV_CLIPBOARD_ReadProperty(w, prop, &lpdata, &cbytes))
1378 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
1379 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes);
1383 if ((lpClipData = GlobalLock(hClipData)))
1385 memcpy(lpClipData, lpdata, cbytes);
1386 GlobalUnlock(hClipData);
1390 GlobalFree(hClipData);
1395 /* Free the retrieved property data */
1396 HeapFree(GetProcessHeap(), 0, lpdata);
1403 /**************************************************************************
1404 X11DRV_CLIPBOARD_ExportClipboardData
1406 * Generic export clipboard data routine.
1408 HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Window requestor, Atom aTarget,
1409 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1413 HANDLE hClipData = 0;
1415 *lpBytes = 0; /* Assume failure */
1417 if (!X11DRV_CLIPBOARD_RenderFormat(lpData))
1418 ERR("Failed to export %d format\n", lpData->wFormatID);
1421 datasize = GlobalSize(lpData->hData32);
1423 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, datasize);
1424 if (hClipData == 0) return NULL;
1426 if ((lpClipData = GlobalLock(hClipData)))
1428 LPVOID lpdata = GlobalLock(lpData->hData32);
1430 memcpy(lpClipData, lpdata, datasize);
1431 *lpBytes = datasize;
1433 GlobalUnlock(lpData->hData32);
1434 GlobalUnlock(hClipData);
1436 GlobalFree(hClipData);
1445 /**************************************************************************
1446 * X11DRV_CLIPBOARD_ExportXAString
1448 * Export CF_TEXT converting the string to XA_STRING.
1449 * Helper function for X11DRV_CLIPBOARD_ExportString.
1451 static HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1455 LPSTR text, lpstr = NULL;
1457 *lpBytes = 0; /* Assume return has zero bytes */
1459 text = GlobalLock(lpData->hData32);
1460 size = strlen(text);
1462 /* remove carriage returns */
1463 lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1467 for (i = 0,j = 0; i < size && text[i]; i++)
1469 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1471 lpstr[j++] = text[i];
1475 *lpBytes = j; /* Number of bytes in string */
1478 HeapFree(GetProcessHeap(), 0, text);
1479 GlobalUnlock(lpData->hData32);
1485 /**************************************************************************
1486 * X11DRV_CLIPBOARD_ExportUTF8String
1488 * Export CF_UNICODE converting the string to UTF8.
1489 * Helper function for X11DRV_CLIPBOARD_ExportString.
1491 static HANDLE X11DRV_CLIPBOARD_ExportUTF8String(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1496 LPSTR text, lpstr = NULL;
1498 *lpBytes = 0; /* Assume return has zero bytes */
1500 uni_text = GlobalLock(lpData->hData32);
1502 size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1504 text = HeapAlloc(GetProcessHeap(), 0, size);
1507 WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1509 /* remove carriage returns */
1510 lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1514 for (i = 0,j = 0; i < size && text[i]; i++)
1516 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1518 lpstr[j++] = text[i];
1522 *lpBytes = j; /* Number of bytes in string */
1525 HeapFree(GetProcessHeap(), 0, text);
1526 GlobalUnlock(lpData->hData32);
1533 /**************************************************************************
1534 * X11DRV_CLIPBOARD_ExportCompoundText
1536 * Export CF_UNICODE to COMPOUND_TEXT
1537 * Helper function for X11DRV_CLIPBOARD_ExportString.
1539 static HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Window requestor, Atom aTarget, Atom rprop,
1540 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1542 Display *display = thread_display();
1545 XICCEncodingStyle style;
1550 uni_text = GlobalLock(lpData->hData32);
1552 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1553 lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1557 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1559 /* remove carriage returns */
1560 for (i = 0, j = 0; i < size && lpstr[i]; i++)
1562 if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1564 lpstr[j++] = lpstr[i];
1568 GlobalUnlock(lpData->hData32);
1570 if (aTarget == x11drv_atom(COMPOUND_TEXT))
1571 style = XCompoundTextStyle;
1573 style = XStdICCTextStyle;
1575 /* Update the X property */
1577 if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1579 XSetTextProperty(display, requestor, &prop, rprop);
1582 wine_tsx11_unlock();
1584 HeapFree(GetProcessHeap(), 0, lpstr);
1589 /**************************************************************************
1590 * X11DRV_CLIPBOARD_ExportString
1594 HANDLE X11DRV_CLIPBOARD_ExportString(Window requestor, Atom aTarget, Atom rprop,
1595 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1597 if (X11DRV_CLIPBOARD_RenderFormat(lpData))
1599 if (aTarget == XA_STRING)
1600 return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1601 else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1602 return X11DRV_CLIPBOARD_ExportCompoundText(requestor, aTarget,
1603 rprop, lpData, lpBytes);
1606 TRACE("Exporting target %ld to default UTF8_STRING\n", aTarget);
1607 return X11DRV_CLIPBOARD_ExportUTF8String(lpData, lpBytes);
1611 ERR("Failed to render %d format\n", lpData->wFormatID);
1617 /**************************************************************************
1618 * X11DRV_CLIPBOARD_ExportXAPIXMAP
1620 * Export CF_DIB to XA_PIXMAP.
1622 HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Window requestor, Atom aTarget, Atom rprop,
1623 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1627 unsigned char* lpData;
1629 if (!X11DRV_CLIPBOARD_RenderFormat(lpdata))
1631 ERR("Failed to export %d format\n", lpdata->wFormatID);
1635 if (!lpdata->drvData) /* If not already rendered */
1637 /* For convert from packed DIB to Pixmap */
1639 lpdata->drvData = (UINT) X11DRV_DIB_CreatePixmapFromDIB(lpdata->hData32, hdc);
1643 *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1645 /* Wrap pixmap so we can return a handle */
1646 hData = GlobalAlloc(0, *lpBytes);
1647 lpData = GlobalLock(hData);
1648 memcpy(lpData, &lpdata->drvData, *lpBytes);
1649 GlobalUnlock(hData);
1655 /**************************************************************************
1656 * X11DRV_CLIPBOARD_ExportMetaFilePict
1658 * Export MetaFilePict.
1660 HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Window requestor, Atom aTarget, Atom rprop,
1661 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1663 if (!X11DRV_CLIPBOARD_RenderFormat(lpdata))
1665 ERR("Failed to export %d format\n", lpdata->wFormatID);
1669 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata->hData32, lpBytes, TRUE);
1673 /**************************************************************************
1674 * X11DRV_CLIPBOARD_ExportEnhMetaFile
1676 * Export EnhMetaFile.
1678 HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Window requestor, Atom aTarget, Atom rprop,
1679 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1681 if (!X11DRV_CLIPBOARD_RenderFormat(lpdata))
1683 ERR("Failed to export %d format\n", lpdata->wFormatID);
1687 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata->hData32, lpBytes, TRUE);
1691 /**************************************************************************
1692 * X11DRV_CLIPBOARD_QueryTargets
1694 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection,
1695 Atom target, XEvent *xe)
1701 XConvertSelection(display, selection, target,
1702 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1703 wine_tsx11_unlock();
1706 * Wait until SelectionNotify is received
1708 for (i = 0; i < SELECTION_RETRIES; i++)
1711 res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
1712 wine_tsx11_unlock();
1713 if (res && xe->xselection.selection == selection) break;
1715 usleep(SELECTION_WAIT);
1718 /* Verify that the selection returned a valid TARGETS property */
1719 if ((xe->xselection.target != target) || (xe->xselection.property == None))
1721 /* Selection owner failed to respond or we missed the SelectionNotify */
1722 WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
1730 /**************************************************************************
1731 * X11DRV_CLIPBOARD_InsertSelectionProperties
1733 * Mark properties available for future retrieval.
1735 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
1737 UINT i, nb_atoms = 0;
1740 /* Cache these formats in the clipboard cache */
1741 for (i = 0; i < count; i++)
1743 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
1747 /* We found at least one Window's format that mapps to the property.
1748 * Continue looking for more.
1750 * If more than one property map to a Window's format then we use the first
1751 * one and ignore the rest.
1755 TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1756 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
1757 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0, lpFormat, FALSE);
1758 lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
1763 /* add it to the list of atoms that we don't know about yet */
1764 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
1765 (count - i) * sizeof(*atoms) );
1766 if (atoms) atoms[nb_atoms++] = properties[i];
1770 /* query all unknown atoms in one go */
1773 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
1777 /* FIXME: we're at the mercy of the app sending the event here.
1778 * Currently if they send a bogus atom, we will crash.
1779 * We should handle BadAtom errors gracefully in this call.
1781 XGetAtomNames( display, atoms, nb_atoms, names );
1782 wine_tsx11_unlock();
1783 for (i = 0; i < nb_atoms; i++)
1785 WINE_CLIPFORMAT *lpFormat;
1787 int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
1788 wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1789 MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
1791 lpFormat = register_format( wname, atoms[i] );
1792 HeapFree(GetProcessHeap(), 0, wname);
1795 ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
1798 TRACE("Atom#%d Property(%d): --> FormatID(%d) %s\n",
1799 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
1800 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0, lpFormat, FALSE);
1803 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
1804 wine_tsx11_unlock();
1805 HeapFree( GetProcessHeap(), 0, names );
1807 HeapFree( GetProcessHeap(), 0, atoms );
1812 /**************************************************************************
1813 * X11DRV_CLIPBOARD_QueryAvailableData
1815 * Caches the list of data formats available from the current selection.
1816 * This queries the selection owner for the TARGETS property and saves all
1817 * reported property types.
1819 static int X11DRV_CLIPBOARD_QueryAvailableData(LPCLIPBOARDINFO lpcbinfo)
1821 Display *display = thread_display();
1823 Atom atype=AnyPropertyType;
1825 unsigned long remain;
1826 Atom* targetList=NULL;
1828 unsigned long cSelectionTargets = 0;
1830 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
1832 ERR("Received request to cache selection but process is owner=(%08x)\n",
1833 (unsigned) selectionWindow);
1834 return -1; /* Prevent self request */
1837 w = thread_selection_wnd();
1840 ERR("No window available to retrieve selection!\n");
1845 * Query the selection owner for the TARGETS property
1848 if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
1849 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
1851 wine_tsx11_unlock();
1852 if (use_primary_selection && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
1853 selectionCacheSrc = XA_PRIMARY;
1854 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
1855 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1858 Atom xstr = XA_STRING;
1860 /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
1861 if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
1863 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1864 selectionCacheSrc = XA_PRIMARY;
1867 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
1869 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1870 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1875 WARN("Failed to query selection owner for available data.\n");
1880 else /* No selection owner so report 0 targets available */
1882 wine_tsx11_unlock();
1886 /* Read the TARGETS property contents */
1888 if(XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
1889 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
1890 &remain, (unsigned char**)&targetList) != Success)
1892 wine_tsx11_unlock();
1893 WARN("Failed to read TARGETS property\n");
1897 wine_tsx11_unlock();
1898 TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
1899 atype, aformat, cSelectionTargets, remain);
1901 * The TARGETS property should have returned us a list of atoms
1902 * corresponding to each selection target format supported.
1904 if (atype == XA_ATOM || atype == x11drv_atom(TARGETS))
1905 X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, (cSelectionTargets * aformat / (8 * sizeof(Atom))));
1907 /* Free the list of targets */
1910 wine_tsx11_unlock();
1913 return cSelectionTargets;
1917 /**************************************************************************
1918 * X11DRV_CLIPBOARD_ReadSelectionData
1920 * This method is invoked only when we DO NOT own the X selection
1922 * We always get the data from the selection client each time,
1923 * since we have no way of determining if the data in our cache is stale.
1925 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(LPWINE_CLIPDATA lpData)
1927 Display *display = thread_display();
1933 TRACE("%d\n", lpData->wFormatID);
1935 if (!lpData->lpFormat)
1937 ERR("Requesting format %d but no source format linked to data.\n",
1942 if (!selectionAcquired)
1944 Window w = thread_selection_wnd();
1947 ERR("No window available to read selection data!\n");
1951 TRACE("Requesting conversion of %s property (%d) from selection type %08x\n",
1952 debugstr_w(lpData->lpFormat->Name), lpData->lpFormat->drvData, (UINT)selectionCacheSrc);
1955 XConvertSelection(display, selectionCacheSrc, lpData->lpFormat->drvData,
1956 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1957 wine_tsx11_unlock();
1959 /* wait until SelectionNotify is received */
1960 for (i = 0; i < SELECTION_RETRIES; i++)
1963 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
1964 wine_tsx11_unlock();
1965 if (res && xe.xselection.selection == selectionCacheSrc) break;
1967 usleep(SELECTION_WAIT);
1970 /* Verify that the selection returned a valid TARGETS property */
1971 if (xe.xselection.property != None)
1974 * Read the contents of the X selection property
1975 * into WINE's clipboard cache and converting the
1976 * data format if necessary.
1978 HANDLE hData = lpData->lpFormat->lpDrvImportFunc(xe.xselection.requestor,
1979 xe.xselection.property);
1981 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, 0, hData, 0, lpData->lpFormat, TRUE);
1985 TRACE("Failed to convert selection\n");
1990 ERR("Received request to cache selection data but process is owner\n");
1993 TRACE("Returning %d\n", bRet);
1999 /**************************************************************************
2000 * X11DRV_CLIPBOARD_ReadProperty
2001 * Reads the contents of the X selection property.
2003 static BOOL X11DRV_CLIPBOARD_ReadProperty(Window w, Atom prop,
2004 unsigned char** data, unsigned long* datasize)
2006 Display *display = thread_display();
2007 Atom atype = AnyPropertyType;
2009 unsigned long total, nitems, remain, val_cnt;
2012 unsigned char* buffer;
2017 TRACE("Reading property %d from X window %d\n",
2018 (unsigned int)prop, (unsigned int)w);
2021 * First request a zero length in order to figure out the request size.
2024 if(XGetWindowProperty(display,w,prop,0,0,False, AnyPropertyType,
2025 &atype, &aformat, &nitems, &remain, &buffer) != Success)
2027 wine_tsx11_unlock();
2028 WARN("Failed to get property size\n");
2032 /* Free zero length return data if any */
2040 reqlen = remain * bwc;
2042 TRACE("Retrieving %ld bytes\n", reqlen);
2044 val = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, reqlen);
2046 /* Read property in 4K blocks */
2047 for (total = 0, val_cnt = 0; remain;)
2049 if (XGetWindowProperty(display, w, prop, (total / 4), 4096, False,
2050 AnyPropertyType, &atype, &aformat, &nitems, &remain, &buffer) != Success)
2052 wine_tsx11_unlock();
2053 WARN("Failed to read property\n");
2054 HeapFree(GetProcessHeap(), 0, val);
2059 memcpy(&val[val_cnt], buffer, nitems * bwc);
2060 val_cnt += nitems * bwc;
2061 total += nitems*bwc;
2065 /* Delete the property on the window now that we are done
2066 * This will send a PropertyNotify event to the selection owner. */
2067 XDeleteProperty(display, w, prop);
2069 wine_tsx11_unlock();
2078 /**************************************************************************
2079 * CLIPBOARD_SerializeMetafile
2081 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
2085 TRACE(" wFormat=%d hdata=%p out=%d\n", wformat, hdata, out);
2087 if (out) /* Serialize out, caller should free memory */
2089 *lpcbytes = 0; /* Assume failure */
2091 if (wformat == CF_METAFILEPICT)
2093 LPMETAFILEPICT lpmfp = (LPMETAFILEPICT) GlobalLock(hdata);
2094 unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2096 h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
2099 char *pdata = GlobalLock(h);
2101 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
2102 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
2104 *lpcbytes = size + sizeof(METAFILEPICT);
2109 GlobalUnlock(hdata);
2111 else if (wformat == CF_ENHMETAFILE)
2113 int size = GetEnhMetaFileBits(hdata, 0, NULL);
2115 h = GlobalAlloc(0, size);
2118 LPVOID pdata = GlobalLock(h);
2120 GetEnhMetaFileBits(hdata, size, pdata);
2129 if (wformat == CF_METAFILEPICT)
2131 h = GlobalAlloc(0, sizeof(METAFILEPICT));
2134 unsigned int wiresize, size;
2135 LPMETAFILEPICT lpmfp = (LPMETAFILEPICT) GlobalLock(h);
2137 memcpy(lpmfp, hdata, sizeof(METAFILEPICT));
2138 wiresize = *lpcbytes - sizeof(METAFILEPICT);
2139 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
2140 ((const BYTE *)hdata) + sizeof(METAFILEPICT));
2141 size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2145 else if (wformat == CF_ENHMETAFILE)
2147 h = SetEnhMetaFileBits(*lpcbytes, hdata);
2155 /**************************************************************************
2156 * X11DRV_CLIPBOARD_ReleaseSelection
2158 * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
2160 static void X11DRV_CLIPBOARD_ReleaseSelection(Atom selType, Window w, HWND hwnd, Time time)
2162 Display *display = thread_display();
2164 /* w is the window that lost the selection
2166 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
2167 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
2169 if (selectionAcquired && (w == selectionWindow))
2171 CLIPBOARDINFO cbinfo;
2173 /* completely give up the selection */
2174 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
2176 X11DRV_CLIPBOARD_GetClipboardInfo(&cbinfo);
2178 if (cbinfo.flags & CB_PROCESS)
2180 /* Since we're still the owner, this wasn't initiated by
2181 another Wine process */
2182 if (OpenClipboard(hwnd))
2184 /* Destroy private objects */
2185 SendMessageW(cbinfo.hWndOwner, WM_DESTROYCLIPBOARD, 0, 0);
2187 /* Give up ownership of the windows clipboard */
2188 X11DRV_CLIPBOARD_ReleaseOwnership();
2193 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2195 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2198 if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2200 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2201 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2204 TRACE("We no longer own PRIMARY\n");
2205 wine_tsx11_unlock();
2207 else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2209 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2212 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2214 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2215 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2218 TRACE("We no longer own CLIPBOARD\n");
2219 wine_tsx11_unlock();
2222 selectionWindow = None;
2224 X11DRV_EmptyClipboard(FALSE);
2226 /* Reset the selection flags now that we are done */
2227 selectionAcquired = S_NOSELECTION;
2232 /**************************************************************************
2233 * IsSelectionOwner (X11DRV.@)
2235 * Returns: TRUE if the selection is owned by this process, FALSE otherwise
2237 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void)
2239 return selectionAcquired;
2243 /**************************************************************************
2244 * X11DRV Clipboard Exports
2245 **************************************************************************/
2248 /**************************************************************************
2249 * RegisterClipboardFormat (X11DRV.@)
2251 * Registers a custom X clipboard format
2252 * Returns: Format id or 0 on failure
2254 UINT X11DRV_RegisterClipboardFormat(LPCWSTR FormatName)
2256 LPWINE_CLIPFORMAT lpFormat;
2258 if (FormatName == NULL) return 0;
2259 if (!(lpFormat = register_format( FormatName, 0 ))) return 0;
2260 return lpFormat->wFormatID;
2264 /**************************************************************************
2265 * X11DRV_GetClipboardFormatName
2267 INT X11DRV_GetClipboardFormatName(UINT wFormat, LPWSTR retStr, INT maxlen)
2269 LPWINE_CLIPFORMAT lpFormat;
2271 TRACE("(%04X, %p, %d) !\n", wFormat, retStr, maxlen);
2273 if (wFormat < 0xc000)
2275 SetLastError(ERROR_INVALID_PARAMETER);
2279 lpFormat = X11DRV_CLIPBOARD_LookupFormat(wFormat);
2281 if (!lpFormat || (lpFormat->wFlags & CF_FLAG_BUILTINFMT))
2283 TRACE("Unknown format 0x%08x!\n", wFormat);
2284 SetLastError(ERROR_INVALID_HANDLE);
2288 lstrcpynW(retStr, lpFormat->Name, maxlen);
2290 return strlenW(retStr);
2294 /**************************************************************************
2295 * AcquireClipboard (X11DRV.@)
2297 int X11DRV_AcquireClipboard(HWND hWndClipWindow)
2301 Display *display = thread_display();
2303 TRACE(" %p\n", hWndClipWindow);
2306 * It's important that the selection get acquired from the thread
2307 * that owns the clipboard window. The primary reason is that we know
2308 * it is running a message loop and therefore can process the
2309 * X selection events.
2311 if (hWndClipWindow &&
2312 GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, &procid))
2314 if (procid != GetCurrentProcessId())
2316 WARN("Setting clipboard owner to other process is not supported\n");
2317 hWndClipWindow = NULL;
2321 TRACE("Thread %x is acquiring selection with thread %x's window %p\n",
2322 GetCurrentThreadId(),
2323 GetWindowThreadProcessId(hWndClipWindow, NULL), hWndClipWindow);
2325 return SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0);
2329 owner = thread_selection_wnd();
2333 selectionAcquired = 0;
2334 selectionWindow = 0;
2336 /* Grab PRIMARY selection if not owned */
2337 if (use_primary_selection)
2338 XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2340 /* Grab CLIPBOARD selection if not owned */
2341 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2343 if (use_primary_selection && XGetSelectionOwner(display, XA_PRIMARY) == owner)
2344 selectionAcquired |= S_PRIMARY;
2346 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2347 selectionAcquired |= S_CLIPBOARD;
2349 wine_tsx11_unlock();
2351 if (selectionAcquired)
2353 selectionWindow = owner;
2354 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2361 /**************************************************************************
2362 * X11DRV_EmptyClipboard
2364 * Empty cached clipboard data.
2366 void X11DRV_EmptyClipboard(BOOL keepunowned)
2370 LPWINE_CLIPDATA lpData, lpStart;
2371 LPWINE_CLIPDATA lpNext = ClipData;
2373 TRACE(" called with %d entries in cache.\n", ClipDataCount);
2379 lpNext = lpData->NextData;
2381 if (!keepunowned || !(lpData->wFlags & CF_FLAG_UNOWNED))
2383 lpData->PrevData->NextData = lpData->NextData;
2384 lpData->NextData->PrevData = lpData->PrevData;
2386 if (lpData == ClipData)
2387 ClipData = lpNext != lpData ? lpNext : NULL;
2389 X11DRV_CLIPBOARD_FreeData(lpData);
2390 HeapFree(GetProcessHeap(), 0, lpData);
2394 } while (lpNext != lpStart);
2397 TRACE(" %d entries remaining in cache.\n", ClipDataCount);
2402 /**************************************************************************
2403 * X11DRV_SetClipboardData
2405 BOOL X11DRV_SetClipboardData(UINT wFormat, HANDLE16 hData16, HANDLE hData32, BOOL owner)
2408 BOOL bResult = TRUE;
2410 /* If it's not owned, data can only be set if the format data is not already owned
2411 and its rendering is not delayed */
2414 CLIPBOARDINFO cbinfo;
2415 LPWINE_CLIPDATA lpRender;
2417 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2419 if ((!hData16 && !hData32) ||
2420 ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)) &&
2421 !(lpRender->wFlags & CF_FLAG_UNOWNED)))
2424 flags = CF_FLAG_UNOWNED;
2427 bResult &= X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData16, hData32, flags, NULL, TRUE);
2433 /**************************************************************************
2434 * CountClipboardFormats
2436 INT X11DRV_CountClipboardFormats(void)
2438 CLIPBOARDINFO cbinfo;
2440 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2442 TRACE(" count=%d\n", ClipDataCount);
2444 return ClipDataCount;
2448 /**************************************************************************
2449 * X11DRV_EnumClipboardFormats
2451 UINT X11DRV_EnumClipboardFormats(UINT wFormat)
2453 CLIPBOARDINFO cbinfo;
2454 UINT wNextFormat = 0;
2456 TRACE("(%04X)\n", wFormat);
2458 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2463 wNextFormat = ClipData->wFormatID;
2467 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
2469 if (lpData && lpData->NextData != ClipData)
2470 wNextFormat = lpData->NextData->wFormatID;
2477 /**************************************************************************
2478 * X11DRV_IsClipboardFormatAvailable
2480 BOOL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
2483 CLIPBOARDINFO cbinfo;
2485 TRACE("(%04X)\n", wFormat);
2487 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2489 if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
2492 TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
2498 /**************************************************************************
2499 * GetClipboardData (USER.142)
2501 BOOL X11DRV_GetClipboardData(UINT wFormat, HANDLE16* phData16, HANDLE* phData32)
2503 CLIPBOARDINFO cbinfo;
2504 LPWINE_CLIPDATA lpRender;
2506 TRACE("(%04X)\n", wFormat);
2508 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2510 if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
2512 if ( !lpRender->hData32 )
2513 X11DRV_CLIPBOARD_RenderFormat(lpRender);
2515 /* Convert between 32 -> 16 bit data, if necessary */
2516 if (lpRender->hData32 && !lpRender->hData16)
2520 if (lpRender->wFormatID == CF_METAFILEPICT)
2521 size = sizeof(METAFILEPICT16);
2523 size = GlobalSize(lpRender->hData32);
2525 lpRender->hData16 = GlobalAlloc16(GMEM_ZEROINIT, size);
2527 if (!lpRender->hData16)
2528 ERR("(%04X) -- not enough memory in 16b heap\n", wFormat);
2531 if (lpRender->wFormatID == CF_METAFILEPICT)
2533 FIXME("\timplement function CopyMetaFilePict32to16\n");
2534 FIXME("\tin the appropriate file.\n");
2535 #ifdef SOMEONE_IMPLEMENTED_ME
2536 CopyMetaFilePict32to16(GlobalLock16(lpRender->hData16),
2537 GlobalLock(lpRender->hData32));
2542 memcpy(GlobalLock16(lpRender->hData16),
2543 GlobalLock(lpRender->hData32), size);
2546 GlobalUnlock16(lpRender->hData16);
2547 GlobalUnlock(lpRender->hData32);
2551 /* Convert between 32 -> 16 bit data, if necessary */
2552 if (lpRender->hData16 && !lpRender->hData32)
2556 if (lpRender->wFormatID == CF_METAFILEPICT)
2557 size = sizeof(METAFILEPICT16);
2559 size = GlobalSize(lpRender->hData32);
2561 lpRender->hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
2562 GMEM_DDESHARE, size);
2564 if (lpRender->wFormatID == CF_METAFILEPICT)
2566 FIXME("\timplement function CopyMetaFilePict16to32\n");
2567 FIXME("\tin the appropriate file.\n");
2568 #ifdef SOMEONE_IMPLEMENTED_ME
2569 CopyMetaFilePict16to32(GlobalLock16(lpRender->hData32),
2570 GlobalLock(lpRender->hData16));
2575 memcpy(GlobalLock(lpRender->hData32),
2576 GlobalLock16(lpRender->hData16), size);
2579 GlobalUnlock(lpRender->hData32);
2580 GlobalUnlock16(lpRender->hData16);
2584 *phData16 = lpRender->hData16;
2587 *phData32 = lpRender->hData32;
2589 TRACE(" returning hData16(%04x) hData32(%p) (type %d)\n",
2590 lpRender->hData16, lpRender->hData32, lpRender->wFormatID);
2592 return lpRender->hData16 || lpRender->hData32;
2599 /**************************************************************************
2600 * ResetSelectionOwner
2602 * Called when the thread owning the selection is destroyed and we need to
2603 * preserve the selection ownership. We look for another top level window
2604 * in this process and send it a message to acquire the selection.
2606 void X11DRV_ResetSelectionOwner(void)
2613 if (!selectionAcquired || thread_selection_wnd() != selectionWindow)
2616 selectionAcquired = S_NOSELECTION;
2617 selectionWindow = 0;
2619 hwnd = GetWindow(GetDesktopWindow(), GW_CHILD);
2622 if (GetCurrentThreadId() != GetWindowThreadProcessId(hwnd, &procid))
2624 if (GetCurrentProcessId() == procid)
2626 if (SendMessageW(hwnd, WM_X11DRV_ACQUIRE_SELECTION, 0, 0))
2630 } while ((hwnd = GetWindow(hwnd, GW_HWNDNEXT)) != NULL);
2632 WARN("Failed to find another thread to take selection ownership. Clipboard data will be lost.\n");
2634 X11DRV_CLIPBOARD_ReleaseOwnership();
2635 X11DRV_EmptyClipboard(FALSE);
2639 /**************************************************************************
2640 * X11DRV_CLIPBOARD_SynthesizeData
2642 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID)
2645 LPWINE_CLIPDATA lpSource = NULL;
2647 TRACE(" %d\n", wFormatID);
2649 /* Don't need to synthesize if it already exists */
2650 if (X11DRV_CLIPBOARD_LookupData(wFormatID))
2653 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
2655 bsyn = ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
2656 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2657 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
2658 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2659 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
2660 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED);
2662 else if (wFormatID == CF_ENHMETAFILE)
2664 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2665 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2667 else if (wFormatID == CF_METAFILEPICT)
2669 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2670 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2672 else if (wFormatID == CF_DIB)
2674 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
2675 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2677 else if (wFormatID == CF_BITMAP)
2679 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
2680 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2684 X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, 0, CF_FLAG_SYNTHESIZED, NULL, TRUE);
2691 /**************************************************************************
2692 * X11DRV_EndClipboardUpdate
2694 * Add locale if it hasn't already been added
2696 void X11DRV_EndClipboardUpdate(void)
2698 INT count = ClipDataCount;
2700 /* Do Unicode <-> Text <-> OEM mapping */
2701 X11DRV_CLIPBOARD_SynthesizeData(CF_UNICODETEXT);
2702 X11DRV_CLIPBOARD_SynthesizeData(CF_TEXT);
2703 X11DRV_CLIPBOARD_SynthesizeData(CF_OEMTEXT);
2705 /* Enhmetafile <-> MetafilePict mapping */
2706 X11DRV_CLIPBOARD_SynthesizeData(CF_ENHMETAFILE);
2707 X11DRV_CLIPBOARD_SynthesizeData(CF_METAFILEPICT);
2709 /* DIB <-> Bitmap mapping */
2710 X11DRV_CLIPBOARD_SynthesizeData(CF_DIB);
2711 X11DRV_CLIPBOARD_SynthesizeData(CF_BITMAP);
2713 TRACE("%d formats added to cached data\n", ClipDataCount - count);
2717 /***********************************************************************
2718 * X11DRV_SelectionRequest_TARGETS
2719 * Service a TARGETS selection request event
2721 static Atom X11DRV_SelectionRequest_TARGETS( Display *display, Window requestor,
2722 Atom target, Atom rprop )
2727 LPWINE_CLIPFORMAT lpFormats;
2728 LPWINE_CLIPDATA lpData;
2730 /* Create X atoms for any clipboard types which don't have atoms yet.
2731 * This avoids sending bogus zero atoms.
2732 * Without this, copying might not have access to all clipboard types.
2733 * FIXME: is it safe to call this here?
2738 * Count the number of items we wish to expose as selection targets.
2740 cTargets = 1; /* Include TARGETS */
2742 if (!(lpData = ClipData)) return None;
2746 lpFormats = ClipFormats;
2750 if ((lpFormats->wFormatID == lpData->wFormatID) &&
2751 lpFormats->lpDrvExportFunc && lpFormats->drvData)
2754 lpFormats = lpFormats->NextFormat;
2757 lpData = lpData->NextData;
2759 while (lpData != ClipData);
2761 TRACE(" found %d formats\n", cTargets);
2763 /* Allocate temp buffer */
2764 targets = HeapAlloc( GetProcessHeap(), 0, cTargets * sizeof(Atom));
2770 targets[i++] = x11drv_atom(TARGETS);
2774 lpFormats = ClipFormats;
2778 if ((lpFormats->wFormatID == lpData->wFormatID) &&
2779 lpFormats->lpDrvExportFunc && lpFormats->drvData)
2780 targets[i++] = lpFormats->drvData;
2782 lpFormats = lpFormats->NextFormat;
2785 lpData = lpData->NextData;
2787 while (lpData != ClipData);
2791 if (TRACE_ON(clipboard))
2794 for ( i = 0; i < cTargets; i++)
2796 char *itemFmtName = XGetAtomName(display, targets[i]);
2797 TRACE("\tAtom# %d: Property %ld Type %s\n", i, targets[i], itemFmtName);
2802 /* We may want to consider setting the type to xaTargets instead,
2803 * in case some apps expect this instead of XA_ATOM */
2804 XChangeProperty(display, requestor, rprop, XA_ATOM, 32,
2805 PropModeReplace, (unsigned char *)targets, cTargets);
2806 wine_tsx11_unlock();
2808 HeapFree(GetProcessHeap(), 0, targets);
2814 /***********************************************************************
2815 * X11DRV_SelectionRequest_MULTIPLE
2816 * Service a MULTIPLE selection request event
2817 * rprop contains a list of (target,property) atom pairs.
2818 * The first atom names a target and the second names a property.
2819 * The effect is as if we have received a sequence of SelectionRequest events
2820 * (one for each atom pair) except that:
2821 * 1. We reply with a SelectionNotify only when all the requested conversions
2822 * have been performed.
2823 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
2824 * we replace the atom in the property by None.
2826 static Atom X11DRV_SelectionRequest_MULTIPLE( HWND hWnd, XSelectionRequestEvent *pevent )
2828 Display *display = pevent->display;
2830 Atom atype=AnyPropertyType;
2832 unsigned long remain;
2833 Atom* targetPropList=NULL;
2834 unsigned long cTargetPropList = 0;
2836 /* If the specified property is None the requestor is an obsolete client.
2837 * We support these by using the specified target atom as the reply property.
2839 rprop = pevent->property;
2841 rprop = pevent->target;
2845 /* Read the MULTIPLE property contents. This should contain a list of
2846 * (target,property) atom pairs.
2849 if(XGetWindowProperty(display, pevent->requestor, rprop,
2850 0, 0x3FFF, False, AnyPropertyType, &atype,&aformat,
2851 &cTargetPropList, &remain,
2852 (unsigned char**)&targetPropList) != Success)
2854 wine_tsx11_unlock();
2855 TRACE("\tCouldn't read MULTIPLE property\n");
2859 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
2860 XGetAtomName(display, atype), aformat, cTargetPropList, remain);
2861 wine_tsx11_unlock();
2864 * Make sure we got what we expect.
2865 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
2866 * in a MULTIPLE selection request should be of type ATOM_PAIR.
2867 * However some X apps(such as XPaint) are not compliant with this and return
2868 * a user defined atom in atype when XGetWindowProperty is called.
2869 * The data *is* an atom pair but is not denoted as such.
2871 if(aformat == 32 /* atype == xAtomPair */ )
2875 /* Iterate through the ATOM_PAIR list and execute a SelectionRequest
2876 * for each (target,property) pair */
2878 for (i = 0; i < cTargetPropList; i+=2)
2880 XSelectionRequestEvent event;
2882 if (TRACE_ON(clipboard))
2884 char *targetName, *propName;
2886 targetName = XGetAtomName(display, targetPropList[i]);
2887 propName = XGetAtomName(display, targetPropList[i+1]);
2888 TRACE("MULTIPLE(%d): Target='%s' Prop='%s'\n",
2889 i/2, targetName, propName);
2892 wine_tsx11_unlock();
2895 /* We must have a non "None" property to service a MULTIPLE target atom */
2896 if ( !targetPropList[i+1] )
2898 TRACE("\tMULTIPLE(%d): Skipping target with empty property!\n", i);
2902 /* Set up an XSelectionRequestEvent for this (target,property) pair */
2903 memcpy( &event, pevent, sizeof(XSelectionRequestEvent) );
2904 event.target = targetPropList[i];
2905 event.property = targetPropList[i+1];
2907 /* Fire a SelectionRequest, informing the handler that we are processing
2908 * a MULTIPLE selection request event.
2910 X11DRV_HandleSelectionRequest( hWnd, &event, TRUE );
2914 /* Free the list of targets/properties */
2916 XFree(targetPropList);
2917 wine_tsx11_unlock();
2924 /***********************************************************************
2925 * X11DRV_HandleSelectionRequest
2926 * Process an event selection request event.
2927 * The bIsMultiple flag is used to signal when EVENT_SelectionRequest is called
2928 * recursively while servicing a "MULTIPLE" selection target.
2930 * Note: We only receive this event when WINE owns the X selection
2932 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple )
2934 Display *display = event->display;
2935 XSelectionEvent result;
2937 Window request = event->requestor;
2942 * We can only handle the selection request if :
2943 * The selection is PRIMARY or CLIPBOARD, AND we can successfully open the clipboard.
2944 * Don't do these checks or open the clipboard while recursively processing MULTIPLE,
2945 * since this has been already done.
2949 if (((event->selection != XA_PRIMARY) && (event->selection != x11drv_atom(CLIPBOARD))))
2953 /* If the specified property is None the requestor is an obsolete client.
2954 * We support these by using the specified target atom as the reply property.
2956 rprop = event->property;
2958 rprop = event->target;
2960 if(event->target == x11drv_atom(TARGETS)) /* Return a list of all supported targets */
2962 /* TARGETS selection request */
2963 rprop = X11DRV_SelectionRequest_TARGETS( display, request, event->target, rprop );
2965 else if(event->target == x11drv_atom(MULTIPLE)) /* rprop contains a list of (target, property) atom pairs */
2967 /* MULTIPLE selection request */
2968 rprop = X11DRV_SelectionRequest_MULTIPLE( hWnd, event );
2972 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, event->target);
2974 if (lpFormat && lpFormat->lpDrvExportFunc)
2976 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(lpFormat->wFormatID);
2980 unsigned char* lpClipData;
2982 HANDLE hClipData = lpFormat->lpDrvExportFunc(request, event->target,
2983 rprop, lpData, &cBytes);
2985 if (hClipData && (lpClipData = GlobalLock(hClipData)))
2987 TRACE("\tUpdating property %s, %d bytes\n", debugstr_w(lpFormat->Name), cBytes);
2990 XChangeProperty(display, request, rprop, event->target,
2991 8, PropModeReplace, lpClipData, cBytes);
2992 wine_tsx11_unlock();
2994 GlobalUnlock(hClipData);
2995 GlobalFree(hClipData);
3003 * SelectionNotify should be sent only at the end of a MULTIPLE request
3007 result.type = SelectionNotify;
3008 result.display = display;
3009 result.requestor = request;
3010 result.selection = event->selection;
3011 result.property = rprop;
3012 result.target = event->target;
3013 result.time = event->time;
3014 TRACE("Sending SelectionNotify event...\n");
3016 XSendEvent(display,event->requestor,False,NoEventMask,(XEvent*)&result);
3017 wine_tsx11_unlock();
3022 /***********************************************************************
3023 * X11DRV_SelectionRequest
3025 void X11DRV_SelectionRequest( HWND hWnd, XEvent *event )
3027 X11DRV_HandleSelectionRequest( hWnd, &event->xselectionrequest, FALSE );
3031 /***********************************************************************
3032 * X11DRV_SelectionClear
3034 void X11DRV_SelectionClear( HWND hWnd, XEvent *xev )
3036 XSelectionClearEvent *event = &xev->xselectionclear;
3037 if (event->selection == XA_PRIMARY || event->selection == x11drv_atom(CLIPBOARD))
3038 X11DRV_CLIPBOARD_ReleaseSelection( event->selection, event->window, hWnd, event->time );