winex11: Add a helper function to store property data.
[wine.git] / dlls / winex11.drv / clipboard.c
blobbb11819c654eb20a4d32a5520778f69079cb98c2
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 clipboard_format
110 struct list entry;
111 UINT id;
112 Atom atom;
113 DRVIMPORTFUNC lpDrvImportFunc;
114 DRVEXPORTFUNC lpDrvExportFunc;
115 } WINE_CLIPFORMAT, *LPWINE_CLIPFORMAT;
117 typedef struct tagWINE_CLIPDATA {
118 struct list entry;
119 UINT wFormatID;
120 HANDLE hData;
121 UINT drvData;
122 LPWINE_CLIPFORMAT lpFormat;
123 } WINE_CLIPDATA, *LPWINE_CLIPDATA;
125 static int selectionAcquired = 0; /* Contains the current selection masks */
126 static Window selectionWindow = None; /* The top level X window which owns the selection */
127 static Atom selectionCacheSrc = XA_PRIMARY; /* The selection source from which the clipboard cache was filled */
129 static HANDLE import_data(Display *d, Window w, Atom prop);
130 static HANDLE import_enhmetafile(Display *d, Window w, Atom prop);
131 static HANDLE import_metafile(Display *d, Window w, Atom prop);
132 static HANDLE import_pixmap(Display *d, Window w, Atom prop);
133 static HANDLE import_image_bmp(Display *d, Window w, Atom prop);
134 static HANDLE import_string(Display *d, Window w, Atom prop);
135 static HANDLE import_utf8_string(Display *d, Window w, Atom prop);
136 static HANDLE import_compound_text(Display *d, Window w, Atom prop);
137 static HANDLE import_text_uri_list(Display *display, Window w, Atom prop);
139 static HANDLE export_data(Display *display, Window requestor, Atom aTarget,
140 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
141 static HANDLE export_string(Display *display, Window requestor, Atom aTarget,
142 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
143 static HANDLE export_utf8_string(Display *display, Window requestor, Atom aTarget,
144 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
145 static HANDLE export_compound_text(Display *display, Window requestor, Atom aTarget,
146 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
147 static HANDLE export_pixmap(Display *display, Window requestor, Atom aTarget,
148 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
149 static HANDLE export_image_bmp(Display *display, Window requestor, Atom aTarget,
150 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
151 static HANDLE export_metafile(Display *display, Window requestor, Atom aTarget,
152 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
153 static HANDLE export_enhmetafile(Display *display, Window requestor, Atom aTarget,
154 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
155 static HANDLE export_text_html(Display *display, Window requestor, Atom aTarget,
156 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
157 static HANDLE export_hdrop(Display *display, Window requestor, Atom aTarget,
158 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
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 void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple );
167 static void empty_clipboard(void);
169 /* Clipboard formats */
171 static const WCHAR RichTextFormatW[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
172 static const WCHAR GIFW[] = {'G','I','F',0};
173 static const WCHAR JFIFW[] = {'J','F','I','F',0};
174 static const WCHAR PNGW[] = {'P','N','G',0};
175 static const WCHAR HTMLFormatW[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
177 static const struct
179 const WCHAR *name;
180 UINT id;
181 UINT data;
182 DRVIMPORTFUNC import;
183 DRVEXPORTFUNC export;
184 } builtin_formats[] =
186 { 0, CF_TEXT, XA_STRING, import_string, export_string },
187 { 0, CF_TEXT, XATOM_text_plain, import_string, export_string },
188 { 0, CF_BITMAP, XATOM_WCF_BITMAP, import_data, NULL },
189 { 0, CF_METAFILEPICT, XATOM_WCF_METAFILEPICT, import_metafile, export_metafile },
190 { 0, CF_SYLK, XATOM_WCF_SYLK, import_data, export_data },
191 { 0, CF_DIF, XATOM_WCF_DIF, import_data, export_data },
192 { 0, CF_TIFF, XATOM_WCF_TIFF, import_data, export_data },
193 { 0, CF_OEMTEXT, XATOM_WCF_OEMTEXT, import_data, export_data },
194 { 0, CF_DIB, XA_PIXMAP, import_pixmap, export_pixmap },
195 { 0, CF_PALETTE, XATOM_WCF_PALETTE, import_data, export_data },
196 { 0, CF_PENDATA, XATOM_WCF_PENDATA, import_data, export_data },
197 { 0, CF_RIFF, XATOM_WCF_RIFF, import_data, export_data },
198 { 0, CF_WAVE, XATOM_WCF_WAVE, import_data, export_data },
199 { 0, CF_UNICODETEXT, XATOM_UTF8_STRING, import_utf8_string, export_utf8_string },
200 { 0, CF_UNICODETEXT, XATOM_COMPOUND_TEXT, import_compound_text, export_compound_text },
201 { 0, CF_ENHMETAFILE, XATOM_WCF_ENHMETAFILE, import_enhmetafile, export_enhmetafile },
202 { 0, CF_HDROP, XATOM_text_uri_list, import_text_uri_list, export_hdrop },
203 { 0, CF_LOCALE, XATOM_WCF_LOCALE, import_data, export_data },
204 { 0, CF_DIBV5, XATOM_WCF_DIBV5, import_data, export_data },
205 { 0, CF_OWNERDISPLAY, XATOM_WCF_OWNERDISPLAY, import_data, export_data },
206 { 0, CF_DSPTEXT, XATOM_WCF_DSPTEXT, import_data, export_data },
207 { 0, CF_DSPBITMAP, XATOM_WCF_DSPBITMAP, import_data, export_data },
208 { 0, CF_DSPMETAFILEPICT, XATOM_WCF_DSPMETAFILEPICT, import_data, export_data },
209 { 0, CF_DSPENHMETAFILE, XATOM_WCF_DSPENHMETAFILE, import_data, export_data },
210 { 0, CF_DIB, XATOM_image_bmp, import_image_bmp, export_image_bmp },
211 { RichTextFormatW, 0, XATOM_text_rtf, import_data, export_data },
212 { RichTextFormatW, 0, XATOM_text_richtext, import_data, export_data },
213 { GIFW, 0, XATOM_image_gif, import_data, export_data },
214 { JFIFW, 0, XATOM_image_jpeg, import_data, export_data },
215 { PNGW, 0, XATOM_image_png, import_data, export_data },
216 { HTMLFormatW, 0, XATOM_HTML_Format, import_data, export_data },
217 { HTMLFormatW, 0, XATOM_text_html, import_data, export_text_html },
220 static struct list format_list = LIST_INIT( format_list );
222 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
226 * Cached clipboard data.
228 static struct list data_list = LIST_INIT( data_list );
229 static UINT ClipDataCount = 0;
232 * Clipboard sequence number
234 static UINT wSeqNo = 0;
236 /**************************************************************************
237 * Internal Clipboard implementation methods
238 **************************************************************************/
240 static Window thread_selection_wnd(void)
242 struct x11drv_thread_data *thread_data = x11drv_init_thread_data();
243 Window w = thread_data->selection_wnd;
245 if (!w)
247 w = XCreateWindow(thread_data->display, root_window, 0, 0, 1, 1, 0, CopyFromParent,
248 InputOnly, CopyFromParent, 0, NULL);
249 if (w)
251 thread_data->selection_wnd = w;
253 XSelectInput(thread_data->display, w, PropertyChangeMask);
255 else
256 FIXME("Failed to create window. Fetching selection data will fail.\n");
259 return w;
262 static const char *debugstr_format( UINT id )
264 WCHAR buffer[256];
266 if (GetClipboardFormatNameW( id, buffer, 256 ))
267 return wine_dbg_sprintf( "%04x %s", id, debugstr_w(buffer) );
269 switch (id)
271 #define BUILTIN(id) case id: return #id;
272 BUILTIN(CF_TEXT)
273 BUILTIN(CF_BITMAP)
274 BUILTIN(CF_METAFILEPICT)
275 BUILTIN(CF_SYLK)
276 BUILTIN(CF_DIF)
277 BUILTIN(CF_TIFF)
278 BUILTIN(CF_OEMTEXT)
279 BUILTIN(CF_DIB)
280 BUILTIN(CF_PALETTE)
281 BUILTIN(CF_PENDATA)
282 BUILTIN(CF_RIFF)
283 BUILTIN(CF_WAVE)
284 BUILTIN(CF_UNICODETEXT)
285 BUILTIN(CF_ENHMETAFILE)
286 BUILTIN(CF_HDROP)
287 BUILTIN(CF_LOCALE)
288 BUILTIN(CF_DIBV5)
289 BUILTIN(CF_OWNERDISPLAY)
290 BUILTIN(CF_DSPTEXT)
291 BUILTIN(CF_DSPBITMAP)
292 BUILTIN(CF_DSPMETAFILEPICT)
293 BUILTIN(CF_DSPENHMETAFILE)
294 #undef BUILTIN
295 default: return wine_dbg_sprintf( "%04x", id );
299 static const char *debugstr_xatom( Atom atom )
301 const char *ret;
302 char *name;
304 if (!atom) return "(None)";
305 name = XGetAtomName( thread_display(), atom );
306 ret = debugstr_a( name );
307 XFree( name );
308 return ret;
311 /**************************************************************************
312 * X11DRV_InitClipboard
314 void X11DRV_InitClipboard(void)
316 static const unsigned int count = sizeof(builtin_formats) / sizeof(builtin_formats[0]);
317 struct clipboard_format *formats;
318 UINT i;
320 if (!(formats = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*formats)))) return;
322 for (i = 0; i < count; i++)
324 if (builtin_formats[i].name)
325 formats[i].id = RegisterClipboardFormatW( builtin_formats[i].name );
326 else
327 formats[i].id = builtin_formats[i].id;
329 formats[i].atom = GET_ATOM(builtin_formats[i].data);
330 formats[i].lpDrvImportFunc = builtin_formats[i].import;
331 formats[i].lpDrvExportFunc = builtin_formats[i].export;
332 list_add_tail( &format_list, &formats[i].entry );
337 /**************************************************************************
338 * intern_atoms
340 * Intern atoms for formats that don't have one yet.
342 static void intern_atoms(void)
344 LPWINE_CLIPFORMAT format;
345 int i, count, len;
346 char **names;
347 Atom *atoms;
348 Display *display;
349 WCHAR buffer[256];
351 count = 0;
352 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
353 if (!format->atom) count++;
354 if (!count) return;
356 display = thread_init_display();
358 names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
359 atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
361 i = 0;
362 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
363 if (!format->atom) {
364 if (GetClipboardFormatNameW( format->id, buffer, 256 ) > 0)
366 /* use defined format name */
367 len = WideCharToMultiByte(CP_UNIXCP, 0, buffer, -1, NULL, 0, NULL, NULL);
369 else
371 /* create a name in the same way as ntdll/atom.c:integral_atom_name
372 * which is normally used by GetClipboardFormatNameW
374 static const WCHAR fmt[] = {'#','%','u',0};
375 len = sprintfW(buffer, fmt, format->id) + 1;
377 names[i] = HeapAlloc(GetProcessHeap(), 0, len);
378 WideCharToMultiByte(CP_UNIXCP, 0, buffer, -1, names[i++], len, NULL, NULL);
381 XInternAtoms( display, names, count, False, atoms );
383 i = 0;
384 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
385 if (!format->atom) {
386 HeapFree(GetProcessHeap(), 0, names[i]);
387 format->atom = atoms[i++];
390 HeapFree( GetProcessHeap(), 0, names );
391 HeapFree( GetProcessHeap(), 0, atoms );
395 /**************************************************************************
396 * register_format
398 * Register a custom X clipboard format.
400 static struct clipboard_format *register_format( UINT id, Atom prop )
402 struct clipboard_format *format;
404 /* walk format chain to see if it's already registered */
405 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
406 if (format->id == id) return format;
408 if (!(format = HeapAlloc( GetProcessHeap(), 0, sizeof(*format) ))) return NULL;
409 format->id = id;
410 format->atom = prop;
411 format->lpDrvImportFunc = import_data;
412 format->lpDrvExportFunc = export_data;
413 list_add_tail( &format_list, &format->entry );
415 TRACE( "Registering format %s atom %ld\n", debugstr_format(id), prop );
416 return format;
420 /**************************************************************************
421 * X11DRV_CLIPBOARD_LookupProperty
423 static struct clipboard_format *X11DRV_CLIPBOARD_LookupProperty( struct clipboard_format *current, Atom prop )
425 for (;;)
427 struct list *ptr = current ? &current->entry : &format_list;
428 BOOL need_intern = FALSE;
430 while ((ptr = list_next( &format_list, ptr )))
432 struct clipboard_format *format = LIST_ENTRY( ptr, struct clipboard_format, entry );
433 if (format->atom == prop) return format;
434 if (!format->atom) need_intern = TRUE;
436 if (!need_intern) return NULL;
437 intern_atoms();
438 /* restart the search for the new atoms */
443 /**************************************************************************
444 * X11DRV_CLIPBOARD_LookupData
446 static LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
448 WINE_CLIPDATA *data;
450 LIST_FOR_EACH_ENTRY( data, &data_list, WINE_CLIPDATA, entry )
451 if (data->wFormatID == wID) return data;
453 return NULL;
457 /**************************************************************************
458 * X11DRV_CLIPBOARD_IsProcessOwner
460 static BOOL X11DRV_CLIPBOARD_IsProcessOwner( HWND *owner )
462 BOOL ret = FALSE;
464 SERVER_START_REQ( set_clipboard_info )
466 req->flags = 0;
467 if (!wine_server_call_err( req ))
469 *owner = wine_server_ptr_handle( reply->old_owner );
470 ret = (reply->flags & CB_PROCESS);
473 SERVER_END_REQ;
475 return ret;
479 /**************************************************************************
480 * X11DRV_CLIPBOARD_ReleaseOwnership
482 static BOOL X11DRV_CLIPBOARD_ReleaseOwnership(void)
484 BOOL ret;
486 SERVER_START_REQ( set_clipboard_info )
488 req->flags = SET_CB_RELOWNER | SET_CB_SEQNO;
489 ret = !wine_server_call_err( req );
491 SERVER_END_REQ;
493 return ret;
498 /**************************************************************************
499 * X11DRV_CLIPBOARD_InsertClipboardData
501 * Caller *must* have the clipboard open and be the owner.
503 static BOOL X11DRV_CLIPBOARD_InsertClipboardData(UINT wFormatID, HANDLE hData,
504 LPWINE_CLIPFORMAT lpFormat, BOOL override)
506 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormatID);
508 TRACE("format=%04x lpData=%p hData=%p lpFormat=%p override=%d\n",
509 wFormatID, lpData, hData, lpFormat, override);
511 /* make sure the format exists */
512 if (!lpFormat) register_format( wFormatID, 0 );
514 if (lpData && !override)
515 return TRUE;
517 if (lpData)
519 X11DRV_CLIPBOARD_FreeData(lpData);
521 lpData->hData = hData;
523 else
525 lpData = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPDATA));
527 lpData->wFormatID = wFormatID;
528 lpData->hData = hData;
529 lpData->lpFormat = lpFormat;
530 lpData->drvData = 0;
532 list_add_tail( &data_list, &lpData->entry );
533 ClipDataCount++;
536 return TRUE;
540 /**************************************************************************
541 * X11DRV_CLIPBOARD_FreeData
543 * Free clipboard data handle.
545 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData)
547 TRACE("%04x\n", lpData->wFormatID);
549 if (!lpData->hData) return;
551 switch (lpData->wFormatID)
553 case CF_BITMAP:
554 case CF_DSPBITMAP:
555 case CF_PALETTE:
556 DeleteObject(lpData->hData);
557 break;
558 case CF_DIB:
559 if (lpData->drvData) XFreePixmap(gdi_display, lpData->drvData);
560 GlobalFree(lpData->hData);
561 break;
562 case CF_METAFILEPICT:
563 case CF_DSPMETAFILEPICT:
564 DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData ))->hMF );
565 GlobalFree(lpData->hData);
566 break;
567 case CF_ENHMETAFILE:
568 case CF_DSPENHMETAFILE:
569 DeleteEnhMetaFile(lpData->hData);
570 break;
571 default:
572 GlobalFree(lpData->hData);
573 break;
575 lpData->hData = 0;
576 lpData->drvData = 0;
580 /**************************************************************************
581 * X11DRV_CLIPBOARD_UpdateCache
583 static BOOL X11DRV_CLIPBOARD_UpdateCache(void)
585 BOOL bret = TRUE;
587 if (!selectionAcquired)
589 DWORD seqno = GetClipboardSequenceNumber();
591 if (!seqno)
593 ERR("Failed to retrieve clipboard information.\n");
594 bret = FALSE;
596 else if (wSeqNo < seqno)
598 empty_clipboard();
600 if (X11DRV_CLIPBOARD_QueryAvailableData(thread_init_display()) < 0)
602 ERR("Failed to cache clipboard data owned by another process.\n");
603 bret = FALSE;
605 wSeqNo = seqno;
609 return bret;
613 /**************************************************************************
614 * X11DRV_CLIPBOARD_RenderFormat
616 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData)
618 BOOL bret = TRUE;
620 TRACE(" 0x%04x hData(%p)\n", lpData->wFormatID, lpData->hData);
622 if (lpData->hData) return bret; /* Already rendered */
624 if (!selectionAcquired)
626 if (!X11DRV_CLIPBOARD_ReadSelectionData(display, lpData))
628 ERR("Failed to cache clipboard data owned by another process. Format=%04x\n",
629 lpData->wFormatID);
630 bret = FALSE;
633 else
635 HWND owner = GetClipboardOwner();
637 if (owner)
639 /* Send a WM_RENDERFORMAT message to notify the owner to render the
640 * data requested into the clipboard.
642 TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", owner);
643 SendMessageW(owner, WM_RENDERFORMAT, lpData->wFormatID, 0);
645 if (!lpData->hData) bret = FALSE;
647 else
649 ERR("hWndClipOwner is lost!\n");
650 bret = FALSE;
654 return bret;
658 /**************************************************************************
659 * put_property
661 * Put data as a property on the specified window.
663 static void put_property( Display *display, Window win, Atom prop, Atom type, int format,
664 const void *ptr, size_t size )
666 const unsigned char *data = ptr;
667 int mode = PropModeReplace;
668 size_t width = (format == 32) ? sizeof(long) : format / 8;
669 size_t max_size = XExtendedMaxRequestSize( display ) * 4;
671 if (!max_size) max_size = XMaxRequestSize( display ) * 4;
672 max_size -= 64; /* request overhead */
676 size_t count = min( size, max_size / width );
677 XChangeProperty( display, win, prop, type, format, mode, data, count );
678 mode = PropModeAppend;
679 size -= count;
680 data += count * width;
681 } while (size > 0);
685 /***********************************************************************
686 * bitmap_info_size
688 * Return the size of the bitmap info structure including color table.
690 static int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
692 unsigned int colors, size, masks = 0;
694 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
696 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
697 colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
698 return sizeof(BITMAPCOREHEADER) + colors *
699 ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
701 else /* assume BITMAPINFOHEADER */
703 colors = info->bmiHeader.biClrUsed;
704 if (!colors && (info->bmiHeader.biBitCount <= 8))
705 colors = 1 << info->bmiHeader.biBitCount;
706 if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
707 size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
708 return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
713 /***********************************************************************
714 * create_dib_from_bitmap
716 * Allocates a packed DIB and copies the bitmap data into it.
718 static HGLOBAL create_dib_from_bitmap(HBITMAP hBmp)
720 BITMAP bmp;
721 HDC hdc;
722 HGLOBAL hPackedDIB;
723 LPBYTE pPackedDIB;
724 LPBITMAPINFOHEADER pbmiHeader;
725 unsigned int cDataSize, cPackedSize, OffsetBits;
726 int nLinesCopied;
728 if (!GetObjectW( hBmp, sizeof(bmp), &bmp )) return 0;
731 * A packed DIB contains a BITMAPINFO structure followed immediately by
732 * an optional color palette and the pixel data.
735 /* Calculate the size of the packed DIB */
736 cDataSize = abs( bmp.bmHeight ) * (((bmp.bmWidth * bmp.bmBitsPixel + 31) / 8) & ~3);
737 cPackedSize = sizeof(BITMAPINFOHEADER)
738 + ( (bmp.bmBitsPixel <= 8) ? (sizeof(RGBQUAD) * (1 << bmp.bmBitsPixel)) : 0 )
739 + cDataSize;
740 /* Get the offset to the bits */
741 OffsetBits = cPackedSize - cDataSize;
743 /* Allocate the packed DIB */
744 TRACE("\tAllocating packed DIB of size %d\n", cPackedSize);
745 hPackedDIB = GlobalAlloc( GMEM_FIXED, cPackedSize );
746 if ( !hPackedDIB )
748 WARN("Could not allocate packed DIB!\n");
749 return 0;
752 /* A packed DIB starts with a BITMAPINFOHEADER */
753 pPackedDIB = GlobalLock(hPackedDIB);
754 pbmiHeader = (LPBITMAPINFOHEADER)pPackedDIB;
756 /* Init the BITMAPINFOHEADER */
757 pbmiHeader->biSize = sizeof(BITMAPINFOHEADER);
758 pbmiHeader->biWidth = bmp.bmWidth;
759 pbmiHeader->biHeight = bmp.bmHeight;
760 pbmiHeader->biPlanes = 1;
761 pbmiHeader->biBitCount = bmp.bmBitsPixel;
762 pbmiHeader->biCompression = BI_RGB;
763 pbmiHeader->biSizeImage = 0;
764 pbmiHeader->biXPelsPerMeter = pbmiHeader->biYPelsPerMeter = 0;
765 pbmiHeader->biClrUsed = 0;
766 pbmiHeader->biClrImportant = 0;
768 /* Retrieve the DIB bits from the bitmap and fill in the
769 * DIB color table if present */
770 hdc = GetDC( 0 );
771 nLinesCopied = GetDIBits(hdc, /* Handle to device context */
772 hBmp, /* Handle to bitmap */
773 0, /* First scan line to set in dest bitmap */
774 bmp.bmHeight, /* Number of scan lines to copy */
775 pPackedDIB + OffsetBits, /* [out] Address of array for bitmap bits */
776 (LPBITMAPINFO) pbmiHeader, /* [out] Address of BITMAPINFO structure */
777 0); /* RGB or palette index */
778 GlobalUnlock(hPackedDIB);
779 ReleaseDC( 0, hdc );
781 /* Cleanup if GetDIBits failed */
782 if (nLinesCopied != bmp.bmHeight)
784 TRACE("\tGetDIBits returned %d. Actual lines=%d\n", nLinesCopied, bmp.bmHeight);
785 GlobalFree(hPackedDIB);
786 hPackedDIB = 0;
788 return hPackedDIB;
792 /***********************************************************************
793 * uri_to_dos
795 * Converts a text/uri-list URI to DOS filename.
797 static WCHAR* uri_to_dos(char *encodedURI)
799 WCHAR *ret = NULL;
800 int i;
801 int j = 0;
802 char *uri = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, strlen(encodedURI) + 1);
803 if (uri == NULL)
804 return NULL;
805 for (i = 0; encodedURI[i]; ++i)
807 if (encodedURI[i] == '%')
809 if (encodedURI[i+1] && encodedURI[i+2])
811 char buffer[3];
812 int number;
813 buffer[0] = encodedURI[i+1];
814 buffer[1] = encodedURI[i+2];
815 buffer[2] = '\0';
816 sscanf(buffer, "%x", &number);
817 uri[j++] = number;
818 i += 2;
820 else
822 WARN("invalid URI encoding in %s\n", debugstr_a(encodedURI));
823 HeapFree(GetProcessHeap(), 0, uri);
824 return NULL;
827 else
828 uri[j++] = encodedURI[i];
831 /* Read http://www.freedesktop.org/wiki/Draganddropwarts and cry... */
832 if (strncmp(uri, "file:/", 6) == 0)
834 if (uri[6] == '/')
836 if (uri[7] == '/')
838 /* file:///path/to/file (nautilus, thunar) */
839 ret = wine_get_dos_file_name(&uri[7]);
841 else if (uri[7])
843 /* file://hostname/path/to/file (X file drag spec) */
844 char hostname[256];
845 char *path = strchr(&uri[7], '/');
846 if (path)
848 *path = '\0';
849 if (strcmp(&uri[7], "localhost") == 0)
851 *path = '/';
852 ret = wine_get_dos_file_name(path);
854 else if (gethostname(hostname, sizeof(hostname)) == 0)
856 if (strcmp(hostname, &uri[7]) == 0)
858 *path = '/';
859 ret = wine_get_dos_file_name(path);
865 else if (uri[6])
867 /* file:/path/to/file (konqueror) */
868 ret = wine_get_dos_file_name(&uri[5]);
871 HeapFree(GetProcessHeap(), 0, uri);
872 return ret;
876 /**************************************************************************
877 * import_string
879 * Import XA_STRING, converting the string to CF_TEXT.
881 static HANDLE import_string(Display *display, Window w, Atom prop)
883 LPBYTE lpdata;
884 unsigned long cbytes;
885 LPSTR lpstr;
886 unsigned long i, inlcount = 0;
887 HANDLE hText = 0;
889 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
890 return 0;
892 for (i = 0; i <= cbytes; i++)
894 if (lpdata[i] == '\n')
895 inlcount++;
898 if ((hText = GlobalAlloc(GMEM_FIXED, cbytes + inlcount + 1)))
900 lpstr = GlobalLock(hText);
902 for (i = 0, inlcount = 0; i <= cbytes; i++)
904 if (lpdata[i] == '\n')
905 lpstr[inlcount++] = '\r';
907 lpstr[inlcount++] = lpdata[i];
910 GlobalUnlock(hText);
913 /* Free the retrieved property data */
914 HeapFree(GetProcessHeap(), 0, lpdata);
916 return hText;
920 /**************************************************************************
921 * import_utf8_string
923 * Import XA_UTF8_STRING, converting the string to CF_UNICODE.
925 static HANDLE import_utf8_string(Display *display, Window w, Atom prop)
927 LPBYTE lpdata;
928 unsigned long cbytes;
929 LPSTR lpstr;
930 unsigned long i, inlcount = 0;
931 HANDLE hUnicodeText = 0;
933 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
934 return 0;
936 for (i = 0; i <= cbytes; i++)
938 if (lpdata[i] == '\n')
939 inlcount++;
942 if ((lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbytes + inlcount + 1)))
944 UINT count;
946 for (i = 0, inlcount = 0; i <= cbytes; i++)
948 if (lpdata[i] == '\n')
949 lpstr[inlcount++] = '\r';
951 lpstr[inlcount++] = lpdata[i];
954 count = MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, NULL, 0);
955 hUnicodeText = GlobalAlloc(GMEM_FIXED, count * sizeof(WCHAR));
957 if (hUnicodeText)
959 WCHAR *textW = GlobalLock(hUnicodeText);
960 MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, textW, count);
961 GlobalUnlock(hUnicodeText);
964 HeapFree(GetProcessHeap(), 0, lpstr);
967 /* Free the retrieved property data */
968 HeapFree(GetProcessHeap(), 0, lpdata);
970 return hUnicodeText;
974 /**************************************************************************
975 * import_compound_text
977 * Import COMPOUND_TEXT to CF_UNICODE
979 static HANDLE import_compound_text(Display *display, Window w, Atom prop)
981 int i, j, ret;
982 char** srcstr;
983 int count, lcount;
984 int srclen, destlen;
985 HANDLE hUnicodeText;
986 XTextProperty txtprop;
988 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &txtprop.value, &txtprop.nitems))
990 return 0;
993 txtprop.encoding = x11drv_atom(COMPOUND_TEXT);
994 txtprop.format = 8;
995 ret = XmbTextPropertyToTextList(display, &txtprop, &srcstr, &count);
996 HeapFree(GetProcessHeap(), 0, txtprop.value);
997 if (ret != Success || !count) return 0;
999 TRACE("Importing %d line(s)\n", count);
1001 /* Compute number of lines */
1002 srclen = strlen(srcstr[0]);
1003 for (i = 0, lcount = 0; i <= srclen; i++)
1005 if (srcstr[0][i] == '\n')
1006 lcount++;
1009 destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
1011 TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
1013 if ((hUnicodeText = GlobalAlloc(GMEM_FIXED, (destlen + lcount + 1) * sizeof(WCHAR))))
1015 WCHAR *deststr = GlobalLock(hUnicodeText);
1016 MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1018 if (lcount)
1020 for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1022 deststr[j] = deststr[i];
1024 if (deststr[i] == '\n')
1025 deststr[--j] = '\r';
1029 GlobalUnlock(hUnicodeText);
1032 XFreeStringList(srcstr);
1034 return hUnicodeText;
1038 /**************************************************************************
1039 * import_pixmap
1041 * Import XA_PIXMAP, converting the image to CF_DIB.
1043 static HANDLE import_pixmap(Display *display, Window w, Atom prop)
1045 LPBYTE lpdata;
1046 unsigned long cbytes;
1047 Pixmap *pPixmap;
1048 HANDLE hClipData = 0;
1050 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1052 XVisualInfo vis = default_visual;
1053 char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
1054 BITMAPINFO *info = (BITMAPINFO *)buffer;
1055 struct gdi_image_bits bits;
1056 Window root;
1057 int x,y; /* Unused */
1058 unsigned border_width; /* Unused */
1059 unsigned int depth, width, height;
1061 pPixmap = (Pixmap *) lpdata;
1063 /* Get the Pixmap dimensions and bit depth */
1064 if (!XGetGeometry(gdi_display, *pPixmap, &root, &x, &y, &width, &height,
1065 &border_width, &depth)) depth = 0;
1066 if (!pixmap_formats[depth]) return 0;
1068 TRACE("\tPixmap properties: width=%d, height=%d, depth=%d\n",
1069 width, height, depth);
1071 if (depth != vis.depth) switch (pixmap_formats[depth]->bits_per_pixel)
1073 case 1:
1074 case 4:
1075 case 8:
1076 break;
1077 case 16: /* assume R5G5B5 */
1078 vis.red_mask = 0x7c00;
1079 vis.green_mask = 0x03e0;
1080 vis.blue_mask = 0x001f;
1081 break;
1082 case 24: /* assume R8G8B8 */
1083 case 32: /* assume A8R8G8B8 */
1084 vis.red_mask = 0xff0000;
1085 vis.green_mask = 0x00ff00;
1086 vis.blue_mask = 0x0000ff;
1087 break;
1088 default:
1089 return 0;
1092 if (!get_pixmap_image( *pPixmap, width, height, &vis, info, &bits ))
1094 DWORD info_size = bitmap_info_size( info, DIB_RGB_COLORS );
1095 BYTE *ptr;
1097 hClipData = GlobalAlloc( GMEM_FIXED, info_size + info->bmiHeader.biSizeImage );
1098 if (hClipData)
1100 ptr = GlobalLock( hClipData );
1101 memcpy( ptr, info, info_size );
1102 memcpy( ptr + info_size, bits.ptr, info->bmiHeader.biSizeImage );
1103 GlobalUnlock( hClipData );
1105 if (bits.free) bits.free( &bits );
1108 HeapFree(GetProcessHeap(), 0, lpdata);
1111 return hClipData;
1115 /**************************************************************************
1116 * import_image_bmp
1118 * Import image/bmp, converting the image to CF_DIB.
1120 static HANDLE import_image_bmp(Display *display, Window w, Atom prop)
1122 LPBYTE lpdata;
1123 unsigned long cbytes;
1124 HANDLE hClipData = 0;
1126 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1128 BITMAPFILEHEADER *bfh = (BITMAPFILEHEADER*)lpdata;
1130 if (cbytes >= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPCOREHEADER) &&
1131 bfh->bfType == 0x4d42 /* "BM" */)
1133 BITMAPINFO *bmi = (BITMAPINFO*)(bfh+1);
1134 HBITMAP hbmp;
1135 HDC hdc;
1137 hdc = GetDC(0);
1138 hbmp = CreateDIBitmap(
1139 hdc,
1140 &(bmi->bmiHeader),
1141 CBM_INIT,
1142 lpdata+bfh->bfOffBits,
1143 bmi,
1144 DIB_RGB_COLORS
1147 hClipData = create_dib_from_bitmap( hbmp );
1149 DeleteObject(hbmp);
1150 ReleaseDC(0, hdc);
1153 /* Free the retrieved property data */
1154 HeapFree(GetProcessHeap(), 0, lpdata);
1157 return hClipData;
1161 /**************************************************************************
1162 * import_metafile
1164 static HANDLE import_metafile(Display *display, Window w, Atom prop)
1166 LPBYTE lpdata;
1167 unsigned long cbytes;
1168 HANDLE hClipData = 0;
1170 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1172 if (cbytes)
1174 hClipData = GlobalAlloc(0, sizeof(METAFILEPICT));
1175 if (hClipData)
1177 unsigned int wiresize;
1178 LPMETAFILEPICT lpmfp = GlobalLock(hClipData);
1180 memcpy(lpmfp, lpdata, sizeof(METAFILEPICT));
1181 wiresize = cbytes - sizeof(METAFILEPICT);
1182 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
1183 ((const BYTE *)lpdata) + sizeof(METAFILEPICT));
1184 GlobalUnlock(hClipData);
1188 /* Free the retrieved property data */
1189 HeapFree(GetProcessHeap(), 0, lpdata);
1192 return hClipData;
1196 /**************************************************************************
1197 * import_enhmetafile
1199 static HANDLE import_enhmetafile(Display *display, Window w, Atom prop)
1201 LPBYTE lpdata;
1202 unsigned long cbytes;
1203 HANDLE hClipData = 0;
1205 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1207 if (cbytes)
1208 hClipData = SetEnhMetaFileBits(cbytes, lpdata);
1210 /* Free the retrieved property data */
1211 HeapFree(GetProcessHeap(), 0, lpdata);
1214 return hClipData;
1218 /**************************************************************************
1219 * import_text_uri_list
1221 * Import text/uri-list.
1223 static HANDLE import_text_uri_list(Display *display, Window w, Atom prop)
1225 char *uriList;
1226 unsigned long len;
1227 char *uri;
1228 WCHAR *path;
1229 WCHAR *out = NULL;
1230 int size = 0;
1231 int capacity = 4096;
1232 int start = 0;
1233 int end = 0;
1234 HANDLE handle = NULL;
1236 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, (LPBYTE*)&uriList, &len))
1237 return 0;
1239 out = HeapAlloc(GetProcessHeap(), 0, capacity * sizeof(WCHAR));
1240 if (out == NULL) {
1241 HeapFree(GetProcessHeap(), 0, uriList);
1242 return 0;
1245 while (end < len)
1247 while (end < len && uriList[end] != '\r')
1248 ++end;
1249 if (end < (len - 1) && uriList[end+1] != '\n')
1251 WARN("URI list line doesn't end in \\r\\n\n");
1252 break;
1255 uri = HeapAlloc(GetProcessHeap(), 0, end - start + 1);
1256 if (uri == NULL)
1257 break;
1258 lstrcpynA(uri, &uriList[start], end - start + 1);
1259 path = uri_to_dos(uri);
1260 TRACE("converted URI %s to DOS path %s\n", debugstr_a(uri), debugstr_w(path));
1261 HeapFree(GetProcessHeap(), 0, uri);
1263 if (path)
1265 int pathSize = strlenW(path) + 1;
1266 if (pathSize > capacity-size)
1268 capacity = 2*capacity + pathSize;
1269 out = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, out, (capacity + 1)*sizeof(WCHAR));
1270 if (out == NULL)
1271 goto done;
1273 memcpy(&out[size], path, pathSize * sizeof(WCHAR));
1274 size += pathSize;
1275 done:
1276 HeapFree(GetProcessHeap(), 0, path);
1277 if (out == NULL)
1278 break;
1281 start = end + 2;
1282 end = start;
1284 if (out && end >= len)
1286 DROPFILES *dropFiles;
1287 handle = GlobalAlloc(GMEM_FIXED, sizeof(DROPFILES) + (size + 1)*sizeof(WCHAR));
1288 if (handle)
1290 dropFiles = (DROPFILES*) GlobalLock(handle);
1291 dropFiles->pFiles = sizeof(DROPFILES);
1292 dropFiles->pt.x = 0;
1293 dropFiles->pt.y = 0;
1294 dropFiles->fNC = 0;
1295 dropFiles->fWide = TRUE;
1296 out[size] = '\0';
1297 memcpy(((char*)dropFiles) + dropFiles->pFiles, out, (size + 1)*sizeof(WCHAR));
1298 GlobalUnlock(handle);
1301 HeapFree(GetProcessHeap(), 0, out);
1302 HeapFree(GetProcessHeap(), 0, uriList);
1303 return handle;
1307 /**************************************************************************
1308 * import_data
1310 * Generic import clipboard data routine.
1312 static HANDLE import_data(Display *display, Window w, Atom prop)
1314 LPVOID lpClipData;
1315 LPBYTE lpdata;
1316 unsigned long cbytes;
1317 HANDLE hClipData = 0;
1319 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1321 if (cbytes)
1323 hClipData = GlobalAlloc(GMEM_FIXED, cbytes);
1324 if (hClipData == 0)
1326 HeapFree(GetProcessHeap(), 0, lpdata);
1327 return NULL;
1330 if ((lpClipData = GlobalLock(hClipData)))
1332 memcpy(lpClipData, lpdata, cbytes);
1333 GlobalUnlock(hClipData);
1335 else
1337 GlobalFree(hClipData);
1338 hClipData = 0;
1342 /* Free the retrieved property data */
1343 HeapFree(GetProcessHeap(), 0, lpdata);
1346 return hClipData;
1349 /**************************************************************************
1350 * X11DRV_CLIPBOARD_ImportSelection
1352 * Import the X selection into the clipboard format registered for the given X target.
1354 HANDLE X11DRV_CLIPBOARD_ImportSelection(Display *d, Atom target, Window w, Atom prop, UINT *windowsFormat)
1356 WINE_CLIPFORMAT *clipFormat;
1358 clipFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, target);
1359 if (clipFormat)
1361 *windowsFormat = clipFormat->id;
1362 return clipFormat->lpDrvImportFunc(d, w, prop);
1364 return NULL;
1368 /**************************************************************************
1369 * export_data
1371 * Generic export clipboard data routine.
1373 static HANDLE export_data(Display *display, Window requestor, Atom aTarget,
1374 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1376 LPVOID lpClipData;
1377 UINT datasize = 0;
1378 HANDLE hClipData = 0;
1380 *lpBytes = 0; /* Assume failure */
1382 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1383 ERR("Failed to export %04x format\n", lpData->wFormatID);
1384 else
1386 datasize = GlobalSize(lpData->hData);
1388 hClipData = GlobalAlloc(GMEM_FIXED, datasize);
1389 if (hClipData == 0) return NULL;
1391 if ((lpClipData = GlobalLock(hClipData)))
1393 LPVOID lpdata = GlobalLock(lpData->hData);
1395 memcpy(lpClipData, lpdata, datasize);
1396 *lpBytes = datasize;
1398 GlobalUnlock(lpData->hData);
1399 GlobalUnlock(hClipData);
1400 } else {
1401 GlobalFree(hClipData);
1402 hClipData = 0;
1406 return hClipData;
1410 /**************************************************************************
1411 * export_string
1413 * Export CF_TEXT converting the string to XA_STRING.
1415 static HANDLE export_string(Display *display, Window requestor, Atom aTarget, Atom rprop,
1416 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1418 UINT i, j;
1419 UINT size;
1420 LPSTR text, lpstr = NULL;
1422 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpData)) return 0;
1424 *lpBytes = 0; /* Assume return has zero bytes */
1426 text = GlobalLock(lpData->hData);
1427 size = strlen(text);
1429 /* remove carriage returns */
1430 lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1431 if (lpstr == NULL)
1432 goto done;
1434 for (i = 0,j = 0; i < size && text[i]; i++)
1436 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1437 continue;
1438 lpstr[j++] = text[i];
1441 lpstr[j]='\0';
1442 *lpBytes = j; /* Number of bytes in string */
1444 done:
1445 GlobalUnlock(lpData->hData);
1447 return lpstr;
1451 /**************************************************************************
1452 * export_utf8_string
1454 * Export CF_UNICODE converting the string to UTF8.
1456 static HANDLE export_utf8_string(Display *display, Window requestor, Atom aTarget, Atom rprop,
1457 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1459 UINT i, j;
1460 UINT size;
1461 LPWSTR uni_text;
1462 LPSTR text, lpstr = NULL;
1464 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpData)) return 0;
1466 *lpBytes = 0; /* Assume return has zero bytes */
1468 uni_text = GlobalLock(lpData->hData);
1470 size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1472 text = HeapAlloc(GetProcessHeap(), 0, size);
1473 if (!text)
1474 goto done;
1475 WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1477 /* remove carriage returns */
1478 lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1479 if (lpstr == NULL)
1480 goto done;
1482 for (i = 0,j = 0; i < size && text[i]; i++)
1484 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1485 continue;
1486 lpstr[j++] = text[i];
1488 lpstr[j]='\0';
1490 *lpBytes = j; /* Number of bytes in string */
1492 done:
1493 HeapFree(GetProcessHeap(), 0, text);
1494 GlobalUnlock(lpData->hData);
1496 return lpstr;
1501 /**************************************************************************
1502 * export_compound_text
1504 * Export CF_UNICODE to COMPOUND_TEXT
1506 static HANDLE export_compound_text(Display *display, Window requestor, Atom aTarget, Atom rprop,
1507 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1509 char* lpstr = 0;
1510 XTextProperty prop;
1511 XICCEncodingStyle style;
1512 UINT i, j;
1513 UINT size;
1514 LPWSTR uni_text;
1516 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpData)) return 0;
1518 uni_text = GlobalLock(lpData->hData);
1520 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1521 lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1522 if (!lpstr)
1523 return 0;
1525 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1527 /* remove carriage returns */
1528 for (i = 0, j = 0; i < size && lpstr[i]; i++)
1530 if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1531 continue;
1532 lpstr[j++] = lpstr[i];
1534 lpstr[j]='\0';
1536 GlobalUnlock(lpData->hData);
1538 if (aTarget == x11drv_atom(COMPOUND_TEXT))
1539 style = XCompoundTextStyle;
1540 else
1541 style = XStdICCTextStyle;
1543 /* Update the X property */
1544 if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1546 XSetTextProperty(display, requestor, &prop, rprop);
1547 XFree(prop.value);
1550 HeapFree(GetProcessHeap(), 0, lpstr);
1552 return 0;
1556 /**************************************************************************
1557 * export_pixmap
1559 * Export CF_DIB to XA_PIXMAP.
1561 static HANDLE export_pixmap(Display *display, Window requestor, Atom aTarget, Atom rprop,
1562 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1564 HANDLE hData;
1565 unsigned char* lpData;
1567 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1569 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1570 return 0;
1573 if (!lpdata->drvData) /* If not already rendered */
1575 Pixmap pixmap;
1576 LPBITMAPINFO pbmi;
1577 struct gdi_image_bits bits;
1579 pbmi = GlobalLock( lpdata->hData );
1580 bits.ptr = (LPBYTE)pbmi + bitmap_info_size( pbmi, DIB_RGB_COLORS );
1581 bits.free = NULL;
1582 bits.is_copy = FALSE;
1583 pixmap = create_pixmap_from_image( 0, &default_visual, pbmi, &bits, DIB_RGB_COLORS );
1584 GlobalUnlock( lpdata->hData );
1585 lpdata->drvData = pixmap;
1588 *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1590 /* Wrap pixmap so we can return a handle */
1591 hData = GlobalAlloc(0, *lpBytes);
1592 lpData = GlobalLock(hData);
1593 memcpy(lpData, &lpdata->drvData, *lpBytes);
1594 GlobalUnlock(hData);
1596 return hData;
1600 /**************************************************************************
1601 * export_image_bmp
1603 * Export CF_DIB to image/bmp.
1605 static HANDLE export_image_bmp(Display *display, Window requestor, Atom aTarget, Atom rprop,
1606 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1608 HANDLE hpackeddib;
1609 LPBYTE dibdata;
1610 UINT bmpsize;
1611 HANDLE hbmpdata;
1612 LPBYTE bmpdata;
1613 BITMAPFILEHEADER *bfh;
1615 *lpBytes = 0;
1617 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1619 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1620 return 0;
1623 hpackeddib = lpdata->hData;
1625 dibdata = GlobalLock(hpackeddib);
1626 if (!dibdata)
1628 ERR("Failed to lock packed DIB\n");
1629 return 0;
1632 bmpsize = sizeof(BITMAPFILEHEADER) + GlobalSize(hpackeddib);
1634 hbmpdata = GlobalAlloc(0, bmpsize);
1636 if (hbmpdata)
1638 bmpdata = GlobalLock(hbmpdata);
1640 if (!bmpdata)
1642 GlobalFree(hbmpdata);
1643 GlobalUnlock(hpackeddib);
1644 return 0;
1647 /* bitmap file header */
1648 bfh = (BITMAPFILEHEADER*)bmpdata;
1649 bfh->bfType = 0x4d42; /* "BM" */
1650 bfh->bfSize = bmpsize;
1651 bfh->bfReserved1 = 0;
1652 bfh->bfReserved2 = 0;
1653 bfh->bfOffBits = sizeof(BITMAPFILEHEADER) + bitmap_info_size((BITMAPINFO*)dibdata, DIB_RGB_COLORS);
1655 /* rest of bitmap is the same as the packed dib */
1656 memcpy(bfh+1, dibdata, bmpsize-sizeof(BITMAPFILEHEADER));
1658 *lpBytes = bmpsize;
1660 GlobalUnlock(hbmpdata);
1663 GlobalUnlock(hpackeddib);
1665 return hbmpdata;
1669 /**************************************************************************
1670 * export_metafile
1672 * Export MetaFilePict.
1674 static HANDLE export_metafile(Display *display, Window requestor, Atom aTarget, Atom rprop,
1675 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1677 LPMETAFILEPICT lpmfp;
1678 unsigned int size;
1679 HANDLE h;
1681 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1683 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1684 return 0;
1687 *lpBytes = 0; /* Assume failure */
1689 lpmfp = GlobalLock(lpdata->hData);
1690 size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
1692 h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
1693 if (h)
1695 char *pdata = GlobalLock(h);
1697 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
1698 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
1700 *lpBytes = size + sizeof(METAFILEPICT);
1702 GlobalUnlock(h);
1704 GlobalUnlock(lpdata->hData);
1706 return h;
1710 /**************************************************************************
1711 * export_enhmetafile
1713 * Export EnhMetaFile.
1715 static HANDLE export_enhmetafile(Display *display, Window requestor, Atom aTarget, Atom rprop,
1716 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1718 unsigned int size;
1719 HANDLE h;
1721 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1723 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1724 return 0;
1727 *lpBytes = 0; /* Assume failure */
1729 size = GetEnhMetaFileBits(lpdata->hData, 0, NULL);
1730 h = GlobalAlloc(0, size);
1731 if (h)
1733 LPVOID pdata = GlobalLock(h);
1735 GetEnhMetaFileBits(lpdata->hData, size, pdata);
1736 *lpBytes = size;
1738 GlobalUnlock(h);
1740 return h;
1744 /**************************************************************************
1745 * get_html_description_field
1747 * Find the value of a field in an HTML Format description.
1749 static LPCSTR get_html_description_field(LPCSTR data, LPCSTR keyword)
1751 LPCSTR pos=data;
1753 while (pos && *pos && *pos != '<')
1755 if (memcmp(pos, keyword, strlen(keyword)) == 0)
1756 return pos+strlen(keyword);
1758 pos = strchr(pos, '\n');
1759 if (pos) pos++;
1762 return NULL;
1766 /**************************************************************************
1767 * export_text_html
1769 * Export HTML Format to text/html.
1771 * FIXME: We should attempt to add an <a base> tag and convert windows paths.
1773 static HANDLE export_text_html(Display *display, Window requestor, Atom aTarget,
1774 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1776 HANDLE hdata;
1777 LPCSTR data, field_value;
1778 UINT fragmentstart, fragmentend, htmlsize;
1779 HANDLE hhtmldata=NULL;
1780 LPSTR htmldata;
1782 *lpBytes = 0;
1784 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1786 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1787 return 0;
1790 hdata = lpdata->hData;
1792 data = GlobalLock(hdata);
1793 if (!data)
1795 ERR("Failed to lock HTML Format data\n");
1796 return 0;
1799 /* read the important fields */
1800 field_value = get_html_description_field(data, "StartFragment:");
1801 if (!field_value)
1803 ERR("Couldn't find StartFragment value\n");
1804 goto end;
1806 fragmentstart = atoi(field_value);
1808 field_value = get_html_description_field(data, "EndFragment:");
1809 if (!field_value)
1811 ERR("Couldn't find EndFragment value\n");
1812 goto end;
1814 fragmentend = atoi(field_value);
1816 /* export only the fragment */
1817 htmlsize = fragmentend - fragmentstart + 1;
1819 hhtmldata = GlobalAlloc(0, htmlsize);
1821 if (hhtmldata)
1823 htmldata = GlobalLock(hhtmldata);
1825 if (!htmldata)
1827 GlobalFree(hhtmldata);
1828 htmldata = NULL;
1829 goto end;
1832 memcpy(htmldata, &data[fragmentstart], fragmentend-fragmentstart);
1833 htmldata[htmlsize-1] = '\0';
1835 *lpBytes = htmlsize;
1837 GlobalUnlock(htmldata);
1840 end:
1842 GlobalUnlock(hdata);
1844 return hhtmldata;
1848 /**************************************************************************
1849 * export_hdrop
1851 * Export CF_HDROP format to text/uri-list.
1853 static HANDLE export_hdrop(Display *display, Window requestor, Atom aTarget,
1854 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1856 HDROP hDrop;
1857 UINT i;
1858 UINT numFiles;
1859 HGLOBAL hClipData = NULL;
1860 char *textUriList = NULL;
1861 UINT textUriListSize = 32;
1862 UINT next = 0;
1864 *lpBytes = 0;
1866 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1868 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1869 return 0;
1871 hClipData = GlobalAlloc(GMEM_FIXED, textUriListSize);
1872 if (hClipData == NULL)
1873 return 0;
1874 hDrop = (HDROP) lpdata->hData;
1875 numFiles = DragQueryFileW(hDrop, 0xFFFFFFFF, NULL, 0);
1876 for (i = 0; i < numFiles; i++)
1878 UINT dosFilenameSize;
1879 WCHAR *dosFilename = NULL;
1880 char *unixFilename = NULL;
1881 UINT uriSize;
1882 UINT u;
1884 dosFilenameSize = 1 + DragQueryFileW(hDrop, i, NULL, 0);
1885 dosFilename = HeapAlloc(GetProcessHeap(), 0, dosFilenameSize*sizeof(WCHAR));
1886 if (dosFilename == NULL) goto failed;
1887 DragQueryFileW(hDrop, i, dosFilename, dosFilenameSize);
1888 unixFilename = wine_get_unix_file_name(dosFilename);
1889 HeapFree(GetProcessHeap(), 0, dosFilename);
1890 if (unixFilename == NULL) goto failed;
1891 uriSize = 8 + /* file:/// */
1892 3 * (lstrlenA(unixFilename) - 1) + /* "%xy" per char except first '/' */
1893 2; /* \r\n */
1894 if ((next + uriSize) > textUriListSize)
1896 UINT biggerSize = max( 2 * textUriListSize, next + uriSize );
1897 HGLOBAL bigger = GlobalReAlloc(hClipData, biggerSize, 0);
1898 if (bigger)
1900 hClipData = bigger;
1901 textUriListSize = biggerSize;
1903 else
1905 HeapFree(GetProcessHeap(), 0, unixFilename);
1906 goto failed;
1909 textUriList = GlobalLock(hClipData);
1910 lstrcpyA(&textUriList[next], "file:///");
1911 next += 8;
1912 /* URL encode everything - unnecessary, but easier/lighter than linking in shlwapi, and can't hurt */
1913 for (u = 1; unixFilename[u]; u++)
1915 static const char hex_table[] = "0123456789abcdef";
1916 textUriList[next++] = '%';
1917 textUriList[next++] = hex_table[unixFilename[u] >> 4];
1918 textUriList[next++] = hex_table[unixFilename[u] & 0xf];
1920 textUriList[next++] = '\r';
1921 textUriList[next++] = '\n';
1922 GlobalUnlock(hClipData);
1923 HeapFree(GetProcessHeap(), 0, unixFilename);
1926 *lpBytes = next;
1927 return hClipData;
1929 failed:
1930 GlobalFree(hClipData);
1931 *lpBytes = 0;
1932 return 0;
1936 /**************************************************************************
1937 * X11DRV_CLIPBOARD_QueryTargets
1939 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection,
1940 Atom target, XEvent *xe)
1942 INT i;
1944 XConvertSelection(display, selection, target, x11drv_atom(SELECTION_DATA), w, CurrentTime);
1947 * Wait until SelectionNotify is received
1949 for (i = 0; i < SELECTION_RETRIES; i++)
1951 Bool res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
1952 if (res && xe->xselection.selection == selection) break;
1954 usleep(SELECTION_WAIT);
1957 if (i == SELECTION_RETRIES)
1959 ERR("Timed out waiting for SelectionNotify event\n");
1960 return FALSE;
1962 /* Verify that the selection returned a valid TARGETS property */
1963 if ((xe->xselection.target != target) || (xe->xselection.property == None))
1965 /* Selection owner failed to respond or we missed the SelectionNotify */
1966 WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
1967 return FALSE;
1970 return TRUE;
1974 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
1976 return (event->error_code == BadAtom);
1979 static int is_window_error( Display *display, XErrorEvent *event, void *arg )
1981 return (event->error_code == BadWindow);
1984 /**************************************************************************
1985 * X11DRV_CLIPBOARD_InsertSelectionProperties
1987 * Mark properties available for future retrieval.
1989 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
1991 UINT i, nb_atoms = 0;
1992 Atom *atoms = NULL;
1994 /* Cache these formats in the clipboard cache */
1995 for (i = 0; i < count; i++)
1997 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
1999 if (lpFormat)
2001 /* We found at least one Window's format that mapps to the property.
2002 * Continue looking for more.
2004 * If more than one property map to a Window's format then we use the first
2005 * one and ignore the rest.
2007 while (lpFormat)
2009 TRACE( "property %s -> format %s\n",
2010 debugstr_xatom( lpFormat->atom ), debugstr_format( lpFormat->id ));
2011 X11DRV_CLIPBOARD_InsertClipboardData( lpFormat->id, 0, lpFormat, FALSE );
2012 lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
2015 else if (properties[i])
2017 /* add it to the list of atoms that we don't know about yet */
2018 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
2019 (count - i) * sizeof(*atoms) );
2020 if (atoms) atoms[nb_atoms++] = properties[i];
2024 /* query all unknown atoms in one go */
2025 if (atoms)
2027 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
2028 if (names)
2030 X11DRV_expect_error( display, is_atom_error, NULL );
2031 if (!XGetAtomNames( display, atoms, nb_atoms, names )) nb_atoms = 0;
2032 if (X11DRV_check_error())
2034 WARN( "got some bad atoms, ignoring\n" );
2035 nb_atoms = 0;
2037 for (i = 0; i < nb_atoms; i++)
2039 WINE_CLIPFORMAT *lpFormat;
2040 LPWSTR wname;
2041 int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
2042 wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2043 MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
2045 lpFormat = register_format( RegisterClipboardFormatW(wname), atoms[i] );
2046 HeapFree(GetProcessHeap(), 0, wname);
2047 if (!lpFormat)
2049 ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
2050 continue;
2052 TRACE( "property %s -> format %s\n",
2053 debugstr_xatom( lpFormat->atom ), debugstr_format( lpFormat->id ));
2054 X11DRV_CLIPBOARD_InsertClipboardData( lpFormat->id, 0, lpFormat, FALSE );
2056 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
2057 HeapFree( GetProcessHeap(), 0, names );
2059 HeapFree( GetProcessHeap(), 0, atoms );
2064 /**************************************************************************
2065 * X11DRV_CLIPBOARD_QueryAvailableData
2067 * Caches the list of data formats available from the current selection.
2068 * This queries the selection owner for the TARGETS property and saves all
2069 * reported property types.
2071 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display)
2073 XEvent xe;
2074 Atom atype=AnyPropertyType;
2075 int aformat;
2076 unsigned long remain;
2077 Atom* targetList=NULL;
2078 Window w;
2079 unsigned long cSelectionTargets = 0;
2081 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
2083 ERR("Received request to cache selection but process is owner=(%08x)\n",
2084 (unsigned) selectionWindow);
2085 return -1; /* Prevent self request */
2088 w = thread_selection_wnd();
2089 if (!w)
2091 ERR("No window available to retrieve selection!\n");
2092 return -1;
2096 * Query the selection owner for the TARGETS property
2098 if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
2099 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2101 if (use_primary_selection && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
2102 selectionCacheSrc = XA_PRIMARY;
2103 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
2104 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2105 else
2107 Atom xstr = XA_STRING;
2109 /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
2110 if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
2112 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2113 selectionCacheSrc = XA_PRIMARY;
2114 return 1;
2116 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
2118 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2119 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2120 return 1;
2122 else
2124 WARN("Failed to query selection owner for available data.\n");
2125 return -1;
2129 else return 0; /* No selection owner so report 0 targets available */
2131 /* Read the TARGETS property contents */
2132 if (!XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
2133 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
2134 &remain, (unsigned char**)&targetList))
2136 TRACE( "type %s format %d count %ld remain %ld\n",
2137 debugstr_xatom( atype ), aformat, cSelectionTargets, remain);
2139 * The TARGETS property should have returned us a list of atoms
2140 * corresponding to each selection target format supported.
2142 if (atype == XA_ATOM || atype == x11drv_atom(TARGETS))
2144 if (aformat == 32)
2146 X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, cSelectionTargets);
2148 else if (aformat == 8) /* work around quartz-wm brain damage */
2150 unsigned long i, count = cSelectionTargets / sizeof(CARD32);
2151 Atom *atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(Atom) );
2152 for (i = 0; i < count; i++)
2153 atoms[i] = ((CARD32 *)targetList)[i]; /* FIXME: byte swapping */
2154 X11DRV_CLIPBOARD_InsertSelectionProperties( display, atoms, count );
2155 HeapFree( GetProcessHeap(), 0, atoms );
2159 /* Free the list of targets */
2160 XFree(targetList);
2162 else WARN("Failed to read TARGETS property\n");
2164 return cSelectionTargets;
2168 /**************************************************************************
2169 * X11DRV_CLIPBOARD_ReadSelectionData
2171 * This method is invoked only when we DO NOT own the X selection
2173 * We always get the data from the selection client each time,
2174 * since we have no way of determining if the data in our cache is stale.
2176 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData)
2178 Bool res;
2179 DWORD i;
2180 XEvent xe;
2181 BOOL bRet = FALSE;
2183 TRACE("%04x\n", lpData->wFormatID);
2185 if (!lpData->lpFormat)
2187 ERR("Requesting format %04x but no source format linked to data.\n",
2188 lpData->wFormatID);
2189 return FALSE;
2192 if (!selectionAcquired)
2194 Window w = thread_selection_wnd();
2195 if(!w)
2197 ERR("No window available to read selection data!\n");
2198 return FALSE;
2201 TRACE("Requesting conversion of %s property %s from selection type %08x\n",
2202 debugstr_format( lpData->lpFormat->id ), debugstr_xatom( lpData->lpFormat->atom ),
2203 (UINT)selectionCacheSrc);
2205 XConvertSelection(display, selectionCacheSrc, lpData->lpFormat->atom,
2206 x11drv_atom(SELECTION_DATA), w, CurrentTime);
2208 /* wait until SelectionNotify is received */
2209 for (i = 0; i < SELECTION_RETRIES; i++)
2211 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
2212 if (res && xe.xselection.selection == selectionCacheSrc) break;
2214 usleep(SELECTION_WAIT);
2217 if (i == SELECTION_RETRIES)
2219 ERR("Timed out waiting for SelectionNotify event\n");
2221 /* Verify that the selection returned a valid TARGETS property */
2222 else if (xe.xselection.property != None)
2225 * Read the contents of the X selection property
2226 * into WINE's clipboard cache and converting the
2227 * data format if necessary.
2229 HANDLE hData = lpData->lpFormat->lpDrvImportFunc(display, xe.xselection.requestor,
2230 xe.xselection.property);
2232 if (hData)
2233 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, hData, lpData->lpFormat, TRUE);
2234 else
2235 TRACE("Import function failed\n");
2237 else
2239 TRACE("Failed to convert selection\n");
2242 else
2244 ERR("Received request to cache selection data but process is owner\n");
2247 TRACE("Returning %d\n", bRet);
2249 return bRet;
2253 /**************************************************************************
2254 * X11DRV_CLIPBOARD_GetProperty
2255 * Gets type, data and size.
2257 static BOOL X11DRV_CLIPBOARD_GetProperty(Display *display, Window w, Atom prop,
2258 Atom *atype, unsigned char** data, unsigned long* datasize)
2260 int aformat;
2261 unsigned long pos = 0, nitems, remain, count;
2262 unsigned char *val = NULL, *buffer;
2264 TRACE( "Reading property %s from X window %lx\n", debugstr_xatom( prop ), w );
2266 for (;;)
2268 if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
2269 AnyPropertyType, atype, &aformat, &nitems, &remain, &buffer))
2271 WARN("Failed to read property\n");
2272 HeapFree( GetProcessHeap(), 0, val );
2273 return FALSE;
2276 count = get_property_size( aformat, nitems );
2277 if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
2278 else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
2280 if (!*data)
2282 XFree( buffer );
2283 HeapFree( GetProcessHeap(), 0, val );
2284 return FALSE;
2286 val = *data;
2287 memcpy( (int *)val + pos, buffer, count );
2288 XFree( buffer );
2289 if (!remain)
2291 *datasize = pos * sizeof(int) + count;
2292 val[*datasize] = 0;
2293 break;
2295 pos += count / sizeof(int);
2298 /* Delete the property on the window now that we are done
2299 * This will send a PropertyNotify event to the selection owner. */
2300 XDeleteProperty(display, w, prop);
2301 return TRUE;
2305 struct clipboard_data_packet {
2306 struct list entry;
2307 unsigned long size;
2308 unsigned char *data;
2311 /**************************************************************************
2312 * X11DRV_CLIPBOARD_ReadProperty
2313 * Reads the contents of the X selection property.
2315 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
2316 unsigned char** data, unsigned long* datasize)
2318 Atom atype;
2319 XEvent xe;
2321 if (prop == None)
2322 return FALSE;
2324 while (XCheckTypedWindowEvent(display, w, PropertyNotify, &xe))
2327 if (!X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, data, datasize))
2328 return FALSE;
2330 if (atype == x11drv_atom(INCR))
2332 unsigned char *buf;
2333 unsigned long bufsize = 0;
2334 struct list packets;
2335 struct clipboard_data_packet *packet, *packet2;
2336 BOOL res;
2338 HeapFree(GetProcessHeap(), 0, *data);
2339 *data = NULL;
2341 list_init(&packets);
2343 for (;;)
2345 int i;
2346 unsigned char *prop_data;
2347 unsigned long prop_size;
2349 /* Wait until PropertyNotify is received */
2350 for (i = 0; i < SELECTION_RETRIES; i++)
2352 Bool res;
2354 res = XCheckTypedWindowEvent(display, w, PropertyNotify, &xe);
2355 if (res && xe.xproperty.atom == prop &&
2356 xe.xproperty.state == PropertyNewValue)
2357 break;
2358 usleep(SELECTION_WAIT);
2361 if (i >= SELECTION_RETRIES ||
2362 !X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, &prop_data, &prop_size))
2364 res = FALSE;
2365 break;
2368 /* Retrieved entire data. */
2369 if (prop_size == 0)
2371 HeapFree(GetProcessHeap(), 0, prop_data);
2372 res = TRUE;
2373 break;
2376 packet = HeapAlloc(GetProcessHeap(), 0, sizeof(*packet));
2377 if (!packet)
2379 HeapFree(GetProcessHeap(), 0, prop_data);
2380 res = FALSE;
2381 break;
2384 packet->size = prop_size;
2385 packet->data = prop_data;
2386 list_add_tail(&packets, &packet->entry);
2387 bufsize += prop_size;
2390 if (res)
2392 buf = HeapAlloc(GetProcessHeap(), 0, bufsize + 1);
2393 if (buf)
2395 unsigned long bytes_copied = 0;
2396 *datasize = bufsize;
2397 LIST_FOR_EACH_ENTRY( packet, &packets, struct clipboard_data_packet, entry)
2399 memcpy(&buf[bytes_copied], packet->data, packet->size);
2400 bytes_copied += packet->size;
2402 buf[bufsize] = 0;
2403 *data = buf;
2405 else
2406 res = FALSE;
2409 LIST_FOR_EACH_ENTRY_SAFE( packet, packet2, &packets, struct clipboard_data_packet, entry)
2411 HeapFree(GetProcessHeap(), 0, packet->data);
2412 HeapFree(GetProcessHeap(), 0, packet);
2415 return res;
2418 return TRUE;
2422 /**************************************************************************
2423 * X11DRV_CLIPBOARD_ReleaseSelection
2425 * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
2427 static void X11DRV_CLIPBOARD_ReleaseSelection(Display *display, Atom selType, Window w, HWND hwnd, Time time)
2429 /* w is the window that lost the selection
2431 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
2432 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
2434 if (selectionAcquired && (w == selectionWindow))
2436 HWND owner;
2438 /* completely give up the selection */
2439 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
2441 if (X11DRV_CLIPBOARD_IsProcessOwner( &owner ))
2443 /* Since we're still the owner, this wasn't initiated by
2444 another Wine process */
2445 if (OpenClipboard(hwnd))
2447 /* Destroy private objects */
2448 SendMessageW(owner, WM_DESTROYCLIPBOARD, 0, 0);
2450 /* Give up ownership of the windows clipboard */
2451 X11DRV_CLIPBOARD_ReleaseOwnership();
2452 CloseClipboard();
2456 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2458 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2460 if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2462 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2463 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2465 else
2466 TRACE("We no longer own PRIMARY\n");
2468 else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2470 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2472 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2474 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2475 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2477 else
2478 TRACE("We no longer own CLIPBOARD\n");
2481 selectionWindow = None;
2483 empty_clipboard();
2485 /* Reset the selection flags now that we are done */
2486 selectionAcquired = S_NOSELECTION;
2491 /**************************************************************************
2492 * X11DRV Clipboard Exports
2493 **************************************************************************/
2496 static void selection_acquire(void)
2498 Window owner;
2499 Display *display;
2501 owner = thread_selection_wnd();
2502 display = thread_display();
2504 selectionAcquired = 0;
2505 selectionWindow = 0;
2507 /* Grab PRIMARY selection if not owned */
2508 if (use_primary_selection)
2509 XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2511 /* Grab CLIPBOARD selection if not owned */
2512 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2514 if (use_primary_selection && XGetSelectionOwner(display, XA_PRIMARY) == owner)
2515 selectionAcquired |= S_PRIMARY;
2517 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2518 selectionAcquired |= S_CLIPBOARD;
2520 if (selectionAcquired)
2522 selectionWindow = owner;
2523 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2527 static DWORD WINAPI selection_thread_proc(LPVOID p)
2529 HANDLE event = p;
2531 TRACE("\n");
2533 selection_acquire();
2534 SetEvent(event);
2536 while (selectionAcquired)
2538 MsgWaitForMultipleObjectsEx(0, NULL, INFINITE, QS_SENDMESSAGE, 0);
2541 return 0;
2544 /**************************************************************************
2545 * X11DRV_AcquireClipboard
2547 void X11DRV_AcquireClipboard(HWND hWndClipWindow)
2549 DWORD procid;
2550 HANDLE selectionThread;
2552 TRACE(" %p\n", hWndClipWindow);
2555 * It's important that the selection get acquired from the thread
2556 * that owns the clipboard window. The primary reason is that we know
2557 * it is running a message loop and therefore can process the
2558 * X selection events.
2560 if (hWndClipWindow &&
2561 GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, &procid))
2563 if (procid != GetCurrentProcessId())
2565 WARN("Setting clipboard owner to other process is not supported\n");
2566 hWndClipWindow = NULL;
2568 else
2570 TRACE("Thread %x is acquiring selection with thread %x's window %p\n",
2571 GetCurrentThreadId(),
2572 GetWindowThreadProcessId(hWndClipWindow, NULL), hWndClipWindow);
2574 SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0);
2575 return;
2579 if (hWndClipWindow)
2581 selection_acquire();
2583 else
2585 HANDLE event = CreateEventW(NULL, FALSE, FALSE, NULL);
2586 selectionThread = CreateThread(NULL, 0, selection_thread_proc, event, 0, NULL);
2588 if (selectionThread)
2590 WaitForSingleObject(event, INFINITE);
2591 CloseHandle(selectionThread);
2593 CloseHandle(event);
2598 static void empty_clipboard(void)
2600 WINE_CLIPDATA *data, *next;
2602 LIST_FOR_EACH_ENTRY_SAFE( data, next, &data_list, WINE_CLIPDATA, entry )
2604 list_remove( &data->entry );
2605 X11DRV_CLIPBOARD_FreeData( data );
2606 HeapFree( GetProcessHeap(), 0, data );
2607 ClipDataCount--;
2610 TRACE(" %d entries remaining in cache.\n", ClipDataCount);
2613 /**************************************************************************
2614 * X11DRV_EmptyClipboard
2616 * Empty cached clipboard data.
2618 void CDECL X11DRV_EmptyClipboard(void)
2620 X11DRV_AcquireClipboard( GetOpenClipboardWindow() );
2621 empty_clipboard();
2624 /**************************************************************************
2625 * X11DRV_SetClipboardData
2627 BOOL CDECL X11DRV_SetClipboardData(UINT wFormat, HANDLE hData, BOOL owner)
2629 if (!owner) X11DRV_CLIPBOARD_UpdateCache();
2631 return X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData, NULL, TRUE);
2635 /**************************************************************************
2636 * CountClipboardFormats
2638 INT CDECL X11DRV_CountClipboardFormats(void)
2640 X11DRV_CLIPBOARD_UpdateCache();
2642 TRACE(" count=%d\n", ClipDataCount);
2644 return ClipDataCount;
2648 /**************************************************************************
2649 * X11DRV_EnumClipboardFormats
2651 UINT CDECL X11DRV_EnumClipboardFormats(UINT wFormat)
2653 struct list *ptr = NULL;
2655 TRACE("(%04X)\n", wFormat);
2657 X11DRV_CLIPBOARD_UpdateCache();
2659 if (!wFormat)
2661 ptr = list_head( &data_list );
2663 else
2665 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
2666 if (lpData) ptr = list_next( &data_list, &lpData->entry );
2669 if (!ptr) return 0;
2670 return LIST_ENTRY( ptr, WINE_CLIPDATA, entry )->wFormatID;
2674 /**************************************************************************
2675 * X11DRV_IsClipboardFormatAvailable
2677 BOOL CDECL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
2679 BOOL bRet = FALSE;
2681 TRACE("(%04X)\n", wFormat);
2683 X11DRV_CLIPBOARD_UpdateCache();
2685 if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
2686 bRet = TRUE;
2688 TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
2690 return bRet;
2694 /**************************************************************************
2695 * GetClipboardData (USER.142)
2697 HANDLE CDECL X11DRV_GetClipboardData(UINT wFormat)
2699 LPWINE_CLIPDATA lpRender;
2701 TRACE("(%04X)\n", wFormat);
2703 X11DRV_CLIPBOARD_UpdateCache();
2705 if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
2707 if ( !lpRender->hData )
2708 X11DRV_CLIPBOARD_RenderFormat(thread_init_display(), lpRender);
2710 TRACE(" returning %p (type %04x)\n", lpRender->hData, lpRender->wFormatID);
2711 return lpRender->hData;
2714 return 0;
2718 /**************************************************************************
2719 * ResetSelectionOwner
2721 * Called when the thread owning the selection is destroyed and we need to
2722 * preserve the selection ownership. We look for another top level window
2723 * in this process and send it a message to acquire the selection.
2725 void X11DRV_ResetSelectionOwner(void)
2727 HWND hwnd;
2728 DWORD procid;
2730 TRACE("\n");
2732 if (!selectionAcquired || thread_selection_wnd() != selectionWindow)
2733 return;
2735 selectionAcquired = S_NOSELECTION;
2736 selectionWindow = 0;
2738 hwnd = GetWindow(GetDesktopWindow(), GW_CHILD);
2741 if (GetCurrentThreadId() != GetWindowThreadProcessId(hwnd, &procid))
2743 if (GetCurrentProcessId() == procid)
2745 if (SendMessageW(hwnd, WM_X11DRV_ACQUIRE_SELECTION, 0, 0))
2746 return;
2749 } while ((hwnd = GetWindow(hwnd, GW_HWNDNEXT)) != NULL);
2751 WARN("Failed to find another thread to take selection ownership. Clipboard data will be lost.\n");
2753 X11DRV_CLIPBOARD_ReleaseOwnership();
2754 empty_clipboard();
2758 /***********************************************************************
2759 * X11DRV_SelectionRequest_TARGETS
2760 * Service a TARGETS selection request event
2762 static Atom X11DRV_SelectionRequest_TARGETS( Display *display, Window requestor,
2763 Atom target, Atom rprop )
2765 UINT i;
2766 Atom* targets;
2767 ULONG cTargets;
2768 LPWINE_CLIPFORMAT format;
2769 LPWINE_CLIPDATA lpData;
2771 /* Create X atoms for any clipboard types which don't have atoms yet.
2772 * This avoids sending bogus zero atoms.
2773 * Without this, copying might not have access to all clipboard types.
2774 * FIXME: is it safe to call this here?
2776 intern_atoms();
2779 * Count the number of items we wish to expose as selection targets.
2781 cTargets = 1; /* Include TARGETS */
2783 if (!list_head( &data_list )) return None;
2785 LIST_FOR_EACH_ENTRY( lpData, &data_list, WINE_CLIPDATA, entry )
2786 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
2787 if ((format->id == lpData->wFormatID) &&
2788 format->lpDrvExportFunc && format->atom)
2789 cTargets++;
2791 TRACE(" found %d formats\n", cTargets);
2793 /* Allocate temp buffer */
2794 targets = HeapAlloc( GetProcessHeap(), 0, cTargets * sizeof(Atom));
2795 if(targets == NULL)
2796 return None;
2798 i = 0;
2799 targets[i++] = x11drv_atom(TARGETS);
2801 LIST_FOR_EACH_ENTRY( lpData, &data_list, WINE_CLIPDATA, entry )
2802 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
2803 if ((format->id == lpData->wFormatID) &&
2804 format->lpDrvExportFunc && format->atom)
2806 TRACE( "%d: %s -> %s\n", i, debugstr_format( format->id ),
2807 debugstr_xatom( format->atom ));
2808 targets[i++] = format->atom;
2811 put_property( display, requestor, rprop, XA_ATOM, 32, targets, cTargets );
2813 HeapFree(GetProcessHeap(), 0, targets);
2815 return rprop;
2819 /***********************************************************************
2820 * X11DRV_SelectionRequest_MULTIPLE
2821 * Service a MULTIPLE selection request event
2822 * rprop contains a list of (target,property) atom pairs.
2823 * The first atom names a target and the second names a property.
2824 * The effect is as if we have received a sequence of SelectionRequest events
2825 * (one for each atom pair) except that:
2826 * 1. We reply with a SelectionNotify only when all the requested conversions
2827 * have been performed.
2828 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
2829 * we replace the atom in the property by None.
2831 static Atom X11DRV_SelectionRequest_MULTIPLE( HWND hWnd, XSelectionRequestEvent *pevent )
2833 Display *display = pevent->display;
2834 Atom rprop;
2835 Atom atype=AnyPropertyType;
2836 int aformat;
2837 unsigned long remain;
2838 Atom* targetPropList=NULL;
2839 unsigned long cTargetPropList = 0;
2841 /* If the specified property is None the requestor is an obsolete client.
2842 * We support these by using the specified target atom as the reply property.
2844 rprop = pevent->property;
2845 if( rprop == None )
2846 rprop = pevent->target;
2847 if (!rprop)
2848 return 0;
2850 /* Read the MULTIPLE property contents. This should contain a list of
2851 * (target,property) atom pairs.
2853 if (!XGetWindowProperty(display, pevent->requestor, rprop,
2854 0, 0x3FFF, False, AnyPropertyType, &atype,&aformat,
2855 &cTargetPropList, &remain,
2856 (unsigned char**)&targetPropList))
2858 TRACE( "type %s format %d count %ld remain %ld\n",
2859 debugstr_xatom( atype ), aformat, cTargetPropList, remain );
2862 * Make sure we got what we expect.
2863 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
2864 * in a MULTIPLE selection request should be of type ATOM_PAIR.
2865 * However some X apps(such as XPaint) are not compliant with this and return
2866 * a user defined atom in atype when XGetWindowProperty is called.
2867 * The data *is* an atom pair but is not denoted as such.
2869 if(aformat == 32 /* atype == xAtomPair */ )
2871 unsigned int i;
2873 /* Iterate through the ATOM_PAIR list and execute a SelectionRequest
2874 * for each (target,property) pair */
2876 for (i = 0; i < cTargetPropList; i+=2)
2878 XSelectionRequestEvent event;
2880 TRACE( "MULTIPLE(%d): target %s property %s\n",
2881 i/2, debugstr_xatom( targetPropList[i] ), debugstr_xatom( targetPropList[i + 1] ));
2883 /* We must have a non "None" property to service a MULTIPLE target atom */
2884 if ( !targetPropList[i+1] )
2886 TRACE("\tMULTIPLE(%d): Skipping target with empty property!\n", i);
2887 continue;
2890 /* Set up an XSelectionRequestEvent for this (target,property) pair */
2891 event = *pevent;
2892 event.target = targetPropList[i];
2893 event.property = targetPropList[i+1];
2895 /* Fire a SelectionRequest, informing the handler that we are processing
2896 * a MULTIPLE selection request event.
2898 X11DRV_HandleSelectionRequest( hWnd, &event, TRUE );
2902 /* Free the list of targets/properties */
2903 XFree(targetPropList);
2905 else TRACE("Couldn't read MULTIPLE property\n");
2907 return rprop;
2911 /***********************************************************************
2912 * X11DRV_HandleSelectionRequest
2913 * Process an event selection request event.
2914 * The bIsMultiple flag is used to signal when EVENT_SelectionRequest is called
2915 * recursively while servicing a "MULTIPLE" selection target.
2917 * Note: We only receive this event when WINE owns the X selection
2919 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple )
2921 Display *display = event->display;
2922 XSelectionEvent result;
2923 Atom rprop = None;
2924 Window request = event->requestor;
2926 TRACE("\n");
2928 X11DRV_expect_error( display, is_window_error, NULL );
2931 * We can only handle the selection request if :
2932 * The selection is PRIMARY or CLIPBOARD, AND we can successfully open the clipboard.
2933 * Don't do these checks or open the clipboard while recursively processing MULTIPLE,
2934 * since this has been already done.
2936 if ( !bIsMultiple )
2938 if (((event->selection != XA_PRIMARY) && (event->selection != x11drv_atom(CLIPBOARD))))
2939 goto END;
2942 /* If the specified property is None the requestor is an obsolete client.
2943 * We support these by using the specified target atom as the reply property.
2945 rprop = event->property;
2946 if( rprop == None )
2947 rprop = event->target;
2949 if(event->target == x11drv_atom(TARGETS)) /* Return a list of all supported targets */
2951 /* TARGETS selection request */
2952 rprop = X11DRV_SelectionRequest_TARGETS( display, request, event->target, rprop );
2954 else if(event->target == x11drv_atom(MULTIPLE)) /* rprop contains a list of (target, property) atom pairs */
2956 /* MULTIPLE selection request */
2957 rprop = X11DRV_SelectionRequest_MULTIPLE( hWnd, event );
2959 else
2961 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, event->target);
2962 BOOL success = FALSE;
2964 if (lpFormat && lpFormat->lpDrvExportFunc)
2966 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(lpFormat->id);
2968 if (lpData)
2970 unsigned char* lpClipData;
2971 DWORD cBytes;
2972 HANDLE hClipData = lpFormat->lpDrvExportFunc(display, request, event->target,
2973 rprop, lpData, &cBytes);
2975 if (hClipData && (lpClipData = GlobalLock(hClipData)))
2977 TRACE("\tUpdating property %s, %d bytes\n",
2978 debugstr_format(lpFormat->id), cBytes);
2980 put_property( display, request, rprop, event->target, 8, lpClipData, cBytes );
2982 GlobalUnlock(hClipData);
2983 GlobalFree(hClipData);
2984 success = TRUE;
2989 if (!success)
2990 rprop = None; /* report failure to client */
2993 END:
2994 /* reply to sender
2995 * SelectionNotify should be sent only at the end of a MULTIPLE request
2997 if ( !bIsMultiple )
2999 result.type = SelectionNotify;
3000 result.display = display;
3001 result.requestor = request;
3002 result.selection = event->selection;
3003 result.property = rprop;
3004 result.target = event->target;
3005 result.time = event->time;
3006 TRACE("Sending SelectionNotify event...\n");
3007 XSendEvent(display,event->requestor,False,NoEventMask,(XEvent*)&result);
3009 XSync( display, False );
3010 if (X11DRV_check_error()) WARN( "requestor %lx is no longer valid\n", event->requestor );
3014 /***********************************************************************
3015 * X11DRV_SelectionRequest
3017 BOOL X11DRV_SelectionRequest( HWND hWnd, XEvent *event )
3019 X11DRV_HandleSelectionRequest( hWnd, &event->xselectionrequest, FALSE );
3020 return FALSE;
3024 /***********************************************************************
3025 * X11DRV_SelectionClear
3027 BOOL X11DRV_SelectionClear( HWND hWnd, XEvent *xev )
3029 XSelectionClearEvent *event = &xev->xselectionclear;
3030 if (event->selection == XA_PRIMARY || event->selection == x11drv_atom(CLIPBOARD))
3031 X11DRV_CLIPBOARD_ReleaseSelection( event->display, event->selection,
3032 event->window, hWnd, event->time );
3033 return FALSE;