winex11: Don't try to free custom GDI formats at all.
[wine.git] / dlls / winex11.drv / clipboard.c
blob5424c535b9df41fa79ae93bcc99788d7125409ba
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
8 * 2014 Damjan Jovanovic
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 * NOTES:
25 * This file contains the X specific implementation for the windows
26 * Clipboard API.
28 * Wine's internal clipboard is exposed to external apps via the X
29 * selection mechanism.
30 * Currently the driver asserts ownership via two selection atoms:
31 * 1. PRIMARY(XA_PRIMARY)
32 * 2. CLIPBOARD
34 * In our implementation, the CLIPBOARD selection takes precedence over PRIMARY,
35 * i.e. if a CLIPBOARD selection is available, it is used instead of PRIMARY.
36 * When Wine takes ownership of the clipboard, it takes ownership of BOTH selections.
37 * While giving up selection ownership, if the CLIPBOARD selection is lost,
38 * it will lose both PRIMARY and CLIPBOARD and empty the clipboard.
39 * However if only PRIMARY is lost, it will continue to hold the CLIPBOARD selection
40 * (leaving the clipboard cache content unaffected).
42 * Every format exposed via a windows clipboard format is also exposed through
43 * a corresponding X selection target. A selection target atom is synthesized
44 * whenever a new Windows clipboard format is registered via RegisterClipboardFormat,
45 * or when a built-in format is used for the first time.
46 * Windows native format are exposed by prefixing the format name with "<WCF>"
47 * This allows us to uniquely identify windows native formats exposed by other
48 * running WINE apps.
50 * In order to allow external applications to query WINE for supported formats,
51 * we respond to the "TARGETS" selection target. (See EVENT_SelectionRequest
52 * for implementation) We use the same mechanism to query external clients for
53 * availability of a particular format, by caching the list of available targets
54 * by using the clipboard cache's "delayed render" mechanism. If a selection client
55 * does not support the "TARGETS" selection target, we actually attempt to retrieve
56 * the format requested as a fallback mechanism.
58 * Certain Windows native formats are automatically converted to X native formats
59 * and vice versa. If a native format is available in the selection, it takes
60 * precedence, in order to avoid unnecessary conversions.
62 * FIXME: global format list needs a critical section
65 #include "config.h"
66 #include "wine/port.h"
68 #include <string.h>
69 #include <stdarg.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #ifdef HAVE_UNISTD_H
73 # include <unistd.h>
74 #endif
75 #include <fcntl.h>
76 #include <limits.h>
77 #include <time.h>
78 #include <assert.h>
80 #include "windef.h"
81 #include "winbase.h"
82 #include "shlobj.h"
83 #include "shellapi.h"
84 #include "shlwapi.h"
85 #include "x11drv.h"
86 #include "wine/list.h"
87 #include "wine/debug.h"
88 #include "wine/unicode.h"
89 #include "wine/server.h"
91 WINE_DEFAULT_DEBUG_CHANNEL(clipboard);
93 /* Maximum wait time for selection notify */
94 #define SELECTION_RETRIES 500 /* wait for .5 seconds */
95 #define SELECTION_WAIT 1000 /* us */
97 /* Selection masks */
98 #define S_NOSELECTION 0
99 #define S_PRIMARY 1
100 #define S_CLIPBOARD 2
102 struct tagWINE_CLIPDATA; /* Forward */
104 typedef HANDLE (*DRVEXPORTFUNC)(Display *display, Window requestor, Atom aTarget, Atom rprop,
105 struct tagWINE_CLIPDATA* lpData, LPDWORD lpBytes);
106 typedef HANDLE (*DRVIMPORTFUNC)(Display *d, Window w, Atom prop);
108 typedef struct tagWINE_CLIPFORMAT {
109 struct list entry;
110 UINT wFormatID;
111 UINT drvData;
112 DRVIMPORTFUNC lpDrvImportFunc;
113 DRVEXPORTFUNC lpDrvExportFunc;
114 } WINE_CLIPFORMAT, *LPWINE_CLIPFORMAT;
116 typedef struct tagWINE_CLIPDATA {
117 struct list entry;
118 UINT wFormatID;
119 HANDLE hData;
120 UINT wFlags;
121 UINT drvData;
122 LPWINE_CLIPFORMAT lpFormat;
123 } WINE_CLIPDATA, *LPWINE_CLIPDATA;
125 #define CF_FLAG_UNOWNED 0x0001 /* cached data is not owned */
126 #define CF_FLAG_SYNTHESIZED 0x0002 /* Implicitly converted data */
128 static int selectionAcquired = 0; /* Contains the current selection masks */
129 static Window selectionWindow = None; /* The top level X window which owns the selection */
130 static Atom selectionCacheSrc = XA_PRIMARY; /* The selection source from which the clipboard cache was filled */
132 void CDECL X11DRV_EndClipboardUpdate(void);
133 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *d, Window w, Atom prop);
134 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *d, Window w, Atom prop);
135 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *d, Window w, Atom prop);
136 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *d, Window w, Atom prop);
137 static HANDLE X11DRV_CLIPBOARD_ImportImageBmp(Display *d, Window w, Atom prop);
138 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *d, Window w, Atom prop);
139 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *d, Window w, Atom prop);
140 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *d, Window w, Atom prop);
141 static HANDLE X11DRV_CLIPBOARD_ImportTextUriList(Display *display, Window w, Atom prop);
142 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
143 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
144 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget,
145 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
146 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget,
147 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
148 static HANDLE X11DRV_CLIPBOARD_ExportImageBmp(Display *display, Window requestor, Atom aTarget,
149 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
150 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget,
151 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
152 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget,
153 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
154 static HANDLE X11DRV_CLIPBOARD_ExportTextHtml(Display *display, Window requestor, Atom aTarget,
155 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
156 static HANDLE X11DRV_CLIPBOARD_ExportHDROP(Display *display, Window requestor, Atom aTarget,
157 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
158 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(UINT id, Atom prop);
159 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID);
160 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData);
161 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display);
162 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData);
163 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
164 unsigned char** data, unsigned long* datasize);
165 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData);
166 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out);
167 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID);
168 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData);
169 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display);
170 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display);
171 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile(Display *display);
172 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple );
173 static void empty_clipboard( BOOL keepunowned );
175 /* Clipboard formats */
177 static const struct
179 UINT id;
180 UINT data;
181 DRVIMPORTFUNC import;
182 DRVEXPORTFUNC export;
183 } builtin_formats[] =
185 { CF_TEXT, XA_STRING, X11DRV_CLIPBOARD_ImportXAString, X11DRV_CLIPBOARD_ExportString},
186 { CF_TEXT, XATOM_text_plain, X11DRV_CLIPBOARD_ImportXAString, X11DRV_CLIPBOARD_ExportString},
187 { CF_BITMAP, XATOM_WCF_BITMAP, X11DRV_CLIPBOARD_ImportClipboardData, NULL},
188 { CF_METAFILEPICT, XATOM_WCF_METAFILEPICT, X11DRV_CLIPBOARD_ImportMetaFilePict, X11DRV_CLIPBOARD_ExportMetaFilePict },
189 { CF_SYLK, XATOM_WCF_SYLK, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
190 { CF_DIF, XATOM_WCF_DIF, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
191 { CF_TIFF, XATOM_WCF_TIFF, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
192 { CF_OEMTEXT, XATOM_WCF_OEMTEXT, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
193 { CF_DIB, XA_PIXMAP, X11DRV_CLIPBOARD_ImportXAPIXMAP, X11DRV_CLIPBOARD_ExportXAPIXMAP },
194 { CF_PALETTE, XATOM_WCF_PALETTE, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
195 { CF_PENDATA, XATOM_WCF_PENDATA, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
196 { CF_RIFF, XATOM_WCF_RIFF, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
197 { CF_WAVE, XATOM_WCF_WAVE, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
198 { CF_UNICODETEXT, XATOM_UTF8_STRING, X11DRV_CLIPBOARD_ImportUTF8, X11DRV_CLIPBOARD_ExportString },
199 /* If UTF8_STRING is not available, attempt COMPOUND_TEXT */
200 { CF_UNICODETEXT, XATOM_COMPOUND_TEXT, X11DRV_CLIPBOARD_ImportCompoundText, X11DRV_CLIPBOARD_ExportString },
201 { CF_ENHMETAFILE, XATOM_WCF_ENHMETAFILE, X11DRV_CLIPBOARD_ImportEnhMetaFile, X11DRV_CLIPBOARD_ExportEnhMetaFile },
202 { CF_HDROP, XATOM_text_uri_list, X11DRV_CLIPBOARD_ImportTextUriList, X11DRV_CLIPBOARD_ExportHDROP },
203 { CF_LOCALE, XATOM_WCF_LOCALE, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
204 { CF_DIBV5, XATOM_WCF_DIBV5, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
205 { CF_OWNERDISPLAY, XATOM_WCF_OWNERDISPLAY, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
206 { CF_DSPTEXT, XATOM_WCF_DSPTEXT, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
207 { CF_DSPBITMAP, XATOM_WCF_DSPBITMAP, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
208 { CF_DSPMETAFILEPICT, XATOM_WCF_DSPMETAFILEPICT, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
209 { CF_DSPENHMETAFILE, XATOM_WCF_DSPENHMETAFILE, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
210 { CF_DIB, XATOM_image_bmp, X11DRV_CLIPBOARD_ImportImageBmp, X11DRV_CLIPBOARD_ExportImageBmp },
213 static struct list format_list = LIST_INIT( format_list );
215 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
217 /* Maps X properties to Windows formats */
218 static const WCHAR wszRichTextFormat[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
219 static const WCHAR wszGIF[] = {'G','I','F',0};
220 static const WCHAR wszJFIF[] = {'J','F','I','F',0};
221 static const WCHAR wszPNG[] = {'P','N','G',0};
222 static const WCHAR wszHTMLFormat[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
223 static const struct
225 LPCWSTR lpszFormat;
226 UINT prop;
227 } PropertyFormatMap[] =
229 { wszRichTextFormat, XATOM_text_rtf },
230 { wszRichTextFormat, XATOM_text_richtext },
231 { wszGIF, XATOM_image_gif },
232 { wszJFIF, XATOM_image_jpeg },
233 { wszPNG, XATOM_image_png },
234 { wszHTMLFormat, XATOM_HTML_Format }, /* prefer this to text/html */
239 * Cached clipboard data.
241 static struct list data_list = LIST_INIT( data_list );
242 static UINT ClipDataCount = 0;
245 * Clipboard sequence number
247 static UINT wSeqNo = 0;
249 /**************************************************************************
250 * Internal Clipboard implementation methods
251 **************************************************************************/
253 static Window thread_selection_wnd(void)
255 struct x11drv_thread_data *thread_data = x11drv_init_thread_data();
256 Window w = thread_data->selection_wnd;
258 if (!w)
260 w = XCreateWindow(thread_data->display, root_window, 0, 0, 1, 1, 0, CopyFromParent,
261 InputOnly, CopyFromParent, 0, NULL);
262 if (w)
264 thread_data->selection_wnd = w;
266 XSelectInput(thread_data->display, w, PropertyChangeMask);
268 else
269 FIXME("Failed to create window. Fetching selection data will fail.\n");
272 return w;
275 static const char *debugstr_format( UINT id )
277 WCHAR buffer[256];
279 if (GetClipboardFormatNameW( id, buffer, 256 ))
280 return wine_dbg_sprintf( "%04x %s", id, debugstr_w(buffer) );
282 switch (id)
284 #define BUILTIN(id) case id: return #id;
285 BUILTIN(CF_TEXT)
286 BUILTIN(CF_BITMAP)
287 BUILTIN(CF_METAFILEPICT)
288 BUILTIN(CF_SYLK)
289 BUILTIN(CF_DIF)
290 BUILTIN(CF_TIFF)
291 BUILTIN(CF_OEMTEXT)
292 BUILTIN(CF_DIB)
293 BUILTIN(CF_PALETTE)
294 BUILTIN(CF_PENDATA)
295 BUILTIN(CF_RIFF)
296 BUILTIN(CF_WAVE)
297 BUILTIN(CF_UNICODETEXT)
298 BUILTIN(CF_ENHMETAFILE)
299 BUILTIN(CF_HDROP)
300 BUILTIN(CF_LOCALE)
301 BUILTIN(CF_DIBV5)
302 BUILTIN(CF_OWNERDISPLAY)
303 BUILTIN(CF_DSPTEXT)
304 BUILTIN(CF_DSPBITMAP)
305 BUILTIN(CF_DSPMETAFILEPICT)
306 BUILTIN(CF_DSPENHMETAFILE)
307 #undef BUILTIN
308 default: return wine_dbg_sprintf( "%04x", id );
312 /**************************************************************************
313 * X11DRV_InitClipboard
315 void X11DRV_InitClipboard(void)
317 UINT i;
318 WINE_CLIPFORMAT *format;
320 /* Register built-in formats */
321 for (i = 0; i < sizeof(builtin_formats)/sizeof(builtin_formats[0]); i++)
323 if (!(format = HeapAlloc( GetProcessHeap(), 0, sizeof(*format )))) break;
324 format->wFormatID = builtin_formats[i].id;
325 format->drvData = GET_ATOM(builtin_formats[i].data);
326 format->lpDrvImportFunc = builtin_formats[i].import;
327 format->lpDrvExportFunc = builtin_formats[i].export;
328 list_add_tail( &format_list, &format->entry );
331 /* Register known mapping between window formats and X properties */
332 for (i = 0; i < sizeof(PropertyFormatMap)/sizeof(PropertyFormatMap[0]); i++)
333 X11DRV_CLIPBOARD_InsertClipboardFormat( RegisterClipboardFormatW(PropertyFormatMap[i].lpszFormat),
334 GET_ATOM(PropertyFormatMap[i].prop));
336 /* Set up a conversion function from "HTML Format" to "text/html" */
337 format = X11DRV_CLIPBOARD_InsertClipboardFormat( RegisterClipboardFormatW(wszHTMLFormat),
338 GET_ATOM(XATOM_text_html));
339 format->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportTextHtml;
343 /**************************************************************************
344 * intern_atoms
346 * Intern atoms for formats that don't have one yet.
348 static void intern_atoms(void)
350 LPWINE_CLIPFORMAT format;
351 int i, count, len;
352 char **names;
353 Atom *atoms;
354 Display *display;
355 WCHAR buffer[256];
357 count = 0;
358 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
359 if (!format->drvData) count++;
360 if (!count) return;
362 display = thread_init_display();
364 names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
365 atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
367 i = 0;
368 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
369 if (!format->drvData) {
370 if (GetClipboardFormatNameW(format->wFormatID, buffer, 256) > 0)
372 /* use defined format name */
373 len = WideCharToMultiByte(CP_UNIXCP, 0, buffer, -1, NULL, 0, NULL, NULL);
375 else
377 /* create a name in the same way as ntdll/atom.c:integral_atom_name
378 * which is normally used by GetClipboardFormatNameW
380 static const WCHAR fmt[] = {'#','%','u',0};
381 len = sprintfW(buffer, fmt, format->wFormatID) + 1;
383 names[i] = HeapAlloc(GetProcessHeap(), 0, len);
384 WideCharToMultiByte(CP_UNIXCP, 0, buffer, -1, names[i++], len, NULL, NULL);
387 XInternAtoms( display, names, count, False, atoms );
389 i = 0;
390 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
391 if (!format->drvData) {
392 HeapFree(GetProcessHeap(), 0, names[i]);
393 format->drvData = atoms[i++];
396 HeapFree( GetProcessHeap(), 0, names );
397 HeapFree( GetProcessHeap(), 0, atoms );
401 /**************************************************************************
402 * register_format
404 * Register a custom X clipboard format.
406 static WINE_CLIPFORMAT *register_format( UINT id, Atom prop )
408 LPWINE_CLIPFORMAT lpFormat;
410 /* walk format chain to see if it's already registered */
411 LIST_FOR_EACH_ENTRY( lpFormat, &format_list, WINE_CLIPFORMAT, entry )
412 if (lpFormat->wFormatID == id) return lpFormat;
414 return X11DRV_CLIPBOARD_InsertClipboardFormat(id, prop);
418 /**************************************************************************
419 * X11DRV_CLIPBOARD_LookupProperty
421 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupProperty(LPWINE_CLIPFORMAT current, UINT drvData)
423 for (;;)
425 struct list *ptr = current ? &current->entry : &format_list;
426 BOOL need_intern = FALSE;
428 while ((ptr = list_next( &format_list, ptr )))
430 LPWINE_CLIPFORMAT lpFormat = LIST_ENTRY( ptr, WINE_CLIPFORMAT, entry );
431 if (lpFormat->drvData == drvData) return lpFormat;
432 if (!lpFormat->drvData) need_intern = TRUE;
434 if (!need_intern) return NULL;
435 intern_atoms();
436 /* restart the search for the new atoms */
441 /**************************************************************************
442 * X11DRV_CLIPBOARD_LookupData
444 static LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
446 WINE_CLIPDATA *data;
448 LIST_FOR_EACH_ENTRY( data, &data_list, WINE_CLIPDATA, entry )
449 if (data->wFormatID == wID) return data;
451 return NULL;
455 /**************************************************************************
456 * InsertClipboardFormat
458 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat( UINT id, Atom prop )
460 LPWINE_CLIPFORMAT lpNewFormat;
462 /* allocate storage for new format entry */
463 lpNewFormat = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPFORMAT));
465 if(lpNewFormat == NULL)
467 WARN("No more memory for a new format!\n");
468 return NULL;
470 lpNewFormat->wFormatID = id;
471 lpNewFormat->drvData = prop;
472 lpNewFormat->lpDrvImportFunc = X11DRV_CLIPBOARD_ImportClipboardData;
473 lpNewFormat->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportClipboardData;
475 list_add_tail( &format_list, &lpNewFormat->entry );
477 TRACE("Registering format %s drvData %d\n",
478 debugstr_format(lpNewFormat->wFormatID), lpNewFormat->drvData);
480 return lpNewFormat;
486 /**************************************************************************
487 * X11DRV_CLIPBOARD_IsProcessOwner
489 static BOOL X11DRV_CLIPBOARD_IsProcessOwner( HWND *owner )
491 BOOL ret = FALSE;
493 SERVER_START_REQ( set_clipboard_info )
495 req->flags = 0;
496 if (!wine_server_call_err( req ))
498 *owner = wine_server_ptr_handle( reply->old_owner );
499 ret = (reply->flags & CB_PROCESS);
502 SERVER_END_REQ;
504 return ret;
508 /**************************************************************************
509 * X11DRV_CLIPBOARD_ReleaseOwnership
511 static BOOL X11DRV_CLIPBOARD_ReleaseOwnership(void)
513 BOOL ret;
515 SERVER_START_REQ( set_clipboard_info )
517 req->flags = SET_CB_RELOWNER | SET_CB_SEQNO;
518 ret = !wine_server_call_err( req );
520 SERVER_END_REQ;
522 return ret;
527 /**************************************************************************
528 * X11DRV_CLIPBOARD_InsertClipboardData
530 * Caller *must* have the clipboard open and be the owner.
532 static BOOL X11DRV_CLIPBOARD_InsertClipboardData(UINT wFormatID, HANDLE hData, DWORD flags,
533 LPWINE_CLIPFORMAT lpFormat, BOOL override)
535 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormatID);
537 TRACE("format=%04x lpData=%p hData=%p flags=0x%08x lpFormat=%p override=%d\n",
538 wFormatID, lpData, hData, flags, lpFormat, override);
540 /* make sure the format exists */
541 if (!lpFormat) register_format( wFormatID, 0 );
543 if (lpData && !override)
544 return TRUE;
546 if (lpData)
548 X11DRV_CLIPBOARD_FreeData(lpData);
550 lpData->hData = hData;
552 else
554 lpData = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPDATA));
556 lpData->wFormatID = wFormatID;
557 lpData->hData = hData;
558 lpData->lpFormat = lpFormat;
559 lpData->drvData = 0;
561 list_add_tail( &data_list, &lpData->entry );
562 ClipDataCount++;
565 lpData->wFlags = flags;
567 return TRUE;
571 /**************************************************************************
572 * X11DRV_CLIPBOARD_FreeData
574 * Free clipboard data handle.
576 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData)
578 TRACE("%04x\n", lpData->wFormatID);
580 if (!lpData->hData) return;
582 switch (lpData->wFormatID)
584 case CF_BITMAP:
585 case CF_PALETTE:
586 DeleteObject(lpData->hData);
587 break;
588 case CF_DIB:
589 if (lpData->drvData) XFreePixmap(gdi_display, lpData->drvData);
590 GlobalFree(lpData->hData);
591 break;
592 case CF_METAFILEPICT:
593 DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData ))->hMF );
594 GlobalFree(lpData->hData);
595 break;
596 case CF_ENHMETAFILE:
597 DeleteEnhMetaFile(lpData->hData);
598 break;
599 default:
600 if (lpData->wFormatID >= CF_GDIOBJFIRST && lpData->wFormatID <= CF_GDIOBJLAST) break;
601 if (lpData->wFormatID >= CF_PRIVATEFIRST && lpData->wFormatID <= CF_PRIVATELAST) break;
602 GlobalFree(lpData->hData);
603 break;
605 lpData->hData = 0;
606 lpData->drvData = 0;
610 /**************************************************************************
611 * X11DRV_CLIPBOARD_UpdateCache
613 static BOOL X11DRV_CLIPBOARD_UpdateCache(void)
615 BOOL bret = TRUE;
617 if (!selectionAcquired)
619 DWORD seqno = GetClipboardSequenceNumber();
621 if (!seqno)
623 ERR("Failed to retrieve clipboard information.\n");
624 bret = FALSE;
626 else if (wSeqNo < seqno)
628 empty_clipboard( TRUE );
630 if (X11DRV_CLIPBOARD_QueryAvailableData(thread_init_display()) < 0)
632 ERR("Failed to cache clipboard data owned by another process.\n");
633 bret = FALSE;
635 else
637 X11DRV_EndClipboardUpdate();
640 wSeqNo = seqno;
644 return bret;
648 /**************************************************************************
649 * X11DRV_CLIPBOARD_RenderFormat
651 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData)
653 BOOL bret = TRUE;
655 TRACE(" 0x%04x hData(%p)\n", lpData->wFormatID, lpData->hData);
657 if (lpData->hData) return bret; /* Already rendered */
659 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
660 bret = X11DRV_CLIPBOARD_RenderSynthesizedFormat(display, lpData);
661 else if (!selectionAcquired)
663 if (!X11DRV_CLIPBOARD_ReadSelectionData(display, lpData))
665 ERR("Failed to cache clipboard data owned by another process. Format=%04x\n",
666 lpData->wFormatID);
667 bret = FALSE;
670 else
672 HWND owner = GetClipboardOwner();
674 if (owner)
676 /* Send a WM_RENDERFORMAT message to notify the owner to render the
677 * data requested into the clipboard.
679 TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", owner);
680 SendMessageW(owner, WM_RENDERFORMAT, lpData->wFormatID, 0);
682 if (!lpData->hData) bret = FALSE;
684 else
686 ERR("hWndClipOwner is lost!\n");
687 bret = FALSE;
691 return bret;
695 /**************************************************************************
696 * CLIPBOARD_ConvertText
697 * Returns number of required/converted characters - not bytes!
699 static INT CLIPBOARD_ConvertText(WORD src_fmt, void const *src, INT src_size,
700 WORD dst_fmt, void *dst, INT dst_size)
702 UINT cp;
704 if(src_fmt == CF_UNICODETEXT)
706 switch(dst_fmt)
708 case CF_TEXT:
709 cp = CP_ACP;
710 break;
711 case CF_OEMTEXT:
712 cp = CP_OEMCP;
713 break;
714 default:
715 return 0;
717 return WideCharToMultiByte(cp, 0, src, src_size, dst, dst_size, NULL, NULL);
720 if(dst_fmt == CF_UNICODETEXT)
722 switch(src_fmt)
724 case CF_TEXT:
725 cp = CP_ACP;
726 break;
727 case CF_OEMTEXT:
728 cp = CP_OEMCP;
729 break;
730 default:
731 return 0;
733 return MultiByteToWideChar(cp, 0, src, src_size, dst, dst_size);
736 if(!dst_size) return src_size;
738 if(dst_size > src_size) dst_size = src_size;
740 if(src_fmt == CF_TEXT )
741 CharToOemBuffA(src, dst, dst_size);
742 else
743 OemToCharBuffA(src, dst, dst_size);
745 return dst_size;
749 /**************************************************************************
750 * X11DRV_CLIPBOARD_RenderSynthesizedFormat
752 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData)
754 BOOL bret = FALSE;
756 TRACE("\n");
758 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
760 UINT wFormatID = lpData->wFormatID;
762 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
763 bret = X11DRV_CLIPBOARD_RenderSynthesizedText(display, wFormatID);
764 else
766 switch (wFormatID)
768 case CF_DIB:
769 bret = X11DRV_CLIPBOARD_RenderSynthesizedDIB( display );
770 break;
772 case CF_BITMAP:
773 bret = X11DRV_CLIPBOARD_RenderSynthesizedBitmap( display );
774 break;
776 case CF_ENHMETAFILE:
777 bret = X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile( display );
778 break;
780 case CF_METAFILEPICT:
781 FIXME("Synthesizing CF_METAFILEPICT not implemented\n");
782 break;
784 default:
785 FIXME("Called to synthesize unknown format 0x%08x\n", wFormatID);
786 break;
790 lpData->wFlags &= ~CF_FLAG_SYNTHESIZED;
793 return bret;
797 /**************************************************************************
798 * X11DRV_CLIPBOARD_RenderSynthesizedText
800 * Renders synthesized text
802 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID)
804 LPCSTR lpstrS;
805 LPSTR lpstrT;
806 HANDLE hData;
807 INT src_chars, dst_chars, alloc_size;
808 LPWINE_CLIPDATA lpSource = NULL;
810 TRACE("%04x\n", wFormatID);
812 if ((lpSource = X11DRV_CLIPBOARD_LookupData(wFormatID)) &&
813 lpSource->hData)
814 return TRUE;
816 /* Look for rendered source or non-synthesized source */
817 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
818 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
820 TRACE("UNICODETEXT -> %04x\n", wFormatID);
822 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
823 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
825 TRACE("TEXT -> %04x\n", wFormatID);
827 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
828 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
830 TRACE("OEMTEXT -> %04x\n", wFormatID);
833 if (!lpSource || (lpSource->wFlags & CF_FLAG_SYNTHESIZED &&
834 !lpSource->hData))
835 return FALSE;
837 /* Ask the clipboard owner to render the source text if necessary */
838 if (!lpSource->hData && !X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
839 return FALSE;
841 lpstrS = GlobalLock(lpSource->hData);
842 if (!lpstrS)
843 return FALSE;
845 /* Text always NULL terminated */
846 if(lpSource->wFormatID == CF_UNICODETEXT)
847 src_chars = strlenW((LPCWSTR)lpstrS) + 1;
848 else
849 src_chars = strlen(lpstrS) + 1;
851 /* Calculate number of characters in the destination buffer */
852 dst_chars = CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS,
853 src_chars, wFormatID, NULL, 0);
855 if (!dst_chars)
856 return FALSE;
858 TRACE("Converting from '%04x' to '%04x', %i chars\n",
859 lpSource->wFormatID, wFormatID, src_chars);
861 /* Convert characters to bytes */
862 if(wFormatID == CF_UNICODETEXT)
863 alloc_size = dst_chars * sizeof(WCHAR);
864 else
865 alloc_size = dst_chars;
867 hData = GlobalAlloc(GMEM_ZEROINIT | GMEM_FIXED, alloc_size);
869 lpstrT = GlobalLock(hData);
871 if (lpstrT)
873 CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS, src_chars,
874 wFormatID, lpstrT, dst_chars);
875 GlobalUnlock(hData);
878 GlobalUnlock(lpSource->hData);
880 return X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, hData, 0, NULL, TRUE);
884 /***********************************************************************
885 * bitmap_info_size
887 * Return the size of the bitmap info structure including color table.
889 static int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
891 unsigned int colors, size, masks = 0;
893 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
895 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
896 colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
897 return sizeof(BITMAPCOREHEADER) + colors *
898 ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
900 else /* assume BITMAPINFOHEADER */
902 colors = info->bmiHeader.biClrUsed;
903 if (!colors && (info->bmiHeader.biBitCount <= 8))
904 colors = 1 << info->bmiHeader.biBitCount;
905 if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
906 size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
907 return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
912 /***********************************************************************
913 * create_dib_from_bitmap
915 * Allocates a packed DIB and copies the bitmap data into it.
917 static HGLOBAL create_dib_from_bitmap(HBITMAP hBmp)
919 BITMAP bmp;
920 HDC hdc;
921 HGLOBAL hPackedDIB;
922 LPBYTE pPackedDIB;
923 LPBITMAPINFOHEADER pbmiHeader;
924 unsigned int cDataSize, cPackedSize, OffsetBits;
925 int nLinesCopied;
927 if (!GetObjectW( hBmp, sizeof(bmp), &bmp )) return 0;
930 * A packed DIB contains a BITMAPINFO structure followed immediately by
931 * an optional color palette and the pixel data.
934 /* Calculate the size of the packed DIB */
935 cDataSize = abs( bmp.bmHeight ) * (((bmp.bmWidth * bmp.bmBitsPixel + 31) / 8) & ~3);
936 cPackedSize = sizeof(BITMAPINFOHEADER)
937 + ( (bmp.bmBitsPixel <= 8) ? (sizeof(RGBQUAD) * (1 << bmp.bmBitsPixel)) : 0 )
938 + cDataSize;
939 /* Get the offset to the bits */
940 OffsetBits = cPackedSize - cDataSize;
942 /* Allocate the packed DIB */
943 TRACE("\tAllocating packed DIB of size %d\n", cPackedSize);
944 hPackedDIB = GlobalAlloc( GMEM_FIXED, cPackedSize );
945 if ( !hPackedDIB )
947 WARN("Could not allocate packed DIB!\n");
948 return 0;
951 /* A packed DIB starts with a BITMAPINFOHEADER */
952 pPackedDIB = GlobalLock(hPackedDIB);
953 pbmiHeader = (LPBITMAPINFOHEADER)pPackedDIB;
955 /* Init the BITMAPINFOHEADER */
956 pbmiHeader->biSize = sizeof(BITMAPINFOHEADER);
957 pbmiHeader->biWidth = bmp.bmWidth;
958 pbmiHeader->biHeight = bmp.bmHeight;
959 pbmiHeader->biPlanes = 1;
960 pbmiHeader->biBitCount = bmp.bmBitsPixel;
961 pbmiHeader->biCompression = BI_RGB;
962 pbmiHeader->biSizeImage = 0;
963 pbmiHeader->biXPelsPerMeter = pbmiHeader->biYPelsPerMeter = 0;
964 pbmiHeader->biClrUsed = 0;
965 pbmiHeader->biClrImportant = 0;
967 /* Retrieve the DIB bits from the bitmap and fill in the
968 * DIB color table if present */
969 hdc = GetDC( 0 );
970 nLinesCopied = GetDIBits(hdc, /* Handle to device context */
971 hBmp, /* Handle to bitmap */
972 0, /* First scan line to set in dest bitmap */
973 bmp.bmHeight, /* Number of scan lines to copy */
974 pPackedDIB + OffsetBits, /* [out] Address of array for bitmap bits */
975 (LPBITMAPINFO) pbmiHeader, /* [out] Address of BITMAPINFO structure */
976 0); /* RGB or palette index */
977 GlobalUnlock(hPackedDIB);
978 ReleaseDC( 0, hdc );
980 /* Cleanup if GetDIBits failed */
981 if (nLinesCopied != bmp.bmHeight)
983 TRACE("\tGetDIBits returned %d. Actual lines=%d\n", nLinesCopied, bmp.bmHeight);
984 GlobalFree(hPackedDIB);
985 hPackedDIB = 0;
987 return hPackedDIB;
991 /***********************************************************************
992 * uri_to_dos
994 * Converts a text/uri-list URI to DOS filename.
996 static WCHAR* uri_to_dos(char *encodedURI)
998 WCHAR *ret = NULL;
999 int i;
1000 int j = 0;
1001 char *uri = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, strlen(encodedURI) + 1);
1002 if (uri == NULL)
1003 return NULL;
1004 for (i = 0; encodedURI[i]; ++i)
1006 if (encodedURI[i] == '%')
1008 if (encodedURI[i+1] && encodedURI[i+2])
1010 char buffer[3];
1011 int number;
1012 buffer[0] = encodedURI[i+1];
1013 buffer[1] = encodedURI[i+2];
1014 buffer[2] = '\0';
1015 sscanf(buffer, "%x", &number);
1016 uri[j++] = number;
1017 i += 2;
1019 else
1021 WARN("invalid URI encoding in %s\n", debugstr_a(encodedURI));
1022 HeapFree(GetProcessHeap(), 0, uri);
1023 return NULL;
1026 else
1027 uri[j++] = encodedURI[i];
1030 /* Read http://www.freedesktop.org/wiki/Draganddropwarts and cry... */
1031 if (strncmp(uri, "file:/", 6) == 0)
1033 if (uri[6] == '/')
1035 if (uri[7] == '/')
1037 /* file:///path/to/file (nautilus, thunar) */
1038 ret = wine_get_dos_file_name(&uri[7]);
1040 else if (uri[7])
1042 /* file://hostname/path/to/file (X file drag spec) */
1043 char hostname[256];
1044 char *path = strchr(&uri[7], '/');
1045 if (path)
1047 *path = '\0';
1048 if (strcmp(&uri[7], "localhost") == 0)
1050 *path = '/';
1051 ret = wine_get_dos_file_name(path);
1053 else if (gethostname(hostname, sizeof(hostname)) == 0)
1055 if (strcmp(hostname, &uri[7]) == 0)
1057 *path = '/';
1058 ret = wine_get_dos_file_name(path);
1064 else if (uri[6])
1066 /* file:/path/to/file (konqueror) */
1067 ret = wine_get_dos_file_name(&uri[5]);
1070 HeapFree(GetProcessHeap(), 0, uri);
1071 return ret;
1075 /**************************************************************************
1076 * X11DRV_CLIPBOARD_RenderSynthesizedDIB
1078 * Renders synthesized DIB
1080 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display)
1082 BOOL bret = FALSE;
1083 LPWINE_CLIPDATA lpSource = NULL;
1085 TRACE("\n");
1087 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) && lpSource->hData)
1089 bret = TRUE;
1091 /* If we have a bitmap and it's not synthesized or it has been rendered */
1092 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
1093 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1095 /* Render source if required */
1096 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1098 HGLOBAL hData = create_dib_from_bitmap( lpSource->hData );
1099 if (hData)
1101 X11DRV_CLIPBOARD_InsertClipboardData(CF_DIB, hData, 0, NULL, TRUE);
1102 bret = TRUE;
1107 return bret;
1111 /**************************************************************************
1112 * X11DRV_CLIPBOARD_RenderSynthesizedBitmap
1114 * Renders synthesized bitmap
1116 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display)
1118 BOOL bret = FALSE;
1119 LPWINE_CLIPDATA lpSource = NULL;
1121 TRACE("\n");
1123 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) && lpSource->hData)
1125 bret = TRUE;
1127 /* If we have a dib and it's not synthesized or it has been rendered */
1128 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
1129 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1131 /* Render source if required */
1132 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1134 HDC hdc;
1135 HBITMAP hData = NULL;
1136 unsigned int offset;
1137 LPBITMAPINFOHEADER lpbmih;
1139 hdc = GetDC(NULL);
1140 lpbmih = GlobalLock(lpSource->hData);
1141 if (lpbmih)
1143 offset = sizeof(BITMAPINFOHEADER)
1144 + ((lpbmih->biBitCount <= 8) ? (sizeof(RGBQUAD) *
1145 (1 << lpbmih->biBitCount)) : 0);
1147 hData = CreateDIBitmap(hdc, lpbmih, CBM_INIT, (LPBYTE)lpbmih +
1148 offset, (LPBITMAPINFO) lpbmih, DIB_RGB_COLORS);
1150 GlobalUnlock(lpSource->hData);
1152 ReleaseDC(NULL, hdc);
1154 if (hData)
1156 X11DRV_CLIPBOARD_InsertClipboardData(CF_BITMAP, hData, 0, NULL, TRUE);
1157 bret = TRUE;
1162 return bret;
1166 /**************************************************************************
1167 * X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile
1169 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile(Display *display)
1171 LPWINE_CLIPDATA lpSource = NULL;
1173 TRACE("\n");
1175 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_ENHMETAFILE)) && lpSource->hData)
1176 return TRUE;
1177 /* If we have a MF pict and it's not synthesized or it has been rendered */
1178 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
1179 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1181 /* Render source if required */
1182 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1184 METAFILEPICT *pmfp;
1185 HENHMETAFILE hData = NULL;
1187 pmfp = GlobalLock(lpSource->hData);
1188 if (pmfp)
1190 UINT size_mf_bits = GetMetaFileBitsEx(pmfp->hMF, 0, NULL);
1191 void *mf_bits = HeapAlloc(GetProcessHeap(), 0, size_mf_bits);
1192 if (mf_bits)
1194 GetMetaFileBitsEx(pmfp->hMF, size_mf_bits, mf_bits);
1195 hData = SetWinMetaFileBits(size_mf_bits, mf_bits, NULL, pmfp);
1196 HeapFree(GetProcessHeap(), 0, mf_bits);
1198 GlobalUnlock(lpSource->hData);
1201 if (hData)
1203 X11DRV_CLIPBOARD_InsertClipboardData(CF_ENHMETAFILE, hData, 0, NULL, TRUE);
1204 return TRUE;
1209 return FALSE;
1213 /**************************************************************************
1214 * X11DRV_CLIPBOARD_ImportXAString
1216 * Import XA_STRING, converting the string to CF_TEXT.
1218 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *display, Window w, Atom prop)
1220 LPBYTE lpdata;
1221 unsigned long cbytes;
1222 LPSTR lpstr;
1223 unsigned long i, inlcount = 0;
1224 HANDLE hText = 0;
1226 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1227 return 0;
1229 for (i = 0; i <= cbytes; i++)
1231 if (lpdata[i] == '\n')
1232 inlcount++;
1235 if ((hText = GlobalAlloc(GMEM_FIXED, cbytes + inlcount + 1)))
1237 lpstr = GlobalLock(hText);
1239 for (i = 0, inlcount = 0; i <= cbytes; i++)
1241 if (lpdata[i] == '\n')
1242 lpstr[inlcount++] = '\r';
1244 lpstr[inlcount++] = lpdata[i];
1247 GlobalUnlock(hText);
1250 /* Free the retrieved property data */
1251 HeapFree(GetProcessHeap(), 0, lpdata);
1253 return hText;
1257 /**************************************************************************
1258 * X11DRV_CLIPBOARD_ImportUTF8
1260 * Import XA_STRING, converting the string to CF_UNICODE.
1262 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *display, Window w, Atom prop)
1264 LPBYTE lpdata;
1265 unsigned long cbytes;
1266 LPSTR lpstr;
1267 unsigned long i, inlcount = 0;
1268 HANDLE hUnicodeText = 0;
1270 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1271 return 0;
1273 for (i = 0; i <= cbytes; i++)
1275 if (lpdata[i] == '\n')
1276 inlcount++;
1279 if ((lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbytes + inlcount + 1)))
1281 UINT count;
1283 for (i = 0, inlcount = 0; i <= cbytes; i++)
1285 if (lpdata[i] == '\n')
1286 lpstr[inlcount++] = '\r';
1288 lpstr[inlcount++] = lpdata[i];
1291 count = MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, NULL, 0);
1292 hUnicodeText = GlobalAlloc(GMEM_FIXED, count * sizeof(WCHAR));
1294 if (hUnicodeText)
1296 WCHAR *textW = GlobalLock(hUnicodeText);
1297 MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, textW, count);
1298 GlobalUnlock(hUnicodeText);
1301 HeapFree(GetProcessHeap(), 0, lpstr);
1304 /* Free the retrieved property data */
1305 HeapFree(GetProcessHeap(), 0, lpdata);
1307 return hUnicodeText;
1311 /**************************************************************************
1312 * X11DRV_CLIPBOARD_ImportCompoundText
1314 * Import COMPOUND_TEXT to CF_UNICODE
1316 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *display, Window w, Atom prop)
1318 int i, j, ret;
1319 char** srcstr;
1320 int count, lcount;
1321 int srclen, destlen;
1322 HANDLE hUnicodeText;
1323 XTextProperty txtprop;
1325 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &txtprop.value, &txtprop.nitems))
1327 return 0;
1330 txtprop.encoding = x11drv_atom(COMPOUND_TEXT);
1331 txtprop.format = 8;
1332 ret = XmbTextPropertyToTextList(display, &txtprop, &srcstr, &count);
1333 HeapFree(GetProcessHeap(), 0, txtprop.value);
1334 if (ret != Success || !count) return 0;
1336 TRACE("Importing %d line(s)\n", count);
1338 /* Compute number of lines */
1339 srclen = strlen(srcstr[0]);
1340 for (i = 0, lcount = 0; i <= srclen; i++)
1342 if (srcstr[0][i] == '\n')
1343 lcount++;
1346 destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
1348 TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
1350 if ((hUnicodeText = GlobalAlloc(GMEM_FIXED, (destlen + lcount + 1) * sizeof(WCHAR))))
1352 WCHAR *deststr = GlobalLock(hUnicodeText);
1353 MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1355 if (lcount)
1357 for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1359 deststr[j] = deststr[i];
1361 if (deststr[i] == '\n')
1362 deststr[--j] = '\r';
1366 GlobalUnlock(hUnicodeText);
1369 XFreeStringList(srcstr);
1371 return hUnicodeText;
1375 /**************************************************************************
1376 * X11DRV_CLIPBOARD_ImportXAPIXMAP
1378 * Import XA_PIXMAP, converting the image to CF_DIB.
1380 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *display, Window w, Atom prop)
1382 LPBYTE lpdata;
1383 unsigned long cbytes;
1384 Pixmap *pPixmap;
1385 HANDLE hClipData = 0;
1387 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1389 XVisualInfo vis = default_visual;
1390 char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
1391 BITMAPINFO *info = (BITMAPINFO *)buffer;
1392 struct gdi_image_bits bits;
1393 Window root;
1394 int x,y; /* Unused */
1395 unsigned border_width; /* Unused */
1396 unsigned int depth, width, height;
1398 pPixmap = (Pixmap *) lpdata;
1400 /* Get the Pixmap dimensions and bit depth */
1401 if (!XGetGeometry(gdi_display, *pPixmap, &root, &x, &y, &width, &height,
1402 &border_width, &depth)) depth = 0;
1403 if (!pixmap_formats[depth]) return 0;
1405 TRACE("\tPixmap properties: width=%d, height=%d, depth=%d\n",
1406 width, height, depth);
1408 if (depth != vis.depth) switch (pixmap_formats[depth]->bits_per_pixel)
1410 case 1:
1411 case 4:
1412 case 8:
1413 break;
1414 case 16: /* assume R5G5B5 */
1415 vis.red_mask = 0x7c00;
1416 vis.green_mask = 0x03e0;
1417 vis.blue_mask = 0x001f;
1418 break;
1419 case 24: /* assume R8G8B8 */
1420 case 32: /* assume A8R8G8B8 */
1421 vis.red_mask = 0xff0000;
1422 vis.green_mask = 0x00ff00;
1423 vis.blue_mask = 0x0000ff;
1424 break;
1425 default:
1426 return 0;
1429 if (!get_pixmap_image( *pPixmap, width, height, &vis, info, &bits ))
1431 DWORD info_size = bitmap_info_size( info, DIB_RGB_COLORS );
1432 BYTE *ptr;
1434 hClipData = GlobalAlloc( GMEM_FIXED, info_size + info->bmiHeader.biSizeImage );
1435 if (hClipData)
1437 ptr = GlobalLock( hClipData );
1438 memcpy( ptr, info, info_size );
1439 memcpy( ptr + info_size, bits.ptr, info->bmiHeader.biSizeImage );
1440 GlobalUnlock( hClipData );
1442 if (bits.free) bits.free( &bits );
1445 HeapFree(GetProcessHeap(), 0, lpdata);
1448 return hClipData;
1452 /**************************************************************************
1453 * X11DRV_CLIPBOARD_ImportImageBmp
1455 * Import image/bmp, converting the image to CF_DIB.
1457 static HANDLE X11DRV_CLIPBOARD_ImportImageBmp(Display *display, Window w, Atom prop)
1459 LPBYTE lpdata;
1460 unsigned long cbytes;
1461 HANDLE hClipData = 0;
1463 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1465 BITMAPFILEHEADER *bfh = (BITMAPFILEHEADER*)lpdata;
1467 if (cbytes >= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPCOREHEADER) &&
1468 bfh->bfType == 0x4d42 /* "BM" */)
1470 BITMAPINFO *bmi = (BITMAPINFO*)(bfh+1);
1471 HBITMAP hbmp;
1472 HDC hdc;
1474 hdc = GetDC(0);
1475 hbmp = CreateDIBitmap(
1476 hdc,
1477 &(bmi->bmiHeader),
1478 CBM_INIT,
1479 lpdata+bfh->bfOffBits,
1480 bmi,
1481 DIB_RGB_COLORS
1484 hClipData = create_dib_from_bitmap( hbmp );
1486 DeleteObject(hbmp);
1487 ReleaseDC(0, hdc);
1490 /* Free the retrieved property data */
1491 HeapFree(GetProcessHeap(), 0, lpdata);
1494 return hClipData;
1498 /**************************************************************************
1499 * X11DRV_CLIPBOARD_ImportMetaFilePict
1501 * Import MetaFilePict.
1503 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *display, Window w, Atom prop)
1505 LPBYTE lpdata;
1506 unsigned long cbytes;
1507 HANDLE hClipData = 0;
1509 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1511 if (cbytes)
1512 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata, (LPDWORD)&cbytes, FALSE);
1514 /* Free the retrieved property data */
1515 HeapFree(GetProcessHeap(), 0, lpdata);
1518 return hClipData;
1522 /**************************************************************************
1523 * X11DRV_ImportEnhMetaFile
1525 * Import EnhMetaFile.
1527 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *display, Window w, Atom prop)
1529 LPBYTE lpdata;
1530 unsigned long cbytes;
1531 HANDLE hClipData = 0;
1533 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1535 if (cbytes)
1536 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata, (LPDWORD)&cbytes, FALSE);
1538 /* Free the retrieved property data */
1539 HeapFree(GetProcessHeap(), 0, lpdata);
1542 return hClipData;
1546 /**************************************************************************
1547 * X11DRV_CLIPBOARD_ImportTextUriList
1549 * Import text/uri-list.
1551 static HANDLE X11DRV_CLIPBOARD_ImportTextUriList(Display *display, Window w, Atom prop)
1553 char *uriList;
1554 unsigned long len;
1555 char *uri;
1556 WCHAR *path;
1557 WCHAR *out = NULL;
1558 int size = 0;
1559 int capacity = 4096;
1560 int start = 0;
1561 int end = 0;
1562 HANDLE handle = NULL;
1564 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, (LPBYTE*)&uriList, &len))
1565 return 0;
1567 out = HeapAlloc(GetProcessHeap(), 0, capacity * sizeof(WCHAR));
1568 if (out == NULL) {
1569 HeapFree(GetProcessHeap(), 0, uriList);
1570 return 0;
1573 while (end < len)
1575 while (end < len && uriList[end] != '\r')
1576 ++end;
1577 if (end < (len - 1) && uriList[end+1] != '\n')
1579 WARN("URI list line doesn't end in \\r\\n\n");
1580 break;
1583 uri = HeapAlloc(GetProcessHeap(), 0, end - start + 1);
1584 if (uri == NULL)
1585 break;
1586 lstrcpynA(uri, &uriList[start], end - start + 1);
1587 path = uri_to_dos(uri);
1588 TRACE("converted URI %s to DOS path %s\n", debugstr_a(uri), debugstr_w(path));
1589 HeapFree(GetProcessHeap(), 0, uri);
1591 if (path)
1593 int pathSize = strlenW(path) + 1;
1594 if (pathSize > capacity-size)
1596 capacity = 2*capacity + pathSize;
1597 out = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, out, (capacity + 1)*sizeof(WCHAR));
1598 if (out == NULL)
1599 goto done;
1601 memcpy(&out[size], path, pathSize * sizeof(WCHAR));
1602 size += pathSize;
1603 done:
1604 HeapFree(GetProcessHeap(), 0, path);
1605 if (out == NULL)
1606 break;
1609 start = end + 2;
1610 end = start;
1612 if (out && end >= len)
1614 DROPFILES *dropFiles;
1615 handle = GlobalAlloc(GMEM_FIXED, sizeof(DROPFILES) + (size + 1)*sizeof(WCHAR));
1616 if (handle)
1618 dropFiles = (DROPFILES*) GlobalLock(handle);
1619 dropFiles->pFiles = sizeof(DROPFILES);
1620 dropFiles->pt.x = 0;
1621 dropFiles->pt.y = 0;
1622 dropFiles->fNC = 0;
1623 dropFiles->fWide = TRUE;
1624 out[size] = '\0';
1625 memcpy(((char*)dropFiles) + dropFiles->pFiles, out, (size + 1)*sizeof(WCHAR));
1626 GlobalUnlock(handle);
1629 HeapFree(GetProcessHeap(), 0, out);
1630 HeapFree(GetProcessHeap(), 0, uriList);
1631 return handle;
1635 /**************************************************************************
1636 * X11DRV_ImportClipbordaData
1638 * Generic import clipboard data routine.
1640 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *display, Window w, Atom prop)
1642 LPVOID lpClipData;
1643 LPBYTE lpdata;
1644 unsigned long cbytes;
1645 HANDLE hClipData = 0;
1647 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1649 if (cbytes)
1651 hClipData = GlobalAlloc(GMEM_FIXED, cbytes);
1652 if (hClipData == 0)
1654 HeapFree(GetProcessHeap(), 0, lpdata);
1655 return NULL;
1658 if ((lpClipData = GlobalLock(hClipData)))
1660 memcpy(lpClipData, lpdata, cbytes);
1661 GlobalUnlock(hClipData);
1663 else
1665 GlobalFree(hClipData);
1666 hClipData = 0;
1670 /* Free the retrieved property data */
1671 HeapFree(GetProcessHeap(), 0, lpdata);
1674 return hClipData;
1677 /**************************************************************************
1678 * X11DRV_CLIPBOARD_ImportSelection
1680 * Import the X selection into the clipboard format registered for the given X target.
1682 HANDLE X11DRV_CLIPBOARD_ImportSelection(Display *d, Atom target, Window w, Atom prop, UINT *windowsFormat)
1684 WINE_CLIPFORMAT *clipFormat;
1686 clipFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, target);
1687 if (clipFormat)
1689 *windowsFormat = clipFormat->wFormatID;
1690 return clipFormat->lpDrvImportFunc(d, w, prop);
1692 return NULL;
1696 /**************************************************************************
1697 X11DRV_CLIPBOARD_ExportClipboardData
1699 * Generic export clipboard data routine.
1701 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
1702 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1704 LPVOID lpClipData;
1705 UINT datasize = 0;
1706 HANDLE hClipData = 0;
1708 *lpBytes = 0; /* Assume failure */
1710 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1711 ERR("Failed to export %04x format\n", lpData->wFormatID);
1712 else
1714 datasize = GlobalSize(lpData->hData);
1716 hClipData = GlobalAlloc(GMEM_FIXED, datasize);
1717 if (hClipData == 0) return NULL;
1719 if ((lpClipData = GlobalLock(hClipData)))
1721 LPVOID lpdata = GlobalLock(lpData->hData);
1723 memcpy(lpClipData, lpdata, datasize);
1724 *lpBytes = datasize;
1726 GlobalUnlock(lpData->hData);
1727 GlobalUnlock(hClipData);
1728 } else {
1729 GlobalFree(hClipData);
1730 hClipData = 0;
1734 return hClipData;
1738 /**************************************************************************
1739 * X11DRV_CLIPBOARD_ExportXAString
1741 * Export CF_TEXT converting the string to XA_STRING.
1742 * Helper function for X11DRV_CLIPBOARD_ExportString.
1744 static HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1746 UINT i, j;
1747 UINT size;
1748 LPSTR text, lpstr = NULL;
1750 *lpBytes = 0; /* Assume return has zero bytes */
1752 text = GlobalLock(lpData->hData);
1753 size = strlen(text);
1755 /* remove carriage returns */
1756 lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1757 if (lpstr == NULL)
1758 goto done;
1760 for (i = 0,j = 0; i < size && text[i]; i++)
1762 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1763 continue;
1764 lpstr[j++] = text[i];
1767 lpstr[j]='\0';
1768 *lpBytes = j; /* Number of bytes in string */
1770 done:
1771 GlobalUnlock(lpData->hData);
1773 return lpstr;
1777 /**************************************************************************
1778 * X11DRV_CLIPBOARD_ExportUTF8String
1780 * Export CF_UNICODE converting the string to UTF8.
1781 * Helper function for X11DRV_CLIPBOARD_ExportString.
1783 static HANDLE X11DRV_CLIPBOARD_ExportUTF8String(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1785 UINT i, j;
1786 UINT size;
1787 LPWSTR uni_text;
1788 LPSTR text, lpstr = NULL;
1790 *lpBytes = 0; /* Assume return has zero bytes */
1792 uni_text = GlobalLock(lpData->hData);
1794 size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1796 text = HeapAlloc(GetProcessHeap(), 0, size);
1797 if (!text)
1798 goto done;
1799 WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1801 /* remove carriage returns */
1802 lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1803 if (lpstr == NULL)
1804 goto done;
1806 for (i = 0,j = 0; i < size && text[i]; i++)
1808 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1809 continue;
1810 lpstr[j++] = text[i];
1812 lpstr[j]='\0';
1814 *lpBytes = j; /* Number of bytes in string */
1816 done:
1817 HeapFree(GetProcessHeap(), 0, text);
1818 GlobalUnlock(lpData->hData);
1820 return lpstr;
1825 /**************************************************************************
1826 * X11DRV_CLIPBOARD_ExportCompoundText
1828 * Export CF_UNICODE to COMPOUND_TEXT
1829 * Helper function for X11DRV_CLIPBOARD_ExportString.
1831 static HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Display *display, Window requestor, Atom aTarget, Atom rprop,
1832 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1834 char* lpstr = 0;
1835 XTextProperty prop;
1836 XICCEncodingStyle style;
1837 UINT i, j;
1838 UINT size;
1839 LPWSTR uni_text;
1841 uni_text = GlobalLock(lpData->hData);
1843 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1844 lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1845 if (!lpstr)
1846 return 0;
1848 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1850 /* remove carriage returns */
1851 for (i = 0, j = 0; i < size && lpstr[i]; i++)
1853 if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1854 continue;
1855 lpstr[j++] = lpstr[i];
1857 lpstr[j]='\0';
1859 GlobalUnlock(lpData->hData);
1861 if (aTarget == x11drv_atom(COMPOUND_TEXT))
1862 style = XCompoundTextStyle;
1863 else
1864 style = XStdICCTextStyle;
1866 /* Update the X property */
1867 if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1869 XSetTextProperty(display, requestor, &prop, rprop);
1870 XFree(prop.value);
1873 HeapFree(GetProcessHeap(), 0, lpstr);
1875 return 0;
1878 /**************************************************************************
1879 * X11DRV_CLIPBOARD_ExportString
1881 * Export string
1883 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget, Atom rprop,
1884 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1886 if (X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1888 if (aTarget == XA_STRING)
1889 return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1890 else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1891 return X11DRV_CLIPBOARD_ExportCompoundText(display, requestor, aTarget,
1892 rprop, lpData, lpBytes);
1893 else
1895 TRACE("Exporting target %ld to default UTF8_STRING\n", aTarget);
1896 return X11DRV_CLIPBOARD_ExportUTF8String(lpData, lpBytes);
1899 else
1900 ERR("Failed to render %04x format\n", lpData->wFormatID);
1902 return 0;
1906 /**************************************************************************
1907 * X11DRV_CLIPBOARD_ExportXAPIXMAP
1909 * Export CF_DIB to XA_PIXMAP.
1911 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget, Atom rprop,
1912 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1914 HANDLE hData;
1915 unsigned char* lpData;
1917 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1919 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1920 return 0;
1923 if (!lpdata->drvData) /* If not already rendered */
1925 Pixmap pixmap;
1926 LPBITMAPINFO pbmi;
1927 struct gdi_image_bits bits;
1929 pbmi = GlobalLock( lpdata->hData );
1930 bits.ptr = (LPBYTE)pbmi + bitmap_info_size( pbmi, DIB_RGB_COLORS );
1931 bits.free = NULL;
1932 bits.is_copy = FALSE;
1933 pixmap = create_pixmap_from_image( 0, &default_visual, pbmi, &bits, DIB_RGB_COLORS );
1934 GlobalUnlock( lpdata->hData );
1935 lpdata->drvData = pixmap;
1938 *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1940 /* Wrap pixmap so we can return a handle */
1941 hData = GlobalAlloc(0, *lpBytes);
1942 lpData = GlobalLock(hData);
1943 memcpy(lpData, &lpdata->drvData, *lpBytes);
1944 GlobalUnlock(hData);
1946 return hData;
1950 /**************************************************************************
1951 * X11DRV_CLIPBOARD_ExportImageBmp
1953 * Export CF_DIB to image/bmp.
1955 static HANDLE X11DRV_CLIPBOARD_ExportImageBmp(Display *display, Window requestor, Atom aTarget, Atom rprop,
1956 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1958 HANDLE hpackeddib;
1959 LPBYTE dibdata;
1960 UINT bmpsize;
1961 HANDLE hbmpdata;
1962 LPBYTE bmpdata;
1963 BITMAPFILEHEADER *bfh;
1965 *lpBytes = 0;
1967 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1969 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1970 return 0;
1973 hpackeddib = lpdata->hData;
1975 dibdata = GlobalLock(hpackeddib);
1976 if (!dibdata)
1978 ERR("Failed to lock packed DIB\n");
1979 return 0;
1982 bmpsize = sizeof(BITMAPFILEHEADER) + GlobalSize(hpackeddib);
1984 hbmpdata = GlobalAlloc(0, bmpsize);
1986 if (hbmpdata)
1988 bmpdata = GlobalLock(hbmpdata);
1990 if (!bmpdata)
1992 GlobalFree(hbmpdata);
1993 GlobalUnlock(hpackeddib);
1994 return 0;
1997 /* bitmap file header */
1998 bfh = (BITMAPFILEHEADER*)bmpdata;
1999 bfh->bfType = 0x4d42; /* "BM" */
2000 bfh->bfSize = bmpsize;
2001 bfh->bfReserved1 = 0;
2002 bfh->bfReserved2 = 0;
2003 bfh->bfOffBits = sizeof(BITMAPFILEHEADER) + bitmap_info_size((BITMAPINFO*)dibdata, DIB_RGB_COLORS);
2005 /* rest of bitmap is the same as the packed dib */
2006 memcpy(bfh+1, dibdata, bmpsize-sizeof(BITMAPFILEHEADER));
2008 *lpBytes = bmpsize;
2010 GlobalUnlock(hbmpdata);
2013 GlobalUnlock(hpackeddib);
2015 return hbmpdata;
2019 /**************************************************************************
2020 * X11DRV_CLIPBOARD_ExportMetaFilePict
2022 * Export MetaFilePict.
2024 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget, Atom rprop,
2025 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
2027 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
2029 ERR("Failed to export %04x format\n", lpdata->wFormatID);
2030 return 0;
2033 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata->hData, lpBytes, TRUE);
2037 /**************************************************************************
2038 * X11DRV_CLIPBOARD_ExportEnhMetaFile
2040 * Export EnhMetaFile.
2042 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget, Atom rprop,
2043 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
2045 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
2047 ERR("Failed to export %04x format\n", lpdata->wFormatID);
2048 return 0;
2051 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata->hData, lpBytes, TRUE);
2055 /**************************************************************************
2056 * get_html_description_field
2058 * Find the value of a field in an HTML Format description.
2060 static LPCSTR get_html_description_field(LPCSTR data, LPCSTR keyword)
2062 LPCSTR pos=data;
2064 while (pos && *pos && *pos != '<')
2066 if (memcmp(pos, keyword, strlen(keyword)) == 0)
2067 return pos+strlen(keyword);
2069 pos = strchr(pos, '\n');
2070 if (pos) pos++;
2073 return NULL;
2077 /**************************************************************************
2078 * X11DRV_CLIPBOARD_ExportTextHtml
2080 * Export HTML Format to text/html.
2082 * FIXME: We should attempt to add an <a base> tag and convert windows paths.
2084 static HANDLE X11DRV_CLIPBOARD_ExportTextHtml(Display *display, Window requestor, Atom aTarget,
2085 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
2087 HANDLE hdata;
2088 LPCSTR data, field_value;
2089 UINT fragmentstart, fragmentend, htmlsize;
2090 HANDLE hhtmldata=NULL;
2091 LPSTR htmldata;
2093 *lpBytes = 0;
2095 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
2097 ERR("Failed to export %04x format\n", lpdata->wFormatID);
2098 return 0;
2101 hdata = lpdata->hData;
2103 data = GlobalLock(hdata);
2104 if (!data)
2106 ERR("Failed to lock HTML Format data\n");
2107 return 0;
2110 /* read the important fields */
2111 field_value = get_html_description_field(data, "StartFragment:");
2112 if (!field_value)
2114 ERR("Couldn't find StartFragment value\n");
2115 goto end;
2117 fragmentstart = atoi(field_value);
2119 field_value = get_html_description_field(data, "EndFragment:");
2120 if (!field_value)
2122 ERR("Couldn't find EndFragment value\n");
2123 goto end;
2125 fragmentend = atoi(field_value);
2127 /* export only the fragment */
2128 htmlsize = fragmentend - fragmentstart + 1;
2130 hhtmldata = GlobalAlloc(0, htmlsize);
2132 if (hhtmldata)
2134 htmldata = GlobalLock(hhtmldata);
2136 if (!htmldata)
2138 GlobalFree(hhtmldata);
2139 htmldata = NULL;
2140 goto end;
2143 memcpy(htmldata, &data[fragmentstart], fragmentend-fragmentstart);
2144 htmldata[htmlsize-1] = '\0';
2146 *lpBytes = htmlsize;
2148 GlobalUnlock(htmldata);
2151 end:
2153 GlobalUnlock(hdata);
2155 return hhtmldata;
2159 /**************************************************************************
2160 * X11DRV_CLIPBOARD_ExportHDROP
2162 * Export CF_HDROP format to text/uri-list.
2164 static HANDLE X11DRV_CLIPBOARD_ExportHDROP(Display *display, Window requestor, Atom aTarget,
2165 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
2167 HDROP hDrop;
2168 UINT i;
2169 UINT numFiles;
2170 HGLOBAL hClipData = NULL;
2171 char *textUriList = NULL;
2172 UINT textUriListSize = 32;
2173 UINT next = 0;
2175 *lpBytes = 0;
2177 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
2179 ERR("Failed to export %04x format\n", lpdata->wFormatID);
2180 return 0;
2182 hClipData = GlobalAlloc(GMEM_FIXED, textUriListSize);
2183 if (hClipData == NULL)
2184 return 0;
2185 hDrop = (HDROP) lpdata->hData;
2186 numFiles = DragQueryFileW(hDrop, 0xFFFFFFFF, NULL, 0);
2187 for (i = 0; i < numFiles; i++)
2189 UINT dosFilenameSize;
2190 WCHAR *dosFilename = NULL;
2191 char *unixFilename = NULL;
2192 UINT uriSize;
2193 UINT u;
2195 dosFilenameSize = 1 + DragQueryFileW(hDrop, i, NULL, 0);
2196 dosFilename = HeapAlloc(GetProcessHeap(), 0, dosFilenameSize*sizeof(WCHAR));
2197 if (dosFilename == NULL) goto failed;
2198 DragQueryFileW(hDrop, i, dosFilename, dosFilenameSize);
2199 unixFilename = wine_get_unix_file_name(dosFilename);
2200 HeapFree(GetProcessHeap(), 0, dosFilename);
2201 if (unixFilename == NULL) goto failed;
2202 uriSize = 8 + /* file:/// */
2203 3 * (lstrlenA(unixFilename) - 1) + /* "%xy" per char except first '/' */
2204 2; /* \r\n */
2205 if ((next + uriSize) > textUriListSize)
2207 UINT biggerSize = max( 2 * textUriListSize, next + uriSize );
2208 HGLOBAL bigger = GlobalReAlloc(hClipData, biggerSize, 0);
2209 if (bigger)
2211 hClipData = bigger;
2212 textUriListSize = biggerSize;
2214 else
2216 HeapFree(GetProcessHeap(), 0, unixFilename);
2217 goto failed;
2220 textUriList = GlobalLock(hClipData);
2221 lstrcpyA(&textUriList[next], "file:///");
2222 next += 8;
2223 /* URL encode everything - unnecessary, but easier/lighter than linking in shlwapi, and can't hurt */
2224 for (u = 1; unixFilename[u]; u++)
2226 static const char hex_table[] = "0123456789abcdef";
2227 textUriList[next++] = '%';
2228 textUriList[next++] = hex_table[unixFilename[u] >> 4];
2229 textUriList[next++] = hex_table[unixFilename[u] & 0xf];
2231 textUriList[next++] = '\r';
2232 textUriList[next++] = '\n';
2233 GlobalUnlock(hClipData);
2234 HeapFree(GetProcessHeap(), 0, unixFilename);
2237 *lpBytes = next;
2238 return hClipData;
2240 failed:
2241 GlobalFree(hClipData);
2242 *lpBytes = 0;
2243 return 0;
2247 /**************************************************************************
2248 * X11DRV_CLIPBOARD_QueryTargets
2250 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection,
2251 Atom target, XEvent *xe)
2253 INT i;
2255 XConvertSelection(display, selection, target, x11drv_atom(SELECTION_DATA), w, CurrentTime);
2258 * Wait until SelectionNotify is received
2260 for (i = 0; i < SELECTION_RETRIES; i++)
2262 Bool res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
2263 if (res && xe->xselection.selection == selection) break;
2265 usleep(SELECTION_WAIT);
2268 if (i == SELECTION_RETRIES)
2270 ERR("Timed out waiting for SelectionNotify event\n");
2271 return FALSE;
2273 /* Verify that the selection returned a valid TARGETS property */
2274 if ((xe->xselection.target != target) || (xe->xselection.property == None))
2276 /* Selection owner failed to respond or we missed the SelectionNotify */
2277 WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
2278 return FALSE;
2281 return TRUE;
2285 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
2287 return (event->error_code == BadAtom);
2290 static int is_window_error( Display *display, XErrorEvent *event, void *arg )
2292 return (event->error_code == BadWindow);
2295 /**************************************************************************
2296 * X11DRV_CLIPBOARD_InsertSelectionProperties
2298 * Mark properties available for future retrieval.
2300 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
2302 UINT i, nb_atoms = 0;
2303 Atom *atoms = NULL;
2305 /* Cache these formats in the clipboard cache */
2306 for (i = 0; i < count; i++)
2308 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
2310 if (lpFormat)
2312 /* We found at least one Window's format that mapps to the property.
2313 * Continue looking for more.
2315 * If more than one property map to a Window's format then we use the first
2316 * one and ignore the rest.
2318 while (lpFormat)
2320 TRACE("Atom#%d Property(%d): --> Format %s\n",
2321 i, lpFormat->drvData, debugstr_format(lpFormat->wFormatID));
2322 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, lpFormat, FALSE);
2323 lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
2326 else if (properties[i])
2328 /* add it to the list of atoms that we don't know about yet */
2329 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
2330 (count - i) * sizeof(*atoms) );
2331 if (atoms) atoms[nb_atoms++] = properties[i];
2335 /* query all unknown atoms in one go */
2336 if (atoms)
2338 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
2339 if (names)
2341 X11DRV_expect_error( display, is_atom_error, NULL );
2342 if (!XGetAtomNames( display, atoms, nb_atoms, names )) nb_atoms = 0;
2343 if (X11DRV_check_error())
2345 WARN( "got some bad atoms, ignoring\n" );
2346 nb_atoms = 0;
2348 for (i = 0; i < nb_atoms; i++)
2350 WINE_CLIPFORMAT *lpFormat;
2351 LPWSTR wname;
2352 int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
2353 wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2354 MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
2356 lpFormat = register_format( RegisterClipboardFormatW(wname), atoms[i] );
2357 HeapFree(GetProcessHeap(), 0, wname);
2358 if (!lpFormat)
2360 ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
2361 continue;
2363 TRACE("Atom#%d Property(%d): --> Format %s\n",
2364 i, lpFormat->drvData, debugstr_format(lpFormat->wFormatID));
2365 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, lpFormat, FALSE);
2367 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
2368 HeapFree( GetProcessHeap(), 0, names );
2370 HeapFree( GetProcessHeap(), 0, atoms );
2375 /**************************************************************************
2376 * X11DRV_CLIPBOARD_QueryAvailableData
2378 * Caches the list of data formats available from the current selection.
2379 * This queries the selection owner for the TARGETS property and saves all
2380 * reported property types.
2382 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display)
2384 XEvent xe;
2385 Atom atype=AnyPropertyType;
2386 int aformat;
2387 unsigned long remain;
2388 Atom* targetList=NULL;
2389 Window w;
2390 unsigned long cSelectionTargets = 0;
2392 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
2394 ERR("Received request to cache selection but process is owner=(%08x)\n",
2395 (unsigned) selectionWindow);
2396 return -1; /* Prevent self request */
2399 w = thread_selection_wnd();
2400 if (!w)
2402 ERR("No window available to retrieve selection!\n");
2403 return -1;
2407 * Query the selection owner for the TARGETS property
2409 if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
2410 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2412 if (use_primary_selection && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
2413 selectionCacheSrc = XA_PRIMARY;
2414 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
2415 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2416 else
2418 Atom xstr = XA_STRING;
2420 /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
2421 if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
2423 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2424 selectionCacheSrc = XA_PRIMARY;
2425 return 1;
2427 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
2429 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2430 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2431 return 1;
2433 else
2435 WARN("Failed to query selection owner for available data.\n");
2436 return -1;
2440 else return 0; /* No selection owner so report 0 targets available */
2442 /* Read the TARGETS property contents */
2443 if (!XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
2444 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
2445 &remain, (unsigned char**)&targetList))
2447 TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
2448 atype, aformat, cSelectionTargets, remain);
2450 * The TARGETS property should have returned us a list of atoms
2451 * corresponding to each selection target format supported.
2453 if (atype == XA_ATOM || atype == x11drv_atom(TARGETS))
2455 if (aformat == 32)
2457 X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, cSelectionTargets);
2459 else if (aformat == 8) /* work around quartz-wm brain damage */
2461 unsigned long i, count = cSelectionTargets / sizeof(CARD32);
2462 Atom *atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(Atom) );
2463 for (i = 0; i < count; i++)
2464 atoms[i] = ((CARD32 *)targetList)[i]; /* FIXME: byte swapping */
2465 X11DRV_CLIPBOARD_InsertSelectionProperties( display, atoms, count );
2466 HeapFree( GetProcessHeap(), 0, atoms );
2470 /* Free the list of targets */
2471 XFree(targetList);
2473 else WARN("Failed to read TARGETS property\n");
2475 return cSelectionTargets;
2479 /**************************************************************************
2480 * X11DRV_CLIPBOARD_ReadSelectionData
2482 * This method is invoked only when we DO NOT own the X selection
2484 * We always get the data from the selection client each time,
2485 * since we have no way of determining if the data in our cache is stale.
2487 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData)
2489 Bool res;
2490 DWORD i;
2491 XEvent xe;
2492 BOOL bRet = FALSE;
2494 TRACE("%04x\n", lpData->wFormatID);
2496 if (!lpData->lpFormat)
2498 ERR("Requesting format %04x but no source format linked to data.\n",
2499 lpData->wFormatID);
2500 return FALSE;
2503 if (!selectionAcquired)
2505 Window w = thread_selection_wnd();
2506 if(!w)
2508 ERR("No window available to read selection data!\n");
2509 return FALSE;
2512 TRACE("Requesting conversion of %s property (%d) from selection type %08x\n",
2513 debugstr_format(lpData->lpFormat->wFormatID), lpData->lpFormat->drvData,
2514 (UINT)selectionCacheSrc);
2516 XConvertSelection(display, selectionCacheSrc, lpData->lpFormat->drvData,
2517 x11drv_atom(SELECTION_DATA), w, CurrentTime);
2519 /* wait until SelectionNotify is received */
2520 for (i = 0; i < SELECTION_RETRIES; i++)
2522 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
2523 if (res && xe.xselection.selection == selectionCacheSrc) break;
2525 usleep(SELECTION_WAIT);
2528 if (i == SELECTION_RETRIES)
2530 ERR("Timed out waiting for SelectionNotify event\n");
2532 /* Verify that the selection returned a valid TARGETS property */
2533 else if (xe.xselection.property != None)
2536 * Read the contents of the X selection property
2537 * into WINE's clipboard cache and converting the
2538 * data format if necessary.
2540 HANDLE hData = lpData->lpFormat->lpDrvImportFunc(display, xe.xselection.requestor,
2541 xe.xselection.property);
2543 if (hData)
2544 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, hData, 0, lpData->lpFormat, TRUE);
2545 else
2546 TRACE("Import function failed\n");
2548 else
2550 TRACE("Failed to convert selection\n");
2553 else
2555 ERR("Received request to cache selection data but process is owner\n");
2558 TRACE("Returning %d\n", bRet);
2560 return bRet;
2564 /**************************************************************************
2565 * X11DRV_CLIPBOARD_GetProperty
2566 * Gets type, data and size.
2568 static BOOL X11DRV_CLIPBOARD_GetProperty(Display *display, Window w, Atom prop,
2569 Atom *atype, unsigned char** data, unsigned long* datasize)
2571 int aformat;
2572 unsigned long pos = 0, nitems, remain, count;
2573 unsigned char *val = NULL, *buffer;
2575 TRACE("Reading property %lu from X window %lx\n", prop, w);
2577 for (;;)
2579 if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
2580 AnyPropertyType, atype, &aformat, &nitems, &remain, &buffer))
2582 WARN("Failed to read property\n");
2583 HeapFree( GetProcessHeap(), 0, val );
2584 return FALSE;
2587 count = get_property_size( aformat, nitems );
2588 if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
2589 else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
2591 if (!*data)
2593 XFree( buffer );
2594 HeapFree( GetProcessHeap(), 0, val );
2595 return FALSE;
2597 val = *data;
2598 memcpy( (int *)val + pos, buffer, count );
2599 XFree( buffer );
2600 if (!remain)
2602 *datasize = pos * sizeof(int) + count;
2603 val[*datasize] = 0;
2604 break;
2606 pos += count / sizeof(int);
2609 /* Delete the property on the window now that we are done
2610 * This will send a PropertyNotify event to the selection owner. */
2611 XDeleteProperty(display, w, prop);
2612 return TRUE;
2616 struct clipboard_data_packet {
2617 struct list entry;
2618 unsigned long size;
2619 unsigned char *data;
2622 /**************************************************************************
2623 * X11DRV_CLIPBOARD_ReadProperty
2624 * Reads the contents of the X selection property.
2626 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
2627 unsigned char** data, unsigned long* datasize)
2629 Atom atype;
2630 XEvent xe;
2632 if (prop == None)
2633 return FALSE;
2635 while (XCheckTypedWindowEvent(display, w, PropertyNotify, &xe))
2638 if (!X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, data, datasize))
2639 return FALSE;
2641 if (atype == x11drv_atom(INCR))
2643 unsigned char *buf;
2644 unsigned long bufsize = 0;
2645 struct list packets;
2646 struct clipboard_data_packet *packet, *packet2;
2647 BOOL res;
2649 HeapFree(GetProcessHeap(), 0, *data);
2650 *data = NULL;
2652 list_init(&packets);
2654 for (;;)
2656 int i;
2657 unsigned char *prop_data;
2658 unsigned long prop_size;
2660 /* Wait until PropertyNotify is received */
2661 for (i = 0; i < SELECTION_RETRIES; i++)
2663 Bool res;
2665 res = XCheckTypedWindowEvent(display, w, PropertyNotify, &xe);
2666 if (res && xe.xproperty.atom == prop &&
2667 xe.xproperty.state == PropertyNewValue)
2668 break;
2669 usleep(SELECTION_WAIT);
2672 if (i >= SELECTION_RETRIES ||
2673 !X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, &prop_data, &prop_size))
2675 res = FALSE;
2676 break;
2679 /* Retrieved entire data. */
2680 if (prop_size == 0)
2682 HeapFree(GetProcessHeap(), 0, prop_data);
2683 res = TRUE;
2684 break;
2687 packet = HeapAlloc(GetProcessHeap(), 0, sizeof(*packet));
2688 if (!packet)
2690 HeapFree(GetProcessHeap(), 0, prop_data);
2691 res = FALSE;
2692 break;
2695 packet->size = prop_size;
2696 packet->data = prop_data;
2697 list_add_tail(&packets, &packet->entry);
2698 bufsize += prop_size;
2701 if (res)
2703 buf = HeapAlloc(GetProcessHeap(), 0, bufsize + 1);
2704 if (buf)
2706 unsigned long bytes_copied = 0;
2707 *datasize = bufsize;
2708 LIST_FOR_EACH_ENTRY( packet, &packets, struct clipboard_data_packet, entry)
2710 memcpy(&buf[bytes_copied], packet->data, packet->size);
2711 bytes_copied += packet->size;
2713 buf[bufsize] = 0;
2714 *data = buf;
2716 else
2717 res = FALSE;
2720 LIST_FOR_EACH_ENTRY_SAFE( packet, packet2, &packets, struct clipboard_data_packet, entry)
2722 HeapFree(GetProcessHeap(), 0, packet->data);
2723 HeapFree(GetProcessHeap(), 0, packet);
2726 return res;
2729 return TRUE;
2733 /**************************************************************************
2734 * CLIPBOARD_SerializeMetafile
2736 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
2738 HANDLE h = 0;
2740 TRACE(" wFormat=%d hdata=%p out=%d\n", wformat, hdata, out);
2742 if (out) /* Serialize out, caller should free memory */
2744 *lpcbytes = 0; /* Assume failure */
2746 if (wformat == CF_METAFILEPICT)
2748 LPMETAFILEPICT lpmfp = GlobalLock(hdata);
2749 unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2751 h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
2752 if (h)
2754 char *pdata = GlobalLock(h);
2756 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
2757 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
2759 *lpcbytes = size + sizeof(METAFILEPICT);
2761 GlobalUnlock(h);
2764 GlobalUnlock(hdata);
2766 else if (wformat == CF_ENHMETAFILE)
2768 int size = GetEnhMetaFileBits(hdata, 0, NULL);
2770 h = GlobalAlloc(0, size);
2771 if (h)
2773 LPVOID pdata = GlobalLock(h);
2775 GetEnhMetaFileBits(hdata, size, pdata);
2776 *lpcbytes = size;
2778 GlobalUnlock(h);
2782 else
2784 if (wformat == CF_METAFILEPICT)
2786 h = GlobalAlloc(0, sizeof(METAFILEPICT));
2787 if (h)
2789 unsigned int wiresize;
2790 LPMETAFILEPICT lpmfp = GlobalLock(h);
2792 memcpy(lpmfp, hdata, sizeof(METAFILEPICT));
2793 wiresize = *lpcbytes - sizeof(METAFILEPICT);
2794 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
2795 ((const BYTE *)hdata) + sizeof(METAFILEPICT));
2796 GlobalUnlock(h);
2799 else if (wformat == CF_ENHMETAFILE)
2801 h = SetEnhMetaFileBits(*lpcbytes, hdata);
2805 return h;
2809 /**************************************************************************
2810 * X11DRV_CLIPBOARD_ReleaseSelection
2812 * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
2814 static void X11DRV_CLIPBOARD_ReleaseSelection(Display *display, Atom selType, Window w, HWND hwnd, Time time)
2816 /* w is the window that lost the selection
2818 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
2819 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
2821 if (selectionAcquired && (w == selectionWindow))
2823 HWND owner;
2825 /* completely give up the selection */
2826 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
2828 if (X11DRV_CLIPBOARD_IsProcessOwner( &owner ))
2830 /* Since we're still the owner, this wasn't initiated by
2831 another Wine process */
2832 if (OpenClipboard(hwnd))
2834 /* Destroy private objects */
2835 SendMessageW(owner, WM_DESTROYCLIPBOARD, 0, 0);
2837 /* Give up ownership of the windows clipboard */
2838 X11DRV_CLIPBOARD_ReleaseOwnership();
2839 CloseClipboard();
2843 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2845 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2847 if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2849 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2850 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2852 else
2853 TRACE("We no longer own PRIMARY\n");
2855 else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2857 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2859 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2861 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2862 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2864 else
2865 TRACE("We no longer own CLIPBOARD\n");
2868 selectionWindow = None;
2870 empty_clipboard( FALSE );
2872 /* Reset the selection flags now that we are done */
2873 selectionAcquired = S_NOSELECTION;
2878 /**************************************************************************
2879 * X11DRV Clipboard Exports
2880 **************************************************************************/
2883 static void selection_acquire(void)
2885 Window owner;
2886 Display *display;
2888 owner = thread_selection_wnd();
2889 display = thread_display();
2891 selectionAcquired = 0;
2892 selectionWindow = 0;
2894 /* Grab PRIMARY selection if not owned */
2895 if (use_primary_selection)
2896 XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2898 /* Grab CLIPBOARD selection if not owned */
2899 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2901 if (use_primary_selection && XGetSelectionOwner(display, XA_PRIMARY) == owner)
2902 selectionAcquired |= S_PRIMARY;
2904 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2905 selectionAcquired |= S_CLIPBOARD;
2907 if (selectionAcquired)
2909 selectionWindow = owner;
2910 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2914 static DWORD WINAPI selection_thread_proc(LPVOID p)
2916 HANDLE event = p;
2918 TRACE("\n");
2920 selection_acquire();
2921 SetEvent(event);
2923 while (selectionAcquired)
2925 MsgWaitForMultipleObjectsEx(0, NULL, INFINITE, QS_SENDMESSAGE, 0);
2928 return 0;
2931 /**************************************************************************
2932 * X11DRV_AcquireClipboard
2934 void X11DRV_AcquireClipboard(HWND hWndClipWindow)
2936 DWORD procid;
2937 HANDLE selectionThread;
2939 TRACE(" %p\n", hWndClipWindow);
2942 * It's important that the selection get acquired from the thread
2943 * that owns the clipboard window. The primary reason is that we know
2944 * it is running a message loop and therefore can process the
2945 * X selection events.
2947 if (hWndClipWindow &&
2948 GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, &procid))
2950 if (procid != GetCurrentProcessId())
2952 WARN("Setting clipboard owner to other process is not supported\n");
2953 hWndClipWindow = NULL;
2955 else
2957 TRACE("Thread %x is acquiring selection with thread %x's window %p\n",
2958 GetCurrentThreadId(),
2959 GetWindowThreadProcessId(hWndClipWindow, NULL), hWndClipWindow);
2961 SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0);
2962 return;
2966 if (hWndClipWindow)
2968 selection_acquire();
2970 else
2972 HANDLE event = CreateEventW(NULL, FALSE, FALSE, NULL);
2973 selectionThread = CreateThread(NULL, 0, selection_thread_proc, event, 0, NULL);
2975 if (selectionThread)
2977 WaitForSingleObject(event, INFINITE);
2978 CloseHandle(selectionThread);
2980 CloseHandle(event);
2985 static void empty_clipboard(BOOL keepunowned)
2987 WINE_CLIPDATA *data, *next;
2989 LIST_FOR_EACH_ENTRY_SAFE( data, next, &data_list, WINE_CLIPDATA, entry )
2991 if (keepunowned && (data->wFlags & CF_FLAG_UNOWNED)) continue;
2992 list_remove( &data->entry );
2993 X11DRV_CLIPBOARD_FreeData( data );
2994 HeapFree( GetProcessHeap(), 0, data );
2995 ClipDataCount--;
2998 TRACE(" %d entries remaining in cache.\n", ClipDataCount);
3001 /**************************************************************************
3002 * X11DRV_EmptyClipboard
3004 * Empty cached clipboard data.
3006 void CDECL X11DRV_EmptyClipboard(void)
3008 X11DRV_AcquireClipboard( GetOpenClipboardWindow() );
3009 empty_clipboard( FALSE );
3012 /**************************************************************************
3013 * X11DRV_SetClipboardData
3015 BOOL CDECL X11DRV_SetClipboardData(UINT wFormat, HANDLE hData, BOOL owner)
3017 if (!owner) X11DRV_CLIPBOARD_UpdateCache();
3019 return X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData, 0, NULL, TRUE);
3023 /**************************************************************************
3024 * CountClipboardFormats
3026 INT CDECL X11DRV_CountClipboardFormats(void)
3028 X11DRV_CLIPBOARD_UpdateCache();
3030 TRACE(" count=%d\n", ClipDataCount);
3032 return ClipDataCount;
3036 /**************************************************************************
3037 * X11DRV_EnumClipboardFormats
3039 UINT CDECL X11DRV_EnumClipboardFormats(UINT wFormat)
3041 struct list *ptr = NULL;
3043 TRACE("(%04X)\n", wFormat);
3045 X11DRV_CLIPBOARD_UpdateCache();
3047 if (!wFormat)
3049 ptr = list_head( &data_list );
3051 else
3053 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
3054 if (lpData) ptr = list_next( &data_list, &lpData->entry );
3057 if (!ptr) return 0;
3058 return LIST_ENTRY( ptr, WINE_CLIPDATA, entry )->wFormatID;
3062 /**************************************************************************
3063 * X11DRV_IsClipboardFormatAvailable
3065 BOOL CDECL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
3067 BOOL bRet = FALSE;
3069 TRACE("(%04X)\n", wFormat);
3071 X11DRV_CLIPBOARD_UpdateCache();
3073 if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
3074 bRet = TRUE;
3076 TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
3078 return bRet;
3082 /**************************************************************************
3083 * GetClipboardData (USER.142)
3085 HANDLE CDECL X11DRV_GetClipboardData(UINT wFormat)
3087 LPWINE_CLIPDATA lpRender;
3089 TRACE("(%04X)\n", wFormat);
3091 X11DRV_CLIPBOARD_UpdateCache();
3093 if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
3095 if ( !lpRender->hData )
3096 X11DRV_CLIPBOARD_RenderFormat(thread_init_display(), lpRender);
3098 TRACE(" returning %p (type %04x)\n", lpRender->hData, lpRender->wFormatID);
3099 return lpRender->hData;
3102 return 0;
3106 /**************************************************************************
3107 * ResetSelectionOwner
3109 * Called when the thread owning the selection is destroyed and we need to
3110 * preserve the selection ownership. We look for another top level window
3111 * in this process and send it a message to acquire the selection.
3113 void X11DRV_ResetSelectionOwner(void)
3115 HWND hwnd;
3116 DWORD procid;
3118 TRACE("\n");
3120 if (!selectionAcquired || thread_selection_wnd() != selectionWindow)
3121 return;
3123 selectionAcquired = S_NOSELECTION;
3124 selectionWindow = 0;
3126 hwnd = GetWindow(GetDesktopWindow(), GW_CHILD);
3129 if (GetCurrentThreadId() != GetWindowThreadProcessId(hwnd, &procid))
3131 if (GetCurrentProcessId() == procid)
3133 if (SendMessageW(hwnd, WM_X11DRV_ACQUIRE_SELECTION, 0, 0))
3134 return;
3137 } while ((hwnd = GetWindow(hwnd, GW_HWNDNEXT)) != NULL);
3139 WARN("Failed to find another thread to take selection ownership. Clipboard data will be lost.\n");
3141 X11DRV_CLIPBOARD_ReleaseOwnership();
3142 empty_clipboard( FALSE );
3146 /**************************************************************************
3147 * X11DRV_CLIPBOARD_SynthesizeData
3149 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID)
3151 BOOL bsyn = TRUE;
3152 LPWINE_CLIPDATA lpSource = NULL;
3154 TRACE(" %04x\n", wFormatID);
3156 /* Don't need to synthesize if it already exists */
3157 if (X11DRV_CLIPBOARD_LookupData(wFormatID))
3158 return TRUE;
3160 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
3162 bsyn = ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
3163 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
3164 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
3165 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
3166 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
3167 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED);
3169 else if (wFormatID == CF_ENHMETAFILE)
3171 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
3172 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
3174 else if (wFormatID == CF_METAFILEPICT)
3176 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_ENHMETAFILE)) &&
3177 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
3179 else if (wFormatID == CF_DIB)
3181 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
3182 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
3184 else if (wFormatID == CF_BITMAP)
3186 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
3187 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
3190 if (bsyn)
3191 X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, CF_FLAG_SYNTHESIZED, NULL, TRUE);
3193 return bsyn;
3198 /**************************************************************************
3199 * X11DRV_EndClipboardUpdate
3200 * TODO:
3201 * Add locale if it hasn't already been added
3203 void CDECL X11DRV_EndClipboardUpdate(void)
3205 INT count = ClipDataCount;
3207 /* Do Unicode <-> Text <-> OEM mapping */
3208 X11DRV_CLIPBOARD_SynthesizeData(CF_TEXT);
3209 X11DRV_CLIPBOARD_SynthesizeData(CF_OEMTEXT);
3210 X11DRV_CLIPBOARD_SynthesizeData(CF_UNICODETEXT);
3212 /* Enhmetafile <-> MetafilePict mapping */
3213 X11DRV_CLIPBOARD_SynthesizeData(CF_ENHMETAFILE);
3214 X11DRV_CLIPBOARD_SynthesizeData(CF_METAFILEPICT);
3216 /* DIB <-> Bitmap mapping */
3217 X11DRV_CLIPBOARD_SynthesizeData(CF_DIB);
3218 X11DRV_CLIPBOARD_SynthesizeData(CF_BITMAP);
3220 TRACE("%d formats added to cached data\n", ClipDataCount - count);
3224 /***********************************************************************
3225 * X11DRV_SelectionRequest_TARGETS
3226 * Service a TARGETS selection request event
3228 static Atom X11DRV_SelectionRequest_TARGETS( Display *display, Window requestor,
3229 Atom target, Atom rprop )
3231 UINT i;
3232 Atom* targets;
3233 ULONG cTargets;
3234 LPWINE_CLIPFORMAT format;
3235 LPWINE_CLIPDATA lpData;
3237 /* Create X atoms for any clipboard types which don't have atoms yet.
3238 * This avoids sending bogus zero atoms.
3239 * Without this, copying might not have access to all clipboard types.
3240 * FIXME: is it safe to call this here?
3242 intern_atoms();
3245 * Count the number of items we wish to expose as selection targets.
3247 cTargets = 1; /* Include TARGETS */
3249 if (!list_head( &data_list )) return None;
3251 LIST_FOR_EACH_ENTRY( lpData, &data_list, WINE_CLIPDATA, entry )
3252 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
3253 if ((format->wFormatID == lpData->wFormatID) &&
3254 format->lpDrvExportFunc && format->drvData)
3255 cTargets++;
3257 TRACE(" found %d formats\n", cTargets);
3259 /* Allocate temp buffer */
3260 targets = HeapAlloc( GetProcessHeap(), 0, cTargets * sizeof(Atom));
3261 if(targets == NULL)
3262 return None;
3264 i = 0;
3265 targets[i++] = x11drv_atom(TARGETS);
3267 LIST_FOR_EACH_ENTRY( lpData, &data_list, WINE_CLIPDATA, entry )
3268 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
3269 if ((format->wFormatID == lpData->wFormatID) &&
3270 format->lpDrvExportFunc && format->drvData)
3271 targets[i++] = format->drvData;
3273 if (TRACE_ON(clipboard))
3275 unsigned int i;
3276 for ( i = 0; i < cTargets; i++)
3278 char *itemFmtName = XGetAtomName(display, targets[i]);
3279 TRACE("\tAtom# %d: Property %ld Type %s\n", i, targets[i], itemFmtName);
3280 XFree(itemFmtName);
3284 /* We may want to consider setting the type to xaTargets instead,
3285 * in case some apps expect this instead of XA_ATOM */
3286 XChangeProperty(display, requestor, rprop, XA_ATOM, 32,
3287 PropModeReplace, (unsigned char *)targets, cTargets);
3289 HeapFree(GetProcessHeap(), 0, targets);
3291 return rprop;
3295 /***********************************************************************
3296 * X11DRV_SelectionRequest_MULTIPLE
3297 * Service a MULTIPLE selection request event
3298 * rprop contains a list of (target,property) atom pairs.
3299 * The first atom names a target and the second names a property.
3300 * The effect is as if we have received a sequence of SelectionRequest events
3301 * (one for each atom pair) except that:
3302 * 1. We reply with a SelectionNotify only when all the requested conversions
3303 * have been performed.
3304 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
3305 * we replace the atom in the property by None.
3307 static Atom X11DRV_SelectionRequest_MULTIPLE( HWND hWnd, XSelectionRequestEvent *pevent )
3309 Display *display = pevent->display;
3310 Atom rprop;
3311 Atom atype=AnyPropertyType;
3312 int aformat;
3313 unsigned long remain;
3314 Atom* targetPropList=NULL;
3315 unsigned long cTargetPropList = 0;
3317 /* If the specified property is None the requestor is an obsolete client.
3318 * We support these by using the specified target atom as the reply property.
3320 rprop = pevent->property;
3321 if( rprop == None )
3322 rprop = pevent->target;
3323 if (!rprop)
3324 return 0;
3326 /* Read the MULTIPLE property contents. This should contain a list of
3327 * (target,property) atom pairs.
3329 if (!XGetWindowProperty(display, pevent->requestor, rprop,
3330 0, 0x3FFF, False, AnyPropertyType, &atype,&aformat,
3331 &cTargetPropList, &remain,
3332 (unsigned char**)&targetPropList))
3334 if (TRACE_ON(clipboard))
3336 char * const typeName = XGetAtomName(display, atype);
3337 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
3338 typeName, aformat, cTargetPropList, remain);
3339 XFree(typeName);
3343 * Make sure we got what we expect.
3344 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
3345 * in a MULTIPLE selection request should be of type ATOM_PAIR.
3346 * However some X apps(such as XPaint) are not compliant with this and return
3347 * a user defined atom in atype when XGetWindowProperty is called.
3348 * The data *is* an atom pair but is not denoted as such.
3350 if(aformat == 32 /* atype == xAtomPair */ )
3352 unsigned int i;
3354 /* Iterate through the ATOM_PAIR list and execute a SelectionRequest
3355 * for each (target,property) pair */
3357 for (i = 0; i < cTargetPropList; i+=2)
3359 XSelectionRequestEvent event;
3361 if (TRACE_ON(clipboard))
3363 char *targetName, *propName;
3364 targetName = XGetAtomName(display, targetPropList[i]);
3365 propName = XGetAtomName(display, targetPropList[i+1]);
3366 TRACE("MULTIPLE(%d): Target='%s' Prop='%s'\n",
3367 i/2, targetName, propName);
3368 XFree(targetName);
3369 XFree(propName);
3372 /* We must have a non "None" property to service a MULTIPLE target atom */
3373 if ( !targetPropList[i+1] )
3375 TRACE("\tMULTIPLE(%d): Skipping target with empty property!\n", i);
3376 continue;
3379 /* Set up an XSelectionRequestEvent for this (target,property) pair */
3380 event = *pevent;
3381 event.target = targetPropList[i];
3382 event.property = targetPropList[i+1];
3384 /* Fire a SelectionRequest, informing the handler that we are processing
3385 * a MULTIPLE selection request event.
3387 X11DRV_HandleSelectionRequest( hWnd, &event, TRUE );
3391 /* Free the list of targets/properties */
3392 XFree(targetPropList);
3394 else TRACE("Couldn't read MULTIPLE property\n");
3396 return rprop;
3400 /***********************************************************************
3401 * X11DRV_HandleSelectionRequest
3402 * Process an event selection request event.
3403 * The bIsMultiple flag is used to signal when EVENT_SelectionRequest is called
3404 * recursively while servicing a "MULTIPLE" selection target.
3406 * Note: We only receive this event when WINE owns the X selection
3408 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple )
3410 Display *display = event->display;
3411 XSelectionEvent result;
3412 Atom rprop = None;
3413 Window request = event->requestor;
3415 TRACE("\n");
3417 X11DRV_expect_error( display, is_window_error, NULL );
3420 * We can only handle the selection request if :
3421 * The selection is PRIMARY or CLIPBOARD, AND we can successfully open the clipboard.
3422 * Don't do these checks or open the clipboard while recursively processing MULTIPLE,
3423 * since this has been already done.
3425 if ( !bIsMultiple )
3427 if (((event->selection != XA_PRIMARY) && (event->selection != x11drv_atom(CLIPBOARD))))
3428 goto END;
3431 /* If the specified property is None the requestor is an obsolete client.
3432 * We support these by using the specified target atom as the reply property.
3434 rprop = event->property;
3435 if( rprop == None )
3436 rprop = event->target;
3438 if(event->target == x11drv_atom(TARGETS)) /* Return a list of all supported targets */
3440 /* TARGETS selection request */
3441 rprop = X11DRV_SelectionRequest_TARGETS( display, request, event->target, rprop );
3443 else if(event->target == x11drv_atom(MULTIPLE)) /* rprop contains a list of (target, property) atom pairs */
3445 /* MULTIPLE selection request */
3446 rprop = X11DRV_SelectionRequest_MULTIPLE( hWnd, event );
3448 else
3450 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, event->target);
3451 BOOL success = FALSE;
3453 if (lpFormat && lpFormat->lpDrvExportFunc)
3455 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(lpFormat->wFormatID);
3457 if (lpData)
3459 unsigned char* lpClipData;
3460 DWORD cBytes;
3461 HANDLE hClipData = lpFormat->lpDrvExportFunc(display, request, event->target,
3462 rprop, lpData, &cBytes);
3464 if (hClipData && (lpClipData = GlobalLock(hClipData)))
3466 int mode = PropModeReplace;
3468 TRACE("\tUpdating property %s, %d bytes\n",
3469 debugstr_format(lpFormat->wFormatID), cBytes);
3472 int nelements = min(cBytes, 65536);
3473 XChangeProperty(display, request, rprop, event->target,
3474 8, mode, lpClipData, nelements);
3475 mode = PropModeAppend;
3476 cBytes -= nelements;
3477 lpClipData += nelements;
3478 } while (cBytes > 0);
3480 GlobalUnlock(hClipData);
3481 GlobalFree(hClipData);
3482 success = TRUE;
3487 if (!success)
3488 rprop = None; /* report failure to client */
3491 END:
3492 /* reply to sender
3493 * SelectionNotify should be sent only at the end of a MULTIPLE request
3495 if ( !bIsMultiple )
3497 result.type = SelectionNotify;
3498 result.display = display;
3499 result.requestor = request;
3500 result.selection = event->selection;
3501 result.property = rprop;
3502 result.target = event->target;
3503 result.time = event->time;
3504 TRACE("Sending SelectionNotify event...\n");
3505 XSendEvent(display,event->requestor,False,NoEventMask,(XEvent*)&result);
3507 XSync( display, False );
3508 if (X11DRV_check_error()) WARN( "requestor %lx is no longer valid\n", event->requestor );
3512 /***********************************************************************
3513 * X11DRV_SelectionRequest
3515 void X11DRV_SelectionRequest( HWND hWnd, XEvent *event )
3517 X11DRV_HandleSelectionRequest( hWnd, &event->xselectionrequest, FALSE );
3521 /***********************************************************************
3522 * X11DRV_SelectionClear
3524 void X11DRV_SelectionClear( HWND hWnd, XEvent *xev )
3526 XSelectionClearEvent *event = &xev->xselectionclear;
3527 if (event->selection == XA_PRIMARY || event->selection == x11drv_atom(CLIPBOARD))
3528 X11DRV_CLIPBOARD_ReleaseSelection( event->display, event->selection,
3529 event->window, hWnd, event->time );