winex11: Support import multiple drag&drop properties in a single call.
[wine.git] / dlls / winex11.drv / clipboard.c
blobd7480ae807d43fa1af119f808fcded6c8333361c
1 /*
2 * X11 clipboard windows driver
4 * Copyright 1994 Martin Ayotte
5 * Copyright 1996 Alex Korobka
6 * Copyright 1999 Noel Borthwick
7 * Copyright 2003 Ulrich Czekalla for CodeWeavers
8 * Copyright 2014 Damjan Jovanovic
9 * Copyright 2016 Alexandre Julliard
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 * NOTES:
26 * This file contains the X specific implementation for the windows
27 * Clipboard API.
29 * Wine's internal clipboard is exposed to external apps via the X
30 * selection mechanism.
31 * Currently the driver asserts ownership via two selection atoms:
32 * 1. PRIMARY(XA_PRIMARY)
33 * 2. CLIPBOARD
35 * In our implementation, the CLIPBOARD selection takes precedence over PRIMARY,
36 * i.e. if a CLIPBOARD selection is available, it is used instead of PRIMARY.
37 * When Wine takes ownership of the clipboard, it takes ownership of BOTH selections.
38 * While giving up selection ownership, if the CLIPBOARD selection is lost,
39 * it will lose both PRIMARY and CLIPBOARD and empty the clipboard.
40 * However if only PRIMARY is lost, it will continue to hold the CLIPBOARD selection
41 * (leaving the clipboard cache content unaffected).
43 * Every format exposed via a windows clipboard format is also exposed through
44 * a corresponding X selection target. A selection target atom is synthesized
45 * whenever a new Windows clipboard format is registered via RegisterClipboardFormat,
46 * or when a built-in format is used for the first time.
47 * Windows native format are exposed by prefixing the format name with "<WCF>"
48 * This allows us to uniquely identify windows native formats exposed by other
49 * running WINE apps.
51 * In order to allow external applications to query WINE for supported formats,
52 * we respond to the "TARGETS" selection target. (See EVENT_SelectionRequest
53 * for implementation) We use the same mechanism to query external clients for
54 * availability of a particular format, by caching the list of available targets
55 * by using the clipboard cache's "delayed render" mechanism. If a selection client
56 * does not support the "TARGETS" selection target, we actually attempt to retrieve
57 * the format requested as a fallback mechanism.
59 * Certain Windows native formats are automatically converted to X native formats
60 * and vice versa. If a native format is available in the selection, it takes
61 * precedence, in order to avoid unnecessary conversions.
63 * FIXME: global format list needs a critical section
66 #include "config.h"
67 #include "wine/port.h"
69 #include <string.h>
70 #include <stdarg.h>
71 #include <stdio.h>
72 #include <stdlib.h>
73 #ifdef HAVE_UNISTD_H
74 # include <unistd.h>
75 #endif
76 #include <fcntl.h>
77 #include <limits.h>
78 #include <time.h>
79 #include <assert.h>
81 #include "windef.h"
82 #include "winbase.h"
83 #include "shlobj.h"
84 #include "shellapi.h"
85 #include "shlwapi.h"
86 #include "x11drv.h"
87 #include "wine/list.h"
88 #include "wine/debug.h"
89 #include "wine/unicode.h"
90 #include "wine/server.h"
92 WINE_DEFAULT_DEBUG_CHANNEL(clipboard);
94 /* Maximum wait time for selection notify */
95 #define SELECTION_RETRIES 500 /* wait for .5 seconds */
96 #define SELECTION_WAIT 1000 /* us */
98 /* Selection masks */
99 #define S_NOSELECTION 0
100 #define S_PRIMARY 1
101 #define S_CLIPBOARD 2
103 struct tagWINE_CLIPDATA; /* Forward */
105 typedef BOOL (*EXPORTFUNC)( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
106 typedef HANDLE (*IMPORTFUNC)( Atom type, const void *data, size_t size );
108 typedef struct clipboard_format
110 struct list entry;
111 UINT id;
112 Atom atom;
113 IMPORTFUNC import;
114 EXPORTFUNC export;
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( Atom type, const void *data, size_t size );
130 static HANDLE import_enhmetafile( Atom type, const void *data, size_t size );
131 static HANDLE import_metafile( Atom type, const void *data, size_t size );
132 static HANDLE import_pixmap( Atom type, const void *data, size_t size );
133 static HANDLE import_image_bmp( Atom type, const void *data, size_t size );
134 static HANDLE import_string( Atom type, const void *data, size_t size );
135 static HANDLE import_utf8_string( Atom type, const void *data, size_t size );
136 static HANDLE import_compound_text( Atom type, const void *data, size_t size );
137 static HANDLE import_text_uri_list( Atom type, const void *data, size_t size );
138 static HANDLE import_targets( Atom type, const void *data, size_t size );
140 static BOOL export_data( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
141 static BOOL export_string( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
142 static BOOL export_utf8_string( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
143 static BOOL export_compound_text( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
144 static BOOL export_pixmap( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
145 static BOOL export_image_bmp( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
146 static BOOL export_metafile( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
147 static BOOL export_enhmetafile( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
148 static BOOL export_text_html( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
149 static BOOL export_hdrop( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
150 static BOOL export_targets( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
151 static BOOL export_multiple( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
153 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData);
154 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display);
155 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData);
156 static BOOL X11DRV_CLIPBOARD_ReadProperty( Display *display, Window w, Atom prop,
157 Atom *type, unsigned char **data, unsigned long *datasize );
158 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData);
159 static void empty_clipboard(void);
161 /* Clipboard formats */
163 static const WCHAR RichTextFormatW[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
164 static const WCHAR GIFW[] = {'G','I','F',0};
165 static const WCHAR JFIFW[] = {'J','F','I','F',0};
166 static const WCHAR PNGW[] = {'P','N','G',0};
167 static const WCHAR HTMLFormatW[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
169 static const struct
171 const WCHAR *name;
172 UINT id;
173 UINT data;
174 IMPORTFUNC import;
175 EXPORTFUNC export;
176 } builtin_formats[] =
178 { 0, CF_TEXT, XA_STRING, import_string, export_string },
179 { 0, CF_TEXT, XATOM_text_plain, import_string, export_string },
180 { 0, CF_BITMAP, XATOM_WCF_BITMAP, import_data, NULL },
181 { 0, CF_METAFILEPICT, XATOM_WCF_METAFILEPICT, import_metafile, export_metafile },
182 { 0, CF_SYLK, XATOM_WCF_SYLK, import_data, export_data },
183 { 0, CF_DIF, XATOM_WCF_DIF, import_data, export_data },
184 { 0, CF_TIFF, XATOM_WCF_TIFF, import_data, export_data },
185 { 0, CF_OEMTEXT, XATOM_WCF_OEMTEXT, import_data, export_data },
186 { 0, CF_DIB, XA_PIXMAP, import_pixmap, export_pixmap },
187 { 0, CF_PALETTE, XATOM_WCF_PALETTE, import_data, export_data },
188 { 0, CF_PENDATA, XATOM_WCF_PENDATA, import_data, export_data },
189 { 0, CF_RIFF, XATOM_WCF_RIFF, import_data, export_data },
190 { 0, CF_WAVE, XATOM_WCF_WAVE, import_data, export_data },
191 { 0, CF_UNICODETEXT, XATOM_UTF8_STRING, import_utf8_string, export_utf8_string },
192 { 0, CF_UNICODETEXT, XATOM_COMPOUND_TEXT, import_compound_text, export_compound_text },
193 { 0, CF_ENHMETAFILE, XATOM_WCF_ENHMETAFILE, import_enhmetafile, export_enhmetafile },
194 { 0, CF_HDROP, XATOM_text_uri_list, import_text_uri_list, export_hdrop },
195 { 0, CF_LOCALE, XATOM_WCF_LOCALE, import_data, export_data },
196 { 0, CF_DIBV5, XATOM_WCF_DIBV5, import_data, export_data },
197 { 0, CF_OWNERDISPLAY, XATOM_WCF_OWNERDISPLAY, import_data, export_data },
198 { 0, CF_DSPTEXT, XATOM_WCF_DSPTEXT, import_data, export_data },
199 { 0, CF_DSPBITMAP, XATOM_WCF_DSPBITMAP, import_data, export_data },
200 { 0, CF_DSPMETAFILEPICT, XATOM_WCF_DSPMETAFILEPICT, import_data, export_data },
201 { 0, CF_DSPENHMETAFILE, XATOM_WCF_DSPENHMETAFILE, import_data, export_data },
202 { 0, CF_DIB, XATOM_image_bmp, import_image_bmp, export_image_bmp },
203 { RichTextFormatW, 0, XATOM_text_rtf, import_data, export_data },
204 { RichTextFormatW, 0, XATOM_text_richtext, import_data, export_data },
205 { GIFW, 0, XATOM_image_gif, import_data, export_data },
206 { JFIFW, 0, XATOM_image_jpeg, import_data, export_data },
207 { PNGW, 0, XATOM_image_png, import_data, export_data },
208 { HTMLFormatW, 0, XATOM_HTML_Format, import_data, export_data },
209 { HTMLFormatW, 0, XATOM_text_html, import_data, export_text_html },
210 { 0, 0, XATOM_TARGETS, import_targets, export_targets },
211 { 0, 0, XATOM_MULTIPLE, NULL, export_multiple },
214 static struct list format_list = LIST_INIT( format_list );
216 #define NB_BUILTIN_FORMATS (sizeof(builtin_formats) / sizeof(builtin_formats[0]))
217 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
221 * Cached clipboard data.
223 static struct list data_list = LIST_INIT( data_list );
224 static UINT ClipDataCount = 0;
227 * Clipboard sequence number
229 static UINT wSeqNo = 0;
231 /**************************************************************************
232 * Internal Clipboard implementation methods
233 **************************************************************************/
235 static Window thread_selection_wnd(void)
237 struct x11drv_thread_data *thread_data = x11drv_init_thread_data();
238 Window w = thread_data->selection_wnd;
240 if (!w)
242 w = XCreateWindow(thread_data->display, root_window, 0, 0, 1, 1, 0, CopyFromParent,
243 InputOnly, CopyFromParent, 0, NULL);
244 if (w)
246 thread_data->selection_wnd = w;
248 XSelectInput(thread_data->display, w, PropertyChangeMask);
250 else
251 FIXME("Failed to create window. Fetching selection data will fail.\n");
254 return w;
257 static const char *debugstr_format( UINT id )
259 WCHAR buffer[256];
261 if (GetClipboardFormatNameW( id, buffer, 256 ))
262 return wine_dbg_sprintf( "%04x %s", id, debugstr_w(buffer) );
264 switch (id)
266 case 0: return "(none)";
267 #define BUILTIN(id) case id: return #id;
268 BUILTIN(CF_TEXT)
269 BUILTIN(CF_BITMAP)
270 BUILTIN(CF_METAFILEPICT)
271 BUILTIN(CF_SYLK)
272 BUILTIN(CF_DIF)
273 BUILTIN(CF_TIFF)
274 BUILTIN(CF_OEMTEXT)
275 BUILTIN(CF_DIB)
276 BUILTIN(CF_PALETTE)
277 BUILTIN(CF_PENDATA)
278 BUILTIN(CF_RIFF)
279 BUILTIN(CF_WAVE)
280 BUILTIN(CF_UNICODETEXT)
281 BUILTIN(CF_ENHMETAFILE)
282 BUILTIN(CF_HDROP)
283 BUILTIN(CF_LOCALE)
284 BUILTIN(CF_DIBV5)
285 BUILTIN(CF_OWNERDISPLAY)
286 BUILTIN(CF_DSPTEXT)
287 BUILTIN(CF_DSPBITMAP)
288 BUILTIN(CF_DSPMETAFILEPICT)
289 BUILTIN(CF_DSPENHMETAFILE)
290 #undef BUILTIN
291 default: return wine_dbg_sprintf( "%04x", id );
295 static const char *debugstr_xatom( Atom atom )
297 const char *ret;
298 char *name;
300 if (!atom) return "(None)";
301 name = XGetAtomName( thread_display(), atom );
302 ret = debugstr_a( name );
303 XFree( name );
304 return ret;
307 /**************************************************************************
308 * X11DRV_InitClipboard
310 void X11DRV_InitClipboard(void)
312 struct clipboard_format *formats;
313 UINT i;
315 if (!(formats = HeapAlloc( GetProcessHeap(), 0, NB_BUILTIN_FORMATS * sizeof(*formats)))) return;
317 for (i = 0; i < NB_BUILTIN_FORMATS; i++)
319 if (builtin_formats[i].name)
320 formats[i].id = RegisterClipboardFormatW( builtin_formats[i].name );
321 else
322 formats[i].id = builtin_formats[i].id;
324 formats[i].atom = GET_ATOM(builtin_formats[i].data);
325 formats[i].import = builtin_formats[i].import;
326 formats[i].export = builtin_formats[i].export;
327 list_add_tail( &format_list, &formats[i].entry );
332 /**************************************************************************
333 * intern_atoms
335 * Intern atoms for formats that don't have one yet.
337 static void intern_atoms(void)
339 LPWINE_CLIPFORMAT format;
340 int i, count, len;
341 char **names;
342 Atom *atoms;
343 Display *display;
344 WCHAR buffer[256];
346 count = 0;
347 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
348 if (!format->atom) count++;
349 if (!count) return;
351 display = thread_init_display();
353 names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
354 atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
356 i = 0;
357 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
358 if (!format->atom) {
359 if (GetClipboardFormatNameW( format->id, buffer, 256 ) > 0)
361 /* use defined format name */
362 len = WideCharToMultiByte(CP_UNIXCP, 0, buffer, -1, NULL, 0, NULL, NULL);
364 else
366 /* create a name in the same way as ntdll/atom.c:integral_atom_name
367 * which is normally used by GetClipboardFormatNameW
369 static const WCHAR fmt[] = {'#','%','u',0};
370 len = sprintfW(buffer, fmt, format->id) + 1;
372 names[i] = HeapAlloc(GetProcessHeap(), 0, len);
373 WideCharToMultiByte(CP_UNIXCP, 0, buffer, -1, names[i++], len, NULL, NULL);
376 XInternAtoms( display, names, count, False, atoms );
378 i = 0;
379 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
380 if (!format->atom) {
381 HeapFree(GetProcessHeap(), 0, names[i]);
382 format->atom = atoms[i++];
385 HeapFree( GetProcessHeap(), 0, names );
386 HeapFree( GetProcessHeap(), 0, atoms );
390 /**************************************************************************
391 * register_format
393 * Register a custom X clipboard format.
395 static struct clipboard_format *register_format( UINT id, Atom prop )
397 struct clipboard_format *format;
399 /* walk format chain to see if it's already registered */
400 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
401 if (format->id == id) return format;
403 if (!(format = HeapAlloc( GetProcessHeap(), 0, sizeof(*format) ))) return NULL;
404 format->id = id;
405 format->atom = prop;
406 format->import = import_data;
407 format->export = export_data;
408 list_add_tail( &format_list, &format->entry );
410 TRACE( "Registering format %s atom %ld\n", debugstr_format(id), prop );
411 return format;
415 /**************************************************************************
416 * X11DRV_CLIPBOARD_LookupProperty
418 static struct clipboard_format *X11DRV_CLIPBOARD_LookupProperty( struct clipboard_format *current, Atom prop )
420 for (;;)
422 struct list *ptr = current ? &current->entry : &format_list;
423 BOOL need_intern = FALSE;
425 while ((ptr = list_next( &format_list, ptr )))
427 struct clipboard_format *format = LIST_ENTRY( ptr, struct clipboard_format, entry );
428 if (format->atom == prop) return format;
429 if (!format->atom) need_intern = TRUE;
431 if (!need_intern) return NULL;
432 intern_atoms();
433 /* restart the search for the new atoms */
438 /**************************************************************************
439 * X11DRV_CLIPBOARD_LookupData
441 static LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
443 WINE_CLIPDATA *data;
445 LIST_FOR_EACH_ENTRY( data, &data_list, WINE_CLIPDATA, entry )
446 if (data->wFormatID == wID) return data;
448 return NULL;
452 /**************************************************************************
453 * X11DRV_CLIPBOARD_IsProcessOwner
455 static BOOL X11DRV_CLIPBOARD_IsProcessOwner( HWND *owner )
457 BOOL ret = FALSE;
459 SERVER_START_REQ( set_clipboard_info )
461 req->flags = 0;
462 if (!wine_server_call_err( req ))
464 *owner = wine_server_ptr_handle( reply->old_owner );
465 ret = (reply->flags & CB_PROCESS);
468 SERVER_END_REQ;
470 return ret;
474 /**************************************************************************
475 * X11DRV_CLIPBOARD_ReleaseOwnership
477 static BOOL X11DRV_CLIPBOARD_ReleaseOwnership(void)
479 BOOL ret;
481 SERVER_START_REQ( set_clipboard_info )
483 req->flags = SET_CB_RELOWNER | SET_CB_SEQNO;
484 ret = !wine_server_call_err( req );
486 SERVER_END_REQ;
488 return ret;
493 /**************************************************************************
494 * X11DRV_CLIPBOARD_InsertClipboardData
496 * Caller *must* have the clipboard open and be the owner.
498 static BOOL X11DRV_CLIPBOARD_InsertClipboardData(UINT wFormatID, HANDLE hData,
499 LPWINE_CLIPFORMAT lpFormat, BOOL override)
501 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormatID);
503 TRACE("format=%04x lpData=%p hData=%p lpFormat=%p override=%d\n",
504 wFormatID, lpData, hData, lpFormat, override);
506 /* make sure the format exists */
507 if (!lpFormat) register_format( wFormatID, 0 );
509 if (lpData && !override)
510 return TRUE;
512 if (lpData)
514 X11DRV_CLIPBOARD_FreeData(lpData);
516 lpData->hData = hData;
518 else
520 lpData = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPDATA));
522 lpData->wFormatID = wFormatID;
523 lpData->hData = hData;
524 lpData->lpFormat = lpFormat;
525 lpData->drvData = 0;
527 list_add_tail( &data_list, &lpData->entry );
528 ClipDataCount++;
531 return TRUE;
535 /**************************************************************************
536 * X11DRV_CLIPBOARD_FreeData
538 * Free clipboard data handle.
540 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData)
542 TRACE("%04x\n", lpData->wFormatID);
544 if (!lpData->hData) return;
546 switch (lpData->wFormatID)
548 case CF_BITMAP:
549 case CF_DSPBITMAP:
550 case CF_PALETTE:
551 DeleteObject(lpData->hData);
552 break;
553 case CF_DIB:
554 if (lpData->drvData) XFreePixmap(gdi_display, lpData->drvData);
555 GlobalFree(lpData->hData);
556 break;
557 case CF_METAFILEPICT:
558 case CF_DSPMETAFILEPICT:
559 DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData ))->hMF );
560 GlobalFree(lpData->hData);
561 break;
562 case CF_ENHMETAFILE:
563 case CF_DSPENHMETAFILE:
564 DeleteEnhMetaFile(lpData->hData);
565 break;
566 default:
567 GlobalFree(lpData->hData);
568 break;
570 lpData->hData = 0;
571 lpData->drvData = 0;
575 /**************************************************************************
576 * X11DRV_CLIPBOARD_UpdateCache
578 static BOOL X11DRV_CLIPBOARD_UpdateCache(void)
580 BOOL bret = TRUE;
582 if (!selectionAcquired)
584 DWORD seqno = GetClipboardSequenceNumber();
586 if (!seqno)
588 ERR("Failed to retrieve clipboard information.\n");
589 bret = FALSE;
591 else if (wSeqNo < seqno)
593 empty_clipboard();
595 if (X11DRV_CLIPBOARD_QueryAvailableData(thread_init_display()) < 0)
597 ERR("Failed to cache clipboard data owned by another process.\n");
598 bret = FALSE;
600 wSeqNo = seqno;
604 return bret;
608 /**************************************************************************
609 * X11DRV_CLIPBOARD_RenderFormat
611 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData)
613 BOOL bret = TRUE;
615 TRACE(" 0x%04x hData(%p)\n", lpData->wFormatID, lpData->hData);
617 if (lpData->hData) return bret; /* Already rendered */
619 if (!selectionAcquired)
621 if (!X11DRV_CLIPBOARD_ReadSelectionData(display, lpData))
623 ERR("Failed to cache clipboard data owned by another process. Format=%04x\n",
624 lpData->wFormatID);
625 bret = FALSE;
628 else
630 HWND owner = GetClipboardOwner();
632 if (owner)
634 /* Send a WM_RENDERFORMAT message to notify the owner to render the
635 * data requested into the clipboard.
637 TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", owner);
638 SendMessageW(owner, WM_RENDERFORMAT, lpData->wFormatID, 0);
640 if (!lpData->hData) bret = FALSE;
642 else
644 ERR("hWndClipOwner is lost!\n");
645 bret = FALSE;
649 return bret;
653 /**************************************************************************
654 * put_property
656 * Put data as a property on the specified window.
658 static void put_property( Display *display, Window win, Atom prop, Atom type, int format,
659 const void *ptr, size_t size )
661 const unsigned char *data = ptr;
662 int mode = PropModeReplace;
663 size_t width = (format == 32) ? sizeof(long) : format / 8;
664 size_t max_size = XExtendedMaxRequestSize( display ) * 4;
666 if (!max_size) max_size = XMaxRequestSize( display ) * 4;
667 max_size -= 64; /* request overhead */
671 size_t count = min( size, max_size / width );
672 XChangeProperty( display, win, prop, type, format, mode, data, count );
673 mode = PropModeAppend;
674 size -= count;
675 data += count * width;
676 } while (size > 0);
680 /**************************************************************************
681 * convert_selection
683 static Atom convert_selection( Display *display, Window win, Atom selection, Atom target )
685 int i;
686 XEvent event;
688 XConvertSelection( display, selection, target, x11drv_atom(SELECTION_DATA), win, CurrentTime );
690 for (i = 0; i < SELECTION_RETRIES; i++)
692 Bool res = XCheckTypedWindowEvent( display, win, SelectionNotify, &event );
693 if (res && event.xselection.selection == selection && event.xselection.target == target)
694 return event.xselection.property;
695 usleep( SELECTION_WAIT );
697 ERR( "Timed out waiting for SelectionNotify event\n" );
698 return None;
702 /***********************************************************************
703 * bitmap_info_size
705 * Return the size of the bitmap info structure including color table.
707 static int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
709 unsigned int colors, size, masks = 0;
711 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
713 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
714 colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
715 return sizeof(BITMAPCOREHEADER) + colors *
716 ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
718 else /* assume BITMAPINFOHEADER */
720 colors = info->bmiHeader.biClrUsed;
721 if (!colors && (info->bmiHeader.biBitCount <= 8))
722 colors = 1 << info->bmiHeader.biBitCount;
723 if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
724 size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
725 return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
730 /***********************************************************************
731 * create_dib_from_bitmap
733 * Allocates a packed DIB and copies the bitmap data into it.
735 static HGLOBAL create_dib_from_bitmap(HBITMAP hBmp)
737 BITMAP bmp;
738 HDC hdc;
739 HGLOBAL hPackedDIB;
740 LPBYTE pPackedDIB;
741 LPBITMAPINFOHEADER pbmiHeader;
742 unsigned int cDataSize, cPackedSize, OffsetBits;
743 int nLinesCopied;
745 if (!GetObjectW( hBmp, sizeof(bmp), &bmp )) return 0;
748 * A packed DIB contains a BITMAPINFO structure followed immediately by
749 * an optional color palette and the pixel data.
752 /* Calculate the size of the packed DIB */
753 cDataSize = abs( bmp.bmHeight ) * (((bmp.bmWidth * bmp.bmBitsPixel + 31) / 8) & ~3);
754 cPackedSize = sizeof(BITMAPINFOHEADER)
755 + ( (bmp.bmBitsPixel <= 8) ? (sizeof(RGBQUAD) * (1 << bmp.bmBitsPixel)) : 0 )
756 + cDataSize;
757 /* Get the offset to the bits */
758 OffsetBits = cPackedSize - cDataSize;
760 /* Allocate the packed DIB */
761 TRACE("\tAllocating packed DIB of size %d\n", cPackedSize);
762 hPackedDIB = GlobalAlloc( GMEM_FIXED, cPackedSize );
763 if ( !hPackedDIB )
765 WARN("Could not allocate packed DIB!\n");
766 return 0;
769 /* A packed DIB starts with a BITMAPINFOHEADER */
770 pPackedDIB = GlobalLock(hPackedDIB);
771 pbmiHeader = (LPBITMAPINFOHEADER)pPackedDIB;
773 /* Init the BITMAPINFOHEADER */
774 pbmiHeader->biSize = sizeof(BITMAPINFOHEADER);
775 pbmiHeader->biWidth = bmp.bmWidth;
776 pbmiHeader->biHeight = bmp.bmHeight;
777 pbmiHeader->biPlanes = 1;
778 pbmiHeader->biBitCount = bmp.bmBitsPixel;
779 pbmiHeader->biCompression = BI_RGB;
780 pbmiHeader->biSizeImage = 0;
781 pbmiHeader->biXPelsPerMeter = pbmiHeader->biYPelsPerMeter = 0;
782 pbmiHeader->biClrUsed = 0;
783 pbmiHeader->biClrImportant = 0;
785 /* Retrieve the DIB bits from the bitmap and fill in the
786 * DIB color table if present */
787 hdc = GetDC( 0 );
788 nLinesCopied = GetDIBits(hdc, /* Handle to device context */
789 hBmp, /* Handle to bitmap */
790 0, /* First scan line to set in dest bitmap */
791 bmp.bmHeight, /* Number of scan lines to copy */
792 pPackedDIB + OffsetBits, /* [out] Address of array for bitmap bits */
793 (LPBITMAPINFO) pbmiHeader, /* [out] Address of BITMAPINFO structure */
794 0); /* RGB or palette index */
795 GlobalUnlock(hPackedDIB);
796 ReleaseDC( 0, hdc );
798 /* Cleanup if GetDIBits failed */
799 if (nLinesCopied != bmp.bmHeight)
801 TRACE("\tGetDIBits returned %d. Actual lines=%d\n", nLinesCopied, bmp.bmHeight);
802 GlobalFree(hPackedDIB);
803 hPackedDIB = 0;
805 return hPackedDIB;
809 /***********************************************************************
810 * uri_to_dos
812 * Converts a text/uri-list URI to DOS filename.
814 static WCHAR* uri_to_dos(char *encodedURI)
816 WCHAR *ret = NULL;
817 int i;
818 int j = 0;
819 char *uri = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, strlen(encodedURI) + 1);
820 if (uri == NULL)
821 return NULL;
822 for (i = 0; encodedURI[i]; ++i)
824 if (encodedURI[i] == '%')
826 if (encodedURI[i+1] && encodedURI[i+2])
828 char buffer[3];
829 int number;
830 buffer[0] = encodedURI[i+1];
831 buffer[1] = encodedURI[i+2];
832 buffer[2] = '\0';
833 sscanf(buffer, "%x", &number);
834 uri[j++] = number;
835 i += 2;
837 else
839 WARN("invalid URI encoding in %s\n", debugstr_a(encodedURI));
840 HeapFree(GetProcessHeap(), 0, uri);
841 return NULL;
844 else
845 uri[j++] = encodedURI[i];
848 /* Read http://www.freedesktop.org/wiki/Draganddropwarts and cry... */
849 if (strncmp(uri, "file:/", 6) == 0)
851 if (uri[6] == '/')
853 if (uri[7] == '/')
855 /* file:///path/to/file (nautilus, thunar) */
856 ret = wine_get_dos_file_name(&uri[7]);
858 else if (uri[7])
860 /* file://hostname/path/to/file (X file drag spec) */
861 char hostname[256];
862 char *path = strchr(&uri[7], '/');
863 if (path)
865 *path = '\0';
866 if (strcmp(&uri[7], "localhost") == 0)
868 *path = '/';
869 ret = wine_get_dos_file_name(path);
871 else if (gethostname(hostname, sizeof(hostname)) == 0)
873 if (strcmp(hostname, &uri[7]) == 0)
875 *path = '/';
876 ret = wine_get_dos_file_name(path);
882 else if (uri[6])
884 /* file:/path/to/file (konqueror) */
885 ret = wine_get_dos_file_name(&uri[5]);
888 HeapFree(GetProcessHeap(), 0, uri);
889 return ret;
893 /**************************************************************************
894 * import_string
896 * Import XA_STRING, converting the string to CF_TEXT.
898 static HANDLE import_string( Atom type, const void *data, size_t size )
900 const char *lpdata = data;
901 LPSTR lpstr;
902 size_t i, inlcount = 0;
904 for (i = 0; i < size; i++)
906 if (lpdata[i] == '\n')
907 inlcount++;
910 if ((lpstr = GlobalAlloc( GMEM_FIXED, size + inlcount + 1 )))
912 for (i = 0, inlcount = 0; i < size; i++)
914 if (lpdata[i] == '\n')
915 lpstr[inlcount++] = '\r';
917 lpstr[inlcount++] = lpdata[i];
919 lpstr[inlcount] = 0;
921 return lpstr;
925 /**************************************************************************
926 * import_utf8_string
928 * Import XA_UTF8_STRING, converting the string to CF_UNICODE.
930 static HANDLE import_utf8_string( Atom type, const void *data, size_t size )
932 const char *lpdata = data;
933 LPSTR lpstr;
934 size_t i, inlcount = 0;
935 WCHAR *textW = NULL;
937 for (i = 0; i < size; i++)
939 if (lpdata[i] == '\n')
940 inlcount++;
943 if ((lpstr = HeapAlloc( GetProcessHeap(), 0, size + inlcount + 1 )))
945 UINT count;
947 for (i = 0, inlcount = 0; i < size; i++)
949 if (lpdata[i] == '\n')
950 lpstr[inlcount++] = '\r';
952 lpstr[inlcount++] = lpdata[i];
954 lpstr[inlcount] = 0;
956 count = MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, NULL, 0);
957 textW = GlobalAlloc( GMEM_FIXED, count * sizeof(WCHAR) );
958 if (textW) MultiByteToWideChar( CP_UTF8, 0, lpstr, -1, textW, count );
959 HeapFree(GetProcessHeap(), 0, lpstr);
961 return textW;
965 /**************************************************************************
966 * import_compound_text
968 * Import COMPOUND_TEXT to CF_UNICODE
970 static HANDLE import_compound_text( Atom type, const void *data, size_t size )
972 int i, j;
973 char** srcstr;
974 int count, lcount;
975 int srclen, destlen;
976 WCHAR *deststr;
977 XTextProperty txtprop;
979 txtprop.value = (BYTE *)data;
980 txtprop.nitems = size;
981 txtprop.encoding = x11drv_atom(COMPOUND_TEXT);
982 txtprop.format = 8;
983 if (XmbTextPropertyToTextList( thread_display(), &txtprop, &srcstr, &count ) != Success) return 0;
984 if (!count) return 0;
986 TRACE("Importing %d line(s)\n", count);
988 /* Compute number of lines */
989 srclen = strlen(srcstr[0]);
990 for (i = 0, lcount = 0; i <= srclen; i++)
992 if (srcstr[0][i] == '\n')
993 lcount++;
996 destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
998 TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
1000 if ((deststr = GlobalAlloc( GMEM_FIXED, (destlen + lcount + 1) * sizeof(WCHAR) )))
1002 MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1004 if (lcount)
1006 for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1008 deststr[j] = deststr[i];
1010 if (deststr[i] == '\n')
1011 deststr[--j] = '\r';
1016 XFreeStringList(srcstr);
1018 return deststr;
1022 /**************************************************************************
1023 * import_pixmap
1025 * Import XA_PIXMAP, converting the image to CF_DIB.
1027 static HANDLE import_pixmap( Atom type, const void *data, size_t size )
1029 const Pixmap *pPixmap = (const Pixmap *)data;
1030 BYTE *ptr = NULL;
1031 XVisualInfo vis = default_visual;
1032 char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
1033 BITMAPINFO *info = (BITMAPINFO *)buffer;
1034 struct gdi_image_bits bits;
1035 Window root;
1036 int x,y; /* Unused */
1037 unsigned border_width; /* Unused */
1038 unsigned int depth, width, height;
1040 /* Get the Pixmap dimensions and bit depth */
1041 if (!XGetGeometry(gdi_display, *pPixmap, &root, &x, &y, &width, &height,
1042 &border_width, &depth)) depth = 0;
1043 if (!pixmap_formats[depth]) return 0;
1045 TRACE( "pixmap properties: width=%d, height=%d, depth=%d\n", width, height, depth );
1047 if (depth != vis.depth) switch (pixmap_formats[depth]->bits_per_pixel)
1049 case 1:
1050 case 4:
1051 case 8:
1052 break;
1053 case 16: /* assume R5G5B5 */
1054 vis.red_mask = 0x7c00;
1055 vis.green_mask = 0x03e0;
1056 vis.blue_mask = 0x001f;
1057 break;
1058 case 24: /* assume R8G8B8 */
1059 case 32: /* assume A8R8G8B8 */
1060 vis.red_mask = 0xff0000;
1061 vis.green_mask = 0x00ff00;
1062 vis.blue_mask = 0x0000ff;
1063 break;
1064 default:
1065 return 0;
1068 if (!get_pixmap_image( *pPixmap, width, height, &vis, info, &bits ))
1070 DWORD info_size = bitmap_info_size( info, DIB_RGB_COLORS );
1072 ptr = GlobalAlloc( GMEM_FIXED, info_size + info->bmiHeader.biSizeImage );
1073 if (ptr)
1075 memcpy( ptr, info, info_size );
1076 memcpy( ptr + info_size, bits.ptr, info->bmiHeader.biSizeImage );
1078 if (bits.free) bits.free( &bits );
1080 return ptr;
1084 /**************************************************************************
1085 * import_image_bmp
1087 * Import image/bmp, converting the image to CF_DIB.
1089 static HANDLE import_image_bmp( Atom type, const void *data, size_t size )
1091 HANDLE hClipData = 0;
1092 const BITMAPFILEHEADER *bfh = data;
1094 if (size >= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPCOREHEADER) &&
1095 bfh->bfType == 0x4d42 /* "BM" */)
1097 const BITMAPINFO *bmi = (const BITMAPINFO *)(bfh + 1);
1098 HBITMAP hbmp;
1099 HDC hdc = GetDC(0);
1101 if ((hbmp = CreateDIBitmap( hdc, &bmi->bmiHeader, CBM_INIT,
1102 (const BYTE *)data + bfh->bfOffBits, bmi, DIB_RGB_COLORS )))
1104 hClipData = create_dib_from_bitmap( hbmp );
1105 DeleteObject(hbmp);
1107 ReleaseDC(0, hdc);
1109 return hClipData;
1113 /**************************************************************************
1114 * import_metafile
1116 static HANDLE import_metafile( Atom type, const void *data, size_t size )
1118 METAFILEPICT *mf;
1120 if (size < sizeof(METAFILEPICT)) return 0;
1121 if ((mf = GlobalAlloc( GMEM_FIXED, sizeof(METAFILEPICT) )))
1123 memcpy( mf, data, sizeof(METAFILEPICT) );
1124 mf->hMF = SetMetaFileBitsEx( size - sizeof(METAFILEPICT),
1125 (const BYTE *)data + sizeof(METAFILEPICT) );
1127 return mf;
1131 /**************************************************************************
1132 * import_enhmetafile
1134 static HANDLE import_enhmetafile( Atom type, const void *data, size_t size )
1136 return SetEnhMetaFileBits( size, data );
1140 /**************************************************************************
1141 * import_text_uri_list
1143 * Import text/uri-list.
1145 static HANDLE import_text_uri_list( Atom type, const void *data, size_t size )
1147 const char *uriList = data;
1148 char *uri;
1149 WCHAR *path;
1150 WCHAR *out = NULL;
1151 int total = 0;
1152 int capacity = 4096;
1153 int start = 0;
1154 int end = 0;
1155 DROPFILES *dropFiles = NULL;
1157 if (!(out = HeapAlloc(GetProcessHeap(), 0, capacity * sizeof(WCHAR)))) return 0;
1159 while (end < size)
1161 while (end < size && uriList[end] != '\r')
1162 ++end;
1163 if (end < (size - 1) && uriList[end+1] != '\n')
1165 WARN("URI list line doesn't end in \\r\\n\n");
1166 break;
1169 uri = HeapAlloc(GetProcessHeap(), 0, end - start + 1);
1170 if (uri == NULL)
1171 break;
1172 lstrcpynA(uri, &uriList[start], end - start + 1);
1173 path = uri_to_dos(uri);
1174 TRACE("converted URI %s to DOS path %s\n", debugstr_a(uri), debugstr_w(path));
1175 HeapFree(GetProcessHeap(), 0, uri);
1177 if (path)
1179 int pathSize = strlenW(path) + 1;
1180 if (pathSize > capacity - total)
1182 capacity = 2*capacity + pathSize;
1183 out = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, out, (capacity + 1)*sizeof(WCHAR));
1184 if (out == NULL)
1185 goto done;
1187 memcpy(&out[total], path, pathSize * sizeof(WCHAR));
1188 total += pathSize;
1189 done:
1190 HeapFree(GetProcessHeap(), 0, path);
1191 if (out == NULL)
1192 break;
1195 start = end + 2;
1196 end = start;
1198 if (out && end >= size)
1200 if ((dropFiles = GlobalAlloc( GMEM_FIXED, sizeof(DROPFILES) + (total + 1) * sizeof(WCHAR) )))
1202 dropFiles->pFiles = sizeof(DROPFILES);
1203 dropFiles->pt.x = 0;
1204 dropFiles->pt.y = 0;
1205 dropFiles->fNC = 0;
1206 dropFiles->fWide = TRUE;
1207 out[total] = '\0';
1208 memcpy( (char*)dropFiles + dropFiles->pFiles, out, (total + 1) * sizeof(WCHAR) );
1211 HeapFree(GetProcessHeap(), 0, out);
1212 return dropFiles;
1216 /**************************************************************************
1217 * import_data
1219 * Generic import clipboard data routine.
1221 static HANDLE import_data( Atom type, const void *data, size_t size )
1223 void *ret = GlobalAlloc( GMEM_FIXED, size );
1225 if (ret) memcpy( ret, data, size );
1226 return ret;
1230 /**************************************************************************
1231 * import_selection
1233 * Import the specified format from the selection and return a global handle to the data.
1235 static HANDLE import_selection( Display *display, Window win, Atom selection,
1236 struct clipboard_format *format )
1238 unsigned char *data;
1239 unsigned long size;
1240 Atom prop, type;
1241 HANDLE ret;
1243 if (!format->import) return 0;
1245 TRACE( "import %s from %s win %lx to format %s\n",
1246 debugstr_xatom( format->atom ), debugstr_xatom( selection ),
1247 win, debugstr_format( format->id ) );
1249 if ((prop = convert_selection( display, win, selection, format->atom )) == None)
1251 TRACE( "failed to convert selection\n" );
1252 return 0;
1254 if (!X11DRV_CLIPBOARD_ReadProperty( display, win, prop, &type, &data, &size ))
1256 TRACE( "failed to read property\n" );
1257 return 0;
1259 ret = format->import( type, data, size );
1260 HeapFree( GetProcessHeap(), 0, data );
1261 return ret;
1265 /**************************************************************************
1266 * X11DRV_CLIPBOARD_ImportSelection
1268 * Import the X selection into the clipboard format registered for the given X target.
1270 void X11DRV_CLIPBOARD_ImportSelection( Display *display, Window win, Atom selection,
1271 Atom *targets, UINT count,
1272 void (*callback)( Atom, UINT, HANDLE ))
1274 UINT i;
1275 HANDLE handle;
1276 struct clipboard_format *format;
1278 for (i = 0; i < count; i++)
1280 if (!(format = X11DRV_CLIPBOARD_LookupProperty( NULL, targets[i] ))) continue;
1281 if (!format->id) continue;
1282 if (!(handle = import_selection( display, win, selection, format ))) continue;
1283 callback( targets[i], format->id, handle );
1288 /**************************************************************************
1289 * export_data
1291 * Generic export clipboard data routine.
1293 static BOOL export_data( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1295 void *ptr = GlobalLock( handle );
1297 if (!ptr) return FALSE;
1298 put_property( display, win, prop, target, 8, ptr, GlobalSize( handle ));
1299 GlobalUnlock( handle );
1300 return TRUE;
1304 /**************************************************************************
1305 * export_string
1307 * Export CF_TEXT converting the string to XA_STRING.
1309 static BOOL export_string( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1311 UINT i, j;
1312 UINT size;
1313 LPSTR text, lpstr = NULL;
1315 text = GlobalLock( handle );
1316 size = strlen(text);
1318 /* remove carriage returns */
1319 lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1320 if (lpstr == NULL)
1322 GlobalUnlock( handle );
1323 return FALSE;
1325 for (i = 0,j = 0; i < size && text[i]; i++)
1327 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1328 continue;
1329 lpstr[j++] = text[i];
1331 put_property( display, win, prop, target, 8, lpstr, j );
1332 HeapFree( GetProcessHeap(), 0, lpstr );
1333 GlobalUnlock( handle );
1334 return TRUE;
1338 /**************************************************************************
1339 * export_utf8_string
1341 * Export CF_UNICODE converting the string to UTF8.
1343 static BOOL export_utf8_string( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1345 UINT i, j;
1346 UINT size;
1347 LPSTR text, lpstr;
1348 LPWSTR uni_text = GlobalLock( handle );
1350 size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1351 text = HeapAlloc(GetProcessHeap(), 0, size);
1352 if (!text)
1354 GlobalUnlock( handle );
1355 return FALSE;
1358 WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1359 GlobalUnlock( handle );
1361 /* remove carriage returns */
1362 lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1363 if (lpstr == NULL)
1365 HeapFree(GetProcessHeap(), 0, text);
1366 return FALSE;
1368 for (i = 0,j = 0; i < size && text[i]; i++)
1370 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1371 continue;
1372 lpstr[j++] = text[i];
1374 put_property( display, win, prop, target, 8, lpstr, j );
1375 HeapFree(GetProcessHeap(), 0, lpstr);
1376 HeapFree(GetProcessHeap(), 0, text);
1377 GlobalUnlock( handle );
1378 return TRUE;
1382 /**************************************************************************
1383 * export_compound_text
1385 * Export CF_UNICODE to COMPOUND_TEXT
1387 static BOOL export_compound_text( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1389 char* lpstr;
1390 XTextProperty textprop;
1391 XICCEncodingStyle style;
1392 UINT i, j;
1393 UINT size;
1394 LPWSTR uni_text = GlobalLock( handle );
1396 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1397 lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1398 if (!lpstr)
1400 GlobalUnlock( handle );
1401 return FALSE;
1404 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1406 /* remove carriage returns */
1407 for (i = 0, j = 0; i < size && lpstr[i]; i++)
1409 if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1410 continue;
1411 lpstr[j++] = lpstr[i];
1413 lpstr[j]='\0';
1415 GlobalUnlock( handle );
1417 if (target == x11drv_atom(COMPOUND_TEXT))
1418 style = XCompoundTextStyle;
1419 else
1420 style = XStdICCTextStyle;
1422 /* Update the X property */
1423 if (XmbTextListToTextProperty( display, &lpstr, 1, style, &textprop ) == Success)
1425 XSetTextProperty( display, win, &textprop, prop );
1426 XFree( textprop.value );
1429 HeapFree(GetProcessHeap(), 0, lpstr);
1430 return TRUE;
1434 /**************************************************************************
1435 * export_pixmap
1437 * Export CF_DIB to XA_PIXMAP.
1439 static BOOL export_pixmap( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1441 Pixmap pixmap;
1442 BITMAPINFO *pbmi;
1443 struct gdi_image_bits bits;
1445 pbmi = GlobalLock( handle );
1446 bits.ptr = (LPBYTE)pbmi + bitmap_info_size( pbmi, DIB_RGB_COLORS );
1447 bits.free = NULL;
1448 bits.is_copy = FALSE;
1449 pixmap = create_pixmap_from_image( 0, &default_visual, pbmi, &bits, DIB_RGB_COLORS );
1450 GlobalUnlock( handle );
1452 put_property( display, win, prop, target, 32, &pixmap, 1 );
1453 /* FIXME: free the pixmap when the property is deleted */
1454 return TRUE;
1458 /**************************************************************************
1459 * export_image_bmp
1461 * Export CF_DIB to image/bmp.
1463 static BOOL export_image_bmp( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1465 LPBYTE dibdata = GlobalLock( handle );
1466 UINT bmpsize;
1467 BITMAPFILEHEADER *bfh;
1469 bmpsize = sizeof(BITMAPFILEHEADER) + GlobalSize( handle );
1470 bfh = HeapAlloc( GetProcessHeap(), 0, bmpsize );
1471 if (bfh)
1473 /* bitmap file header */
1474 bfh->bfType = 0x4d42; /* "BM" */
1475 bfh->bfSize = bmpsize;
1476 bfh->bfReserved1 = 0;
1477 bfh->bfReserved2 = 0;
1478 bfh->bfOffBits = sizeof(BITMAPFILEHEADER) + bitmap_info_size((BITMAPINFO*)dibdata, DIB_RGB_COLORS);
1480 /* rest of bitmap is the same as the packed dib */
1481 memcpy(bfh+1, dibdata, bmpsize-sizeof(BITMAPFILEHEADER));
1483 GlobalUnlock( handle );
1484 put_property( display, win, prop, target, 8, bfh, bmpsize );
1485 HeapFree( GetProcessHeap(), 0, bfh );
1486 return TRUE;
1490 /**************************************************************************
1491 * export_metafile
1493 * Export MetaFilePict.
1495 static BOOL export_metafile( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1497 METAFILEPICT *src, *dst;
1498 unsigned int size;
1500 src = GlobalLock( handle );
1501 size = GetMetaFileBitsEx(src->hMF, 0, NULL);
1503 dst = HeapAlloc( GetProcessHeap(), 0, size + sizeof(*dst) );
1504 if (dst)
1506 *dst = *src;
1507 GetMetaFileBitsEx( src->hMF, size, dst + 1 );
1509 GlobalUnlock( handle );
1510 put_property( display, win, prop, target, 8, dst, size + sizeof(*dst) );
1511 HeapFree( GetProcessHeap(), 0, dst );
1512 return TRUE;
1516 /**************************************************************************
1517 * export_enhmetafile
1519 * Export EnhMetaFile.
1521 static BOOL export_enhmetafile( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1523 unsigned int size;
1524 void *ptr;
1526 if (!(size = GetEnhMetaFileBits( handle, 0, NULL ))) return FALSE;
1527 if (!(ptr = HeapAlloc( GetProcessHeap(), 0, size ))) return FALSE;
1529 GetEnhMetaFileBits( handle, size, ptr );
1530 put_property( display, win, prop, target, 8, ptr, size );
1531 HeapFree( GetProcessHeap(), 0, ptr );
1532 return TRUE;
1536 /**************************************************************************
1537 * get_html_description_field
1539 * Find the value of a field in an HTML Format description.
1541 static LPCSTR get_html_description_field(LPCSTR data, LPCSTR keyword)
1543 LPCSTR pos=data;
1545 while (pos && *pos && *pos != '<')
1547 if (memcmp(pos, keyword, strlen(keyword)) == 0)
1548 return pos+strlen(keyword);
1550 pos = strchr(pos, '\n');
1551 if (pos) pos++;
1554 return NULL;
1558 /**************************************************************************
1559 * export_text_html
1561 * Export HTML Format to text/html.
1563 * FIXME: We should attempt to add an <a base> tag and convert windows paths.
1565 static BOOL export_text_html( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1567 LPCSTR data, field_value;
1568 UINT fragmentstart, fragmentend;
1570 data = GlobalLock( handle );
1572 /* read the important fields */
1573 field_value = get_html_description_field(data, "StartFragment:");
1574 if (!field_value)
1576 ERR("Couldn't find StartFragment value\n");
1577 goto failed;
1579 fragmentstart = atoi(field_value);
1581 field_value = get_html_description_field(data, "EndFragment:");
1582 if (!field_value)
1584 ERR("Couldn't find EndFragment value\n");
1585 goto failed;
1587 fragmentend = atoi(field_value);
1589 /* export only the fragment */
1590 put_property( display, win, prop, target, 8, &data[fragmentstart], fragmentend - fragmentstart );
1591 GlobalUnlock( handle );
1592 return TRUE;
1594 failed:
1595 GlobalUnlock( handle );
1596 return FALSE;
1600 /**************************************************************************
1601 * export_hdrop
1603 * Export CF_HDROP format to text/uri-list.
1605 static BOOL export_hdrop( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1607 UINT i;
1608 UINT numFiles;
1609 char *textUriList;
1610 UINT textUriListSize = 32;
1611 UINT next = 0;
1613 textUriList = HeapAlloc( GetProcessHeap(), 0, textUriListSize );
1614 if (!textUriList) return FALSE;
1615 numFiles = DragQueryFileW( handle, 0xFFFFFFFF, NULL, 0 );
1616 for (i = 0; i < numFiles; i++)
1618 UINT dosFilenameSize;
1619 WCHAR *dosFilename = NULL;
1620 char *unixFilename = NULL;
1621 UINT uriSize;
1622 UINT u;
1624 dosFilenameSize = 1 + DragQueryFileW( handle, i, NULL, 0 );
1625 dosFilename = HeapAlloc(GetProcessHeap(), 0, dosFilenameSize*sizeof(WCHAR));
1626 if (dosFilename == NULL) goto failed;
1627 DragQueryFileW( handle, i, dosFilename, dosFilenameSize );
1628 unixFilename = wine_get_unix_file_name(dosFilename);
1629 HeapFree(GetProcessHeap(), 0, dosFilename);
1630 if (unixFilename == NULL) goto failed;
1631 uriSize = 8 + /* file:/// */
1632 3 * (lstrlenA(unixFilename) - 1) + /* "%xy" per char except first '/' */
1633 2; /* \r\n */
1634 if ((next + uriSize) > textUriListSize)
1636 UINT biggerSize = max( 2 * textUriListSize, next + uriSize );
1637 void *bigger = HeapReAlloc( GetProcessHeap(), 0, textUriList, biggerSize );
1638 if (bigger)
1640 textUriList = bigger;
1641 textUriListSize = biggerSize;
1643 else
1645 HeapFree(GetProcessHeap(), 0, unixFilename);
1646 goto failed;
1649 lstrcpyA(&textUriList[next], "file:///");
1650 next += 8;
1651 /* URL encode everything - unnecessary, but easier/lighter than linking in shlwapi, and can't hurt */
1652 for (u = 1; unixFilename[u]; u++)
1654 static const char hex_table[] = "0123456789abcdef";
1655 textUriList[next++] = '%';
1656 textUriList[next++] = hex_table[unixFilename[u] >> 4];
1657 textUriList[next++] = hex_table[unixFilename[u] & 0xf];
1659 textUriList[next++] = '\r';
1660 textUriList[next++] = '\n';
1661 HeapFree(GetProcessHeap(), 0, unixFilename);
1663 put_property( display, win, prop, target, 8, textUriList, next );
1664 HeapFree( GetProcessHeap(), 0, textUriList );
1665 return TRUE;
1667 failed:
1668 HeapFree( GetProcessHeap(), 0, textUriList );
1669 return FALSE;
1673 /***********************************************************************
1674 * get_clipboard_formats
1676 * Return a list of all formats currently available on the Win32 clipboard.
1677 * Helper for export_targets.
1679 static UINT *get_clipboard_formats( UINT *size )
1681 UINT *ids;
1683 *size = 256;
1684 for (;;)
1686 if (!(ids = HeapAlloc( GetProcessHeap(), 0, *size * sizeof(*ids) ))) return NULL;
1687 if (GetUpdatedClipboardFormats( ids, *size, size )) break;
1688 HeapFree( GetProcessHeap(), 0, ids );
1689 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) return NULL;
1691 return ids;
1695 /***********************************************************************
1696 * is_format_available
1698 * Check if a clipboard format is included in the list.
1699 * Helper for export_targets.
1701 static BOOL is_format_available( UINT format, const UINT *ids, unsigned int count )
1703 while (count--) if (*ids++ == format) return TRUE;
1704 return FALSE;
1708 /***********************************************************************
1709 * export_targets
1711 * Service a TARGETS selection request event
1713 static BOOL export_targets( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1715 struct clipboard_format *format;
1716 UINT pos, count, *formats;
1717 Atom *targets;
1719 intern_atoms();
1721 if (!(formats = get_clipboard_formats( &count ))) return FALSE;
1723 /* the builtin formats contain duplicates, so allocate some extra space */
1724 if (!(targets = HeapAlloc( GetProcessHeap(), 0, (count + NB_BUILTIN_FORMATS) * sizeof(*targets) )))
1726 HeapFree( GetProcessHeap(), 0, formats );
1727 return FALSE;
1730 pos = 0;
1731 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
1733 if (!format->export) continue;
1734 /* formats with id==0 are always exported */
1735 if (format->id && !is_format_available( format->id, formats, count )) continue;
1736 TRACE( "%d: %s -> %s\n", pos, debugstr_format( format->id ), debugstr_xatom( format->atom ));
1737 targets[pos++] = format->atom;
1740 put_property( display, win, prop, XA_ATOM, 32, targets, pos );
1741 HeapFree( GetProcessHeap(), 0, targets );
1742 HeapFree( GetProcessHeap(), 0, formats );
1743 return TRUE;
1747 /**************************************************************************
1748 * export_selection
1750 * Export selection data, depending on the target type.
1752 static BOOL export_selection( Display *display, Window win, Atom prop, Atom target )
1754 struct clipboard_format *format = X11DRV_CLIPBOARD_LookupProperty( NULL, target );
1755 HANDLE handle = 0;
1756 BOOL ret = FALSE;
1758 if (!format || !format->export) return FALSE;
1760 TRACE( "win %lx prop %s target %s exporting %s\n", win,
1761 debugstr_xatom( prop ), debugstr_xatom( target ), debugstr_format( format->id ) );
1763 if (!format->id) return format->export( display, win, prop, target, 0 );
1765 if (!OpenClipboard( 0 ))
1767 ERR( "failed to open clipboard for %s\n", debugstr_format( format->id ));
1768 return FALSE;
1771 if ((handle = GetClipboardData( format->id )))
1772 ret = format->export( display, win, prop, target, handle );
1774 CloseClipboard();
1775 return ret;
1779 /***********************************************************************
1780 * export_multiple
1782 * Service a MULTIPLE selection request event
1783 * prop contains a list of (target,property) atom pairs.
1784 * The first atom names a target and the second names a property.
1785 * The effect is as if we have received a sequence of SelectionRequest events
1786 * (one for each atom pair) except that:
1787 * 1. We reply with a SelectionNotify only when all the requested conversions
1788 * have been performed.
1789 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
1790 * we replace the atom in the property by None.
1792 static BOOL export_multiple( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1794 Atom atype;
1795 int aformat;
1796 Atom *list;
1797 unsigned long i, count, failed, remain;
1799 /* Read the MULTIPLE property contents. This should contain a list of
1800 * (target,property) atom pairs.
1802 if (XGetWindowProperty( display, win, prop, 0, 0x3FFF, False, AnyPropertyType, &atype, &aformat,
1803 &count, &remain, (unsigned char**)&list ))
1804 return FALSE;
1806 TRACE( "type %s format %d count %ld remain %ld\n",
1807 debugstr_xatom( atype ), aformat, count, remain );
1810 * Make sure we got what we expect.
1811 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
1812 * in a MULTIPLE selection request should be of type ATOM_PAIR.
1813 * However some X apps(such as XPaint) are not compliant with this and return
1814 * a user defined atom in atype when XGetWindowProperty is called.
1815 * The data *is* an atom pair but is not denoted as such.
1817 if (aformat == 32 /* atype == xAtomPair */ )
1819 for (i = failed = 0; i < count; i += 2)
1821 if (list[i+1] == None) continue;
1822 if (export_selection( display, win, list[i + 1], list[i] )) continue;
1823 failed++;
1824 list[i + 1] = None;
1826 if (failed) put_property( display, win, prop, atype, 32, list, count );
1828 XFree( list );
1829 return TRUE;
1833 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
1835 return (event->error_code == BadAtom);
1838 static int is_window_error( Display *display, XErrorEvent *event, void *arg )
1840 return (event->error_code == BadWindow);
1843 /**************************************************************************
1844 * import_targets
1846 * Import TARGETS and mark the corresponding clipboard formats as available.
1848 static HANDLE import_targets( Atom type, const void *data, size_t size )
1850 UINT count = size / sizeof(Atom);
1851 const Atom *properties = data;
1852 UINT i, nb_atoms = 0;
1853 Atom *atoms = NULL;
1855 if (type != XA_ATOM && type != x11drv_atom(TARGETS)) return 0;
1857 /* Cache these formats in the clipboard cache */
1858 for (i = 0; i < count; i++)
1860 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
1862 if (lpFormat)
1864 /* We found at least one Window's format that mapps to the property.
1865 * Continue looking for more.
1867 * If more than one property map to a Window's format then we use the first
1868 * one and ignore the rest.
1870 while (lpFormat)
1872 TRACE( "property %s -> format %s\n",
1873 debugstr_xatom( lpFormat->atom ), debugstr_format( lpFormat->id ));
1874 if (lpFormat->id)
1875 X11DRV_CLIPBOARD_InsertClipboardData( lpFormat->id, 0, lpFormat, FALSE );
1876 lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
1879 else if (properties[i])
1881 /* add it to the list of atoms that we don't know about yet */
1882 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
1883 (count - i) * sizeof(*atoms) );
1884 if (atoms) atoms[nb_atoms++] = properties[i];
1888 /* query all unknown atoms in one go */
1889 if (atoms)
1891 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
1892 if (names)
1894 Display *display = thread_display();
1896 X11DRV_expect_error( display, is_atom_error, NULL );
1897 if (!XGetAtomNames( display, atoms, nb_atoms, names )) nb_atoms = 0;
1898 if (X11DRV_check_error())
1900 WARN( "got some bad atoms, ignoring\n" );
1901 nb_atoms = 0;
1903 for (i = 0; i < nb_atoms; i++)
1905 WINE_CLIPFORMAT *lpFormat;
1906 LPWSTR wname;
1907 int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
1908 wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1909 MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
1911 lpFormat = register_format( RegisterClipboardFormatW(wname), atoms[i] );
1912 HeapFree(GetProcessHeap(), 0, wname);
1913 if (!lpFormat)
1915 ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
1916 continue;
1918 TRACE( "property %s -> format %s\n",
1919 debugstr_xatom( lpFormat->atom ), debugstr_format( lpFormat->id ));
1920 X11DRV_CLIPBOARD_InsertClipboardData( lpFormat->id, 0, lpFormat, FALSE );
1922 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
1923 HeapFree( GetProcessHeap(), 0, names );
1925 HeapFree( GetProcessHeap(), 0, atoms );
1927 return (HANDLE)1;
1931 /**************************************************************************
1932 * X11DRV_CLIPBOARD_QueryAvailableData
1934 * Caches the list of data formats available from the current selection.
1935 * This queries the selection owner for the TARGETS property and saves all
1936 * reported property types.
1938 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display)
1940 Window w;
1942 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
1944 ERR("Received request to cache selection but process is owner=(%08x)\n",
1945 (unsigned) selectionWindow);
1946 return -1; /* Prevent self request */
1949 w = thread_selection_wnd();
1950 if (!w)
1952 ERR("No window available to retrieve selection!\n");
1953 return -1;
1957 * Query the selection owner for the TARGETS property
1959 if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
1960 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
1962 struct clipboard_format *format = X11DRV_CLIPBOARD_LookupProperty( NULL, x11drv_atom(TARGETS) );
1964 assert( format );
1965 if (use_primary_selection && import_selection( display, w, XA_PRIMARY, format ))
1966 selectionCacheSrc = XA_PRIMARY;
1967 else if (import_selection( display, w, x11drv_atom(CLIPBOARD), format ))
1968 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1969 else
1971 HANDLE handle;
1973 format = X11DRV_CLIPBOARD_LookupProperty( NULL, XA_STRING );
1974 assert( format );
1975 /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
1976 if (use_primary_selection && (handle = import_selection( display, w, XA_PRIMARY, format )))
1978 X11DRV_CLIPBOARD_InsertClipboardData( format->id, handle, format, TRUE );
1979 selectionCacheSrc = XA_PRIMARY;
1981 else if ((handle = import_selection( display, w, x11drv_atom(CLIPBOARD), format )))
1983 X11DRV_CLIPBOARD_InsertClipboardData( format->id, handle, format, TRUE );
1984 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1986 else
1988 WARN("Failed to query selection owner for available data.\n");
1989 return -1;
1992 return 1;
1994 else return 0; /* No selection owner so report 0 targets available */
1998 /**************************************************************************
1999 * X11DRV_CLIPBOARD_ReadSelectionData
2001 * This method is invoked only when we DO NOT own the X selection
2003 * We always get the data from the selection client each time,
2004 * since we have no way of determining if the data in our cache is stale.
2006 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData)
2008 BOOL bRet = FALSE;
2009 HANDLE hData;
2011 if (!lpData->lpFormat)
2013 ERR("Requesting format %04x but no source format linked to data.\n",
2014 lpData->wFormatID);
2015 return FALSE;
2018 if (!selectionAcquired)
2020 Window w = thread_selection_wnd();
2021 if(!w)
2023 ERR("No window available to read selection data!\n");
2024 return FALSE;
2027 hData = import_selection( display, w, selectionCacheSrc, lpData->lpFormat );
2028 if (hData)
2029 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, hData, lpData->lpFormat, TRUE);
2031 else
2033 ERR("Received request to cache selection data but process is owner\n");
2036 TRACE("Returning %d\n", bRet);
2038 return bRet;
2042 /**************************************************************************
2043 * X11DRV_CLIPBOARD_GetProperty
2044 * Gets type, data and size.
2046 static BOOL X11DRV_CLIPBOARD_GetProperty(Display *display, Window w, Atom prop,
2047 Atom *atype, unsigned char** data, unsigned long* datasize)
2049 int aformat;
2050 unsigned long pos = 0, nitems, remain, count;
2051 unsigned char *val = NULL, *buffer;
2053 for (;;)
2055 if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
2056 AnyPropertyType, atype, &aformat, &nitems, &remain, &buffer))
2058 WARN("Failed to read property\n");
2059 HeapFree( GetProcessHeap(), 0, val );
2060 return FALSE;
2063 count = get_property_size( aformat, nitems );
2064 if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
2065 else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
2067 if (!*data)
2069 XFree( buffer );
2070 HeapFree( GetProcessHeap(), 0, val );
2071 return FALSE;
2073 val = *data;
2074 memcpy( (int *)val + pos, buffer, count );
2075 XFree( buffer );
2076 if (!remain)
2078 *datasize = pos * sizeof(int) + count;
2079 val[*datasize] = 0;
2080 break;
2082 pos += count / sizeof(int);
2085 TRACE( "got property %s type %s format %u len %lu from window %lx\n",
2086 debugstr_xatom( prop ), debugstr_xatom( *atype ), aformat, *datasize, w );
2088 /* Delete the property on the window now that we are done
2089 * This will send a PropertyNotify event to the selection owner. */
2090 XDeleteProperty(display, w, prop);
2091 return TRUE;
2095 struct clipboard_data_packet {
2096 struct list entry;
2097 unsigned long size;
2098 unsigned char *data;
2101 /**************************************************************************
2102 * X11DRV_CLIPBOARD_ReadProperty
2103 * Reads the contents of the X selection property.
2105 static BOOL X11DRV_CLIPBOARD_ReadProperty( Display *display, Window w, Atom prop,
2106 Atom *type, unsigned char** data, unsigned long* datasize )
2108 XEvent xe;
2110 if (prop == None)
2111 return FALSE;
2113 while (XCheckTypedWindowEvent(display, w, PropertyNotify, &xe))
2116 if (!X11DRV_CLIPBOARD_GetProperty(display, w, prop, type, data, datasize))
2117 return FALSE;
2119 if (*type == x11drv_atom(INCR))
2121 unsigned char *buf;
2122 unsigned long bufsize = 0;
2123 struct list packets;
2124 struct clipboard_data_packet *packet, *packet2;
2125 BOOL res;
2127 HeapFree(GetProcessHeap(), 0, *data);
2128 *data = NULL;
2130 list_init(&packets);
2132 for (;;)
2134 int i;
2135 unsigned char *prop_data;
2136 unsigned long prop_size;
2138 /* Wait until PropertyNotify is received */
2139 for (i = 0; i < SELECTION_RETRIES; i++)
2141 Bool res;
2143 res = XCheckTypedWindowEvent(display, w, PropertyNotify, &xe);
2144 if (res && xe.xproperty.atom == prop &&
2145 xe.xproperty.state == PropertyNewValue)
2146 break;
2147 usleep(SELECTION_WAIT);
2150 if (i >= SELECTION_RETRIES ||
2151 !X11DRV_CLIPBOARD_GetProperty(display, w, prop, type, &prop_data, &prop_size))
2153 res = FALSE;
2154 break;
2157 /* Retrieved entire data. */
2158 if (prop_size == 0)
2160 HeapFree(GetProcessHeap(), 0, prop_data);
2161 res = TRUE;
2162 break;
2165 packet = HeapAlloc(GetProcessHeap(), 0, sizeof(*packet));
2166 if (!packet)
2168 HeapFree(GetProcessHeap(), 0, prop_data);
2169 res = FALSE;
2170 break;
2173 packet->size = prop_size;
2174 packet->data = prop_data;
2175 list_add_tail(&packets, &packet->entry);
2176 bufsize += prop_size;
2179 if (res)
2181 buf = HeapAlloc(GetProcessHeap(), 0, bufsize + 1);
2182 if (buf)
2184 unsigned long bytes_copied = 0;
2185 *datasize = bufsize;
2186 LIST_FOR_EACH_ENTRY( packet, &packets, struct clipboard_data_packet, entry)
2188 memcpy(&buf[bytes_copied], packet->data, packet->size);
2189 bytes_copied += packet->size;
2191 buf[bufsize] = 0;
2192 *data = buf;
2194 else
2195 res = FALSE;
2198 LIST_FOR_EACH_ENTRY_SAFE( packet, packet2, &packets, struct clipboard_data_packet, entry)
2200 HeapFree(GetProcessHeap(), 0, packet->data);
2201 HeapFree(GetProcessHeap(), 0, packet);
2204 return res;
2207 return TRUE;
2211 /**************************************************************************
2212 * X11DRV_CLIPBOARD_ReleaseSelection
2214 * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
2216 static void X11DRV_CLIPBOARD_ReleaseSelection(Display *display, Atom selType, Window w, HWND hwnd, Time time)
2218 /* w is the window that lost the selection
2220 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
2221 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
2223 if (selectionAcquired && (w == selectionWindow))
2225 HWND owner;
2227 /* completely give up the selection */
2228 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
2230 if (X11DRV_CLIPBOARD_IsProcessOwner( &owner ))
2232 /* Since we're still the owner, this wasn't initiated by
2233 another Wine process */
2234 if (OpenClipboard(hwnd))
2236 /* Destroy private objects */
2237 SendMessageW(owner, WM_DESTROYCLIPBOARD, 0, 0);
2239 /* Give up ownership of the windows clipboard */
2240 X11DRV_CLIPBOARD_ReleaseOwnership();
2241 CloseClipboard();
2245 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2247 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2249 if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2251 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2252 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2254 else
2255 TRACE("We no longer own PRIMARY\n");
2257 else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2259 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2261 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2263 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2264 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2266 else
2267 TRACE("We no longer own CLIPBOARD\n");
2270 selectionWindow = None;
2272 empty_clipboard();
2274 /* Reset the selection flags now that we are done */
2275 selectionAcquired = S_NOSELECTION;
2280 /**************************************************************************
2281 * X11DRV Clipboard Exports
2282 **************************************************************************/
2285 static void selection_acquire(void)
2287 Window owner;
2288 Display *display;
2290 owner = thread_selection_wnd();
2291 display = thread_display();
2293 selectionAcquired = 0;
2294 selectionWindow = 0;
2296 /* Grab PRIMARY selection if not owned */
2297 if (use_primary_selection)
2298 XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2300 /* Grab CLIPBOARD selection if not owned */
2301 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2303 if (use_primary_selection && XGetSelectionOwner(display, XA_PRIMARY) == owner)
2304 selectionAcquired |= S_PRIMARY;
2306 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2307 selectionAcquired |= S_CLIPBOARD;
2309 if (selectionAcquired)
2311 selectionWindow = owner;
2312 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2316 static DWORD WINAPI selection_thread_proc(LPVOID p)
2318 HANDLE event = p;
2320 TRACE("\n");
2322 selection_acquire();
2323 SetEvent(event);
2325 while (selectionAcquired)
2327 MsgWaitForMultipleObjectsEx(0, NULL, INFINITE, QS_SENDMESSAGE, 0);
2330 return 0;
2333 /**************************************************************************
2334 * X11DRV_AcquireClipboard
2336 void X11DRV_AcquireClipboard(HWND hWndClipWindow)
2338 DWORD procid;
2339 HANDLE selectionThread;
2341 TRACE(" %p\n", hWndClipWindow);
2344 * It's important that the selection get acquired from the thread
2345 * that owns the clipboard window. The primary reason is that we know
2346 * it is running a message loop and therefore can process the
2347 * X selection events.
2349 if (hWndClipWindow &&
2350 GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, &procid))
2352 if (procid != GetCurrentProcessId())
2354 WARN("Setting clipboard owner to other process is not supported\n");
2355 hWndClipWindow = NULL;
2357 else
2359 TRACE("Thread %x is acquiring selection with thread %x's window %p\n",
2360 GetCurrentThreadId(),
2361 GetWindowThreadProcessId(hWndClipWindow, NULL), hWndClipWindow);
2363 SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0);
2364 return;
2368 if (hWndClipWindow)
2370 selection_acquire();
2372 else
2374 HANDLE event = CreateEventW(NULL, FALSE, FALSE, NULL);
2375 selectionThread = CreateThread(NULL, 0, selection_thread_proc, event, 0, NULL);
2377 if (selectionThread)
2379 WaitForSingleObject(event, INFINITE);
2380 CloseHandle(selectionThread);
2382 CloseHandle(event);
2387 static void empty_clipboard(void)
2389 WINE_CLIPDATA *data, *next;
2391 LIST_FOR_EACH_ENTRY_SAFE( data, next, &data_list, WINE_CLIPDATA, entry )
2393 list_remove( &data->entry );
2394 X11DRV_CLIPBOARD_FreeData( data );
2395 HeapFree( GetProcessHeap(), 0, data );
2396 ClipDataCount--;
2399 TRACE(" %d entries remaining in cache.\n", ClipDataCount);
2402 /**************************************************************************
2403 * X11DRV_EmptyClipboard
2405 * Empty cached clipboard data.
2407 void CDECL X11DRV_EmptyClipboard(void)
2409 X11DRV_AcquireClipboard( GetOpenClipboardWindow() );
2410 empty_clipboard();
2413 /**************************************************************************
2414 * X11DRV_SetClipboardData
2416 BOOL CDECL X11DRV_SetClipboardData(UINT wFormat, HANDLE hData, BOOL owner)
2418 if (!owner) X11DRV_CLIPBOARD_UpdateCache();
2420 return X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData, NULL, TRUE);
2424 /**************************************************************************
2425 * CountClipboardFormats
2427 INT CDECL X11DRV_CountClipboardFormats(void)
2429 X11DRV_CLIPBOARD_UpdateCache();
2431 TRACE(" count=%d\n", ClipDataCount);
2433 return ClipDataCount;
2437 /**************************************************************************
2438 * X11DRV_EnumClipboardFormats
2440 UINT CDECL X11DRV_EnumClipboardFormats(UINT wFormat)
2442 struct list *ptr = NULL;
2444 TRACE("(%04X)\n", wFormat);
2446 X11DRV_CLIPBOARD_UpdateCache();
2448 if (!wFormat)
2450 ptr = list_head( &data_list );
2452 else
2454 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
2455 if (lpData) ptr = list_next( &data_list, &lpData->entry );
2458 if (!ptr) return 0;
2459 return LIST_ENTRY( ptr, WINE_CLIPDATA, entry )->wFormatID;
2463 /**************************************************************************
2464 * X11DRV_IsClipboardFormatAvailable
2466 BOOL CDECL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
2468 BOOL bRet = FALSE;
2470 TRACE("(%04X)\n", wFormat);
2472 X11DRV_CLIPBOARD_UpdateCache();
2474 if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
2475 bRet = TRUE;
2477 TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
2479 return bRet;
2483 /**************************************************************************
2484 * GetClipboardData (USER.142)
2486 HANDLE CDECL X11DRV_GetClipboardData(UINT wFormat)
2488 LPWINE_CLIPDATA lpRender;
2490 TRACE("(%04X)\n", wFormat);
2492 X11DRV_CLIPBOARD_UpdateCache();
2494 if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
2496 if ( !lpRender->hData )
2497 X11DRV_CLIPBOARD_RenderFormat(thread_init_display(), lpRender);
2499 TRACE(" returning %p (type %04x)\n", lpRender->hData, lpRender->wFormatID);
2500 return lpRender->hData;
2503 return 0;
2507 /**************************************************************************
2508 * ResetSelectionOwner
2510 * Called when the thread owning the selection is destroyed and we need to
2511 * preserve the selection ownership. We look for another top level window
2512 * in this process and send it a message to acquire the selection.
2514 void X11DRV_ResetSelectionOwner(void)
2516 HWND hwnd;
2517 DWORD procid;
2519 TRACE("\n");
2521 if (!selectionAcquired || thread_selection_wnd() != selectionWindow)
2522 return;
2524 selectionAcquired = S_NOSELECTION;
2525 selectionWindow = 0;
2527 hwnd = GetWindow(GetDesktopWindow(), GW_CHILD);
2530 if (GetCurrentThreadId() != GetWindowThreadProcessId(hwnd, &procid))
2532 if (GetCurrentProcessId() == procid)
2534 if (SendMessageW(hwnd, WM_X11DRV_ACQUIRE_SELECTION, 0, 0))
2535 return;
2538 } while ((hwnd = GetWindow(hwnd, GW_HWNDNEXT)) != NULL);
2540 WARN("Failed to find another thread to take selection ownership. Clipboard data will be lost.\n");
2542 X11DRV_CLIPBOARD_ReleaseOwnership();
2543 empty_clipboard();
2547 /***********************************************************************
2548 * X11DRV_HandleSelectionRequest
2550 BOOL X11DRV_SelectionRequest( HWND hwnd, XEvent *xev )
2552 XSelectionRequestEvent *event = &xev->xselectionrequest;
2553 Display *display = event->display;
2554 XEvent result;
2555 Atom rprop = None;
2557 X11DRV_expect_error( display, is_window_error, NULL );
2560 * We can only handle the selection request if :
2561 * The selection is PRIMARY or CLIPBOARD, AND we can successfully open the clipboard.
2563 if (((event->selection != XA_PRIMARY) && (event->selection != x11drv_atom(CLIPBOARD))))
2564 goto done;
2566 /* If the specified property is None the requestor is an obsolete client.
2567 * We support these by using the specified target atom as the reply property.
2569 rprop = event->property;
2570 if( rprop == None )
2571 rprop = event->target;
2573 if (!export_selection( display, event->requestor, rprop, event->target ))
2574 rprop = None; /* report failure to client */
2576 done:
2577 result.xselection.type = SelectionNotify;
2578 result.xselection.display = display;
2579 result.xselection.requestor = event->requestor;
2580 result.xselection.selection = event->selection;
2581 result.xselection.property = rprop;
2582 result.xselection.target = event->target;
2583 result.xselection.time = event->time;
2584 TRACE( "sending SelectionNotify for %s to %lx\n", debugstr_xatom( rprop ), event->requestor );
2585 XSendEvent( display, event->requestor, False, NoEventMask, &result );
2586 XSync( display, False );
2587 if (X11DRV_check_error()) WARN( "requestor %lx is no longer valid\n", event->requestor );
2588 return FALSE;
2592 /***********************************************************************
2593 * X11DRV_SelectionClear
2595 BOOL X11DRV_SelectionClear( HWND hWnd, XEvent *xev )
2597 XSelectionClearEvent *event = &xev->xselectionclear;
2598 if (event->selection == XA_PRIMARY || event->selection == x11drv_atom(CLIPBOARD))
2599 X11DRV_CLIPBOARD_ReleaseSelection( event->display, event->selection,
2600 event->window, hWnd, event->time );
2601 return FALSE;