wined3d: Use the texture dimension helpers in wined3d_texture_update_overlay().
[wine.git] / dlls / winex11.drv / clipboard.c
blob5dc5e3c164aac8c69bee6563ea35f28281fb7439
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->wFormatID >= CF_GDIOBJFIRST &&
581 lpData->wFormatID <= CF_GDIOBJLAST) ||
582 lpData->wFormatID == CF_BITMAP ||
583 lpData->wFormatID == CF_DIB ||
584 lpData->wFormatID == CF_PALETTE)
586 if (lpData->hData)
587 DeleteObject(lpData->hData);
589 if ((lpData->wFormatID == CF_DIB) && lpData->drvData)
590 XFreePixmap(gdi_display, lpData->drvData);
592 else if (lpData->wFormatID == CF_METAFILEPICT)
594 if (lpData->hData)
596 DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData ))->hMF );
597 GlobalFree(lpData->hData);
600 else if (lpData->wFormatID == CF_ENHMETAFILE)
602 if (lpData->hData)
603 DeleteEnhMetaFile(lpData->hData);
605 else if (lpData->wFormatID < CF_PRIVATEFIRST ||
606 lpData->wFormatID > CF_PRIVATELAST)
608 if (lpData->hData)
609 GlobalFree(lpData->hData);
612 lpData->hData = 0;
613 lpData->drvData = 0;
617 /**************************************************************************
618 * X11DRV_CLIPBOARD_UpdateCache
620 static BOOL X11DRV_CLIPBOARD_UpdateCache(void)
622 BOOL bret = TRUE;
624 if (!selectionAcquired)
626 DWORD seqno = GetClipboardSequenceNumber();
628 if (!seqno)
630 ERR("Failed to retrieve clipboard information.\n");
631 bret = FALSE;
633 else if (wSeqNo < seqno)
635 empty_clipboard( TRUE );
637 if (X11DRV_CLIPBOARD_QueryAvailableData(thread_init_display()) < 0)
639 ERR("Failed to cache clipboard data owned by another process.\n");
640 bret = FALSE;
642 else
644 X11DRV_EndClipboardUpdate();
647 wSeqNo = seqno;
651 return bret;
655 /**************************************************************************
656 * X11DRV_CLIPBOARD_RenderFormat
658 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData)
660 BOOL bret = TRUE;
662 TRACE(" 0x%04x hData(%p)\n", lpData->wFormatID, lpData->hData);
664 if (lpData->hData) return bret; /* Already rendered */
666 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
667 bret = X11DRV_CLIPBOARD_RenderSynthesizedFormat(display, lpData);
668 else if (!selectionAcquired)
670 if (!X11DRV_CLIPBOARD_ReadSelectionData(display, lpData))
672 ERR("Failed to cache clipboard data owned by another process. Format=%04x\n",
673 lpData->wFormatID);
674 bret = FALSE;
677 else
679 HWND owner = GetClipboardOwner();
681 if (owner)
683 /* Send a WM_RENDERFORMAT message to notify the owner to render the
684 * data requested into the clipboard.
686 TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", owner);
687 SendMessageW(owner, WM_RENDERFORMAT, lpData->wFormatID, 0);
689 if (!lpData->hData) bret = FALSE;
691 else
693 ERR("hWndClipOwner is lost!\n");
694 bret = FALSE;
698 return bret;
702 /**************************************************************************
703 * CLIPBOARD_ConvertText
704 * Returns number of required/converted characters - not bytes!
706 static INT CLIPBOARD_ConvertText(WORD src_fmt, void const *src, INT src_size,
707 WORD dst_fmt, void *dst, INT dst_size)
709 UINT cp;
711 if(src_fmt == CF_UNICODETEXT)
713 switch(dst_fmt)
715 case CF_TEXT:
716 cp = CP_ACP;
717 break;
718 case CF_OEMTEXT:
719 cp = CP_OEMCP;
720 break;
721 default:
722 return 0;
724 return WideCharToMultiByte(cp, 0, src, src_size, dst, dst_size, NULL, NULL);
727 if(dst_fmt == CF_UNICODETEXT)
729 switch(src_fmt)
731 case CF_TEXT:
732 cp = CP_ACP;
733 break;
734 case CF_OEMTEXT:
735 cp = CP_OEMCP;
736 break;
737 default:
738 return 0;
740 return MultiByteToWideChar(cp, 0, src, src_size, dst, dst_size);
743 if(!dst_size) return src_size;
745 if(dst_size > src_size) dst_size = src_size;
747 if(src_fmt == CF_TEXT )
748 CharToOemBuffA(src, dst, dst_size);
749 else
750 OemToCharBuffA(src, dst, dst_size);
752 return dst_size;
756 /**************************************************************************
757 * X11DRV_CLIPBOARD_RenderSynthesizedFormat
759 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData)
761 BOOL bret = FALSE;
763 TRACE("\n");
765 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
767 UINT wFormatID = lpData->wFormatID;
769 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
770 bret = X11DRV_CLIPBOARD_RenderSynthesizedText(display, wFormatID);
771 else
773 switch (wFormatID)
775 case CF_DIB:
776 bret = X11DRV_CLIPBOARD_RenderSynthesizedDIB( display );
777 break;
779 case CF_BITMAP:
780 bret = X11DRV_CLIPBOARD_RenderSynthesizedBitmap( display );
781 break;
783 case CF_ENHMETAFILE:
784 bret = X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile( display );
785 break;
787 case CF_METAFILEPICT:
788 FIXME("Synthesizing CF_METAFILEPICT not implemented\n");
789 break;
791 default:
792 FIXME("Called to synthesize unknown format 0x%08x\n", wFormatID);
793 break;
797 lpData->wFlags &= ~CF_FLAG_SYNTHESIZED;
800 return bret;
804 /**************************************************************************
805 * X11DRV_CLIPBOARD_RenderSynthesizedText
807 * Renders synthesized text
809 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID)
811 LPCSTR lpstrS;
812 LPSTR lpstrT;
813 HANDLE hData;
814 INT src_chars, dst_chars, alloc_size;
815 LPWINE_CLIPDATA lpSource = NULL;
817 TRACE("%04x\n", wFormatID);
819 if ((lpSource = X11DRV_CLIPBOARD_LookupData(wFormatID)) &&
820 lpSource->hData)
821 return TRUE;
823 /* Look for rendered source or non-synthesized source */
824 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
825 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
827 TRACE("UNICODETEXT -> %04x\n", wFormatID);
829 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
830 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
832 TRACE("TEXT -> %04x\n", wFormatID);
834 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
835 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
837 TRACE("OEMTEXT -> %04x\n", wFormatID);
840 if (!lpSource || (lpSource->wFlags & CF_FLAG_SYNTHESIZED &&
841 !lpSource->hData))
842 return FALSE;
844 /* Ask the clipboard owner to render the source text if necessary */
845 if (!lpSource->hData && !X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
846 return FALSE;
848 lpstrS = GlobalLock(lpSource->hData);
849 if (!lpstrS)
850 return FALSE;
852 /* Text always NULL terminated */
853 if(lpSource->wFormatID == CF_UNICODETEXT)
854 src_chars = strlenW((LPCWSTR)lpstrS) + 1;
855 else
856 src_chars = strlen(lpstrS) + 1;
858 /* Calculate number of characters in the destination buffer */
859 dst_chars = CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS,
860 src_chars, wFormatID, NULL, 0);
862 if (!dst_chars)
863 return FALSE;
865 TRACE("Converting from '%04x' to '%04x', %i chars\n",
866 lpSource->wFormatID, wFormatID, src_chars);
868 /* Convert characters to bytes */
869 if(wFormatID == CF_UNICODETEXT)
870 alloc_size = dst_chars * sizeof(WCHAR);
871 else
872 alloc_size = dst_chars;
874 hData = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
875 GMEM_DDESHARE, alloc_size);
877 lpstrT = GlobalLock(hData);
879 if (lpstrT)
881 CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS, src_chars,
882 wFormatID, lpstrT, dst_chars);
883 GlobalUnlock(hData);
886 GlobalUnlock(lpSource->hData);
888 return X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, hData, 0, NULL, TRUE);
892 /***********************************************************************
893 * bitmap_info_size
895 * Return the size of the bitmap info structure including color table.
897 static int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
899 unsigned int colors, size, masks = 0;
901 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
903 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
904 colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
905 return sizeof(BITMAPCOREHEADER) + colors *
906 ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
908 else /* assume BITMAPINFOHEADER */
910 colors = info->bmiHeader.biClrUsed;
911 if (!colors && (info->bmiHeader.biBitCount <= 8))
912 colors = 1 << info->bmiHeader.biBitCount;
913 if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
914 size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
915 return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
920 /***********************************************************************
921 * create_dib_from_bitmap
923 * Allocates a packed DIB and copies the bitmap data into it.
925 static HGLOBAL create_dib_from_bitmap(HBITMAP hBmp)
927 BITMAP bmp;
928 HDC hdc;
929 HGLOBAL hPackedDIB;
930 LPBYTE pPackedDIB;
931 LPBITMAPINFOHEADER pbmiHeader;
932 unsigned int cDataSize, cPackedSize, OffsetBits;
933 int nLinesCopied;
935 if (!GetObjectW( hBmp, sizeof(bmp), &bmp )) return 0;
938 * A packed DIB contains a BITMAPINFO structure followed immediately by
939 * an optional color palette and the pixel data.
942 /* Calculate the size of the packed DIB */
943 cDataSize = abs( bmp.bmHeight ) * (((bmp.bmWidth * bmp.bmBitsPixel + 31) / 8) & ~3);
944 cPackedSize = sizeof(BITMAPINFOHEADER)
945 + ( (bmp.bmBitsPixel <= 8) ? (sizeof(RGBQUAD) * (1 << bmp.bmBitsPixel)) : 0 )
946 + cDataSize;
947 /* Get the offset to the bits */
948 OffsetBits = cPackedSize - cDataSize;
950 /* Allocate the packed DIB */
951 TRACE("\tAllocating packed DIB of size %d\n", cPackedSize);
952 hPackedDIB = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE /*| GMEM_ZEROINIT*/,
953 cPackedSize );
954 if ( !hPackedDIB )
956 WARN("Could not allocate packed DIB!\n");
957 return 0;
960 /* A packed DIB starts with a BITMAPINFOHEADER */
961 pPackedDIB = GlobalLock(hPackedDIB);
962 pbmiHeader = (LPBITMAPINFOHEADER)pPackedDIB;
964 /* Init the BITMAPINFOHEADER */
965 pbmiHeader->biSize = sizeof(BITMAPINFOHEADER);
966 pbmiHeader->biWidth = bmp.bmWidth;
967 pbmiHeader->biHeight = bmp.bmHeight;
968 pbmiHeader->biPlanes = 1;
969 pbmiHeader->biBitCount = bmp.bmBitsPixel;
970 pbmiHeader->biCompression = BI_RGB;
971 pbmiHeader->biSizeImage = 0;
972 pbmiHeader->biXPelsPerMeter = pbmiHeader->biYPelsPerMeter = 0;
973 pbmiHeader->biClrUsed = 0;
974 pbmiHeader->biClrImportant = 0;
976 /* Retrieve the DIB bits from the bitmap and fill in the
977 * DIB color table if present */
978 hdc = GetDC( 0 );
979 nLinesCopied = GetDIBits(hdc, /* Handle to device context */
980 hBmp, /* Handle to bitmap */
981 0, /* First scan line to set in dest bitmap */
982 bmp.bmHeight, /* Number of scan lines to copy */
983 pPackedDIB + OffsetBits, /* [out] Address of array for bitmap bits */
984 (LPBITMAPINFO) pbmiHeader, /* [out] Address of BITMAPINFO structure */
985 0); /* RGB or palette index */
986 GlobalUnlock(hPackedDIB);
987 ReleaseDC( 0, hdc );
989 /* Cleanup if GetDIBits failed */
990 if (nLinesCopied != bmp.bmHeight)
992 TRACE("\tGetDIBits returned %d. Actual lines=%d\n", nLinesCopied, bmp.bmHeight);
993 GlobalFree(hPackedDIB);
994 hPackedDIB = 0;
996 return hPackedDIB;
1000 /***********************************************************************
1001 * uri_to_dos
1003 * Converts a text/uri-list URI to DOS filename.
1005 static WCHAR* uri_to_dos(char *encodedURI)
1007 WCHAR *ret = NULL;
1008 int i;
1009 int j = 0;
1010 char *uri = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, strlen(encodedURI) + 1);
1011 if (uri == NULL)
1012 return NULL;
1013 for (i = 0; encodedURI[i]; ++i)
1015 if (encodedURI[i] == '%')
1017 if (encodedURI[i+1] && encodedURI[i+2])
1019 char buffer[3];
1020 int number;
1021 buffer[0] = encodedURI[i+1];
1022 buffer[1] = encodedURI[i+2];
1023 buffer[2] = '\0';
1024 sscanf(buffer, "%x", &number);
1025 uri[j++] = number;
1026 i += 2;
1028 else
1030 WARN("invalid URI encoding in %s\n", debugstr_a(encodedURI));
1031 HeapFree(GetProcessHeap(), 0, uri);
1032 return NULL;
1035 else
1036 uri[j++] = encodedURI[i];
1039 /* Read http://www.freedesktop.org/wiki/Draganddropwarts and cry... */
1040 if (strncmp(uri, "file:/", 6) == 0)
1042 if (uri[6] == '/')
1044 if (uri[7] == '/')
1046 /* file:///path/to/file (nautilus, thunar) */
1047 ret = wine_get_dos_file_name(&uri[7]);
1049 else if (uri[7])
1051 /* file://hostname/path/to/file (X file drag spec) */
1052 char hostname[256];
1053 char *path = strchr(&uri[7], '/');
1054 if (path)
1056 *path = '\0';
1057 if (strcmp(&uri[7], "localhost") == 0)
1059 *path = '/';
1060 ret = wine_get_dos_file_name(path);
1062 else if (gethostname(hostname, sizeof(hostname)) == 0)
1064 if (strcmp(hostname, &uri[7]) == 0)
1066 *path = '/';
1067 ret = wine_get_dos_file_name(path);
1073 else if (uri[6])
1075 /* file:/path/to/file (konqueror) */
1076 ret = wine_get_dos_file_name(&uri[5]);
1079 HeapFree(GetProcessHeap(), 0, uri);
1080 return ret;
1084 /**************************************************************************
1085 * X11DRV_CLIPBOARD_RenderSynthesizedDIB
1087 * Renders synthesized DIB
1089 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display)
1091 BOOL bret = FALSE;
1092 LPWINE_CLIPDATA lpSource = NULL;
1094 TRACE("\n");
1096 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) && lpSource->hData)
1098 bret = TRUE;
1100 /* If we have a bitmap and it's not synthesized or it has been rendered */
1101 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
1102 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1104 /* Render source if required */
1105 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1107 HGLOBAL hData = create_dib_from_bitmap( lpSource->hData );
1108 if (hData)
1110 X11DRV_CLIPBOARD_InsertClipboardData(CF_DIB, hData, 0, NULL, TRUE);
1111 bret = TRUE;
1116 return bret;
1120 /**************************************************************************
1121 * X11DRV_CLIPBOARD_RenderSynthesizedBitmap
1123 * Renders synthesized bitmap
1125 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display)
1127 BOOL bret = FALSE;
1128 LPWINE_CLIPDATA lpSource = NULL;
1130 TRACE("\n");
1132 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) && lpSource->hData)
1134 bret = TRUE;
1136 /* If we have a dib and it's not synthesized or it has been rendered */
1137 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
1138 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1140 /* Render source if required */
1141 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1143 HDC hdc;
1144 HBITMAP hData = NULL;
1145 unsigned int offset;
1146 LPBITMAPINFOHEADER lpbmih;
1148 hdc = GetDC(NULL);
1149 lpbmih = GlobalLock(lpSource->hData);
1150 if (lpbmih)
1152 offset = sizeof(BITMAPINFOHEADER)
1153 + ((lpbmih->biBitCount <= 8) ? (sizeof(RGBQUAD) *
1154 (1 << lpbmih->biBitCount)) : 0);
1156 hData = CreateDIBitmap(hdc, lpbmih, CBM_INIT, (LPBYTE)lpbmih +
1157 offset, (LPBITMAPINFO) lpbmih, DIB_RGB_COLORS);
1159 GlobalUnlock(lpSource->hData);
1161 ReleaseDC(NULL, hdc);
1163 if (hData)
1165 X11DRV_CLIPBOARD_InsertClipboardData(CF_BITMAP, hData, 0, NULL, TRUE);
1166 bret = TRUE;
1171 return bret;
1175 /**************************************************************************
1176 * X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile
1178 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile(Display *display)
1180 LPWINE_CLIPDATA lpSource = NULL;
1182 TRACE("\n");
1184 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_ENHMETAFILE)) && lpSource->hData)
1185 return TRUE;
1186 /* If we have a MF pict and it's not synthesized or it has been rendered */
1187 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
1188 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1190 /* Render source if required */
1191 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1193 METAFILEPICT *pmfp;
1194 HENHMETAFILE hData = NULL;
1196 pmfp = GlobalLock(lpSource->hData);
1197 if (pmfp)
1199 UINT size_mf_bits = GetMetaFileBitsEx(pmfp->hMF, 0, NULL);
1200 void *mf_bits = HeapAlloc(GetProcessHeap(), 0, size_mf_bits);
1201 if (mf_bits)
1203 GetMetaFileBitsEx(pmfp->hMF, size_mf_bits, mf_bits);
1204 hData = SetWinMetaFileBits(size_mf_bits, mf_bits, NULL, pmfp);
1205 HeapFree(GetProcessHeap(), 0, mf_bits);
1207 GlobalUnlock(lpSource->hData);
1210 if (hData)
1212 X11DRV_CLIPBOARD_InsertClipboardData(CF_ENHMETAFILE, hData, 0, NULL, TRUE);
1213 return TRUE;
1218 return FALSE;
1222 /**************************************************************************
1223 * X11DRV_CLIPBOARD_ImportXAString
1225 * Import XA_STRING, converting the string to CF_TEXT.
1227 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *display, Window w, Atom prop)
1229 LPBYTE lpdata;
1230 unsigned long cbytes;
1231 LPSTR lpstr;
1232 unsigned long i, inlcount = 0;
1233 HANDLE hText = 0;
1235 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1236 return 0;
1238 for (i = 0; i <= cbytes; i++)
1240 if (lpdata[i] == '\n')
1241 inlcount++;
1244 if ((hText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes + inlcount + 1)))
1246 lpstr = GlobalLock(hText);
1248 for (i = 0, inlcount = 0; i <= cbytes; i++)
1250 if (lpdata[i] == '\n')
1251 lpstr[inlcount++] = '\r';
1253 lpstr[inlcount++] = lpdata[i];
1256 GlobalUnlock(hText);
1259 /* Free the retrieved property data */
1260 HeapFree(GetProcessHeap(), 0, lpdata);
1262 return hText;
1266 /**************************************************************************
1267 * X11DRV_CLIPBOARD_ImportUTF8
1269 * Import XA_STRING, converting the string to CF_UNICODE.
1271 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *display, Window w, Atom prop)
1273 LPBYTE lpdata;
1274 unsigned long cbytes;
1275 LPSTR lpstr;
1276 unsigned long i, inlcount = 0;
1277 HANDLE hUnicodeText = 0;
1279 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1280 return 0;
1282 for (i = 0; i <= cbytes; i++)
1284 if (lpdata[i] == '\n')
1285 inlcount++;
1288 if ((lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbytes + inlcount + 1)))
1290 UINT count;
1292 for (i = 0, inlcount = 0; i <= cbytes; i++)
1294 if (lpdata[i] == '\n')
1295 lpstr[inlcount++] = '\r';
1297 lpstr[inlcount++] = lpdata[i];
1300 count = MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, NULL, 0);
1301 hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
1303 if (hUnicodeText)
1305 WCHAR *textW = GlobalLock(hUnicodeText);
1306 MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, textW, count);
1307 GlobalUnlock(hUnicodeText);
1310 HeapFree(GetProcessHeap(), 0, lpstr);
1313 /* Free the retrieved property data */
1314 HeapFree(GetProcessHeap(), 0, lpdata);
1316 return hUnicodeText;
1320 /**************************************************************************
1321 * X11DRV_CLIPBOARD_ImportCompoundText
1323 * Import COMPOUND_TEXT to CF_UNICODE
1325 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *display, Window w, Atom prop)
1327 int i, j, ret;
1328 char** srcstr;
1329 int count, lcount;
1330 int srclen, destlen;
1331 HANDLE hUnicodeText;
1332 XTextProperty txtprop;
1334 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &txtprop.value, &txtprop.nitems))
1336 return 0;
1339 txtprop.encoding = x11drv_atom(COMPOUND_TEXT);
1340 txtprop.format = 8;
1341 ret = XmbTextPropertyToTextList(display, &txtprop, &srcstr, &count);
1342 HeapFree(GetProcessHeap(), 0, txtprop.value);
1343 if (ret != Success || !count) return 0;
1345 TRACE("Importing %d line(s)\n", count);
1347 /* Compute number of lines */
1348 srclen = strlen(srcstr[0]);
1349 for (i = 0, lcount = 0; i <= srclen; i++)
1351 if (srcstr[0][i] == '\n')
1352 lcount++;
1355 destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
1357 TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
1359 if ((hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (destlen + lcount + 1) * sizeof(WCHAR))))
1361 WCHAR *deststr = GlobalLock(hUnicodeText);
1362 MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1364 if (lcount)
1366 for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1368 deststr[j] = deststr[i];
1370 if (deststr[i] == '\n')
1371 deststr[--j] = '\r';
1375 GlobalUnlock(hUnicodeText);
1378 XFreeStringList(srcstr);
1380 return hUnicodeText;
1384 /**************************************************************************
1385 * X11DRV_CLIPBOARD_ImportXAPIXMAP
1387 * Import XA_PIXMAP, converting the image to CF_DIB.
1389 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *display, Window w, Atom prop)
1391 LPBYTE lpdata;
1392 unsigned long cbytes;
1393 Pixmap *pPixmap;
1394 HANDLE hClipData = 0;
1396 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1398 XVisualInfo vis = default_visual;
1399 char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
1400 BITMAPINFO *info = (BITMAPINFO *)buffer;
1401 struct gdi_image_bits bits;
1402 Window root;
1403 int x,y; /* Unused */
1404 unsigned border_width; /* Unused */
1405 unsigned int depth, width, height;
1407 pPixmap = (Pixmap *) lpdata;
1409 /* Get the Pixmap dimensions and bit depth */
1410 if (!XGetGeometry(gdi_display, *pPixmap, &root, &x, &y, &width, &height,
1411 &border_width, &depth)) depth = 0;
1412 if (!pixmap_formats[depth]) return 0;
1414 TRACE("\tPixmap properties: width=%d, height=%d, depth=%d\n",
1415 width, height, depth);
1417 if (depth != vis.depth) switch (pixmap_formats[depth]->bits_per_pixel)
1419 case 1:
1420 case 4:
1421 case 8:
1422 break;
1423 case 16: /* assume R5G5B5 */
1424 vis.red_mask = 0x7c00;
1425 vis.green_mask = 0x03e0;
1426 vis.blue_mask = 0x001f;
1427 break;
1428 case 24: /* assume R8G8B8 */
1429 case 32: /* assume A8R8G8B8 */
1430 vis.red_mask = 0xff0000;
1431 vis.green_mask = 0x00ff00;
1432 vis.blue_mask = 0x0000ff;
1433 break;
1434 default:
1435 return 0;
1438 if (!get_pixmap_image( *pPixmap, width, height, &vis, info, &bits ))
1440 DWORD info_size = bitmap_info_size( info, DIB_RGB_COLORS );
1441 BYTE *ptr;
1443 hClipData = GlobalAlloc( GMEM_MOVEABLE | GMEM_DDESHARE,
1444 info_size + info->bmiHeader.biSizeImage );
1445 if (hClipData)
1447 ptr = GlobalLock( hClipData );
1448 memcpy( ptr, info, info_size );
1449 memcpy( ptr + info_size, bits.ptr, info->bmiHeader.biSizeImage );
1450 GlobalUnlock( hClipData );
1452 if (bits.free) bits.free( &bits );
1455 HeapFree(GetProcessHeap(), 0, lpdata);
1458 return hClipData;
1462 /**************************************************************************
1463 * X11DRV_CLIPBOARD_ImportImageBmp
1465 * Import image/bmp, converting the image to CF_DIB.
1467 static HANDLE X11DRV_CLIPBOARD_ImportImageBmp(Display *display, Window w, Atom prop)
1469 LPBYTE lpdata;
1470 unsigned long cbytes;
1471 HANDLE hClipData = 0;
1473 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1475 BITMAPFILEHEADER *bfh = (BITMAPFILEHEADER*)lpdata;
1477 if (cbytes >= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPCOREHEADER) &&
1478 bfh->bfType == 0x4d42 /* "BM" */)
1480 BITMAPINFO *bmi = (BITMAPINFO*)(bfh+1);
1481 HBITMAP hbmp;
1482 HDC hdc;
1484 hdc = GetDC(0);
1485 hbmp = CreateDIBitmap(
1486 hdc,
1487 &(bmi->bmiHeader),
1488 CBM_INIT,
1489 lpdata+bfh->bfOffBits,
1490 bmi,
1491 DIB_RGB_COLORS
1494 hClipData = create_dib_from_bitmap( hbmp );
1496 DeleteObject(hbmp);
1497 ReleaseDC(0, hdc);
1500 /* Free the retrieved property data */
1501 HeapFree(GetProcessHeap(), 0, lpdata);
1504 return hClipData;
1508 /**************************************************************************
1509 * X11DRV_CLIPBOARD_ImportMetaFilePict
1511 * Import MetaFilePict.
1513 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *display, Window w, Atom prop)
1515 LPBYTE lpdata;
1516 unsigned long cbytes;
1517 HANDLE hClipData = 0;
1519 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1521 if (cbytes)
1522 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata, (LPDWORD)&cbytes, FALSE);
1524 /* Free the retrieved property data */
1525 HeapFree(GetProcessHeap(), 0, lpdata);
1528 return hClipData;
1532 /**************************************************************************
1533 * X11DRV_ImportEnhMetaFile
1535 * Import EnhMetaFile.
1537 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *display, Window w, Atom prop)
1539 LPBYTE lpdata;
1540 unsigned long cbytes;
1541 HANDLE hClipData = 0;
1543 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1545 if (cbytes)
1546 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata, (LPDWORD)&cbytes, FALSE);
1548 /* Free the retrieved property data */
1549 HeapFree(GetProcessHeap(), 0, lpdata);
1552 return hClipData;
1556 /**************************************************************************
1557 * X11DRV_CLIPBOARD_ImportTextUriList
1559 * Import text/uri-list.
1561 static HANDLE X11DRV_CLIPBOARD_ImportTextUriList(Display *display, Window w, Atom prop)
1563 char *uriList;
1564 unsigned long len;
1565 char *uri;
1566 WCHAR *path;
1567 WCHAR *out = NULL;
1568 int size = 0;
1569 int capacity = 4096;
1570 int start = 0;
1571 int end = 0;
1572 HANDLE handle = NULL;
1574 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, (LPBYTE*)&uriList, &len))
1575 return 0;
1577 out = HeapAlloc(GetProcessHeap(), 0, capacity * sizeof(WCHAR));
1578 if (out == NULL) {
1579 HeapFree(GetProcessHeap(), 0, uriList);
1580 return 0;
1583 while (end < len)
1585 while (end < len && uriList[end] != '\r')
1586 ++end;
1587 if (end < (len - 1) && uriList[end+1] != '\n')
1589 WARN("URI list line doesn't end in \\r\\n\n");
1590 break;
1593 uri = HeapAlloc(GetProcessHeap(), 0, end - start + 1);
1594 if (uri == NULL)
1595 break;
1596 lstrcpynA(uri, &uriList[start], end - start + 1);
1597 path = uri_to_dos(uri);
1598 TRACE("converted URI %s to DOS path %s\n", debugstr_a(uri), debugstr_w(path));
1599 HeapFree(GetProcessHeap(), 0, uri);
1601 if (path)
1603 int pathSize = strlenW(path) + 1;
1604 if (pathSize > capacity-size)
1606 capacity = 2*capacity + pathSize;
1607 out = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, out, (capacity + 1)*sizeof(WCHAR));
1608 if (out == NULL)
1609 goto done;
1611 memcpy(&out[size], path, pathSize * sizeof(WCHAR));
1612 size += pathSize;
1613 done:
1614 HeapFree(GetProcessHeap(), 0, path);
1615 if (out == NULL)
1616 break;
1619 start = end + 2;
1620 end = start;
1622 if (out && end >= len)
1624 DROPFILES *dropFiles;
1625 handle = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, sizeof(DROPFILES) + (size + 1)*sizeof(WCHAR));
1626 if (handle)
1628 dropFiles = (DROPFILES*) GlobalLock(handle);
1629 dropFiles->pFiles = sizeof(DROPFILES);
1630 dropFiles->pt.x = 0;
1631 dropFiles->pt.y = 0;
1632 dropFiles->fNC = 0;
1633 dropFiles->fWide = TRUE;
1634 out[size] = '\0';
1635 memcpy(((char*)dropFiles) + dropFiles->pFiles, out, (size + 1)*sizeof(WCHAR));
1636 GlobalUnlock(handle);
1639 HeapFree(GetProcessHeap(), 0, out);
1640 HeapFree(GetProcessHeap(), 0, uriList);
1641 return handle;
1645 /**************************************************************************
1646 * X11DRV_ImportClipbordaData
1648 * Generic import clipboard data routine.
1650 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *display, Window w, Atom prop)
1652 LPVOID lpClipData;
1653 LPBYTE lpdata;
1654 unsigned long cbytes;
1655 HANDLE hClipData = 0;
1657 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1659 if (cbytes)
1661 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
1662 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes);
1663 if (hClipData == 0)
1665 HeapFree(GetProcessHeap(), 0, lpdata);
1666 return NULL;
1669 if ((lpClipData = GlobalLock(hClipData)))
1671 memcpy(lpClipData, lpdata, cbytes);
1672 GlobalUnlock(hClipData);
1674 else
1676 GlobalFree(hClipData);
1677 hClipData = 0;
1681 /* Free the retrieved property data */
1682 HeapFree(GetProcessHeap(), 0, lpdata);
1685 return hClipData;
1688 /**************************************************************************
1689 * X11DRV_CLIPBOARD_ImportSelection
1691 * Import the X selection into the clipboard format registered for the given X target.
1693 HANDLE X11DRV_CLIPBOARD_ImportSelection(Display *d, Atom target, Window w, Atom prop, UINT *windowsFormat)
1695 WINE_CLIPFORMAT *clipFormat;
1697 clipFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, target);
1698 if (clipFormat)
1700 *windowsFormat = clipFormat->wFormatID;
1701 return clipFormat->lpDrvImportFunc(d, w, prop);
1703 return NULL;
1707 /**************************************************************************
1708 X11DRV_CLIPBOARD_ExportClipboardData
1710 * Generic export clipboard data routine.
1712 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
1713 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1715 LPVOID lpClipData;
1716 UINT datasize = 0;
1717 HANDLE hClipData = 0;
1719 *lpBytes = 0; /* Assume failure */
1721 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1722 ERR("Failed to export %04x format\n", lpData->wFormatID);
1723 else
1725 datasize = GlobalSize(lpData->hData);
1727 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, datasize);
1728 if (hClipData == 0) return NULL;
1730 if ((lpClipData = GlobalLock(hClipData)))
1732 LPVOID lpdata = GlobalLock(lpData->hData);
1734 memcpy(lpClipData, lpdata, datasize);
1735 *lpBytes = datasize;
1737 GlobalUnlock(lpData->hData);
1738 GlobalUnlock(hClipData);
1739 } else {
1740 GlobalFree(hClipData);
1741 hClipData = 0;
1745 return hClipData;
1749 /**************************************************************************
1750 * X11DRV_CLIPBOARD_ExportXAString
1752 * Export CF_TEXT converting the string to XA_STRING.
1753 * Helper function for X11DRV_CLIPBOARD_ExportString.
1755 static HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1757 UINT i, j;
1758 UINT size;
1759 LPSTR text, lpstr = NULL;
1761 *lpBytes = 0; /* Assume return has zero bytes */
1763 text = GlobalLock(lpData->hData);
1764 size = strlen(text);
1766 /* remove carriage returns */
1767 lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1768 if (lpstr == NULL)
1769 goto done;
1771 for (i = 0,j = 0; i < size && text[i]; i++)
1773 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1774 continue;
1775 lpstr[j++] = text[i];
1778 lpstr[j]='\0';
1779 *lpBytes = j; /* Number of bytes in string */
1781 done:
1782 GlobalUnlock(lpData->hData);
1784 return lpstr;
1788 /**************************************************************************
1789 * X11DRV_CLIPBOARD_ExportUTF8String
1791 * Export CF_UNICODE converting the string to UTF8.
1792 * Helper function for X11DRV_CLIPBOARD_ExportString.
1794 static HANDLE X11DRV_CLIPBOARD_ExportUTF8String(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1796 UINT i, j;
1797 UINT size;
1798 LPWSTR uni_text;
1799 LPSTR text, lpstr = NULL;
1801 *lpBytes = 0; /* Assume return has zero bytes */
1803 uni_text = GlobalLock(lpData->hData);
1805 size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1807 text = HeapAlloc(GetProcessHeap(), 0, size);
1808 if (!text)
1809 goto done;
1810 WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1812 /* remove carriage returns */
1813 lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1814 if (lpstr == NULL)
1815 goto done;
1817 for (i = 0,j = 0; i < size && text[i]; i++)
1819 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1820 continue;
1821 lpstr[j++] = text[i];
1823 lpstr[j]='\0';
1825 *lpBytes = j; /* Number of bytes in string */
1827 done:
1828 HeapFree(GetProcessHeap(), 0, text);
1829 GlobalUnlock(lpData->hData);
1831 return lpstr;
1836 /**************************************************************************
1837 * X11DRV_CLIPBOARD_ExportCompoundText
1839 * Export CF_UNICODE to COMPOUND_TEXT
1840 * Helper function for X11DRV_CLIPBOARD_ExportString.
1842 static HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Display *display, Window requestor, Atom aTarget, Atom rprop,
1843 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1845 char* lpstr = 0;
1846 XTextProperty prop;
1847 XICCEncodingStyle style;
1848 UINT i, j;
1849 UINT size;
1850 LPWSTR uni_text;
1852 uni_text = GlobalLock(lpData->hData);
1854 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1855 lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1856 if (!lpstr)
1857 return 0;
1859 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1861 /* remove carriage returns */
1862 for (i = 0, j = 0; i < size && lpstr[i]; i++)
1864 if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1865 continue;
1866 lpstr[j++] = lpstr[i];
1868 lpstr[j]='\0';
1870 GlobalUnlock(lpData->hData);
1872 if (aTarget == x11drv_atom(COMPOUND_TEXT))
1873 style = XCompoundTextStyle;
1874 else
1875 style = XStdICCTextStyle;
1877 /* Update the X property */
1878 if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1880 XSetTextProperty(display, requestor, &prop, rprop);
1881 XFree(prop.value);
1884 HeapFree(GetProcessHeap(), 0, lpstr);
1886 return 0;
1889 /**************************************************************************
1890 * X11DRV_CLIPBOARD_ExportString
1892 * Export string
1894 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget, Atom rprop,
1895 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1897 if (X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1899 if (aTarget == XA_STRING)
1900 return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1901 else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1902 return X11DRV_CLIPBOARD_ExportCompoundText(display, requestor, aTarget,
1903 rprop, lpData, lpBytes);
1904 else
1906 TRACE("Exporting target %ld to default UTF8_STRING\n", aTarget);
1907 return X11DRV_CLIPBOARD_ExportUTF8String(lpData, lpBytes);
1910 else
1911 ERR("Failed to render %04x format\n", lpData->wFormatID);
1913 return 0;
1917 /**************************************************************************
1918 * X11DRV_CLIPBOARD_ExportXAPIXMAP
1920 * Export CF_DIB to XA_PIXMAP.
1922 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget, Atom rprop,
1923 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1925 HANDLE hData;
1926 unsigned char* lpData;
1928 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1930 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1931 return 0;
1934 if (!lpdata->drvData) /* If not already rendered */
1936 Pixmap pixmap;
1937 LPBITMAPINFO pbmi;
1938 struct gdi_image_bits bits;
1940 pbmi = GlobalLock( lpdata->hData );
1941 bits.ptr = (LPBYTE)pbmi + bitmap_info_size( pbmi, DIB_RGB_COLORS );
1942 bits.free = NULL;
1943 bits.is_copy = FALSE;
1944 pixmap = create_pixmap_from_image( 0, &default_visual, pbmi, &bits, DIB_RGB_COLORS );
1945 GlobalUnlock( lpdata->hData );
1946 lpdata->drvData = pixmap;
1949 *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1951 /* Wrap pixmap so we can return a handle */
1952 hData = GlobalAlloc(0, *lpBytes);
1953 lpData = GlobalLock(hData);
1954 memcpy(lpData, &lpdata->drvData, *lpBytes);
1955 GlobalUnlock(hData);
1957 return hData;
1961 /**************************************************************************
1962 * X11DRV_CLIPBOARD_ExportImageBmp
1964 * Export CF_DIB to image/bmp.
1966 static HANDLE X11DRV_CLIPBOARD_ExportImageBmp(Display *display, Window requestor, Atom aTarget, Atom rprop,
1967 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1969 HANDLE hpackeddib;
1970 LPBYTE dibdata;
1971 UINT bmpsize;
1972 HANDLE hbmpdata;
1973 LPBYTE bmpdata;
1974 BITMAPFILEHEADER *bfh;
1976 *lpBytes = 0;
1978 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1980 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1981 return 0;
1984 hpackeddib = lpdata->hData;
1986 dibdata = GlobalLock(hpackeddib);
1987 if (!dibdata)
1989 ERR("Failed to lock packed DIB\n");
1990 return 0;
1993 bmpsize = sizeof(BITMAPFILEHEADER) + GlobalSize(hpackeddib);
1995 hbmpdata = GlobalAlloc(0, bmpsize);
1997 if (hbmpdata)
1999 bmpdata = GlobalLock(hbmpdata);
2001 if (!bmpdata)
2003 GlobalFree(hbmpdata);
2004 GlobalUnlock(hpackeddib);
2005 return 0;
2008 /* bitmap file header */
2009 bfh = (BITMAPFILEHEADER*)bmpdata;
2010 bfh->bfType = 0x4d42; /* "BM" */
2011 bfh->bfSize = bmpsize;
2012 bfh->bfReserved1 = 0;
2013 bfh->bfReserved2 = 0;
2014 bfh->bfOffBits = sizeof(BITMAPFILEHEADER) + bitmap_info_size((BITMAPINFO*)dibdata, DIB_RGB_COLORS);
2016 /* rest of bitmap is the same as the packed dib */
2017 memcpy(bfh+1, dibdata, bmpsize-sizeof(BITMAPFILEHEADER));
2019 *lpBytes = bmpsize;
2021 GlobalUnlock(hbmpdata);
2024 GlobalUnlock(hpackeddib);
2026 return hbmpdata;
2030 /**************************************************************************
2031 * X11DRV_CLIPBOARD_ExportMetaFilePict
2033 * Export MetaFilePict.
2035 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget, Atom rprop,
2036 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
2038 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
2040 ERR("Failed to export %04x format\n", lpdata->wFormatID);
2041 return 0;
2044 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata->hData, lpBytes, TRUE);
2048 /**************************************************************************
2049 * X11DRV_CLIPBOARD_ExportEnhMetaFile
2051 * Export EnhMetaFile.
2053 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget, Atom rprop,
2054 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
2056 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
2058 ERR("Failed to export %04x format\n", lpdata->wFormatID);
2059 return 0;
2062 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata->hData, lpBytes, TRUE);
2066 /**************************************************************************
2067 * get_html_description_field
2069 * Find the value of a field in an HTML Format description.
2071 static LPCSTR get_html_description_field(LPCSTR data, LPCSTR keyword)
2073 LPCSTR pos=data;
2075 while (pos && *pos && *pos != '<')
2077 if (memcmp(pos, keyword, strlen(keyword)) == 0)
2078 return pos+strlen(keyword);
2080 pos = strchr(pos, '\n');
2081 if (pos) pos++;
2084 return NULL;
2088 /**************************************************************************
2089 * X11DRV_CLIPBOARD_ExportTextHtml
2091 * Export HTML Format to text/html.
2093 * FIXME: We should attempt to add an <a base> tag and convert windows paths.
2095 static HANDLE X11DRV_CLIPBOARD_ExportTextHtml(Display *display, Window requestor, Atom aTarget,
2096 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
2098 HANDLE hdata;
2099 LPCSTR data, field_value;
2100 UINT fragmentstart, fragmentend, htmlsize;
2101 HANDLE hhtmldata=NULL;
2102 LPSTR htmldata;
2104 *lpBytes = 0;
2106 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
2108 ERR("Failed to export %04x format\n", lpdata->wFormatID);
2109 return 0;
2112 hdata = lpdata->hData;
2114 data = GlobalLock(hdata);
2115 if (!data)
2117 ERR("Failed to lock HTML Format data\n");
2118 return 0;
2121 /* read the important fields */
2122 field_value = get_html_description_field(data, "StartFragment:");
2123 if (!field_value)
2125 ERR("Couldn't find StartFragment value\n");
2126 goto end;
2128 fragmentstart = atoi(field_value);
2130 field_value = get_html_description_field(data, "EndFragment:");
2131 if (!field_value)
2133 ERR("Couldn't find EndFragment value\n");
2134 goto end;
2136 fragmentend = atoi(field_value);
2138 /* export only the fragment */
2139 htmlsize = fragmentend - fragmentstart + 1;
2141 hhtmldata = GlobalAlloc(0, htmlsize);
2143 if (hhtmldata)
2145 htmldata = GlobalLock(hhtmldata);
2147 if (!htmldata)
2149 GlobalFree(hhtmldata);
2150 htmldata = NULL;
2151 goto end;
2154 memcpy(htmldata, &data[fragmentstart], fragmentend-fragmentstart);
2155 htmldata[htmlsize-1] = '\0';
2157 *lpBytes = htmlsize;
2159 GlobalUnlock(htmldata);
2162 end:
2164 GlobalUnlock(hdata);
2166 return hhtmldata;
2170 /**************************************************************************
2171 * X11DRV_CLIPBOARD_ExportHDROP
2173 * Export CF_HDROP format to text/uri-list.
2175 static HANDLE X11DRV_CLIPBOARD_ExportHDROP(Display *display, Window requestor, Atom aTarget,
2176 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
2178 HDROP hDrop;
2179 UINT i;
2180 UINT numFiles;
2181 HGLOBAL hClipData = NULL;
2182 char *textUriList = NULL;
2183 UINT textUriListSize = 32;
2184 UINT next = 0;
2186 *lpBytes = 0;
2188 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
2190 ERR("Failed to export %04x format\n", lpdata->wFormatID);
2191 return 0;
2193 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, textUriListSize);
2194 if (hClipData == NULL)
2195 return 0;
2196 hDrop = (HDROP) lpdata->hData;
2197 numFiles = DragQueryFileW(hDrop, 0xFFFFFFFF, NULL, 0);
2198 for (i = 0; i < numFiles; i++)
2200 UINT dosFilenameSize;
2201 WCHAR *dosFilename = NULL;
2202 char *unixFilename = NULL;
2203 UINT uriSize;
2204 UINT u;
2206 dosFilenameSize = 1 + DragQueryFileW(hDrop, i, NULL, 0);
2207 dosFilename = HeapAlloc(GetProcessHeap(), 0, dosFilenameSize*sizeof(WCHAR));
2208 if (dosFilename == NULL) goto failed;
2209 DragQueryFileW(hDrop, i, dosFilename, dosFilenameSize);
2210 unixFilename = wine_get_unix_file_name(dosFilename);
2211 HeapFree(GetProcessHeap(), 0, dosFilename);
2212 if (unixFilename == NULL) goto failed;
2213 uriSize = 8 + /* file:/// */
2214 3 * (lstrlenA(unixFilename) - 1) + /* "%xy" per char except first '/' */
2215 2; /* \r\n */
2216 if ((next + uriSize) > textUriListSize)
2218 UINT biggerSize = max( 2 * textUriListSize, next + uriSize );
2219 HGLOBAL bigger = GlobalReAlloc(hClipData, biggerSize, 0);
2220 if (bigger)
2222 hClipData = bigger;
2223 textUriListSize = biggerSize;
2225 else
2227 HeapFree(GetProcessHeap(), 0, unixFilename);
2228 goto failed;
2231 textUriList = GlobalLock(hClipData);
2232 lstrcpyA(&textUriList[next], "file:///");
2233 next += 8;
2234 /* URL encode everything - unnecessary, but easier/lighter than linking in shlwapi, and can't hurt */
2235 for (u = 1; unixFilename[u]; u++)
2237 static const char hex_table[] = "0123456789abcdef";
2238 textUriList[next++] = '%';
2239 textUriList[next++] = hex_table[unixFilename[u] >> 4];
2240 textUriList[next++] = hex_table[unixFilename[u] & 0xf];
2242 textUriList[next++] = '\r';
2243 textUriList[next++] = '\n';
2244 GlobalUnlock(hClipData);
2245 HeapFree(GetProcessHeap(), 0, unixFilename);
2248 *lpBytes = next;
2249 return hClipData;
2251 failed:
2252 GlobalFree(hClipData);
2253 *lpBytes = 0;
2254 return 0;
2258 /**************************************************************************
2259 * X11DRV_CLIPBOARD_QueryTargets
2261 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection,
2262 Atom target, XEvent *xe)
2264 INT i;
2266 XConvertSelection(display, selection, target, x11drv_atom(SELECTION_DATA), w, CurrentTime);
2269 * Wait until SelectionNotify is received
2271 for (i = 0; i < SELECTION_RETRIES; i++)
2273 Bool res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
2274 if (res && xe->xselection.selection == selection) break;
2276 usleep(SELECTION_WAIT);
2279 if (i == SELECTION_RETRIES)
2281 ERR("Timed out waiting for SelectionNotify event\n");
2282 return FALSE;
2284 /* Verify that the selection returned a valid TARGETS property */
2285 if ((xe->xselection.target != target) || (xe->xselection.property == None))
2287 /* Selection owner failed to respond or we missed the SelectionNotify */
2288 WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
2289 return FALSE;
2292 return TRUE;
2296 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
2298 return (event->error_code == BadAtom);
2301 /**************************************************************************
2302 * X11DRV_CLIPBOARD_InsertSelectionProperties
2304 * Mark properties available for future retrieval.
2306 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
2308 UINT i, nb_atoms = 0;
2309 Atom *atoms = NULL;
2311 /* Cache these formats in the clipboard cache */
2312 for (i = 0; i < count; i++)
2314 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
2316 if (lpFormat)
2318 /* We found at least one Window's format that mapps to the property.
2319 * Continue looking for more.
2321 * If more than one property map to a Window's format then we use the first
2322 * one and ignore the rest.
2324 while (lpFormat)
2326 TRACE("Atom#%d Property(%d): --> Format %s\n",
2327 i, lpFormat->drvData, debugstr_format(lpFormat->wFormatID));
2328 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, lpFormat, FALSE);
2329 lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
2332 else if (properties[i])
2334 /* add it to the list of atoms that we don't know about yet */
2335 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
2336 (count - i) * sizeof(*atoms) );
2337 if (atoms) atoms[nb_atoms++] = properties[i];
2341 /* query all unknown atoms in one go */
2342 if (atoms)
2344 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
2345 if (names)
2347 X11DRV_expect_error( display, is_atom_error, NULL );
2348 if (!XGetAtomNames( display, atoms, nb_atoms, names )) nb_atoms = 0;
2349 if (X11DRV_check_error())
2351 WARN( "got some bad atoms, ignoring\n" );
2352 nb_atoms = 0;
2354 for (i = 0; i < nb_atoms; i++)
2356 WINE_CLIPFORMAT *lpFormat;
2357 LPWSTR wname;
2358 int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
2359 wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2360 MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
2362 lpFormat = register_format( RegisterClipboardFormatW(wname), atoms[i] );
2363 HeapFree(GetProcessHeap(), 0, wname);
2364 if (!lpFormat)
2366 ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
2367 continue;
2369 TRACE("Atom#%d Property(%d): --> Format %s\n",
2370 i, lpFormat->drvData, debugstr_format(lpFormat->wFormatID));
2371 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, lpFormat, FALSE);
2373 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
2374 HeapFree( GetProcessHeap(), 0, names );
2376 HeapFree( GetProcessHeap(), 0, atoms );
2381 /**************************************************************************
2382 * X11DRV_CLIPBOARD_QueryAvailableData
2384 * Caches the list of data formats available from the current selection.
2385 * This queries the selection owner for the TARGETS property and saves all
2386 * reported property types.
2388 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display)
2390 XEvent xe;
2391 Atom atype=AnyPropertyType;
2392 int aformat;
2393 unsigned long remain;
2394 Atom* targetList=NULL;
2395 Window w;
2396 unsigned long cSelectionTargets = 0;
2398 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
2400 ERR("Received request to cache selection but process is owner=(%08x)\n",
2401 (unsigned) selectionWindow);
2402 return -1; /* Prevent self request */
2405 w = thread_selection_wnd();
2406 if (!w)
2408 ERR("No window available to retrieve selection!\n");
2409 return -1;
2413 * Query the selection owner for the TARGETS property
2415 if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
2416 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2418 if (use_primary_selection && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
2419 selectionCacheSrc = XA_PRIMARY;
2420 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
2421 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2422 else
2424 Atom xstr = XA_STRING;
2426 /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
2427 if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
2429 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2430 selectionCacheSrc = XA_PRIMARY;
2431 return 1;
2433 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
2435 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2436 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2437 return 1;
2439 else
2441 WARN("Failed to query selection owner for available data.\n");
2442 return -1;
2446 else return 0; /* No selection owner so report 0 targets available */
2448 /* Read the TARGETS property contents */
2449 if (!XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
2450 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
2451 &remain, (unsigned char**)&targetList))
2453 TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
2454 atype, aformat, cSelectionTargets, remain);
2456 * The TARGETS property should have returned us a list of atoms
2457 * corresponding to each selection target format supported.
2459 if (atype == XA_ATOM || atype == x11drv_atom(TARGETS))
2461 if (aformat == 32)
2463 X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, cSelectionTargets);
2465 else if (aformat == 8) /* work around quartz-wm brain damage */
2467 unsigned long i, count = cSelectionTargets / sizeof(CARD32);
2468 Atom *atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(Atom) );
2469 for (i = 0; i < count; i++)
2470 atoms[i] = ((CARD32 *)targetList)[i]; /* FIXME: byte swapping */
2471 X11DRV_CLIPBOARD_InsertSelectionProperties( display, atoms, count );
2472 HeapFree( GetProcessHeap(), 0, atoms );
2476 /* Free the list of targets */
2477 XFree(targetList);
2479 else WARN("Failed to read TARGETS property\n");
2481 return cSelectionTargets;
2485 /**************************************************************************
2486 * X11DRV_CLIPBOARD_ReadSelectionData
2488 * This method is invoked only when we DO NOT own the X selection
2490 * We always get the data from the selection client each time,
2491 * since we have no way of determining if the data in our cache is stale.
2493 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData)
2495 Bool res;
2496 DWORD i;
2497 XEvent xe;
2498 BOOL bRet = FALSE;
2500 TRACE("%04x\n", lpData->wFormatID);
2502 if (!lpData->lpFormat)
2504 ERR("Requesting format %04x but no source format linked to data.\n",
2505 lpData->wFormatID);
2506 return FALSE;
2509 if (!selectionAcquired)
2511 Window w = thread_selection_wnd();
2512 if(!w)
2514 ERR("No window available to read selection data!\n");
2515 return FALSE;
2518 TRACE("Requesting conversion of %s property (%d) from selection type %08x\n",
2519 debugstr_format(lpData->lpFormat->wFormatID), lpData->lpFormat->drvData,
2520 (UINT)selectionCacheSrc);
2522 XConvertSelection(display, selectionCacheSrc, lpData->lpFormat->drvData,
2523 x11drv_atom(SELECTION_DATA), w, CurrentTime);
2525 /* wait until SelectionNotify is received */
2526 for (i = 0; i < SELECTION_RETRIES; i++)
2528 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
2529 if (res && xe.xselection.selection == selectionCacheSrc) break;
2531 usleep(SELECTION_WAIT);
2534 if (i == SELECTION_RETRIES)
2536 ERR("Timed out waiting for SelectionNotify event\n");
2538 /* Verify that the selection returned a valid TARGETS property */
2539 else if (xe.xselection.property != None)
2542 * Read the contents of the X selection property
2543 * into WINE's clipboard cache and converting the
2544 * data format if necessary.
2546 HANDLE hData = lpData->lpFormat->lpDrvImportFunc(display, xe.xselection.requestor,
2547 xe.xselection.property);
2549 if (hData)
2550 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, hData, 0, lpData->lpFormat, TRUE);
2551 else
2552 TRACE("Import function failed\n");
2554 else
2556 TRACE("Failed to convert selection\n");
2559 else
2561 ERR("Received request to cache selection data but process is owner\n");
2564 TRACE("Returning %d\n", bRet);
2566 return bRet;
2570 /**************************************************************************
2571 * X11DRV_CLIPBOARD_GetProperty
2572 * Gets type, data and size.
2574 static BOOL X11DRV_CLIPBOARD_GetProperty(Display *display, Window w, Atom prop,
2575 Atom *atype, unsigned char** data, unsigned long* datasize)
2577 int aformat;
2578 unsigned long pos = 0, nitems, remain, count;
2579 unsigned char *val = NULL, *buffer;
2581 TRACE("Reading property %lu from X window %lx\n", prop, w);
2583 for (;;)
2585 if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
2586 AnyPropertyType, atype, &aformat, &nitems, &remain, &buffer))
2588 WARN("Failed to read property\n");
2589 HeapFree( GetProcessHeap(), 0, val );
2590 return FALSE;
2593 count = get_property_size( aformat, nitems );
2594 if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
2595 else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
2597 if (!*data)
2599 XFree( buffer );
2600 HeapFree( GetProcessHeap(), 0, val );
2601 return FALSE;
2603 val = *data;
2604 memcpy( (int *)val + pos, buffer, count );
2605 XFree( buffer );
2606 if (!remain)
2608 *datasize = pos * sizeof(int) + count;
2609 val[*datasize] = 0;
2610 break;
2612 pos += count / sizeof(int);
2615 /* Delete the property on the window now that we are done
2616 * This will send a PropertyNotify event to the selection owner. */
2617 XDeleteProperty(display, w, prop);
2618 return TRUE;
2622 struct clipboard_data_packet {
2623 struct list entry;
2624 unsigned long size;
2625 unsigned char *data;
2628 /**************************************************************************
2629 * X11DRV_CLIPBOARD_ReadProperty
2630 * Reads the contents of the X selection property.
2632 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
2633 unsigned char** data, unsigned long* datasize)
2635 Atom atype;
2636 XEvent xe;
2638 if (prop == None)
2639 return FALSE;
2641 while (XCheckTypedWindowEvent(display, w, PropertyNotify, &xe))
2644 if (!X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, data, datasize))
2645 return FALSE;
2647 if (atype == x11drv_atom(INCR))
2649 unsigned char *buf;
2650 unsigned long bufsize = 0;
2651 struct list packets;
2652 struct clipboard_data_packet *packet, *packet2;
2653 BOOL res;
2655 HeapFree(GetProcessHeap(), 0, *data);
2656 *data = NULL;
2658 list_init(&packets);
2660 for (;;)
2662 int i;
2663 unsigned char *prop_data;
2664 unsigned long prop_size;
2666 /* Wait until PropertyNotify is received */
2667 for (i = 0; i < SELECTION_RETRIES; i++)
2669 Bool res;
2671 res = XCheckTypedWindowEvent(display, w, PropertyNotify, &xe);
2672 if (res && xe.xproperty.atom == prop &&
2673 xe.xproperty.state == PropertyNewValue)
2674 break;
2675 usleep(SELECTION_WAIT);
2678 if (i >= SELECTION_RETRIES ||
2679 !X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, &prop_data, &prop_size))
2681 res = FALSE;
2682 break;
2685 /* Retrieved entire data. */
2686 if (prop_size == 0)
2688 HeapFree(GetProcessHeap(), 0, prop_data);
2689 res = TRUE;
2690 break;
2693 packet = HeapAlloc(GetProcessHeap(), 0, sizeof(*packet));
2694 if (!packet)
2696 HeapFree(GetProcessHeap(), 0, prop_data);
2697 res = FALSE;
2698 break;
2701 packet->size = prop_size;
2702 packet->data = prop_data;
2703 list_add_tail(&packets, &packet->entry);
2704 bufsize += prop_size;
2707 if (res)
2709 buf = HeapAlloc(GetProcessHeap(), 0, bufsize + 1);
2710 if (buf)
2712 unsigned long bytes_copied = 0;
2713 *datasize = bufsize;
2714 LIST_FOR_EACH_ENTRY( packet, &packets, struct clipboard_data_packet, entry)
2716 memcpy(&buf[bytes_copied], packet->data, packet->size);
2717 bytes_copied += packet->size;
2719 buf[bufsize] = 0;
2720 *data = buf;
2722 else
2723 res = FALSE;
2726 LIST_FOR_EACH_ENTRY_SAFE( packet, packet2, &packets, struct clipboard_data_packet, entry)
2728 HeapFree(GetProcessHeap(), 0, packet->data);
2729 HeapFree(GetProcessHeap(), 0, packet);
2732 return res;
2735 return TRUE;
2739 /**************************************************************************
2740 * CLIPBOARD_SerializeMetafile
2742 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
2744 HANDLE h = 0;
2746 TRACE(" wFormat=%d hdata=%p out=%d\n", wformat, hdata, out);
2748 if (out) /* Serialize out, caller should free memory */
2750 *lpcbytes = 0; /* Assume failure */
2752 if (wformat == CF_METAFILEPICT)
2754 LPMETAFILEPICT lpmfp = GlobalLock(hdata);
2755 unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2757 h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
2758 if (h)
2760 char *pdata = GlobalLock(h);
2762 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
2763 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
2765 *lpcbytes = size + sizeof(METAFILEPICT);
2767 GlobalUnlock(h);
2770 GlobalUnlock(hdata);
2772 else if (wformat == CF_ENHMETAFILE)
2774 int size = GetEnhMetaFileBits(hdata, 0, NULL);
2776 h = GlobalAlloc(0, size);
2777 if (h)
2779 LPVOID pdata = GlobalLock(h);
2781 GetEnhMetaFileBits(hdata, size, pdata);
2782 *lpcbytes = size;
2784 GlobalUnlock(h);
2788 else
2790 if (wformat == CF_METAFILEPICT)
2792 h = GlobalAlloc(0, sizeof(METAFILEPICT));
2793 if (h)
2795 unsigned int wiresize;
2796 LPMETAFILEPICT lpmfp = GlobalLock(h);
2798 memcpy(lpmfp, hdata, sizeof(METAFILEPICT));
2799 wiresize = *lpcbytes - sizeof(METAFILEPICT);
2800 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
2801 ((const BYTE *)hdata) + sizeof(METAFILEPICT));
2802 GlobalUnlock(h);
2805 else if (wformat == CF_ENHMETAFILE)
2807 h = SetEnhMetaFileBits(*lpcbytes, hdata);
2811 return h;
2815 /**************************************************************************
2816 * X11DRV_CLIPBOARD_ReleaseSelection
2818 * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
2820 static void X11DRV_CLIPBOARD_ReleaseSelection(Display *display, Atom selType, Window w, HWND hwnd, Time time)
2822 /* w is the window that lost the selection
2824 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
2825 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
2827 if (selectionAcquired && (w == selectionWindow))
2829 HWND owner;
2831 /* completely give up the selection */
2832 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
2834 if (X11DRV_CLIPBOARD_IsProcessOwner( &owner ))
2836 /* Since we're still the owner, this wasn't initiated by
2837 another Wine process */
2838 if (OpenClipboard(hwnd))
2840 /* Destroy private objects */
2841 SendMessageW(owner, WM_DESTROYCLIPBOARD, 0, 0);
2843 /* Give up ownership of the windows clipboard */
2844 X11DRV_CLIPBOARD_ReleaseOwnership();
2845 CloseClipboard();
2849 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2851 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2853 if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2855 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2856 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2858 else
2859 TRACE("We no longer own PRIMARY\n");
2861 else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2863 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2865 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2867 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2868 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2870 else
2871 TRACE("We no longer own CLIPBOARD\n");
2874 selectionWindow = None;
2876 empty_clipboard( FALSE );
2878 /* Reset the selection flags now that we are done */
2879 selectionAcquired = S_NOSELECTION;
2884 /**************************************************************************
2885 * X11DRV Clipboard Exports
2886 **************************************************************************/
2889 static void selection_acquire(void)
2891 Window owner;
2892 Display *display;
2894 owner = thread_selection_wnd();
2895 display = thread_display();
2897 selectionAcquired = 0;
2898 selectionWindow = 0;
2900 /* Grab PRIMARY selection if not owned */
2901 if (use_primary_selection)
2902 XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2904 /* Grab CLIPBOARD selection if not owned */
2905 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2907 if (use_primary_selection && XGetSelectionOwner(display, XA_PRIMARY) == owner)
2908 selectionAcquired |= S_PRIMARY;
2910 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2911 selectionAcquired |= S_CLIPBOARD;
2913 if (selectionAcquired)
2915 selectionWindow = owner;
2916 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2920 static DWORD WINAPI selection_thread_proc(LPVOID p)
2922 HANDLE event = p;
2924 TRACE("\n");
2926 selection_acquire();
2927 SetEvent(event);
2929 while (selectionAcquired)
2931 MsgWaitForMultipleObjectsEx(0, NULL, INFINITE, QS_SENDMESSAGE, 0);
2934 return 0;
2937 /**************************************************************************
2938 * X11DRV_AcquireClipboard
2940 void X11DRV_AcquireClipboard(HWND hWndClipWindow)
2942 DWORD procid;
2943 HANDLE selectionThread;
2945 TRACE(" %p\n", hWndClipWindow);
2948 * It's important that the selection get acquired from the thread
2949 * that owns the clipboard window. The primary reason is that we know
2950 * it is running a message loop and therefore can process the
2951 * X selection events.
2953 if (hWndClipWindow &&
2954 GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, &procid))
2956 if (procid != GetCurrentProcessId())
2958 WARN("Setting clipboard owner to other process is not supported\n");
2959 hWndClipWindow = NULL;
2961 else
2963 TRACE("Thread %x is acquiring selection with thread %x's window %p\n",
2964 GetCurrentThreadId(),
2965 GetWindowThreadProcessId(hWndClipWindow, NULL), hWndClipWindow);
2967 SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0);
2968 return;
2972 if (hWndClipWindow)
2974 selection_acquire();
2976 else
2978 HANDLE event = CreateEventW(NULL, FALSE, FALSE, NULL);
2979 selectionThread = CreateThread(NULL, 0, selection_thread_proc, event, 0, NULL);
2981 if (selectionThread)
2983 WaitForSingleObject(event, INFINITE);
2984 CloseHandle(selectionThread);
2986 CloseHandle(event);
2991 static void empty_clipboard(BOOL keepunowned)
2993 WINE_CLIPDATA *data, *next;
2995 LIST_FOR_EACH_ENTRY_SAFE( data, next, &data_list, WINE_CLIPDATA, entry )
2997 if (keepunowned && (data->wFlags & CF_FLAG_UNOWNED)) continue;
2998 list_remove( &data->entry );
2999 X11DRV_CLIPBOARD_FreeData( data );
3000 HeapFree( GetProcessHeap(), 0, data );
3001 ClipDataCount--;
3004 TRACE(" %d entries remaining in cache.\n", ClipDataCount);
3007 /**************************************************************************
3008 * X11DRV_EmptyClipboard
3010 * Empty cached clipboard data.
3012 void CDECL X11DRV_EmptyClipboard(void)
3014 X11DRV_AcquireClipboard( GetOpenClipboardWindow() );
3015 empty_clipboard( FALSE );
3018 /**************************************************************************
3019 * X11DRV_SetClipboardData
3021 BOOL CDECL X11DRV_SetClipboardData(UINT wFormat, HANDLE hData, BOOL owner)
3023 DWORD flags = 0;
3024 BOOL bResult = TRUE;
3026 /* If it's not owned, data can only be set if the format data is not already owned
3027 and its rendering is not delayed */
3028 if (!owner)
3030 LPWINE_CLIPDATA lpRender;
3032 X11DRV_CLIPBOARD_UpdateCache();
3034 if (!hData ||
3035 ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)) &&
3036 !(lpRender->wFlags & CF_FLAG_UNOWNED)))
3037 bResult = FALSE;
3038 else
3039 flags = CF_FLAG_UNOWNED;
3042 bResult &= X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData, flags, NULL, TRUE);
3044 return bResult;
3048 /**************************************************************************
3049 * CountClipboardFormats
3051 INT CDECL X11DRV_CountClipboardFormats(void)
3053 X11DRV_CLIPBOARD_UpdateCache();
3055 TRACE(" count=%d\n", ClipDataCount);
3057 return ClipDataCount;
3061 /**************************************************************************
3062 * X11DRV_EnumClipboardFormats
3064 UINT CDECL X11DRV_EnumClipboardFormats(UINT wFormat)
3066 struct list *ptr = NULL;
3068 TRACE("(%04X)\n", wFormat);
3070 X11DRV_CLIPBOARD_UpdateCache();
3072 if (!wFormat)
3074 ptr = list_head( &data_list );
3076 else
3078 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
3079 if (lpData) ptr = list_next( &data_list, &lpData->entry );
3082 if (!ptr) return 0;
3083 return LIST_ENTRY( ptr, WINE_CLIPDATA, entry )->wFormatID;
3087 /**************************************************************************
3088 * X11DRV_IsClipboardFormatAvailable
3090 BOOL CDECL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
3092 BOOL bRet = FALSE;
3094 TRACE("(%04X)\n", wFormat);
3096 X11DRV_CLIPBOARD_UpdateCache();
3098 if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
3099 bRet = TRUE;
3101 TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
3103 return bRet;
3107 /**************************************************************************
3108 * GetClipboardData (USER.142)
3110 HANDLE CDECL X11DRV_GetClipboardData(UINT wFormat)
3112 LPWINE_CLIPDATA lpRender;
3114 TRACE("(%04X)\n", wFormat);
3116 X11DRV_CLIPBOARD_UpdateCache();
3118 if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
3120 if ( !lpRender->hData )
3121 X11DRV_CLIPBOARD_RenderFormat(thread_init_display(), lpRender);
3123 TRACE(" returning %p (type %04x)\n", lpRender->hData, lpRender->wFormatID);
3124 return lpRender->hData;
3127 return 0;
3131 /**************************************************************************
3132 * ResetSelectionOwner
3134 * Called when the thread owning the selection is destroyed and we need to
3135 * preserve the selection ownership. We look for another top level window
3136 * in this process and send it a message to acquire the selection.
3138 void X11DRV_ResetSelectionOwner(void)
3140 HWND hwnd;
3141 DWORD procid;
3143 TRACE("\n");
3145 if (!selectionAcquired || thread_selection_wnd() != selectionWindow)
3146 return;
3148 selectionAcquired = S_NOSELECTION;
3149 selectionWindow = 0;
3151 hwnd = GetWindow(GetDesktopWindow(), GW_CHILD);
3154 if (GetCurrentThreadId() != GetWindowThreadProcessId(hwnd, &procid))
3156 if (GetCurrentProcessId() == procid)
3158 if (SendMessageW(hwnd, WM_X11DRV_ACQUIRE_SELECTION, 0, 0))
3159 return;
3162 } while ((hwnd = GetWindow(hwnd, GW_HWNDNEXT)) != NULL);
3164 WARN("Failed to find another thread to take selection ownership. Clipboard data will be lost.\n");
3166 X11DRV_CLIPBOARD_ReleaseOwnership();
3167 empty_clipboard( FALSE );
3171 /**************************************************************************
3172 * X11DRV_CLIPBOARD_SynthesizeData
3174 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID)
3176 BOOL bsyn = TRUE;
3177 LPWINE_CLIPDATA lpSource = NULL;
3179 TRACE(" %04x\n", wFormatID);
3181 /* Don't need to synthesize if it already exists */
3182 if (X11DRV_CLIPBOARD_LookupData(wFormatID))
3183 return TRUE;
3185 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
3187 bsyn = ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
3188 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
3189 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
3190 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
3191 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
3192 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED);
3194 else if (wFormatID == CF_ENHMETAFILE)
3196 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
3197 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
3199 else if (wFormatID == CF_METAFILEPICT)
3201 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_ENHMETAFILE)) &&
3202 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
3204 else if (wFormatID == CF_DIB)
3206 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
3207 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
3209 else if (wFormatID == CF_BITMAP)
3211 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
3212 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
3215 if (bsyn)
3216 X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, CF_FLAG_SYNTHESIZED, NULL, TRUE);
3218 return bsyn;
3223 /**************************************************************************
3224 * X11DRV_EndClipboardUpdate
3225 * TODO:
3226 * Add locale if it hasn't already been added
3228 void CDECL X11DRV_EndClipboardUpdate(void)
3230 INT count = ClipDataCount;
3232 /* Do Unicode <-> Text <-> OEM mapping */
3233 X11DRV_CLIPBOARD_SynthesizeData(CF_TEXT);
3234 X11DRV_CLIPBOARD_SynthesizeData(CF_OEMTEXT);
3235 X11DRV_CLIPBOARD_SynthesizeData(CF_UNICODETEXT);
3237 /* Enhmetafile <-> MetafilePict mapping */
3238 X11DRV_CLIPBOARD_SynthesizeData(CF_ENHMETAFILE);
3239 X11DRV_CLIPBOARD_SynthesizeData(CF_METAFILEPICT);
3241 /* DIB <-> Bitmap mapping */
3242 X11DRV_CLIPBOARD_SynthesizeData(CF_DIB);
3243 X11DRV_CLIPBOARD_SynthesizeData(CF_BITMAP);
3245 TRACE("%d formats added to cached data\n", ClipDataCount - count);
3249 /***********************************************************************
3250 * X11DRV_SelectionRequest_TARGETS
3251 * Service a TARGETS selection request event
3253 static Atom X11DRV_SelectionRequest_TARGETS( Display *display, Window requestor,
3254 Atom target, Atom rprop )
3256 UINT i;
3257 Atom* targets;
3258 ULONG cTargets;
3259 LPWINE_CLIPFORMAT format;
3260 LPWINE_CLIPDATA lpData;
3262 /* Create X atoms for any clipboard types which don't have atoms yet.
3263 * This avoids sending bogus zero atoms.
3264 * Without this, copying might not have access to all clipboard types.
3265 * FIXME: is it safe to call this here?
3267 intern_atoms();
3270 * Count the number of items we wish to expose as selection targets.
3272 cTargets = 1; /* Include TARGETS */
3274 if (!list_head( &data_list )) return None;
3276 LIST_FOR_EACH_ENTRY( lpData, &data_list, WINE_CLIPDATA, entry )
3277 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
3278 if ((format->wFormatID == lpData->wFormatID) &&
3279 format->lpDrvExportFunc && format->drvData)
3280 cTargets++;
3282 TRACE(" found %d formats\n", cTargets);
3284 /* Allocate temp buffer */
3285 targets = HeapAlloc( GetProcessHeap(), 0, cTargets * sizeof(Atom));
3286 if(targets == NULL)
3287 return None;
3289 i = 0;
3290 targets[i++] = x11drv_atom(TARGETS);
3292 LIST_FOR_EACH_ENTRY( lpData, &data_list, WINE_CLIPDATA, entry )
3293 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
3294 if ((format->wFormatID == lpData->wFormatID) &&
3295 format->lpDrvExportFunc && format->drvData)
3296 targets[i++] = format->drvData;
3298 if (TRACE_ON(clipboard))
3300 unsigned int i;
3301 for ( i = 0; i < cTargets; i++)
3303 char *itemFmtName = XGetAtomName(display, targets[i]);
3304 TRACE("\tAtom# %d: Property %ld Type %s\n", i, targets[i], itemFmtName);
3305 XFree(itemFmtName);
3309 /* We may want to consider setting the type to xaTargets instead,
3310 * in case some apps expect this instead of XA_ATOM */
3311 XChangeProperty(display, requestor, rprop, XA_ATOM, 32,
3312 PropModeReplace, (unsigned char *)targets, cTargets);
3314 HeapFree(GetProcessHeap(), 0, targets);
3316 return rprop;
3320 /***********************************************************************
3321 * X11DRV_SelectionRequest_MULTIPLE
3322 * Service a MULTIPLE selection request event
3323 * rprop contains a list of (target,property) atom pairs.
3324 * The first atom names a target and the second names a property.
3325 * The effect is as if we have received a sequence of SelectionRequest events
3326 * (one for each atom pair) except that:
3327 * 1. We reply with a SelectionNotify only when all the requested conversions
3328 * have been performed.
3329 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
3330 * we replace the atom in the property by None.
3332 static Atom X11DRV_SelectionRequest_MULTIPLE( HWND hWnd, XSelectionRequestEvent *pevent )
3334 Display *display = pevent->display;
3335 Atom rprop;
3336 Atom atype=AnyPropertyType;
3337 int aformat;
3338 unsigned long remain;
3339 Atom* targetPropList=NULL;
3340 unsigned long cTargetPropList = 0;
3342 /* If the specified property is None the requestor is an obsolete client.
3343 * We support these by using the specified target atom as the reply property.
3345 rprop = pevent->property;
3346 if( rprop == None )
3347 rprop = pevent->target;
3348 if (!rprop)
3349 return 0;
3351 /* Read the MULTIPLE property contents. This should contain a list of
3352 * (target,property) atom pairs.
3354 if (!XGetWindowProperty(display, pevent->requestor, rprop,
3355 0, 0x3FFF, False, AnyPropertyType, &atype,&aformat,
3356 &cTargetPropList, &remain,
3357 (unsigned char**)&targetPropList))
3359 if (TRACE_ON(clipboard))
3361 char * const typeName = XGetAtomName(display, atype);
3362 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
3363 typeName, aformat, cTargetPropList, remain);
3364 XFree(typeName);
3368 * Make sure we got what we expect.
3369 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
3370 * in a MULTIPLE selection request should be of type ATOM_PAIR.
3371 * However some X apps(such as XPaint) are not compliant with this and return
3372 * a user defined atom in atype when XGetWindowProperty is called.
3373 * The data *is* an atom pair but is not denoted as such.
3375 if(aformat == 32 /* atype == xAtomPair */ )
3377 unsigned int i;
3379 /* Iterate through the ATOM_PAIR list and execute a SelectionRequest
3380 * for each (target,property) pair */
3382 for (i = 0; i < cTargetPropList; i+=2)
3384 XSelectionRequestEvent event;
3386 if (TRACE_ON(clipboard))
3388 char *targetName, *propName;
3389 targetName = XGetAtomName(display, targetPropList[i]);
3390 propName = XGetAtomName(display, targetPropList[i+1]);
3391 TRACE("MULTIPLE(%d): Target='%s' Prop='%s'\n",
3392 i/2, targetName, propName);
3393 XFree(targetName);
3394 XFree(propName);
3397 /* We must have a non "None" property to service a MULTIPLE target atom */
3398 if ( !targetPropList[i+1] )
3400 TRACE("\tMULTIPLE(%d): Skipping target with empty property!\n", i);
3401 continue;
3404 /* Set up an XSelectionRequestEvent for this (target,property) pair */
3405 event = *pevent;
3406 event.target = targetPropList[i];
3407 event.property = targetPropList[i+1];
3409 /* Fire a SelectionRequest, informing the handler that we are processing
3410 * a MULTIPLE selection request event.
3412 X11DRV_HandleSelectionRequest( hWnd, &event, TRUE );
3416 /* Free the list of targets/properties */
3417 XFree(targetPropList);
3419 else TRACE("Couldn't read MULTIPLE property\n");
3421 return rprop;
3425 /***********************************************************************
3426 * X11DRV_HandleSelectionRequest
3427 * Process an event selection request event.
3428 * The bIsMultiple flag is used to signal when EVENT_SelectionRequest is called
3429 * recursively while servicing a "MULTIPLE" selection target.
3431 * Note: We only receive this event when WINE owns the X selection
3433 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple )
3435 Display *display = event->display;
3436 XSelectionEvent result;
3437 Atom rprop = None;
3438 Window request = event->requestor;
3440 TRACE("\n");
3443 * We can only handle the selection request if :
3444 * The selection is PRIMARY or CLIPBOARD, AND we can successfully open the clipboard.
3445 * Don't do these checks or open the clipboard while recursively processing MULTIPLE,
3446 * since this has been already done.
3448 if ( !bIsMultiple )
3450 if (((event->selection != XA_PRIMARY) && (event->selection != x11drv_atom(CLIPBOARD))))
3451 goto END;
3454 /* If the specified property is None the requestor is an obsolete client.
3455 * We support these by using the specified target atom as the reply property.
3457 rprop = event->property;
3458 if( rprop == None )
3459 rprop = event->target;
3461 if(event->target == x11drv_atom(TARGETS)) /* Return a list of all supported targets */
3463 /* TARGETS selection request */
3464 rprop = X11DRV_SelectionRequest_TARGETS( display, request, event->target, rprop );
3466 else if(event->target == x11drv_atom(MULTIPLE)) /* rprop contains a list of (target, property) atom pairs */
3468 /* MULTIPLE selection request */
3469 rprop = X11DRV_SelectionRequest_MULTIPLE( hWnd, event );
3471 else
3473 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, event->target);
3474 BOOL success = FALSE;
3476 if (lpFormat && lpFormat->lpDrvExportFunc)
3478 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(lpFormat->wFormatID);
3480 if (lpData)
3482 unsigned char* lpClipData;
3483 DWORD cBytes;
3484 HANDLE hClipData = lpFormat->lpDrvExportFunc(display, request, event->target,
3485 rprop, lpData, &cBytes);
3487 if (hClipData && (lpClipData = GlobalLock(hClipData)))
3489 int mode = PropModeReplace;
3491 TRACE("\tUpdating property %s, %d bytes\n",
3492 debugstr_format(lpFormat->wFormatID), cBytes);
3495 int nelements = min(cBytes, 65536);
3496 XChangeProperty(display, request, rprop, event->target,
3497 8, mode, lpClipData, nelements);
3498 mode = PropModeAppend;
3499 cBytes -= nelements;
3500 lpClipData += nelements;
3501 } while (cBytes > 0);
3503 GlobalUnlock(hClipData);
3504 GlobalFree(hClipData);
3505 success = TRUE;
3510 if (!success)
3511 rprop = None; /* report failure to client */
3514 END:
3515 /* reply to sender
3516 * SelectionNotify should be sent only at the end of a MULTIPLE request
3518 if ( !bIsMultiple )
3520 result.type = SelectionNotify;
3521 result.display = display;
3522 result.requestor = request;
3523 result.selection = event->selection;
3524 result.property = rprop;
3525 result.target = event->target;
3526 result.time = event->time;
3527 TRACE("Sending SelectionNotify event...\n");
3528 XSendEvent(display,event->requestor,False,NoEventMask,(XEvent*)&result);
3533 /***********************************************************************
3534 * X11DRV_SelectionRequest
3536 void X11DRV_SelectionRequest( HWND hWnd, XEvent *event )
3538 X11DRV_HandleSelectionRequest( hWnd, &event->xselectionrequest, FALSE );
3542 /***********************************************************************
3543 * X11DRV_SelectionClear
3545 void X11DRV_SelectionClear( HWND hWnd, XEvent *xev )
3547 XSelectionClearEvent *event = &xev->xselectionclear;
3548 if (event->selection == XA_PRIMARY || event->selection == x11drv_atom(CLIPBOARD))
3549 X11DRV_CLIPBOARD_ReleaseSelection( event->display, event->selection,
3550 event->window, hWnd, event->time );