winex11.drv: Export copied images as image/bmp.
[wine/multimedia.git] / dlls / winex11.drv / clipboard.c
blobf14a84c3ea17fbc1c711a38a25c28b8563b443a0
1 /*
2 * X11 clipboard windows driver
4 * Copyright 1994 Martin Ayotte
5 * 1996 Alex Korobka
6 * 1999 Noel Borthwick
7 * 2003 Ulrich Czekalla for CodeWeavers
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 * NOTES:
24 * This file contains the X specific implementation for the windows
25 * Clipboard API.
27 * Wine's internal clipboard is exposed to external apps via the X
28 * selection mechanism.
29 * Currently the driver asserts ownership via two selection atoms:
30 * 1. PRIMARY(XA_PRIMARY)
31 * 2. CLIPBOARD
33 * In our implementation, the CLIPBOARD selection takes precedence over PRIMARY,
34 * i.e. if a CLIPBOARD selection is available, it is used instead of PRIMARY.
35 * When Wine takes ownership of the clipboard, it takes ownership of BOTH selections.
36 * While giving up selection ownership, if the CLIPBOARD selection is lost,
37 * it will lose both PRIMARY and CLIPBOARD and empty the clipboard.
38 * However if only PRIMARY is lost, it will continue to hold the CLIPBOARD selection
39 * (leaving the clipboard cache content unaffected).
41 * Every format exposed via a windows clipboard format is also exposed through
42 * a corresponding X selection target. A selection target atom is synthesized
43 * whenever a new Windows clipboard format is registered via RegisterClipboardFormat,
44 * or when a built-in format is used for the first time.
45 * Windows native format are exposed by prefixing the format name with "<WCF>"
46 * This allows us to uniquely identify windows native formats exposed by other
47 * running WINE apps.
49 * In order to allow external applications to query WINE for supported formats,
50 * we respond to the "TARGETS" selection target. (See EVENT_SelectionRequest
51 * for implementation) We use the same mechanism to query external clients for
52 * availability of a particular format, by caching the list of available targets
53 * by using the clipboard cache's "delayed render" mechanism. If a selection client
54 * does not support the "TARGETS" selection target, we actually attempt to retrieve
55 * the format requested as a fallback mechanism.
57 * Certain Windows native formats are automatically converted to X native formats
58 * and vice versa. If a native format is available in the selection, it takes
59 * precedence, in order to avoid unnecessary conversions.
61 * FIXME: global format list needs a critical section
64 #include "config.h"
65 #include "wine/port.h"
67 #include <string.h>
68 #include <stdarg.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #ifdef HAVE_UNISTD_H
72 # include <unistd.h>
73 #endif
74 #include <fcntl.h>
75 #include <limits.h>
76 #include <time.h>
77 #include <assert.h>
79 #include "windef.h"
80 #include "winbase.h"
81 #include "wine/wingdi16.h"
82 #include "x11drv.h"
83 #include "wine/debug.h"
84 #include "wine/unicode.h"
85 #include "wine/server.h"
87 WINE_DEFAULT_DEBUG_CHANNEL(clipboard);
89 #define HGDIOBJ_32(handle16) ((HGDIOBJ)(ULONG_PTR)(handle16))
91 /* Maximum wait time for selection notify */
92 #define SELECTION_RETRIES 500 /* wait for .1 seconds */
93 #define SELECTION_WAIT 1000 /* us */
94 /* Minimum seconds that must lapse between owner queries */
95 #define OWNERQUERYLAPSETIME 1
97 /* Selection masks */
98 #define S_NOSELECTION 0
99 #define S_PRIMARY 1
100 #define S_CLIPBOARD 2
102 typedef struct
104 HWND hWndOpen;
105 HWND hWndOwner;
106 HWND hWndViewer;
107 UINT seqno;
108 UINT flags;
109 } CLIPBOARDINFO, *LPCLIPBOARDINFO;
111 struct tagWINE_CLIPDATA; /* Forward */
113 typedef HANDLE (*DRVEXPORTFUNC)(Display *display, Window requestor, Atom aTarget, Atom rprop,
114 struct tagWINE_CLIPDATA* lpData, LPDWORD lpBytes);
115 typedef HANDLE (*DRVIMPORTFUNC)(Display *d, Window w, Atom prop);
117 typedef struct tagWINE_CLIPFORMAT {
118 UINT wFormatID;
119 LPCWSTR Name;
120 UINT drvData;
121 UINT wFlags;
122 DRVIMPORTFUNC lpDrvImportFunc;
123 DRVEXPORTFUNC lpDrvExportFunc;
124 struct tagWINE_CLIPFORMAT *PrevFormat;
125 struct tagWINE_CLIPFORMAT *NextFormat;
126 } WINE_CLIPFORMAT, *LPWINE_CLIPFORMAT;
128 typedef struct tagWINE_CLIPDATA {
129 UINT wFormatID;
130 HANDLE16 hData16;
131 HANDLE hData32;
132 UINT wFlags;
133 UINT drvData;
134 LPWINE_CLIPFORMAT lpFormat;
135 struct tagWINE_CLIPDATA *PrevData;
136 struct tagWINE_CLIPDATA *NextData;
137 } WINE_CLIPDATA, *LPWINE_CLIPDATA;
139 #define CF_FLAG_BUILTINFMT 0x0001 /* Built-in windows format */
140 #define CF_FLAG_UNOWNED 0x0002 /* cached data is not owned */
141 #define CF_FLAG_SYNTHESIZED 0x0004 /* Implicitly converted data */
142 #define CF_FLAG_UNICODE 0x0008 /* Data is in unicode */
144 static int selectionAcquired = 0; /* Contains the current selection masks */
145 static Window selectionWindow = None; /* The top level X window which owns the selection */
146 static Atom selectionCacheSrc = XA_PRIMARY; /* The selection source from which the clipboard cache was filled */
148 void CDECL X11DRV_EmptyClipboard(BOOL keepunowned);
149 void CDECL X11DRV_EndClipboardUpdate(void);
150 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *d, Window w, Atom prop);
151 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *d, Window w, Atom prop);
152 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *d, Window w, Atom prop);
153 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *d, Window w, Atom prop);
154 static HANDLE X11DRV_CLIPBOARD_ImportImageBmp(Display *d, Window w, Atom prop);
155 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *d, Window w, Atom prop);
156 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *d, Window w, Atom prop);
157 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *d, Window w, Atom prop);
158 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
159 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
160 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget,
161 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
162 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget,
163 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
164 static HANDLE X11DRV_CLIPBOARD_ExportImageBmp(Display *display, Window requestor, Atom aTarget,
165 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
166 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget,
167 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
168 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget,
169 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
170 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCWSTR FormatName, Atom prop);
171 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID);
172 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData);
173 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void);
174 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo);
175 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData);
176 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
177 unsigned char** data, unsigned long* datasize);
178 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData);
179 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out);
180 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID);
181 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData);
182 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display);
183 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display);
184 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple );
186 /* Clipboard formats
187 * WARNING: This data ordering is dependent on the WINE_CLIPFORMAT structure
188 * declared in clipboard.h
190 static const WCHAR wszCF_TEXT[] = {'W','C','F','_','T','E','X','T',0};
191 static const WCHAR wszCF_BITMAP[] = {'W','C','F','_','B','I','T','M','A','P',0};
192 static const WCHAR wszCF_METAFILEPICT[] = {'W','C','F','_','M','E','T','A','F','I','L','E','P','I','C','T',0};
193 static const WCHAR wszCF_SYLK[] = {'W','C','F','_','S','Y','L','K',0};
194 static const WCHAR wszCF_DIF[] = {'W','C','F','_','D','I','F',0};
195 static const WCHAR wszCF_TIFF[] = {'W','C','F','_','T','I','F','F',0};
196 static const WCHAR wszCF_OEMTEXT[] = {'W','C','F','_','O','E','M','T','E','X','T',0};
197 static const WCHAR wszCF_DIB[] = {'W','C','F','_','D','I','B',0};
198 static const WCHAR wszIMAGEBMP[] = {'i','m','a','g','e','/','b','m','p',0};
199 static const WCHAR wszCF_PALETTE[] = {'W','C','F','_','P','A','L','E','T','T','E',0};
200 static const WCHAR wszCF_PENDATA[] = {'W','C','F','_','P','E','N','D','A','T','A',0};
201 static const WCHAR wszCF_RIFF[] = {'W','C','F','_','R','I','F','F',0};
202 static const WCHAR wszCF_WAVE[] = {'W','C','F','_','W','A','V','E',0};
203 static const WCHAR wszCOMPOUNDTEXT[] = {'C','O','M','P','O','U','N','D','_','T','E','X','T',0};
204 static const WCHAR wszUTF8STRING[] = {'U','T','F','8','_','S','T','R','I','N','G',0};
205 static const WCHAR wszCF_ENHMETAFILE[] = {'W','C','F','_','E','N','H','M','E','T','A','F','I','L','E',0};
206 static const WCHAR wszCF_HDROP[] = {'W','C','F','_','H','D','R','O','P',0};
207 static const WCHAR wszCF_LOCALE[] = {'W','C','F','_','L','O','C','A','L','E',0};
208 static const WCHAR wszCF_DIBV5[] = {'W','C','F','_','D','I','B','V','5',0};
209 static const WCHAR wszCF_OWNERDISPLAY[] = {'W','C','F','_','O','W','N','E','R','D','I','S','P','L','A','Y',0};
210 static const WCHAR wszCF_DSPTEXT[] = {'W','C','F','_','D','S','P','T','E','X','T',0};
211 static const WCHAR wszCF_DSPBITMAP[] = {'W','C','F','_','D','S','P','B','I','T','M','A','P',0};
212 static const WCHAR wszCF_DSPMETAFILEPICT[] = {'W','C','F','_','D','S','P','M','E','T','A','F','I','L','E','P','I','C','T',0};
213 static const WCHAR wszCF_DSPENHMETAFILE[] = {'W','C','F','_','D','S','P','E','N','H','M','E','T','A','F','I','L','E',0};
215 static WINE_CLIPFORMAT ClipFormats[] =
217 { CF_TEXT, wszCF_TEXT, XA_STRING, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAString,
218 X11DRV_CLIPBOARD_ExportString, NULL, &ClipFormats[1]},
220 { CF_BITMAP, wszCF_BITMAP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
221 NULL, &ClipFormats[0], &ClipFormats[2]},
223 { CF_METAFILEPICT, wszCF_METAFILEPICT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportMetaFilePict,
224 X11DRV_CLIPBOARD_ExportMetaFilePict, &ClipFormats[1], &ClipFormats[3]},
226 { CF_SYLK, wszCF_SYLK, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
227 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[2], &ClipFormats[4]},
229 { CF_DIF, wszCF_DIF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
230 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[3], &ClipFormats[5]},
232 { CF_TIFF, wszCF_TIFF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
233 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[4], &ClipFormats[6]},
235 { CF_OEMTEXT, wszCF_OEMTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
236 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[5], &ClipFormats[7]},
238 { CF_DIB, wszCF_DIB, XA_PIXMAP, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportXAPIXMAP,
239 X11DRV_CLIPBOARD_ExportXAPIXMAP, &ClipFormats[6], &ClipFormats[8]},
241 { CF_PALETTE, wszCF_PALETTE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
242 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[7], &ClipFormats[9]},
244 { CF_PENDATA, wszCF_PENDATA, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
245 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[8], &ClipFormats[10]},
247 { CF_RIFF, wszCF_RIFF, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
248 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[9], &ClipFormats[11]},
250 { CF_WAVE, wszCF_WAVE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
251 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[10], &ClipFormats[12]},
253 { CF_UNICODETEXT, wszUTF8STRING, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportUTF8,
254 X11DRV_CLIPBOARD_ExportString, &ClipFormats[11], &ClipFormats[13]},
256 /* If UTF8_STRING is not available, attempt COMPUND_TEXT */
257 { CF_UNICODETEXT, wszCOMPOUNDTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportCompoundText,
258 X11DRV_CLIPBOARD_ExportString, &ClipFormats[12], &ClipFormats[14]},
260 { CF_ENHMETAFILE, wszCF_ENHMETAFILE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportEnhMetaFile,
261 X11DRV_CLIPBOARD_ExportEnhMetaFile, &ClipFormats[13], &ClipFormats[15]},
263 { CF_HDROP, wszCF_HDROP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
264 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[14], &ClipFormats[16]},
266 { CF_LOCALE, wszCF_LOCALE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
267 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[15], &ClipFormats[17]},
269 { CF_DIBV5, wszCF_DIBV5, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
270 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[16], &ClipFormats[18]},
272 { CF_OWNERDISPLAY, wszCF_OWNERDISPLAY, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
273 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[17], &ClipFormats[19]},
275 { CF_DSPTEXT, wszCF_DSPTEXT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
276 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[18], &ClipFormats[20]},
278 { CF_DSPBITMAP, wszCF_DSPBITMAP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
279 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[19], &ClipFormats[21]},
281 { CF_DSPMETAFILEPICT, wszCF_DSPMETAFILEPICT, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
282 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[20], &ClipFormats[22]},
284 { CF_DSPENHMETAFILE, wszCF_DSPENHMETAFILE, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportClipboardData,
285 X11DRV_CLIPBOARD_ExportClipboardData, &ClipFormats[21], &ClipFormats[23]},
287 { CF_DIB, wszIMAGEBMP, 0, CF_FLAG_BUILTINFMT, X11DRV_CLIPBOARD_ImportImageBmp,
288 X11DRV_CLIPBOARD_ExportImageBmp, &ClipFormats[22], NULL},
291 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
293 /* Maps X properties to Windows formats */
294 static const WCHAR wszRichTextFormat[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
295 static const WCHAR wszGIF[] = {'G','I','F',0};
296 static const WCHAR wszHTMLFormat[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
297 static const struct
299 LPCWSTR lpszFormat;
300 UINT prop;
301 } PropertyFormatMap[] =
303 { wszRichTextFormat, XATOM_text_rtf },
304 { wszRichTextFormat, XATOM_text_richtext },
305 { wszGIF, XATOM_image_gif },
306 { wszHTMLFormat, XATOM_text_html },
311 * Cached clipboard data.
313 static LPWINE_CLIPDATA ClipData = NULL;
314 static UINT ClipDataCount = 0;
317 * Clipboard sequence number
319 static UINT wSeqNo = 0;
321 /**************************************************************************
322 * Internal Clipboard implementation methods
323 **************************************************************************/
325 static Window thread_selection_wnd(void)
327 struct x11drv_thread_data *thread_data = x11drv_init_thread_data();
328 Window w = thread_data->selection_wnd;
330 if (!w)
332 XSetWindowAttributes attr;
334 attr.event_mask = (ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
335 ButtonPressMask | ButtonReleaseMask | EnterWindowMask | PropertyChangeMask);
337 wine_tsx11_lock();
338 w = XCreateWindow(thread_data->display, root_window, 0, 0, 1, 1, 0, screen_depth,
339 InputOutput, CopyFromParent, CWEventMask, &attr);
340 wine_tsx11_unlock();
342 if (w)
343 thread_data->selection_wnd = w;
344 else
345 FIXME("Failed to create window. Fetching selection data will fail.\n");
348 return w;
351 /**************************************************************************
352 * X11DRV_InitClipboard
354 void X11DRV_InitClipboard(void)
356 UINT i;
358 /* Register known mapping between window formats and X properties */
359 for (i = 0; i < sizeof(PropertyFormatMap)/sizeof(PropertyFormatMap[0]); i++)
360 X11DRV_CLIPBOARD_InsertClipboardFormat(PropertyFormatMap[i].lpszFormat, GET_ATOM(PropertyFormatMap[i].prop));
364 /**************************************************************************
365 * intern_atoms
367 * Intern atoms for formats that don't have one yet.
369 static void intern_atoms(void)
371 LPWINE_CLIPFORMAT format;
372 int i, count, len;
373 char **names;
374 Atom *atoms;
375 Display *display;
377 for (format = ClipFormats, count = 0; format; format = format->NextFormat)
378 if (!format->drvData) count++;
379 if (!count) return;
381 display = thread_init_display();
383 names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
384 atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
386 for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
387 if (!format->drvData) {
388 len = WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, NULL, 0, NULL, NULL);
389 names[i] = HeapAlloc(GetProcessHeap(), 0, len);
390 WideCharToMultiByte(CP_UNIXCP, 0, format->Name, -1, names[i++], len, NULL, NULL);
394 wine_tsx11_lock();
395 XInternAtoms( display, names, count, False, atoms );
396 wine_tsx11_unlock();
398 for (format = ClipFormats, i = 0; format; format = format->NextFormat) {
399 if (!format->drvData) {
400 HeapFree(GetProcessHeap(), 0, names[i]);
401 format->drvData = atoms[i++];
405 HeapFree( GetProcessHeap(), 0, names );
406 HeapFree( GetProcessHeap(), 0, atoms );
410 /**************************************************************************
411 * register_format
413 * Register a custom X clipboard format.
415 static WINE_CLIPFORMAT *register_format( LPCWSTR FormatName, Atom prop )
417 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
419 TRACE("%s\n", debugstr_w(FormatName));
421 /* walk format chain to see if it's already registered */
422 while (lpFormat)
424 if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE, lpFormat->Name, -1, FormatName, -1) == CSTR_EQUAL
425 && (lpFormat->wFlags & CF_FLAG_BUILTINFMT) == 0)
426 return lpFormat;
427 lpFormat = lpFormat->NextFormat;
430 return X11DRV_CLIPBOARD_InsertClipboardFormat(FormatName, prop);
434 /**************************************************************************
435 * X11DRV_CLIPBOARD_LookupFormat
437 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupFormat(WORD wID)
439 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
441 while(lpFormat)
443 if (lpFormat->wFormatID == wID)
444 break;
446 lpFormat = lpFormat->NextFormat;
448 if (lpFormat && !lpFormat->drvData) intern_atoms();
449 return lpFormat;
453 /**************************************************************************
454 * X11DRV_CLIPBOARD_LookupProperty
456 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupProperty(LPWINE_CLIPFORMAT current, UINT drvData)
458 for (;;)
460 LPWINE_CLIPFORMAT lpFormat = ClipFormats;
461 BOOL need_intern = FALSE;
463 if (current)
464 lpFormat = current->NextFormat;
466 while(lpFormat)
468 if (lpFormat->drvData == drvData) return lpFormat;
469 if (!lpFormat->drvData) need_intern = TRUE;
470 lpFormat = lpFormat->NextFormat;
472 if (!need_intern) return NULL;
473 intern_atoms();
474 /* restart the search for the new atoms */
479 /**************************************************************************
480 * X11DRV_CLIPBOARD_LookupData
482 static LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
484 LPWINE_CLIPDATA lpData = ClipData;
486 if (lpData)
490 if (lpData->wFormatID == wID)
491 break;
493 lpData = lpData->NextData;
495 while(lpData != ClipData);
497 if (lpData->wFormatID != wID)
498 lpData = NULL;
501 return lpData;
505 /**************************************************************************
506 * InsertClipboardFormat
508 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(LPCWSTR FormatName, Atom prop)
510 LPWINE_CLIPFORMAT lpFormat;
511 LPWINE_CLIPFORMAT lpNewFormat;
512 LPWSTR new_name;
514 /* allocate storage for new format entry */
515 lpNewFormat = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPFORMAT));
517 if(lpNewFormat == NULL)
519 WARN("No more memory for a new format!\n");
520 return NULL;
523 if (!(new_name = HeapAlloc(GetProcessHeap(), 0, (strlenW(FormatName)+1)*sizeof(WCHAR))))
525 WARN("No more memory for the new format name!\n");
526 HeapFree(GetProcessHeap(), 0, lpNewFormat);
527 return NULL;
530 lpNewFormat->Name = strcpyW(new_name, FormatName);
531 lpNewFormat->wFlags = 0;
532 lpNewFormat->wFormatID = GlobalAddAtomW(lpNewFormat->Name);
533 lpNewFormat->drvData = prop;
534 lpNewFormat->lpDrvImportFunc = X11DRV_CLIPBOARD_ImportClipboardData;
535 lpNewFormat->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportClipboardData;
537 /* Link Format */
538 lpFormat = ClipFormats;
540 while(lpFormat->NextFormat) /* Move to last entry */
541 lpFormat = lpFormat->NextFormat;
543 lpNewFormat->NextFormat = NULL;
544 lpFormat->NextFormat = lpNewFormat;
545 lpNewFormat->PrevFormat = lpFormat;
547 TRACE("Registering format(%04x): %s drvData %d\n",
548 lpNewFormat->wFormatID, debugstr_w(FormatName), lpNewFormat->drvData);
550 return lpNewFormat;
556 /**************************************************************************
557 * X11DRV_CLIPBOARD_GetClipboardInfo
559 static BOOL X11DRV_CLIPBOARD_GetClipboardInfo(LPCLIPBOARDINFO cbInfo)
561 BOOL bRet = FALSE;
563 SERVER_START_REQ( set_clipboard_info )
565 req->flags = 0;
567 if (wine_server_call_err( req ))
569 ERR("Failed to get clipboard owner.\n");
571 else
573 cbInfo->hWndOpen = wine_server_ptr_handle( reply->old_clipboard );
574 cbInfo->hWndOwner = wine_server_ptr_handle( reply->old_owner );
575 cbInfo->hWndViewer = wine_server_ptr_handle( reply->old_viewer );
576 cbInfo->seqno = reply->seqno;
577 cbInfo->flags = reply->flags;
579 bRet = TRUE;
582 SERVER_END_REQ;
584 return bRet;
588 /**************************************************************************
589 * X11DRV_CLIPBOARD_ReleaseOwnership
591 static BOOL X11DRV_CLIPBOARD_ReleaseOwnership(void)
593 BOOL bRet = FALSE;
595 SERVER_START_REQ( set_clipboard_info )
597 req->flags = SET_CB_RELOWNER | SET_CB_SEQNO;
599 if (wine_server_call_err( req ))
601 ERR("Failed to set clipboard.\n");
603 else
605 bRet = TRUE;
608 SERVER_END_REQ;
610 return bRet;
615 /**************************************************************************
616 * X11DRV_CLIPBOARD_InsertClipboardData
618 * Caller *must* have the clipboard open and be the owner.
620 static BOOL X11DRV_CLIPBOARD_InsertClipboardData(UINT wFormatID, HANDLE16 hData16,
621 HANDLE hData32, DWORD flags, LPWINE_CLIPFORMAT lpFormat, BOOL override)
623 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormatID);
625 TRACE("format=%04x lpData=%p hData16=%08x hData32=%p flags=0x%08x lpFormat=%p override=%d\n",
626 wFormatID, lpData, hData16, hData32, flags, lpFormat, override);
628 if (lpData && !override)
629 return TRUE;
631 if (lpData)
633 X11DRV_CLIPBOARD_FreeData(lpData);
635 lpData->hData16 = hData16; /* 0 is legal, see WM_RENDERFORMAT */
636 lpData->hData32 = hData32;
638 else
640 lpData = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPDATA));
642 lpData->wFormatID = wFormatID;
643 lpData->hData16 = hData16; /* 0 is legal, see WM_RENDERFORMAT */
644 lpData->hData32 = hData32;
645 lpData->lpFormat = lpFormat;
646 lpData->drvData = 0;
648 if (ClipData)
650 LPWINE_CLIPDATA lpPrevData = ClipData->PrevData;
652 lpData->PrevData = lpPrevData;
653 lpData->NextData = ClipData;
655 lpPrevData->NextData = lpData;
656 ClipData->PrevData = lpData;
658 else
660 lpData->NextData = lpData;
661 lpData->PrevData = lpData;
662 ClipData = lpData;
665 ClipDataCount++;
668 lpData->wFlags = flags;
670 return TRUE;
674 /**************************************************************************
675 * X11DRV_CLIPBOARD_FreeData
677 * Free clipboard data handle.
679 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData)
681 TRACE("%04x\n", lpData->wFormatID);
683 if ((lpData->wFormatID >= CF_GDIOBJFIRST &&
684 lpData->wFormatID <= CF_GDIOBJLAST) ||
685 lpData->wFormatID == CF_BITMAP ||
686 lpData->wFormatID == CF_DIB ||
687 lpData->wFormatID == CF_PALETTE)
689 if (lpData->hData32)
690 DeleteObject(lpData->hData32);
692 if (lpData->hData16)
693 DeleteObject(HGDIOBJ_32(lpData->hData16));
695 if ((lpData->wFormatID == CF_DIB) && lpData->drvData)
696 XFreePixmap(gdi_display, lpData->drvData);
698 else if (lpData->wFormatID == CF_METAFILEPICT)
700 if (lpData->hData32)
702 DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData32 ))->hMF );
703 GlobalFree(lpData->hData32);
705 if (lpData->hData16)
706 /* HMETAFILE16 and HMETAFILE32 are apparently the same thing,
707 and a shallow copy is enough to share a METAFILEPICT
708 structure between 16bit and 32bit clipboards. The MetaFile
709 should of course only be deleted once. */
710 GlobalFree16(lpData->hData16);
713 if (lpData->hData16)
715 METAFILEPICT16* lpMetaPict = GlobalLock16(lpData->hData16);
717 if (lpMetaPict)
719 /* To delete 16-bit meta file, we just need to free the associated
720 handle. See DeleteMetaFile16() in dlls/gdi/metafile.c. */
721 GlobalFree16(lpMetaPict->hMF);
722 lpMetaPict->hMF = 0;
725 GlobalFree16(lpData->hData16);
728 else if (lpData->wFormatID == CF_ENHMETAFILE)
730 if (lpData->hData32)
731 DeleteEnhMetaFile(lpData->hData32);
733 else if (lpData->wFormatID < CF_PRIVATEFIRST ||
734 lpData->wFormatID > CF_PRIVATELAST)
736 if (lpData->hData32)
737 GlobalFree(lpData->hData32);
739 if (lpData->hData16)
740 GlobalFree16(lpData->hData16);
743 lpData->hData16 = 0;
744 lpData->hData32 = 0;
745 lpData->drvData = 0;
749 /**************************************************************************
750 * X11DRV_CLIPBOARD_UpdateCache
752 static BOOL X11DRV_CLIPBOARD_UpdateCache(LPCLIPBOARDINFO lpcbinfo)
754 BOOL bret = TRUE;
756 if (!X11DRV_CLIPBOARD_IsSelectionOwner())
758 if (!X11DRV_CLIPBOARD_GetClipboardInfo(lpcbinfo))
760 ERR("Failed to retrieve clipboard information.\n");
761 bret = FALSE;
763 else if (wSeqNo < lpcbinfo->seqno)
765 X11DRV_EmptyClipboard(TRUE);
767 if (X11DRV_CLIPBOARD_QueryAvailableData(thread_init_display(), lpcbinfo) < 0)
769 ERR("Failed to cache clipboard data owned by another process.\n");
770 bret = FALSE;
772 else
774 X11DRV_EndClipboardUpdate();
777 wSeqNo = lpcbinfo->seqno;
781 return bret;
785 /**************************************************************************
786 * X11DRV_CLIPBOARD_RenderFormat
788 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData)
790 BOOL bret = TRUE;
792 TRACE(" 0x%04x hData32(%p) hData16(0x%08x)\n",
793 lpData->wFormatID, lpData->hData32, lpData->hData16);
795 if (lpData->hData32 || lpData->hData16)
796 return bret; /* Already rendered */
798 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
799 bret = X11DRV_CLIPBOARD_RenderSynthesizedFormat(display, lpData);
800 else if (!X11DRV_CLIPBOARD_IsSelectionOwner())
802 if (!X11DRV_CLIPBOARD_ReadSelectionData(display, lpData))
804 ERR("Failed to cache clipboard data owned by another process. Format=%04x\n",
805 lpData->wFormatID);
806 bret = FALSE;
809 else
811 CLIPBOARDINFO cbInfo;
813 if (X11DRV_CLIPBOARD_GetClipboardInfo(&cbInfo) && cbInfo.hWndOwner)
815 /* Send a WM_RENDERFORMAT message to notify the owner to render the
816 * data requested into the clipboard.
818 TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", cbInfo.hWndOwner);
819 SendMessageW(cbInfo.hWndOwner, WM_RENDERFORMAT, (WPARAM)lpData->wFormatID, 0);
821 if (!lpData->hData32 && !lpData->hData16)
822 bret = FALSE;
824 else
826 ERR("hWndClipOwner is lost!\n");
827 bret = FALSE;
831 return bret;
835 /**************************************************************************
836 * CLIPBOARD_ConvertText
837 * Returns number of required/converted characters - not bytes!
839 static INT CLIPBOARD_ConvertText(WORD src_fmt, void const *src, INT src_size,
840 WORD dst_fmt, void *dst, INT dst_size)
842 UINT cp;
844 if(src_fmt == CF_UNICODETEXT)
846 switch(dst_fmt)
848 case CF_TEXT:
849 cp = CP_ACP;
850 break;
851 case CF_OEMTEXT:
852 cp = CP_OEMCP;
853 break;
854 default:
855 return 0;
857 return WideCharToMultiByte(cp, 0, src, src_size, dst, dst_size, NULL, NULL);
860 if(dst_fmt == CF_UNICODETEXT)
862 switch(src_fmt)
864 case CF_TEXT:
865 cp = CP_ACP;
866 break;
867 case CF_OEMTEXT:
868 cp = CP_OEMCP;
869 break;
870 default:
871 return 0;
873 return MultiByteToWideChar(cp, 0, src, src_size, dst, dst_size);
876 if(!dst_size) return src_size;
878 if(dst_size > src_size) dst_size = src_size;
880 if(src_fmt == CF_TEXT )
881 CharToOemBuffA(src, dst, dst_size);
882 else
883 OemToCharBuffA(src, dst, dst_size);
885 return dst_size;
889 /**************************************************************************
890 * X11DRV_CLIPBOARD_RenderSynthesizedFormat
892 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData)
894 BOOL bret = FALSE;
896 TRACE("\n");
898 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
900 UINT wFormatID = lpData->wFormatID;
902 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
903 bret = X11DRV_CLIPBOARD_RenderSynthesizedText(display, wFormatID);
904 else
906 switch (wFormatID)
908 case CF_DIB:
909 bret = X11DRV_CLIPBOARD_RenderSynthesizedDIB( display );
910 break;
912 case CF_BITMAP:
913 bret = X11DRV_CLIPBOARD_RenderSynthesizedBitmap( display );
914 break;
916 case CF_ENHMETAFILE:
917 case CF_METAFILEPICT:
918 FIXME("Synthesizing wFormatID(0x%08x) not implemented\n", wFormatID);
919 break;
921 default:
922 FIXME("Called to synthesize unknown format\n");
923 break;
927 lpData->wFlags &= ~CF_FLAG_SYNTHESIZED;
930 return bret;
934 /**************************************************************************
935 * X11DRV_CLIPBOARD_RenderSynthesizedText
937 * Renders synthesized text
939 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID)
941 LPCSTR lpstrS;
942 LPSTR lpstrT;
943 HANDLE hData32;
944 INT src_chars, dst_chars, alloc_size;
945 LPWINE_CLIPDATA lpSource = NULL;
947 TRACE("%04x\n", wFormatID);
949 if ((lpSource = X11DRV_CLIPBOARD_LookupData(wFormatID)) &&
950 lpSource->hData32)
951 return TRUE;
953 /* Look for rendered source or non-synthesized source */
954 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
955 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
957 TRACE("UNICODETEXT -> %04x\n", wFormatID);
959 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
960 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
962 TRACE("TEXT -> %04x\n", wFormatID);
964 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
965 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
967 TRACE("OEMTEXT -> %04x\n", wFormatID);
970 if (!lpSource || (lpSource->wFlags & CF_FLAG_SYNTHESIZED &&
971 !lpSource->hData32))
972 return FALSE;
974 /* Ask the clipboard owner to render the source text if necessary */
975 if (!lpSource->hData32 && !X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
976 return FALSE;
978 if (lpSource->hData32)
980 lpstrS = GlobalLock(lpSource->hData32);
982 else
984 lpstrS = GlobalLock16(lpSource->hData16);
987 if (!lpstrS)
988 return FALSE;
990 /* Text always NULL terminated */
991 if(lpSource->wFormatID == CF_UNICODETEXT)
992 src_chars = strlenW((LPCWSTR)lpstrS) + 1;
993 else
994 src_chars = strlen(lpstrS) + 1;
996 /* Calculate number of characters in the destination buffer */
997 dst_chars = CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS,
998 src_chars, wFormatID, NULL, 0);
1000 if (!dst_chars)
1001 return FALSE;
1003 TRACE("Converting from '%04x' to '%04x', %i chars\n",
1004 lpSource->wFormatID, wFormatID, src_chars);
1006 /* Convert characters to bytes */
1007 if(wFormatID == CF_UNICODETEXT)
1008 alloc_size = dst_chars * sizeof(WCHAR);
1009 else
1010 alloc_size = dst_chars;
1012 hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
1013 GMEM_DDESHARE, alloc_size);
1015 lpstrT = GlobalLock(hData32);
1017 if (lpstrT)
1019 CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS, src_chars,
1020 wFormatID, lpstrT, dst_chars);
1021 GlobalUnlock(hData32);
1024 /* Unlock source */
1025 if (lpSource->hData32)
1026 GlobalUnlock(lpSource->hData32);
1027 else
1028 GlobalUnlock16(lpSource->hData16);
1030 return X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, hData32, 0, NULL, TRUE);
1034 /**************************************************************************
1035 * X11DRV_CLIPBOARD_RenderSynthesizedDIB
1037 * Renders synthesized DIB
1039 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display)
1041 BOOL bret = FALSE;
1042 LPWINE_CLIPDATA lpSource = NULL;
1044 TRACE("\n");
1046 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) && lpSource->hData32)
1048 bret = TRUE;
1050 /* If we have a bitmap and it's not synthesized or it has been rendered */
1051 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
1052 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
1054 /* Render source if required */
1055 if (lpSource->hData32 || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1057 HDC hdc;
1058 HGLOBAL hData32;
1060 hdc = GetDC(NULL);
1061 hData32 = X11DRV_DIB_CreateDIBFromBitmap(hdc, lpSource->hData32);
1062 ReleaseDC(NULL, hdc);
1064 if (hData32)
1066 X11DRV_CLIPBOARD_InsertClipboardData(CF_DIB, 0, hData32, 0, NULL, TRUE);
1067 bret = TRUE;
1072 return bret;
1076 /**************************************************************************
1077 * X11DRV_CLIPBOARD_RenderSynthesizedBitmap
1079 * Renders synthesized bitmap
1081 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display)
1083 BOOL bret = FALSE;
1084 LPWINE_CLIPDATA lpSource = NULL;
1086 TRACE("\n");
1088 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) && lpSource->hData32)
1090 bret = TRUE;
1092 /* If we have a dib and it's not synthesized or it has been rendered */
1093 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
1094 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData32))
1096 /* Render source if required */
1097 if (lpSource->hData32 || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1099 HDC hdc;
1100 HBITMAP hData32;
1101 unsigned int offset;
1102 LPBITMAPINFOHEADER lpbmih;
1104 hdc = GetDC(NULL);
1105 lpbmih = GlobalLock(lpSource->hData32);
1107 offset = sizeof(BITMAPINFOHEADER)
1108 + ((lpbmih->biBitCount <= 8) ? (sizeof(RGBQUAD) *
1109 (1 << lpbmih->biBitCount)) : 0);
1111 hData32 = CreateDIBitmap(hdc, lpbmih, CBM_INIT, (LPBYTE)lpbmih +
1112 offset, (LPBITMAPINFO) lpbmih, DIB_RGB_COLORS);
1114 GlobalUnlock(lpSource->hData32);
1115 ReleaseDC(NULL, hdc);
1117 if (hData32)
1119 X11DRV_CLIPBOARD_InsertClipboardData(CF_BITMAP, 0, hData32, 0, NULL, TRUE);
1120 bret = TRUE;
1125 return bret;
1129 /**************************************************************************
1130 * X11DRV_CLIPBOARD_ImportXAString
1132 * Import XA_STRING, converting the string to CF_TEXT.
1134 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *display, Window w, Atom prop)
1136 LPBYTE lpdata;
1137 unsigned long cbytes;
1138 LPSTR lpstr;
1139 unsigned long i, inlcount = 0;
1140 HANDLE hText = 0;
1142 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1143 return 0;
1145 for (i = 0; i <= cbytes; i++)
1147 if (lpdata[i] == '\n')
1148 inlcount++;
1151 if ((hText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes + inlcount + 1)))
1153 lpstr = GlobalLock(hText);
1155 for (i = 0, inlcount = 0; i <= cbytes; i++)
1157 if (lpdata[i] == '\n')
1158 lpstr[inlcount++] = '\r';
1160 lpstr[inlcount++] = lpdata[i];
1163 GlobalUnlock(hText);
1166 /* Free the retrieved property data */
1167 HeapFree(GetProcessHeap(), 0, lpdata);
1169 return hText;
1173 /**************************************************************************
1174 * X11DRV_CLIPBOARD_ImportUTF8
1176 * Import XA_STRING, converting the string to CF_UNICODE.
1178 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *display, Window w, Atom prop)
1180 LPBYTE lpdata;
1181 unsigned long cbytes;
1182 LPSTR lpstr;
1183 unsigned long i, inlcount = 0;
1184 HANDLE hUnicodeText = 0;
1186 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1187 return 0;
1189 for (i = 0; i <= cbytes; i++)
1191 if (lpdata[i] == '\n')
1192 inlcount++;
1195 if ((lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbytes + inlcount + 1)))
1197 UINT count;
1199 for (i = 0, inlcount = 0; i <= cbytes; i++)
1201 if (lpdata[i] == '\n')
1202 lpstr[inlcount++] = '\r';
1204 lpstr[inlcount++] = lpdata[i];
1207 count = MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, NULL, 0);
1208 hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
1210 if (hUnicodeText)
1212 WCHAR *textW = GlobalLock(hUnicodeText);
1213 MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, textW, count);
1214 GlobalUnlock(hUnicodeText);
1217 HeapFree(GetProcessHeap(), 0, lpstr);
1220 /* Free the retrieved property data */
1221 HeapFree(GetProcessHeap(), 0, lpdata);
1223 return hUnicodeText;
1227 /**************************************************************************
1228 * X11DRV_CLIPBOARD_ImportCompoundText
1230 * Import COMPOUND_TEXT to CF_UNICODE
1232 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *display, Window w, Atom prop)
1234 int i, j, ret;
1235 char** srcstr;
1236 int count, lcount;
1237 int srclen, destlen;
1238 HANDLE hUnicodeText;
1239 XTextProperty txtprop;
1241 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &txtprop.value, &txtprop.nitems))
1243 return 0;
1246 txtprop.encoding = x11drv_atom(COMPOUND_TEXT);
1247 txtprop.format = 8;
1248 wine_tsx11_lock();
1249 ret = XmbTextPropertyToTextList(display, &txtprop, &srcstr, &count);
1250 wine_tsx11_unlock();
1251 HeapFree(GetProcessHeap(), 0, txtprop.value);
1252 if (ret != Success || !count) return 0;
1254 TRACE("Importing %d line(s)\n", count);
1256 /* Compute number of lines */
1257 srclen = strlen(srcstr[0]);
1258 for (i = 0, lcount = 0; i <= srclen; i++)
1260 if (srcstr[0][i] == '\n')
1261 lcount++;
1264 destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
1266 TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
1268 if ((hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (destlen + lcount + 1) * sizeof(WCHAR))))
1270 WCHAR *deststr = GlobalLock(hUnicodeText);
1271 MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1273 if (lcount)
1275 for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1277 deststr[j] = deststr[i];
1279 if (deststr[i] == '\n')
1280 deststr[--j] = '\r';
1284 GlobalUnlock(hUnicodeText);
1287 wine_tsx11_lock();
1288 XFreeStringList(srcstr);
1289 wine_tsx11_unlock();
1291 return hUnicodeText;
1295 /**************************************************************************
1296 * X11DRV_CLIPBOARD_ImportXAPIXMAP
1298 * Import XA_PIXMAP, converting the image to CF_DIB.
1300 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *display, Window w, Atom prop)
1302 HWND hwnd;
1303 HDC hdc;
1304 LPBYTE lpdata;
1305 unsigned long cbytes;
1306 Pixmap *pPixmap;
1307 HANDLE hClipData = 0;
1309 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1311 pPixmap = (Pixmap *) lpdata;
1313 hwnd = GetOpenClipboardWindow();
1314 hdc = GetDC(hwnd);
1316 hClipData = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc);
1317 ReleaseDC(hwnd, hdc);
1319 /* Free the retrieved property data */
1320 HeapFree(GetProcessHeap(), 0, lpdata);
1323 return hClipData;
1327 /**************************************************************************
1328 * X11DRV_CLIPBOARD_ImportImageBmp
1330 * Import image/bmp, converting the image to CF_DIB.
1332 static HANDLE X11DRV_CLIPBOARD_ImportImageBmp(Display *display, Window w, Atom prop)
1334 LPBYTE lpdata;
1335 unsigned long cbytes;
1336 HANDLE hClipData = 0;
1338 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1340 BITMAPFILEHEADER *bfh = (BITMAPFILEHEADER*)lpdata;
1342 if (cbytes >= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPCOREHEADER) &&
1343 bfh->bfType == 0x4d42 /* "BM" */)
1345 BITMAPINFO *bmi = (BITMAPINFO*)(bfh+1);
1346 HBITMAP hbmp;
1347 HDC hdc;
1349 hdc = GetDC(0);
1350 hbmp = CreateDIBitmap(
1351 hdc,
1352 &(bmi->bmiHeader),
1353 CBM_INIT,
1354 lpdata+bfh->bfOffBits,
1355 bmi,
1356 DIB_RGB_COLORS
1359 hClipData = X11DRV_DIB_CreateDIBFromBitmap(hdc, hbmp);
1361 DeleteObject(hbmp);
1362 ReleaseDC(0, hdc);
1365 /* Free the retrieved property data */
1366 HeapFree(GetProcessHeap(), 0, lpdata);
1369 return hClipData;
1373 /**************************************************************************
1374 * X11DRV_CLIPBOARD_ImportMetaFilePict
1376 * Import MetaFilePict.
1378 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *display, Window w, Atom prop)
1380 LPBYTE lpdata;
1381 unsigned long cbytes;
1382 HANDLE hClipData = 0;
1384 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1386 if (cbytes)
1387 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata, (LPDWORD)&cbytes, FALSE);
1389 /* Free the retrieved property data */
1390 HeapFree(GetProcessHeap(), 0, lpdata);
1393 return hClipData;
1397 /**************************************************************************
1398 * X11DRV_ImportEnhMetaFile
1400 * Import EnhMetaFile.
1402 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *display, Window w, Atom prop)
1404 LPBYTE lpdata;
1405 unsigned long cbytes;
1406 HANDLE hClipData = 0;
1408 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1410 if (cbytes)
1411 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata, (LPDWORD)&cbytes, FALSE);
1413 /* Free the retrieved property data */
1414 HeapFree(GetProcessHeap(), 0, lpdata);
1417 return hClipData;
1421 /**************************************************************************
1422 * X11DRV_ImportClipbordaData
1424 * Generic import clipboard data routine.
1426 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *display, Window w, Atom prop)
1428 LPVOID lpClipData;
1429 LPBYTE lpdata;
1430 unsigned long cbytes;
1431 HANDLE hClipData = 0;
1433 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1435 if (cbytes)
1437 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
1438 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes);
1439 if (hClipData == 0)
1440 return NULL;
1442 if ((lpClipData = GlobalLock(hClipData)))
1444 memcpy(lpClipData, lpdata, cbytes);
1445 GlobalUnlock(hClipData);
1447 else
1449 GlobalFree(hClipData);
1450 hClipData = 0;
1454 /* Free the retrieved property data */
1455 HeapFree(GetProcessHeap(), 0, lpdata);
1458 return hClipData;
1462 /**************************************************************************
1463 X11DRV_CLIPBOARD_ExportClipboardData
1465 * Generic export clipboard data routine.
1467 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
1468 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1470 LPVOID lpClipData;
1471 UINT datasize = 0;
1472 HANDLE hClipData = 0;
1474 *lpBytes = 0; /* Assume failure */
1476 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1477 ERR("Failed to export %04x format\n", lpData->wFormatID);
1478 else
1480 datasize = GlobalSize(lpData->hData32);
1482 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, datasize);
1483 if (hClipData == 0) return NULL;
1485 if ((lpClipData = GlobalLock(hClipData)))
1487 LPVOID lpdata = GlobalLock(lpData->hData32);
1489 memcpy(lpClipData, lpdata, datasize);
1490 *lpBytes = datasize;
1492 GlobalUnlock(lpData->hData32);
1493 GlobalUnlock(hClipData);
1494 } else {
1495 GlobalFree(hClipData);
1496 hClipData = 0;
1500 return hClipData;
1504 /**************************************************************************
1505 * X11DRV_CLIPBOARD_ExportXAString
1507 * Export CF_TEXT converting the string to XA_STRING.
1508 * Helper function for X11DRV_CLIPBOARD_ExportString.
1510 static HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1512 UINT i, j;
1513 UINT size;
1514 LPSTR text, lpstr = NULL;
1516 *lpBytes = 0; /* Assume return has zero bytes */
1518 text = GlobalLock(lpData->hData32);
1519 size = strlen(text);
1521 /* remove carriage returns */
1522 lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1523 if (lpstr == NULL)
1524 goto done;
1526 for (i = 0,j = 0; i < size && text[i]; i++)
1528 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1529 continue;
1530 lpstr[j++] = text[i];
1533 lpstr[j]='\0';
1534 *lpBytes = j; /* Number of bytes in string */
1536 done:
1537 HeapFree(GetProcessHeap(), 0, text);
1538 GlobalUnlock(lpData->hData32);
1540 return lpstr;
1544 /**************************************************************************
1545 * X11DRV_CLIPBOARD_ExportUTF8String
1547 * Export CF_UNICODE converting the string to UTF8.
1548 * Helper function for X11DRV_CLIPBOARD_ExportString.
1550 static HANDLE X11DRV_CLIPBOARD_ExportUTF8String(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1552 UINT i, j;
1553 UINT size;
1554 LPWSTR uni_text;
1555 LPSTR text, lpstr = NULL;
1557 *lpBytes = 0; /* Assume return has zero bytes */
1559 uni_text = GlobalLock(lpData->hData32);
1561 size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1563 text = HeapAlloc(GetProcessHeap(), 0, size);
1564 if (!text)
1565 goto done;
1566 WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1568 /* remove carriage returns */
1569 lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1570 if (lpstr == NULL)
1571 goto done;
1573 for (i = 0,j = 0; i < size && text[i]; i++)
1575 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1576 continue;
1577 lpstr[j++] = text[i];
1579 lpstr[j]='\0';
1581 *lpBytes = j; /* Number of bytes in string */
1583 done:
1584 HeapFree(GetProcessHeap(), 0, text);
1585 GlobalUnlock(lpData->hData32);
1587 return lpstr;
1592 /**************************************************************************
1593 * X11DRV_CLIPBOARD_ExportCompoundText
1595 * Export CF_UNICODE to COMPOUND_TEXT
1596 * Helper function for X11DRV_CLIPBOARD_ExportString.
1598 static HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Display *display, Window requestor, Atom aTarget, Atom rprop,
1599 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1601 char* lpstr = 0;
1602 XTextProperty prop;
1603 XICCEncodingStyle style;
1604 UINT i, j;
1605 UINT size;
1606 LPWSTR uni_text;
1608 uni_text = GlobalLock(lpData->hData32);
1610 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1611 lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1612 if (!lpstr)
1613 return 0;
1615 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1617 /* remove carriage returns */
1618 for (i = 0, j = 0; i < size && lpstr[i]; i++)
1620 if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1621 continue;
1622 lpstr[j++] = lpstr[i];
1624 lpstr[j]='\0';
1626 GlobalUnlock(lpData->hData32);
1628 if (aTarget == x11drv_atom(COMPOUND_TEXT))
1629 style = XCompoundTextStyle;
1630 else
1631 style = XStdICCTextStyle;
1633 /* Update the X property */
1634 wine_tsx11_lock();
1635 if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1637 XSetTextProperty(display, requestor, &prop, rprop);
1638 XFree(prop.value);
1640 wine_tsx11_unlock();
1642 HeapFree(GetProcessHeap(), 0, lpstr);
1644 return 0;
1647 /**************************************************************************
1648 * X11DRV_CLIPBOARD_ExportString
1650 * Export string
1652 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget, Atom rprop,
1653 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1655 if (X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1657 if (aTarget == XA_STRING)
1658 return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1659 else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1660 return X11DRV_CLIPBOARD_ExportCompoundText(display, requestor, aTarget,
1661 rprop, lpData, lpBytes);
1662 else
1664 TRACE("Exporting target %ld to default UTF8_STRING\n", aTarget);
1665 return X11DRV_CLIPBOARD_ExportUTF8String(lpData, lpBytes);
1668 else
1669 ERR("Failed to render %04x format\n", lpData->wFormatID);
1671 return 0;
1675 /**************************************************************************
1676 * X11DRV_CLIPBOARD_ExportXAPIXMAP
1678 * Export CF_DIB to XA_PIXMAP.
1680 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget, Atom rprop,
1681 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1683 HDC hdc;
1684 HANDLE hData;
1685 unsigned char* lpData;
1687 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1689 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1690 return 0;
1693 if (!lpdata->drvData) /* If not already rendered */
1695 /* For convert from packed DIB to Pixmap */
1696 hdc = GetDC(0);
1697 lpdata->drvData = (UINT) X11DRV_DIB_CreatePixmapFromDIB(lpdata->hData32, hdc);
1698 ReleaseDC(0, hdc);
1701 *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1703 /* Wrap pixmap so we can return a handle */
1704 hData = GlobalAlloc(0, *lpBytes);
1705 lpData = GlobalLock(hData);
1706 memcpy(lpData, &lpdata->drvData, *lpBytes);
1707 GlobalUnlock(hData);
1709 return hData;
1713 /**************************************************************************
1714 * X11DRV_CLIPBOARD_ExportImageBmp
1716 * Export CF_DIB to image/bmp.
1718 static HANDLE X11DRV_CLIPBOARD_ExportImageBmp(Display *display, Window requestor, Atom aTarget, Atom rprop,
1719 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1721 HANDLE hpackeddib;
1722 LPBYTE dibdata;
1723 UINT bmpsize;
1724 HANDLE hbmpdata;
1725 LPBYTE bmpdata;
1726 BITMAPFILEHEADER *bfh;
1728 *lpBytes = 0;
1730 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1732 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1733 return 0;
1736 hpackeddib = lpdata->hData32;
1738 dibdata = GlobalLock(hpackeddib);
1739 if (!dibdata)
1741 ERR("Failed to lock packed DIB\n");
1742 return 0;
1745 bmpsize = sizeof(BITMAPFILEHEADER) + GlobalSize(hpackeddib);
1747 hbmpdata = GlobalAlloc(0, bmpsize);
1749 if (hbmpdata)
1751 bmpdata = GlobalLock(hbmpdata);
1753 if (!bmpdata)
1755 GlobalFree(hbmpdata);
1756 GlobalUnlock(hpackeddib);
1757 return 0;
1760 /* bitmap file header */
1761 bfh = (BITMAPFILEHEADER*)bmpdata;
1762 bfh->bfType = 0x4d42; /* "BM" */
1763 bfh->bfSize = bmpsize;
1764 bfh->bfReserved1 = 0;
1765 bfh->bfReserved2 = 0;
1766 bfh->bfOffBits = sizeof(BITMAPFILEHEADER) + bitmap_info_size((BITMAPINFO*)dibdata, DIB_RGB_COLORS);
1768 /* rest of bitmap is the same as the packed dib */
1769 memcpy(bfh+1, dibdata, bmpsize-sizeof(BITMAPFILEHEADER));
1771 *lpBytes = bmpsize;
1773 GlobalUnlock(hbmpdata);
1776 GlobalUnlock(hpackeddib);
1778 return hbmpdata;
1782 /**************************************************************************
1783 * X11DRV_CLIPBOARD_ExportMetaFilePict
1785 * Export MetaFilePict.
1787 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget, Atom rprop,
1788 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1790 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1792 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1793 return 0;
1796 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata->hData32, lpBytes, TRUE);
1800 /**************************************************************************
1801 * X11DRV_CLIPBOARD_ExportEnhMetaFile
1803 * Export EnhMetaFile.
1805 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget, Atom rprop,
1806 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1808 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1810 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1811 return 0;
1814 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata->hData32, lpBytes, TRUE);
1818 /**************************************************************************
1819 * X11DRV_CLIPBOARD_QueryTargets
1821 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection,
1822 Atom target, XEvent *xe)
1824 INT i;
1825 Bool res;
1827 wine_tsx11_lock();
1828 XConvertSelection(display, selection, target,
1829 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1830 wine_tsx11_unlock();
1833 * Wait until SelectionNotify is received
1835 for (i = 0; i < SELECTION_RETRIES; i++)
1837 wine_tsx11_lock();
1838 res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
1839 wine_tsx11_unlock();
1840 if (res && xe->xselection.selection == selection) break;
1842 usleep(SELECTION_WAIT);
1845 /* Verify that the selection returned a valid TARGETS property */
1846 if ((xe->xselection.target != target) || (xe->xselection.property == None))
1848 /* Selection owner failed to respond or we missed the SelectionNotify */
1849 WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
1850 return FALSE;
1853 return TRUE;
1857 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
1859 return (event->error_code == BadAtom);
1862 /**************************************************************************
1863 * X11DRV_CLIPBOARD_InsertSelectionProperties
1865 * Mark properties available for future retrieval.
1867 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
1869 UINT i, nb_atoms = 0;
1870 Atom *atoms = NULL;
1872 /* Cache these formats in the clipboard cache */
1873 for (i = 0; i < count; i++)
1875 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
1877 if (lpFormat)
1879 /* We found at least one Window's format that mapps to the property.
1880 * Continue looking for more.
1882 * If more than one property map to a Window's format then we use the first
1883 * one and ignore the rest.
1885 while (lpFormat)
1887 TRACE("Atom#%d Property(%d): --> FormatID(%04x) %s\n",
1888 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
1889 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0, lpFormat, FALSE);
1890 lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
1893 else if (properties[i])
1895 /* add it to the list of atoms that we don't know about yet */
1896 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
1897 (count - i) * sizeof(*atoms) );
1898 if (atoms) atoms[nb_atoms++] = properties[i];
1902 /* query all unknown atoms in one go */
1903 if (atoms)
1905 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
1906 if (names)
1908 X11DRV_expect_error( display, is_atom_error, NULL );
1909 if (!XGetAtomNames( display, atoms, nb_atoms, names )) nb_atoms = 0;
1910 if (X11DRV_check_error())
1912 WARN( "got some bad atoms, ignoring\n" );
1913 nb_atoms = 0;
1915 for (i = 0; i < nb_atoms; i++)
1917 WINE_CLIPFORMAT *lpFormat;
1918 LPWSTR wname;
1919 int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
1920 wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1921 MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
1923 lpFormat = register_format( wname, atoms[i] );
1924 HeapFree(GetProcessHeap(), 0, wname);
1925 if (!lpFormat)
1927 ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
1928 continue;
1930 TRACE("Atom#%d Property(%d): --> FormatID(%04x) %s\n",
1931 i, lpFormat->drvData, lpFormat->wFormatID, debugstr_w(lpFormat->Name));
1932 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, 0, lpFormat, FALSE);
1934 wine_tsx11_lock();
1935 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
1936 wine_tsx11_unlock();
1937 HeapFree( GetProcessHeap(), 0, names );
1939 HeapFree( GetProcessHeap(), 0, atoms );
1944 /**************************************************************************
1945 * X11DRV_CLIPBOARD_QueryAvailableData
1947 * Caches the list of data formats available from the current selection.
1948 * This queries the selection owner for the TARGETS property and saves all
1949 * reported property types.
1951 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo)
1953 XEvent xe;
1954 Atom atype=AnyPropertyType;
1955 int aformat;
1956 unsigned long remain;
1957 Atom* targetList=NULL;
1958 Window w;
1959 unsigned long cSelectionTargets = 0;
1961 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
1963 ERR("Received request to cache selection but process is owner=(%08x)\n",
1964 (unsigned) selectionWindow);
1965 return -1; /* Prevent self request */
1968 w = thread_selection_wnd();
1969 if (!w)
1971 ERR("No window available to retrieve selection!\n");
1972 return -1;
1976 * Query the selection owner for the TARGETS property
1978 wine_tsx11_lock();
1979 if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
1980 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
1982 wine_tsx11_unlock();
1983 if (use_primary_selection && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
1984 selectionCacheSrc = XA_PRIMARY;
1985 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
1986 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1987 else
1989 Atom xstr = XA_STRING;
1991 /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
1992 if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
1994 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1995 selectionCacheSrc = XA_PRIMARY;
1996 return 1;
1998 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
2000 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2001 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2002 return 1;
2004 else
2006 WARN("Failed to query selection owner for available data.\n");
2007 return -1;
2011 else /* No selection owner so report 0 targets available */
2013 wine_tsx11_unlock();
2014 return 0;
2017 /* Read the TARGETS property contents */
2018 wine_tsx11_lock();
2019 if(XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
2020 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
2021 &remain, (unsigned char**)&targetList) != Success)
2023 wine_tsx11_unlock();
2024 WARN("Failed to read TARGETS property\n");
2026 else
2028 wine_tsx11_unlock();
2029 TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
2030 atype, aformat, cSelectionTargets, remain);
2032 * The TARGETS property should have returned us a list of atoms
2033 * corresponding to each selection target format supported.
2035 if (atype == XA_ATOM || atype == x11drv_atom(TARGETS))
2037 if (aformat == 32)
2039 X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, cSelectionTargets);
2041 else if (aformat == 8) /* work around quartz-wm brain damage */
2043 unsigned long i, count = cSelectionTargets / sizeof(CARD32);
2044 Atom *atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(Atom) );
2045 for (i = 0; i < count; i++)
2046 atoms[i] = ((CARD32 *)targetList)[i]; /* FIXME: byte swapping */
2047 X11DRV_CLIPBOARD_InsertSelectionProperties( display, atoms, count );
2048 HeapFree( GetProcessHeap(), 0, atoms );
2052 /* Free the list of targets */
2053 wine_tsx11_lock();
2054 XFree(targetList);
2055 wine_tsx11_unlock();
2058 return cSelectionTargets;
2062 /**************************************************************************
2063 * X11DRV_CLIPBOARD_ReadSelectionData
2065 * This method is invoked only when we DO NOT own the X selection
2067 * We always get the data from the selection client each time,
2068 * since we have no way of determining if the data in our cache is stale.
2070 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData)
2072 Bool res;
2073 DWORD i;
2074 XEvent xe;
2075 BOOL bRet = FALSE;
2077 TRACE("%04x\n", lpData->wFormatID);
2079 if (!lpData->lpFormat)
2081 ERR("Requesting format %04x but no source format linked to data.\n",
2082 lpData->wFormatID);
2083 return FALSE;
2086 if (!selectionAcquired)
2088 Window w = thread_selection_wnd();
2089 if(!w)
2091 ERR("No window available to read selection data!\n");
2092 return FALSE;
2095 TRACE("Requesting conversion of %s property (%d) from selection type %08x\n",
2096 debugstr_w(lpData->lpFormat->Name), lpData->lpFormat->drvData, (UINT)selectionCacheSrc);
2098 wine_tsx11_lock();
2099 XConvertSelection(display, selectionCacheSrc, lpData->lpFormat->drvData,
2100 x11drv_atom(SELECTION_DATA), w, CurrentTime);
2101 wine_tsx11_unlock();
2103 /* wait until SelectionNotify is received */
2104 for (i = 0; i < SELECTION_RETRIES; i++)
2106 wine_tsx11_lock();
2107 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
2108 wine_tsx11_unlock();
2109 if (res && xe.xselection.selection == selectionCacheSrc) break;
2111 usleep(SELECTION_WAIT);
2114 /* Verify that the selection returned a valid TARGETS property */
2115 if (xe.xselection.property != None)
2118 * Read the contents of the X selection property
2119 * into WINE's clipboard cache and converting the
2120 * data format if necessary.
2122 HANDLE hData = lpData->lpFormat->lpDrvImportFunc(display, xe.xselection.requestor,
2123 xe.xselection.property);
2125 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, 0, hData, 0, lpData->lpFormat, TRUE);
2127 else
2129 TRACE("Failed to convert selection\n");
2132 else
2134 ERR("Received request to cache selection data but process is owner\n");
2137 TRACE("Returning %d\n", bRet);
2139 return bRet;
2143 /**************************************************************************
2144 * X11DRV_CLIPBOARD_GetProperty
2145 * Gets type, data and size.
2147 static BOOL X11DRV_CLIPBOARD_GetProperty(Display *display, Window w, Atom prop,
2148 Atom *atype, unsigned char** data, unsigned long* datasize)
2150 int aformat;
2151 unsigned long pos = 0, nitems, remain, count;
2152 unsigned char *val = NULL, *buffer;
2154 TRACE("Reading property %lu from X window %lx\n", prop, w);
2156 for (;;)
2158 wine_tsx11_lock();
2159 if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
2160 AnyPropertyType, atype, &aformat, &nitems, &remain, &buffer) != Success)
2162 wine_tsx11_unlock();
2163 WARN("Failed to read property\n");
2164 HeapFree( GetProcessHeap(), 0, val );
2165 return FALSE;
2168 count = get_property_size( aformat, nitems );
2169 if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
2170 else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
2172 if (!*data)
2174 XFree( buffer );
2175 wine_tsx11_unlock();
2176 HeapFree( GetProcessHeap(), 0, val );
2177 return FALSE;
2179 val = *data;
2180 memcpy( (int *)val + pos, buffer, count );
2181 XFree( buffer );
2182 wine_tsx11_unlock();
2183 if (!remain)
2185 *datasize = pos * sizeof(int) + count;
2186 val[*datasize] = 0;
2187 break;
2189 pos += count / sizeof(int);
2192 /* Delete the property on the window now that we are done
2193 * This will send a PropertyNotify event to the selection owner. */
2194 wine_tsx11_lock();
2195 XDeleteProperty(display, w, prop);
2196 wine_tsx11_unlock();
2197 return TRUE;
2201 /**************************************************************************
2202 * X11DRV_CLIPBOARD_ReadProperty
2203 * Reads the contents of the X selection property.
2205 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
2206 unsigned char** data, unsigned long* datasize)
2208 Atom atype;
2209 XEvent xe;
2211 if (prop == None)
2212 return FALSE;
2214 if (!X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, data, datasize))
2215 return FALSE;
2217 wine_tsx11_lock();
2218 while (XCheckTypedWindowEvent(display, w, PropertyNotify, &xe))
2220 wine_tsx11_unlock();
2222 if (atype == x11drv_atom(INCR))
2224 unsigned char *buf = *data;
2225 unsigned long bufsize = 0;
2227 for (;;)
2229 int i;
2230 unsigned char *prop_data, *tmp;
2231 unsigned long prop_size;
2233 /* Wait until PropertyNotify is received */
2234 for (i = 0; i < SELECTION_RETRIES; i++)
2236 Bool res;
2238 wine_tsx11_lock();
2239 res = XCheckTypedWindowEvent(display, w, PropertyNotify, &xe);
2240 wine_tsx11_unlock();
2241 if (res && xe.xproperty.atom == prop &&
2242 xe.xproperty.state == PropertyNewValue)
2243 break;
2244 usleep(SELECTION_WAIT);
2247 if (i >= SELECTION_RETRIES ||
2248 !X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, &prop_data, &prop_size))
2250 HeapFree(GetProcessHeap(), 0, buf);
2251 return FALSE;
2254 /* Retrieved entire data. */
2255 if (prop_size == 0)
2257 HeapFree(GetProcessHeap(), 0, prop_data);
2258 *data = buf;
2259 *datasize = bufsize;
2260 return TRUE;
2263 tmp = HeapReAlloc(GetProcessHeap(), 0, buf, bufsize + prop_size + 1);
2264 if (!tmp)
2266 HeapFree(GetProcessHeap(), 0, buf);
2267 return FALSE;
2270 buf = tmp;
2271 memcpy(buf + bufsize, prop_data, prop_size + 1);
2272 bufsize += prop_size;
2273 HeapFree(GetProcessHeap(), 0, prop_data);
2277 return TRUE;
2281 /**************************************************************************
2282 * CLIPBOARD_SerializeMetafile
2284 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
2286 HANDLE h = 0;
2288 TRACE(" wFormat=%d hdata=%p out=%d\n", wformat, hdata, out);
2290 if (out) /* Serialize out, caller should free memory */
2292 *lpcbytes = 0; /* Assume failure */
2294 if (wformat == CF_METAFILEPICT)
2296 LPMETAFILEPICT lpmfp = GlobalLock(hdata);
2297 unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2299 h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
2300 if (h)
2302 char *pdata = GlobalLock(h);
2304 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
2305 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
2307 *lpcbytes = size + sizeof(METAFILEPICT);
2309 GlobalUnlock(h);
2312 GlobalUnlock(hdata);
2314 else if (wformat == CF_ENHMETAFILE)
2316 int size = GetEnhMetaFileBits(hdata, 0, NULL);
2318 h = GlobalAlloc(0, size);
2319 if (h)
2321 LPVOID pdata = GlobalLock(h);
2323 GetEnhMetaFileBits(hdata, size, pdata);
2324 *lpcbytes = size;
2326 GlobalUnlock(h);
2330 else
2332 if (wformat == CF_METAFILEPICT)
2334 h = GlobalAlloc(0, sizeof(METAFILEPICT));
2335 if (h)
2337 unsigned int wiresize, size;
2338 LPMETAFILEPICT lpmfp = GlobalLock(h);
2340 memcpy(lpmfp, hdata, sizeof(METAFILEPICT));
2341 wiresize = *lpcbytes - sizeof(METAFILEPICT);
2342 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
2343 ((const BYTE *)hdata) + sizeof(METAFILEPICT));
2344 size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2345 GlobalUnlock(h);
2348 else if (wformat == CF_ENHMETAFILE)
2350 h = SetEnhMetaFileBits(*lpcbytes, hdata);
2354 return h;
2358 /**************************************************************************
2359 * X11DRV_CLIPBOARD_ReleaseSelection
2361 * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
2363 static void X11DRV_CLIPBOARD_ReleaseSelection(Display *display, Atom selType, Window w, HWND hwnd, Time time)
2365 /* w is the window that lost the selection
2367 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
2368 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
2370 if (selectionAcquired && (w == selectionWindow))
2372 CLIPBOARDINFO cbinfo;
2374 /* completely give up the selection */
2375 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
2377 X11DRV_CLIPBOARD_GetClipboardInfo(&cbinfo);
2379 if (cbinfo.flags & CB_PROCESS)
2381 /* Since we're still the owner, this wasn't initiated by
2382 another Wine process */
2383 if (OpenClipboard(hwnd))
2385 /* Destroy private objects */
2386 SendMessageW(cbinfo.hWndOwner, WM_DESTROYCLIPBOARD, 0, 0);
2388 /* Give up ownership of the windows clipboard */
2389 X11DRV_CLIPBOARD_ReleaseOwnership();
2390 CloseClipboard();
2394 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2396 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2398 wine_tsx11_lock();
2399 if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2401 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2402 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2404 else
2405 TRACE("We no longer own PRIMARY\n");
2406 wine_tsx11_unlock();
2408 else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2410 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2412 wine_tsx11_lock();
2413 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2415 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2416 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2418 else
2419 TRACE("We no longer own CLIPBOARD\n");
2420 wine_tsx11_unlock();
2423 selectionWindow = None;
2425 X11DRV_EmptyClipboard(FALSE);
2427 /* Reset the selection flags now that we are done */
2428 selectionAcquired = S_NOSELECTION;
2433 /**************************************************************************
2434 * IsSelectionOwner (X11DRV.@)
2436 * Returns: TRUE if the selection is owned by this process, FALSE otherwise
2438 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void)
2440 return selectionAcquired;
2444 /**************************************************************************
2445 * X11DRV Clipboard Exports
2446 **************************************************************************/
2449 /**************************************************************************
2450 * RegisterClipboardFormat (X11DRV.@)
2452 * Registers a custom X clipboard format
2453 * Returns: Format id or 0 on failure
2455 UINT CDECL X11DRV_RegisterClipboardFormat(LPCWSTR FormatName)
2457 LPWINE_CLIPFORMAT lpFormat;
2459 if (FormatName == NULL) return 0;
2460 if (!(lpFormat = register_format( FormatName, 0 ))) return 0;
2461 return lpFormat->wFormatID;
2465 /**************************************************************************
2466 * X11DRV_GetClipboardFormatName
2468 INT CDECL X11DRV_GetClipboardFormatName(UINT wFormat, LPWSTR retStr, INT maxlen)
2470 LPWINE_CLIPFORMAT lpFormat;
2472 TRACE("(%04X, %p, %d) !\n", wFormat, retStr, maxlen);
2474 if (wFormat < 0xc000)
2476 SetLastError(ERROR_INVALID_PARAMETER);
2477 return 0;
2480 lpFormat = X11DRV_CLIPBOARD_LookupFormat(wFormat);
2482 if (!lpFormat || (lpFormat->wFlags & CF_FLAG_BUILTINFMT))
2484 TRACE("Unknown format 0x%08x!\n", wFormat);
2485 SetLastError(ERROR_INVALID_HANDLE);
2486 return 0;
2489 lstrcpynW(retStr, lpFormat->Name, maxlen);
2491 return strlenW(retStr);
2495 /**************************************************************************
2496 * AcquireClipboard (X11DRV.@)
2498 int CDECL X11DRV_AcquireClipboard(HWND hWndClipWindow)
2500 DWORD procid;
2501 Window owner;
2502 Display *display;
2504 TRACE(" %p\n", hWndClipWindow);
2507 * It's important that the selection get acquired from the thread
2508 * that owns the clipboard window. The primary reason is that we know
2509 * it is running a message loop and therefore can process the
2510 * X selection events.
2512 if (hWndClipWindow &&
2513 GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, &procid))
2515 if (procid != GetCurrentProcessId())
2517 WARN("Setting clipboard owner to other process is not supported\n");
2518 hWndClipWindow = NULL;
2520 else
2522 TRACE("Thread %x is acquiring selection with thread %x's window %p\n",
2523 GetCurrentThreadId(),
2524 GetWindowThreadProcessId(hWndClipWindow, NULL), hWndClipWindow);
2526 return SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0);
2530 owner = thread_selection_wnd();
2531 display = thread_display();
2533 wine_tsx11_lock();
2535 selectionAcquired = 0;
2536 selectionWindow = 0;
2538 /* Grab PRIMARY selection if not owned */
2539 if (use_primary_selection)
2540 XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2542 /* Grab CLIPBOARD selection if not owned */
2543 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2545 if (use_primary_selection && XGetSelectionOwner(display, XA_PRIMARY) == owner)
2546 selectionAcquired |= S_PRIMARY;
2548 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2549 selectionAcquired |= S_CLIPBOARD;
2551 wine_tsx11_unlock();
2553 if (selectionAcquired)
2555 selectionWindow = owner;
2556 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2559 return 1;
2563 /**************************************************************************
2564 * X11DRV_EmptyClipboard
2566 * Empty cached clipboard data.
2568 void CDECL X11DRV_EmptyClipboard(BOOL keepunowned)
2570 if (ClipData)
2572 LPWINE_CLIPDATA lpData, lpStart;
2573 LPWINE_CLIPDATA lpNext = ClipData;
2575 TRACE(" called with %d entries in cache.\n", ClipDataCount);
2579 lpStart = ClipData;
2580 lpData = lpNext;
2581 lpNext = lpData->NextData;
2583 if (!keepunowned || !(lpData->wFlags & CF_FLAG_UNOWNED))
2585 lpData->PrevData->NextData = lpData->NextData;
2586 lpData->NextData->PrevData = lpData->PrevData;
2588 if (lpData == ClipData)
2589 ClipData = lpNext != lpData ? lpNext : NULL;
2591 X11DRV_CLIPBOARD_FreeData(lpData);
2592 HeapFree(GetProcessHeap(), 0, lpData);
2594 ClipDataCount--;
2596 } while (lpNext != lpStart);
2599 TRACE(" %d entries remaining in cache.\n", ClipDataCount);
2604 /**************************************************************************
2605 * X11DRV_SetClipboardData
2607 BOOL CDECL X11DRV_SetClipboardData(UINT wFormat, HANDLE16 hData16, HANDLE hData32, BOOL owner)
2609 DWORD flags = 0;
2610 BOOL bResult = TRUE;
2612 /* If it's not owned, data can only be set if the format data is not already owned
2613 and its rendering is not delayed */
2614 if (!owner)
2616 CLIPBOARDINFO cbinfo;
2617 LPWINE_CLIPDATA lpRender;
2619 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2621 if ((!hData16 && !hData32) ||
2622 ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)) &&
2623 !(lpRender->wFlags & CF_FLAG_UNOWNED)))
2624 bResult = FALSE;
2625 else
2626 flags = CF_FLAG_UNOWNED;
2629 bResult &= X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData16, hData32, flags, NULL, TRUE);
2631 return bResult;
2635 /**************************************************************************
2636 * CountClipboardFormats
2638 INT CDECL X11DRV_CountClipboardFormats(void)
2640 CLIPBOARDINFO cbinfo;
2642 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2644 TRACE(" count=%d\n", ClipDataCount);
2646 return ClipDataCount;
2650 /**************************************************************************
2651 * X11DRV_EnumClipboardFormats
2653 UINT CDECL X11DRV_EnumClipboardFormats(UINT wFormat)
2655 CLIPBOARDINFO cbinfo;
2656 UINT wNextFormat = 0;
2658 TRACE("(%04X)\n", wFormat);
2660 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2662 if (!wFormat)
2664 if (ClipData)
2665 wNextFormat = ClipData->wFormatID;
2667 else
2669 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
2671 if (lpData && lpData->NextData != ClipData)
2672 wNextFormat = lpData->NextData->wFormatID;
2675 return wNextFormat;
2679 /**************************************************************************
2680 * X11DRV_IsClipboardFormatAvailable
2682 BOOL CDECL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
2684 BOOL bRet = FALSE;
2685 CLIPBOARDINFO cbinfo;
2687 TRACE("(%04X)\n", wFormat);
2689 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2691 if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
2692 bRet = TRUE;
2694 TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
2696 return bRet;
2700 /**************************************************************************
2701 * GetClipboardData (USER.142)
2703 BOOL CDECL X11DRV_GetClipboardData(UINT wFormat, HANDLE16* phData16, HANDLE* phData32)
2705 CLIPBOARDINFO cbinfo;
2706 LPWINE_CLIPDATA lpRender;
2708 TRACE("(%04X)\n", wFormat);
2710 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2712 if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
2714 if ( !lpRender->hData32 )
2715 X11DRV_CLIPBOARD_RenderFormat(thread_init_display(), lpRender);
2717 /* Convert between 32 -> 16 bit data, if necessary */
2718 if (lpRender->hData32 && !lpRender->hData16)
2720 int size;
2722 if (lpRender->wFormatID == CF_METAFILEPICT)
2723 size = sizeof(METAFILEPICT16);
2724 else
2725 size = GlobalSize(lpRender->hData32);
2727 lpRender->hData16 = GlobalAlloc16(GMEM_ZEROINIT, size);
2729 if (!lpRender->hData16)
2730 ERR("(%04X) -- not enough memory in 16b heap\n", wFormat);
2731 else
2733 if (lpRender->wFormatID == CF_METAFILEPICT)
2735 FIXME("\timplement function CopyMetaFilePict32to16\n");
2736 FIXME("\tin the appropriate file.\n");
2737 #ifdef SOMEONE_IMPLEMENTED_ME
2738 CopyMetaFilePict32to16(GlobalLock16(lpRender->hData16),
2739 GlobalLock(lpRender->hData32));
2740 #endif
2742 else
2744 memcpy(GlobalLock16(lpRender->hData16),
2745 GlobalLock(lpRender->hData32), size);
2748 GlobalUnlock16(lpRender->hData16);
2749 GlobalUnlock(lpRender->hData32);
2753 /* Convert between 32 -> 16 bit data, if necessary */
2754 if (lpRender->hData16 && !lpRender->hData32)
2756 int size;
2758 if (lpRender->wFormatID == CF_METAFILEPICT)
2759 size = sizeof(METAFILEPICT16);
2760 else
2761 size = GlobalSize(lpRender->hData32);
2763 lpRender->hData32 = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
2764 GMEM_DDESHARE, size);
2766 if (lpRender->wFormatID == CF_METAFILEPICT)
2768 FIXME("\timplement function CopyMetaFilePict16to32\n");
2769 FIXME("\tin the appropriate file.\n");
2770 #ifdef SOMEONE_IMPLEMENTED_ME
2771 CopyMetaFilePict16to32(GlobalLock16(lpRender->hData32),
2772 GlobalLock(lpRender->hData16));
2773 #endif
2775 else
2777 memcpy(GlobalLock(lpRender->hData32),
2778 GlobalLock16(lpRender->hData16), size);
2781 GlobalUnlock(lpRender->hData32);
2782 GlobalUnlock16(lpRender->hData16);
2785 if (phData16)
2786 *phData16 = lpRender->hData16;
2788 if (phData32)
2789 *phData32 = lpRender->hData32;
2791 TRACE(" returning hData16(%04x) hData32(%p) (type %04x)\n",
2792 lpRender->hData16, lpRender->hData32, lpRender->wFormatID);
2794 return lpRender->hData16 || lpRender->hData32;
2797 return 0;
2801 /**************************************************************************
2802 * ResetSelectionOwner
2804 * Called when the thread owning the selection is destroyed and we need to
2805 * preserve the selection ownership. We look for another top level window
2806 * in this process and send it a message to acquire the selection.
2808 void X11DRV_ResetSelectionOwner(void)
2810 HWND hwnd;
2811 DWORD procid;
2813 TRACE("\n");
2815 if (!selectionAcquired || thread_selection_wnd() != selectionWindow)
2816 return;
2818 selectionAcquired = S_NOSELECTION;
2819 selectionWindow = 0;
2821 hwnd = GetWindow(GetDesktopWindow(), GW_CHILD);
2824 if (GetCurrentThreadId() != GetWindowThreadProcessId(hwnd, &procid))
2826 if (GetCurrentProcessId() == procid)
2828 if (SendMessageW(hwnd, WM_X11DRV_ACQUIRE_SELECTION, 0, 0))
2829 return;
2832 } while ((hwnd = GetWindow(hwnd, GW_HWNDNEXT)) != NULL);
2834 WARN("Failed to find another thread to take selection ownership. Clipboard data will be lost.\n");
2836 X11DRV_CLIPBOARD_ReleaseOwnership();
2837 X11DRV_EmptyClipboard(FALSE);
2841 /**************************************************************************
2842 * X11DRV_CLIPBOARD_SynthesizeData
2844 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID)
2846 BOOL bsyn = TRUE;
2847 LPWINE_CLIPDATA lpSource = NULL;
2849 TRACE(" %04x\n", wFormatID);
2851 /* Don't need to synthesize if it already exists */
2852 if (X11DRV_CLIPBOARD_LookupData(wFormatID))
2853 return TRUE;
2855 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
2857 bsyn = ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
2858 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2859 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
2860 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2861 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
2862 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED);
2864 else if (wFormatID == CF_ENHMETAFILE)
2866 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2867 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2869 else if (wFormatID == CF_METAFILEPICT)
2871 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_ENHMETAFILE)) &&
2872 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2874 else if (wFormatID == CF_DIB)
2876 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
2877 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2879 else if (wFormatID == CF_BITMAP)
2881 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
2882 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2885 if (bsyn)
2886 X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, 0, CF_FLAG_SYNTHESIZED, NULL, TRUE);
2888 return bsyn;
2893 /**************************************************************************
2894 * X11DRV_EndClipboardUpdate
2895 * TODO:
2896 * Add locale if it hasn't already been added
2898 void CDECL X11DRV_EndClipboardUpdate(void)
2900 INT count = ClipDataCount;
2902 /* Do Unicode <-> Text <-> OEM mapping */
2903 X11DRV_CLIPBOARD_SynthesizeData(CF_TEXT);
2904 X11DRV_CLIPBOARD_SynthesizeData(CF_OEMTEXT);
2905 X11DRV_CLIPBOARD_SynthesizeData(CF_UNICODETEXT);
2907 /* Enhmetafile <-> MetafilePict mapping */
2908 X11DRV_CLIPBOARD_SynthesizeData(CF_ENHMETAFILE);
2909 X11DRV_CLIPBOARD_SynthesizeData(CF_METAFILEPICT);
2911 /* DIB <-> Bitmap mapping */
2912 X11DRV_CLIPBOARD_SynthesizeData(CF_DIB);
2913 X11DRV_CLIPBOARD_SynthesizeData(CF_BITMAP);
2915 TRACE("%d formats added to cached data\n", ClipDataCount - count);
2919 /***********************************************************************
2920 * X11DRV_SelectionRequest_TARGETS
2921 * Service a TARGETS selection request event
2923 static Atom X11DRV_SelectionRequest_TARGETS( Display *display, Window requestor,
2924 Atom target, Atom rprop )
2926 UINT i;
2927 Atom* targets;
2928 ULONG cTargets;
2929 LPWINE_CLIPFORMAT lpFormats;
2930 LPWINE_CLIPDATA lpData;
2932 /* Create X atoms for any clipboard types which don't have atoms yet.
2933 * This avoids sending bogus zero atoms.
2934 * Without this, copying might not have access to all clipboard types.
2935 * FIXME: is it safe to call this here?
2937 intern_atoms();
2940 * Count the number of items we wish to expose as selection targets.
2942 cTargets = 1; /* Include TARGETS */
2944 if (!(lpData = ClipData)) return None;
2948 lpFormats = ClipFormats;
2950 while (lpFormats)
2952 if ((lpFormats->wFormatID == lpData->wFormatID) &&
2953 lpFormats->lpDrvExportFunc && lpFormats->drvData)
2954 cTargets++;
2956 lpFormats = lpFormats->NextFormat;
2959 lpData = lpData->NextData;
2961 while (lpData != ClipData);
2963 TRACE(" found %d formats\n", cTargets);
2965 /* Allocate temp buffer */
2966 targets = HeapAlloc( GetProcessHeap(), 0, cTargets * sizeof(Atom));
2967 if(targets == NULL)
2968 return None;
2970 i = 0;
2971 lpData = ClipData;
2972 targets[i++] = x11drv_atom(TARGETS);
2976 lpFormats = ClipFormats;
2978 while (lpFormats)
2980 if ((lpFormats->wFormatID == lpData->wFormatID) &&
2981 lpFormats->lpDrvExportFunc && lpFormats->drvData)
2982 targets[i++] = lpFormats->drvData;
2984 lpFormats = lpFormats->NextFormat;
2987 lpData = lpData->NextData;
2989 while (lpData != ClipData);
2991 wine_tsx11_lock();
2993 if (TRACE_ON(clipboard))
2995 unsigned int i;
2996 for ( i = 0; i < cTargets; i++)
2998 char *itemFmtName = XGetAtomName(display, targets[i]);
2999 TRACE("\tAtom# %d: Property %ld Type %s\n", i, targets[i], itemFmtName);
3000 XFree(itemFmtName);
3004 /* We may want to consider setting the type to xaTargets instead,
3005 * in case some apps expect this instead of XA_ATOM */
3006 XChangeProperty(display, requestor, rprop, XA_ATOM, 32,
3007 PropModeReplace, (unsigned char *)targets, cTargets);
3008 wine_tsx11_unlock();
3010 HeapFree(GetProcessHeap(), 0, targets);
3012 return rprop;
3016 /***********************************************************************
3017 * X11DRV_SelectionRequest_MULTIPLE
3018 * Service a MULTIPLE selection request event
3019 * rprop contains a list of (target,property) atom pairs.
3020 * The first atom names a target and the second names a property.
3021 * The effect is as if we have received a sequence of SelectionRequest events
3022 * (one for each atom pair) except that:
3023 * 1. We reply with a SelectionNotify only when all the requested conversions
3024 * have been performed.
3025 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
3026 * we replace the atom in the property by None.
3028 static Atom X11DRV_SelectionRequest_MULTIPLE( HWND hWnd, XSelectionRequestEvent *pevent )
3030 Display *display = pevent->display;
3031 Atom rprop;
3032 Atom atype=AnyPropertyType;
3033 int aformat;
3034 unsigned long remain;
3035 Atom* targetPropList=NULL;
3036 unsigned long cTargetPropList = 0;
3038 /* If the specified property is None the requestor is an obsolete client.
3039 * We support these by using the specified target atom as the reply property.
3041 rprop = pevent->property;
3042 if( rprop == None )
3043 rprop = pevent->target;
3044 if (!rprop)
3045 return 0;
3047 /* Read the MULTIPLE property contents. This should contain a list of
3048 * (target,property) atom pairs.
3050 wine_tsx11_lock();
3051 if(XGetWindowProperty(display, pevent->requestor, rprop,
3052 0, 0x3FFF, False, AnyPropertyType, &atype,&aformat,
3053 &cTargetPropList, &remain,
3054 (unsigned char**)&targetPropList) != Success)
3056 wine_tsx11_unlock();
3057 TRACE("\tCouldn't read MULTIPLE property\n");
3059 else
3061 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
3062 XGetAtomName(display, atype), aformat, cTargetPropList, remain);
3063 wine_tsx11_unlock();
3066 * Make sure we got what we expect.
3067 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
3068 * in a MULTIPLE selection request should be of type ATOM_PAIR.
3069 * However some X apps(such as XPaint) are not compliant with this and return
3070 * a user defined atom in atype when XGetWindowProperty is called.
3071 * The data *is* an atom pair but is not denoted as such.
3073 if(aformat == 32 /* atype == xAtomPair */ )
3075 unsigned int i;
3077 /* Iterate through the ATOM_PAIR list and execute a SelectionRequest
3078 * for each (target,property) pair */
3080 for (i = 0; i < cTargetPropList; i+=2)
3082 XSelectionRequestEvent event;
3084 if (TRACE_ON(clipboard))
3086 char *targetName, *propName;
3087 wine_tsx11_lock();
3088 targetName = XGetAtomName(display, targetPropList[i]);
3089 propName = XGetAtomName(display, targetPropList[i+1]);
3090 TRACE("MULTIPLE(%d): Target='%s' Prop='%s'\n",
3091 i/2, targetName, propName);
3092 XFree(targetName);
3093 XFree(propName);
3094 wine_tsx11_unlock();
3097 /* We must have a non "None" property to service a MULTIPLE target atom */
3098 if ( !targetPropList[i+1] )
3100 TRACE("\tMULTIPLE(%d): Skipping target with empty property!\n", i);
3101 continue;
3104 /* Set up an XSelectionRequestEvent for this (target,property) pair */
3105 event = *pevent;
3106 event.target = targetPropList[i];
3107 event.property = targetPropList[i+1];
3109 /* Fire a SelectionRequest, informing the handler that we are processing
3110 * a MULTIPLE selection request event.
3112 X11DRV_HandleSelectionRequest( hWnd, &event, TRUE );
3116 /* Free the list of targets/properties */
3117 wine_tsx11_lock();
3118 XFree(targetPropList);
3119 wine_tsx11_unlock();
3122 return rprop;
3126 /***********************************************************************
3127 * X11DRV_HandleSelectionRequest
3128 * Process an event selection request event.
3129 * The bIsMultiple flag is used to signal when EVENT_SelectionRequest is called
3130 * recursively while servicing a "MULTIPLE" selection target.
3132 * Note: We only receive this event when WINE owns the X selection
3134 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple )
3136 Display *display = event->display;
3137 XSelectionEvent result;
3138 Atom rprop = None;
3139 Window request = event->requestor;
3141 TRACE("\n");
3144 * We can only handle the selection request if :
3145 * The selection is PRIMARY or CLIPBOARD, AND we can successfully open the clipboard.
3146 * Don't do these checks or open the clipboard while recursively processing MULTIPLE,
3147 * since this has been already done.
3149 if ( !bIsMultiple )
3151 if (((event->selection != XA_PRIMARY) && (event->selection != x11drv_atom(CLIPBOARD))))
3152 goto END;
3155 /* If the specified property is None the requestor is an obsolete client.
3156 * We support these by using the specified target atom as the reply property.
3158 rprop = event->property;
3159 if( rprop == None )
3160 rprop = event->target;
3162 if(event->target == x11drv_atom(TARGETS)) /* Return a list of all supported targets */
3164 /* TARGETS selection request */
3165 rprop = X11DRV_SelectionRequest_TARGETS( display, request, event->target, rprop );
3167 else if(event->target == x11drv_atom(MULTIPLE)) /* rprop contains a list of (target, property) atom pairs */
3169 /* MULTIPLE selection request */
3170 rprop = X11DRV_SelectionRequest_MULTIPLE( hWnd, event );
3172 else
3174 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, event->target);
3176 if (lpFormat && lpFormat->lpDrvExportFunc)
3178 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(lpFormat->wFormatID);
3180 if (lpData)
3182 unsigned char* lpClipData;
3183 DWORD cBytes;
3184 HANDLE hClipData = lpFormat->lpDrvExportFunc(display, request, event->target,
3185 rprop, lpData, &cBytes);
3187 if (hClipData && (lpClipData = GlobalLock(hClipData)))
3189 TRACE("\tUpdating property %s, %d bytes\n", debugstr_w(lpFormat->Name), cBytes);
3191 wine_tsx11_lock();
3192 XChangeProperty(display, request, rprop, event->target,
3193 8, PropModeReplace, lpClipData, cBytes);
3194 wine_tsx11_unlock();
3196 GlobalUnlock(hClipData);
3197 GlobalFree(hClipData);
3203 END:
3204 /* reply to sender
3205 * SelectionNotify should be sent only at the end of a MULTIPLE request
3207 if ( !bIsMultiple )
3209 result.type = SelectionNotify;
3210 result.display = display;
3211 result.requestor = request;
3212 result.selection = event->selection;
3213 result.property = rprop;
3214 result.target = event->target;
3215 result.time = event->time;
3216 TRACE("Sending SelectionNotify event...\n");
3217 wine_tsx11_lock();
3218 XSendEvent(display,event->requestor,False,NoEventMask,(XEvent*)&result);
3219 wine_tsx11_unlock();
3224 /***********************************************************************
3225 * X11DRV_SelectionRequest
3227 void X11DRV_SelectionRequest( HWND hWnd, XEvent *event )
3229 X11DRV_HandleSelectionRequest( hWnd, &event->xselectionrequest, FALSE );
3233 /***********************************************************************
3234 * X11DRV_SelectionClear
3236 void X11DRV_SelectionClear( HWND hWnd, XEvent *xev )
3238 XSelectionClearEvent *event = &xev->xselectionclear;
3239 if (event->selection == XA_PRIMARY || event->selection == x11drv_atom(CLIPBOARD))
3240 X11DRV_CLIPBOARD_ReleaseSelection( event->display, event->selection,
3241 event->window, hWnd, event->time );