winex11: Use standard clipboard APIs to retrieve the data to export.
[wine.git] / dlls / winex11.drv / clipboard.c
blobdcb1403135da36c3f0ac33622e20f63c63fc32fa
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 );
139 static BOOL export_data( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
140 static BOOL export_string( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
141 static BOOL export_utf8_string( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
142 static BOOL export_compound_text( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
143 static BOOL export_pixmap( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
144 static BOOL export_image_bmp( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
145 static BOOL export_metafile( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
146 static BOOL export_enhmetafile( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
147 static BOOL export_text_html( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
148 static BOOL export_hdrop( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
149 static BOOL export_targets( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
150 static BOOL export_multiple( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
152 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData);
153 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display);
154 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData);
155 static BOOL X11DRV_CLIPBOARD_ReadProperty( Display *display, Window w, Atom prop,
156 Atom *type, unsigned char **data, unsigned long *datasize );
157 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData);
158 static void empty_clipboard(void);
160 /* Clipboard formats */
162 static const WCHAR RichTextFormatW[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
163 static const WCHAR GIFW[] = {'G','I','F',0};
164 static const WCHAR JFIFW[] = {'J','F','I','F',0};
165 static const WCHAR PNGW[] = {'P','N','G',0};
166 static const WCHAR HTMLFormatW[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
168 static const struct
170 const WCHAR *name;
171 UINT id;
172 UINT data;
173 IMPORTFUNC import;
174 EXPORTFUNC export;
175 } builtin_formats[] =
177 { 0, CF_TEXT, XA_STRING, import_string, export_string },
178 { 0, CF_TEXT, XATOM_text_plain, import_string, export_string },
179 { 0, CF_BITMAP, XATOM_WCF_BITMAP, import_data, NULL },
180 { 0, CF_METAFILEPICT, XATOM_WCF_METAFILEPICT, import_metafile, export_metafile },
181 { 0, CF_SYLK, XATOM_WCF_SYLK, import_data, export_data },
182 { 0, CF_DIF, XATOM_WCF_DIF, import_data, export_data },
183 { 0, CF_TIFF, XATOM_WCF_TIFF, import_data, export_data },
184 { 0, CF_OEMTEXT, XATOM_WCF_OEMTEXT, import_data, export_data },
185 { 0, CF_DIB, XA_PIXMAP, import_pixmap, export_pixmap },
186 { 0, CF_PALETTE, XATOM_WCF_PALETTE, import_data, export_data },
187 { 0, CF_PENDATA, XATOM_WCF_PENDATA, import_data, export_data },
188 { 0, CF_RIFF, XATOM_WCF_RIFF, import_data, export_data },
189 { 0, CF_WAVE, XATOM_WCF_WAVE, import_data, export_data },
190 { 0, CF_UNICODETEXT, XATOM_UTF8_STRING, import_utf8_string, export_utf8_string },
191 { 0, CF_UNICODETEXT, XATOM_COMPOUND_TEXT, import_compound_text, export_compound_text },
192 { 0, CF_ENHMETAFILE, XATOM_WCF_ENHMETAFILE, import_enhmetafile, export_enhmetafile },
193 { 0, CF_HDROP, XATOM_text_uri_list, import_text_uri_list, export_hdrop },
194 { 0, CF_LOCALE, XATOM_WCF_LOCALE, import_data, export_data },
195 { 0, CF_DIBV5, XATOM_WCF_DIBV5, import_data, export_data },
196 { 0, CF_OWNERDISPLAY, XATOM_WCF_OWNERDISPLAY, import_data, export_data },
197 { 0, CF_DSPTEXT, XATOM_WCF_DSPTEXT, import_data, export_data },
198 { 0, CF_DSPBITMAP, XATOM_WCF_DSPBITMAP, import_data, export_data },
199 { 0, CF_DSPMETAFILEPICT, XATOM_WCF_DSPMETAFILEPICT, import_data, export_data },
200 { 0, CF_DSPENHMETAFILE, XATOM_WCF_DSPENHMETAFILE, import_data, export_data },
201 { 0, CF_DIB, XATOM_image_bmp, import_image_bmp, export_image_bmp },
202 { RichTextFormatW, 0, XATOM_text_rtf, import_data, export_data },
203 { RichTextFormatW, 0, XATOM_text_richtext, import_data, export_data },
204 { GIFW, 0, XATOM_image_gif, import_data, export_data },
205 { JFIFW, 0, XATOM_image_jpeg, import_data, export_data },
206 { PNGW, 0, XATOM_image_png, import_data, export_data },
207 { HTMLFormatW, 0, XATOM_HTML_Format, import_data, export_data },
208 { HTMLFormatW, 0, XATOM_text_html, import_data, export_text_html },
209 { 0, 0, XATOM_TARGETS, NULL, export_targets },
210 { 0, 0, XATOM_MULTIPLE, NULL, export_multiple },
213 static struct list format_list = LIST_INIT( format_list );
215 #define NB_BUILTIN_FORMATS (sizeof(builtin_formats) / sizeof(builtin_formats[0]))
216 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
220 * Cached clipboard data.
222 static struct list data_list = LIST_INIT( data_list );
223 static UINT ClipDataCount = 0;
226 * Clipboard sequence number
228 static UINT wSeqNo = 0;
230 /**************************************************************************
231 * Internal Clipboard implementation methods
232 **************************************************************************/
234 static Window thread_selection_wnd(void)
236 struct x11drv_thread_data *thread_data = x11drv_init_thread_data();
237 Window w = thread_data->selection_wnd;
239 if (!w)
241 w = XCreateWindow(thread_data->display, root_window, 0, 0, 1, 1, 0, CopyFromParent,
242 InputOnly, CopyFromParent, 0, NULL);
243 if (w)
245 thread_data->selection_wnd = w;
247 XSelectInput(thread_data->display, w, PropertyChangeMask);
249 else
250 FIXME("Failed to create window. Fetching selection data will fail.\n");
253 return w;
256 static const char *debugstr_format( UINT id )
258 WCHAR buffer[256];
260 if (GetClipboardFormatNameW( id, buffer, 256 ))
261 return wine_dbg_sprintf( "%04x %s", id, debugstr_w(buffer) );
263 switch (id)
265 case 0: return "(none)";
266 #define BUILTIN(id) case id: return #id;
267 BUILTIN(CF_TEXT)
268 BUILTIN(CF_BITMAP)
269 BUILTIN(CF_METAFILEPICT)
270 BUILTIN(CF_SYLK)
271 BUILTIN(CF_DIF)
272 BUILTIN(CF_TIFF)
273 BUILTIN(CF_OEMTEXT)
274 BUILTIN(CF_DIB)
275 BUILTIN(CF_PALETTE)
276 BUILTIN(CF_PENDATA)
277 BUILTIN(CF_RIFF)
278 BUILTIN(CF_WAVE)
279 BUILTIN(CF_UNICODETEXT)
280 BUILTIN(CF_ENHMETAFILE)
281 BUILTIN(CF_HDROP)
282 BUILTIN(CF_LOCALE)
283 BUILTIN(CF_DIBV5)
284 BUILTIN(CF_OWNERDISPLAY)
285 BUILTIN(CF_DSPTEXT)
286 BUILTIN(CF_DSPBITMAP)
287 BUILTIN(CF_DSPMETAFILEPICT)
288 BUILTIN(CF_DSPENHMETAFILE)
289 #undef BUILTIN
290 default: return wine_dbg_sprintf( "%04x", id );
294 static const char *debugstr_xatom( Atom atom )
296 const char *ret;
297 char *name;
299 if (!atom) return "(None)";
300 name = XGetAtomName( thread_display(), atom );
301 ret = debugstr_a( name );
302 XFree( name );
303 return ret;
306 /**************************************************************************
307 * X11DRV_InitClipboard
309 void X11DRV_InitClipboard(void)
311 struct clipboard_format *formats;
312 UINT i;
314 if (!(formats = HeapAlloc( GetProcessHeap(), 0, NB_BUILTIN_FORMATS * sizeof(*formats)))) return;
316 for (i = 0; i < NB_BUILTIN_FORMATS; i++)
318 if (builtin_formats[i].name)
319 formats[i].id = RegisterClipboardFormatW( builtin_formats[i].name );
320 else
321 formats[i].id = builtin_formats[i].id;
323 formats[i].atom = GET_ATOM(builtin_formats[i].data);
324 formats[i].import = builtin_formats[i].import;
325 formats[i].export = builtin_formats[i].export;
326 list_add_tail( &format_list, &formats[i].entry );
331 /**************************************************************************
332 * intern_atoms
334 * Intern atoms for formats that don't have one yet.
336 static void intern_atoms(void)
338 LPWINE_CLIPFORMAT format;
339 int i, count, len;
340 char **names;
341 Atom *atoms;
342 Display *display;
343 WCHAR buffer[256];
345 count = 0;
346 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
347 if (!format->atom) count++;
348 if (!count) return;
350 display = thread_init_display();
352 names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
353 atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
355 i = 0;
356 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
357 if (!format->atom) {
358 if (GetClipboardFormatNameW( format->id, buffer, 256 ) > 0)
360 /* use defined format name */
361 len = WideCharToMultiByte(CP_UNIXCP, 0, buffer, -1, NULL, 0, NULL, NULL);
363 else
365 /* create a name in the same way as ntdll/atom.c:integral_atom_name
366 * which is normally used by GetClipboardFormatNameW
368 static const WCHAR fmt[] = {'#','%','u',0};
369 len = sprintfW(buffer, fmt, format->id) + 1;
371 names[i] = HeapAlloc(GetProcessHeap(), 0, len);
372 WideCharToMultiByte(CP_UNIXCP, 0, buffer, -1, names[i++], len, NULL, NULL);
375 XInternAtoms( display, names, count, False, atoms );
377 i = 0;
378 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
379 if (!format->atom) {
380 HeapFree(GetProcessHeap(), 0, names[i]);
381 format->atom = atoms[i++];
384 HeapFree( GetProcessHeap(), 0, names );
385 HeapFree( GetProcessHeap(), 0, atoms );
389 /**************************************************************************
390 * register_format
392 * Register a custom X clipboard format.
394 static struct clipboard_format *register_format( UINT id, Atom prop )
396 struct clipboard_format *format;
398 /* walk format chain to see if it's already registered */
399 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
400 if (format->id == id) return format;
402 if (!(format = HeapAlloc( GetProcessHeap(), 0, sizeof(*format) ))) return NULL;
403 format->id = id;
404 format->atom = prop;
405 format->import = import_data;
406 format->export = export_data;
407 list_add_tail( &format_list, &format->entry );
409 TRACE( "Registering format %s atom %ld\n", debugstr_format(id), prop );
410 return format;
414 /**************************************************************************
415 * X11DRV_CLIPBOARD_LookupProperty
417 static struct clipboard_format *X11DRV_CLIPBOARD_LookupProperty( struct clipboard_format *current, Atom prop )
419 for (;;)
421 struct list *ptr = current ? &current->entry : &format_list;
422 BOOL need_intern = FALSE;
424 while ((ptr = list_next( &format_list, ptr )))
426 struct clipboard_format *format = LIST_ENTRY( ptr, struct clipboard_format, entry );
427 if (format->atom == prop) return format;
428 if (!format->atom) need_intern = TRUE;
430 if (!need_intern) return NULL;
431 intern_atoms();
432 /* restart the search for the new atoms */
437 /**************************************************************************
438 * X11DRV_CLIPBOARD_LookupData
440 static LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
442 WINE_CLIPDATA *data;
444 LIST_FOR_EACH_ENTRY( data, &data_list, WINE_CLIPDATA, entry )
445 if (data->wFormatID == wID) return data;
447 return NULL;
451 /**************************************************************************
452 * X11DRV_CLIPBOARD_IsProcessOwner
454 static BOOL X11DRV_CLIPBOARD_IsProcessOwner( HWND *owner )
456 BOOL ret = FALSE;
458 SERVER_START_REQ( set_clipboard_info )
460 req->flags = 0;
461 if (!wine_server_call_err( req ))
463 *owner = wine_server_ptr_handle( reply->old_owner );
464 ret = (reply->flags & CB_PROCESS);
467 SERVER_END_REQ;
469 return ret;
473 /**************************************************************************
474 * X11DRV_CLIPBOARD_ReleaseOwnership
476 static BOOL X11DRV_CLIPBOARD_ReleaseOwnership(void)
478 BOOL ret;
480 SERVER_START_REQ( set_clipboard_info )
482 req->flags = SET_CB_RELOWNER | SET_CB_SEQNO;
483 ret = !wine_server_call_err( req );
485 SERVER_END_REQ;
487 return ret;
492 /**************************************************************************
493 * X11DRV_CLIPBOARD_InsertClipboardData
495 * Caller *must* have the clipboard open and be the owner.
497 static BOOL X11DRV_CLIPBOARD_InsertClipboardData(UINT wFormatID, HANDLE hData,
498 LPWINE_CLIPFORMAT lpFormat, BOOL override)
500 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormatID);
502 TRACE("format=%04x lpData=%p hData=%p lpFormat=%p override=%d\n",
503 wFormatID, lpData, hData, lpFormat, override);
505 /* make sure the format exists */
506 if (!lpFormat) register_format( wFormatID, 0 );
508 if (lpData && !override)
509 return TRUE;
511 if (lpData)
513 X11DRV_CLIPBOARD_FreeData(lpData);
515 lpData->hData = hData;
517 else
519 lpData = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPDATA));
521 lpData->wFormatID = wFormatID;
522 lpData->hData = hData;
523 lpData->lpFormat = lpFormat;
524 lpData->drvData = 0;
526 list_add_tail( &data_list, &lpData->entry );
527 ClipDataCount++;
530 return TRUE;
534 /**************************************************************************
535 * X11DRV_CLIPBOARD_FreeData
537 * Free clipboard data handle.
539 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData)
541 TRACE("%04x\n", lpData->wFormatID);
543 if (!lpData->hData) return;
545 switch (lpData->wFormatID)
547 case CF_BITMAP:
548 case CF_DSPBITMAP:
549 case CF_PALETTE:
550 DeleteObject(lpData->hData);
551 break;
552 case CF_DIB:
553 if (lpData->drvData) XFreePixmap(gdi_display, lpData->drvData);
554 GlobalFree(lpData->hData);
555 break;
556 case CF_METAFILEPICT:
557 case CF_DSPMETAFILEPICT:
558 DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData ))->hMF );
559 GlobalFree(lpData->hData);
560 break;
561 case CF_ENHMETAFILE:
562 case CF_DSPENHMETAFILE:
563 DeleteEnhMetaFile(lpData->hData);
564 break;
565 default:
566 GlobalFree(lpData->hData);
567 break;
569 lpData->hData = 0;
570 lpData->drvData = 0;
574 /**************************************************************************
575 * X11DRV_CLIPBOARD_UpdateCache
577 static BOOL X11DRV_CLIPBOARD_UpdateCache(void)
579 BOOL bret = TRUE;
581 if (!selectionAcquired)
583 DWORD seqno = GetClipboardSequenceNumber();
585 if (!seqno)
587 ERR("Failed to retrieve clipboard information.\n");
588 bret = FALSE;
590 else if (wSeqNo < seqno)
592 empty_clipboard();
594 if (X11DRV_CLIPBOARD_QueryAvailableData(thread_init_display()) < 0)
596 ERR("Failed to cache clipboard data owned by another process.\n");
597 bret = FALSE;
599 wSeqNo = seqno;
603 return bret;
607 /**************************************************************************
608 * X11DRV_CLIPBOARD_RenderFormat
610 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData)
612 BOOL bret = TRUE;
614 TRACE(" 0x%04x hData(%p)\n", lpData->wFormatID, lpData->hData);
616 if (lpData->hData) return bret; /* Already rendered */
618 if (!selectionAcquired)
620 if (!X11DRV_CLIPBOARD_ReadSelectionData(display, lpData))
622 ERR("Failed to cache clipboard data owned by another process. Format=%04x\n",
623 lpData->wFormatID);
624 bret = FALSE;
627 else
629 HWND owner = GetClipboardOwner();
631 if (owner)
633 /* Send a WM_RENDERFORMAT message to notify the owner to render the
634 * data requested into the clipboard.
636 TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", owner);
637 SendMessageW(owner, WM_RENDERFORMAT, lpData->wFormatID, 0);
639 if (!lpData->hData) bret = FALSE;
641 else
643 ERR("hWndClipOwner is lost!\n");
644 bret = FALSE;
648 return bret;
652 /**************************************************************************
653 * put_property
655 * Put data as a property on the specified window.
657 static void put_property( Display *display, Window win, Atom prop, Atom type, int format,
658 const void *ptr, size_t size )
660 const unsigned char *data = ptr;
661 int mode = PropModeReplace;
662 size_t width = (format == 32) ? sizeof(long) : format / 8;
663 size_t max_size = XExtendedMaxRequestSize( display ) * 4;
665 if (!max_size) max_size = XMaxRequestSize( display ) * 4;
666 max_size -= 64; /* request overhead */
670 size_t count = min( size, max_size / width );
671 XChangeProperty( display, win, prop, type, format, mode, data, count );
672 mode = PropModeAppend;
673 size -= count;
674 data += count * width;
675 } while (size > 0);
679 /**************************************************************************
680 * convert_selection
682 static Atom convert_selection( Display *display, Window win, Atom selection, Atom target )
684 int i;
685 XEvent event;
687 XConvertSelection( display, selection, target, x11drv_atom(SELECTION_DATA), win, CurrentTime );
689 for (i = 0; i < SELECTION_RETRIES; i++)
691 Bool res = XCheckTypedWindowEvent( display, win, SelectionNotify, &event );
692 if (res && event.xselection.selection == selection && event.xselection.target == target)
693 return event.xselection.property;
694 usleep( SELECTION_WAIT );
696 ERR( "Timed out waiting for SelectionNotify event\n" );
697 return None;
701 /***********************************************************************
702 * bitmap_info_size
704 * Return the size of the bitmap info structure including color table.
706 static int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
708 unsigned int colors, size, masks = 0;
710 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
712 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
713 colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
714 return sizeof(BITMAPCOREHEADER) + colors *
715 ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
717 else /* assume BITMAPINFOHEADER */
719 colors = info->bmiHeader.biClrUsed;
720 if (!colors && (info->bmiHeader.biBitCount <= 8))
721 colors = 1 << info->bmiHeader.biBitCount;
722 if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
723 size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
724 return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
729 /***********************************************************************
730 * create_dib_from_bitmap
732 * Allocates a packed DIB and copies the bitmap data into it.
734 static HGLOBAL create_dib_from_bitmap(HBITMAP hBmp)
736 BITMAP bmp;
737 HDC hdc;
738 HGLOBAL hPackedDIB;
739 LPBYTE pPackedDIB;
740 LPBITMAPINFOHEADER pbmiHeader;
741 unsigned int cDataSize, cPackedSize, OffsetBits;
742 int nLinesCopied;
744 if (!GetObjectW( hBmp, sizeof(bmp), &bmp )) return 0;
747 * A packed DIB contains a BITMAPINFO structure followed immediately by
748 * an optional color palette and the pixel data.
751 /* Calculate the size of the packed DIB */
752 cDataSize = abs( bmp.bmHeight ) * (((bmp.bmWidth * bmp.bmBitsPixel + 31) / 8) & ~3);
753 cPackedSize = sizeof(BITMAPINFOHEADER)
754 + ( (bmp.bmBitsPixel <= 8) ? (sizeof(RGBQUAD) * (1 << bmp.bmBitsPixel)) : 0 )
755 + cDataSize;
756 /* Get the offset to the bits */
757 OffsetBits = cPackedSize - cDataSize;
759 /* Allocate the packed DIB */
760 TRACE("\tAllocating packed DIB of size %d\n", cPackedSize);
761 hPackedDIB = GlobalAlloc( GMEM_FIXED, cPackedSize );
762 if ( !hPackedDIB )
764 WARN("Could not allocate packed DIB!\n");
765 return 0;
768 /* A packed DIB starts with a BITMAPINFOHEADER */
769 pPackedDIB = GlobalLock(hPackedDIB);
770 pbmiHeader = (LPBITMAPINFOHEADER)pPackedDIB;
772 /* Init the BITMAPINFOHEADER */
773 pbmiHeader->biSize = sizeof(BITMAPINFOHEADER);
774 pbmiHeader->biWidth = bmp.bmWidth;
775 pbmiHeader->biHeight = bmp.bmHeight;
776 pbmiHeader->biPlanes = 1;
777 pbmiHeader->biBitCount = bmp.bmBitsPixel;
778 pbmiHeader->biCompression = BI_RGB;
779 pbmiHeader->biSizeImage = 0;
780 pbmiHeader->biXPelsPerMeter = pbmiHeader->biYPelsPerMeter = 0;
781 pbmiHeader->biClrUsed = 0;
782 pbmiHeader->biClrImportant = 0;
784 /* Retrieve the DIB bits from the bitmap and fill in the
785 * DIB color table if present */
786 hdc = GetDC( 0 );
787 nLinesCopied = GetDIBits(hdc, /* Handle to device context */
788 hBmp, /* Handle to bitmap */
789 0, /* First scan line to set in dest bitmap */
790 bmp.bmHeight, /* Number of scan lines to copy */
791 pPackedDIB + OffsetBits, /* [out] Address of array for bitmap bits */
792 (LPBITMAPINFO) pbmiHeader, /* [out] Address of BITMAPINFO structure */
793 0); /* RGB or palette index */
794 GlobalUnlock(hPackedDIB);
795 ReleaseDC( 0, hdc );
797 /* Cleanup if GetDIBits failed */
798 if (nLinesCopied != bmp.bmHeight)
800 TRACE("\tGetDIBits returned %d. Actual lines=%d\n", nLinesCopied, bmp.bmHeight);
801 GlobalFree(hPackedDIB);
802 hPackedDIB = 0;
804 return hPackedDIB;
808 /***********************************************************************
809 * uri_to_dos
811 * Converts a text/uri-list URI to DOS filename.
813 static WCHAR* uri_to_dos(char *encodedURI)
815 WCHAR *ret = NULL;
816 int i;
817 int j = 0;
818 char *uri = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, strlen(encodedURI) + 1);
819 if (uri == NULL)
820 return NULL;
821 for (i = 0; encodedURI[i]; ++i)
823 if (encodedURI[i] == '%')
825 if (encodedURI[i+1] && encodedURI[i+2])
827 char buffer[3];
828 int number;
829 buffer[0] = encodedURI[i+1];
830 buffer[1] = encodedURI[i+2];
831 buffer[2] = '\0';
832 sscanf(buffer, "%x", &number);
833 uri[j++] = number;
834 i += 2;
836 else
838 WARN("invalid URI encoding in %s\n", debugstr_a(encodedURI));
839 HeapFree(GetProcessHeap(), 0, uri);
840 return NULL;
843 else
844 uri[j++] = encodedURI[i];
847 /* Read http://www.freedesktop.org/wiki/Draganddropwarts and cry... */
848 if (strncmp(uri, "file:/", 6) == 0)
850 if (uri[6] == '/')
852 if (uri[7] == '/')
854 /* file:///path/to/file (nautilus, thunar) */
855 ret = wine_get_dos_file_name(&uri[7]);
857 else if (uri[7])
859 /* file://hostname/path/to/file (X file drag spec) */
860 char hostname[256];
861 char *path = strchr(&uri[7], '/');
862 if (path)
864 *path = '\0';
865 if (strcmp(&uri[7], "localhost") == 0)
867 *path = '/';
868 ret = wine_get_dos_file_name(path);
870 else if (gethostname(hostname, sizeof(hostname)) == 0)
872 if (strcmp(hostname, &uri[7]) == 0)
874 *path = '/';
875 ret = wine_get_dos_file_name(path);
881 else if (uri[6])
883 /* file:/path/to/file (konqueror) */
884 ret = wine_get_dos_file_name(&uri[5]);
887 HeapFree(GetProcessHeap(), 0, uri);
888 return ret;
892 /**************************************************************************
893 * import_string
895 * Import XA_STRING, converting the string to CF_TEXT.
897 static HANDLE import_string( Atom type, const void *data, size_t size )
899 const char *lpdata = data;
900 LPSTR lpstr;
901 size_t i, inlcount = 0;
903 for (i = 0; i < size; i++)
905 if (lpdata[i] == '\n')
906 inlcount++;
909 if ((lpstr = GlobalAlloc( GMEM_FIXED, size + inlcount + 1 )))
911 for (i = 0, inlcount = 0; i < size; i++)
913 if (lpdata[i] == '\n')
914 lpstr[inlcount++] = '\r';
916 lpstr[inlcount++] = lpdata[i];
918 lpstr[inlcount] = 0;
920 return lpstr;
924 /**************************************************************************
925 * import_utf8_string
927 * Import XA_UTF8_STRING, converting the string to CF_UNICODE.
929 static HANDLE import_utf8_string( Atom type, const void *data, size_t size )
931 const char *lpdata = data;
932 LPSTR lpstr;
933 size_t i, inlcount = 0;
934 WCHAR *textW = NULL;
936 for (i = 0; i < size; i++)
938 if (lpdata[i] == '\n')
939 inlcount++;
942 if ((lpstr = HeapAlloc( GetProcessHeap(), 0, size + inlcount + 1 )))
944 UINT count;
946 for (i = 0, inlcount = 0; i < size; i++)
948 if (lpdata[i] == '\n')
949 lpstr[inlcount++] = '\r';
951 lpstr[inlcount++] = lpdata[i];
953 lpstr[inlcount] = 0;
955 count = MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, NULL, 0);
956 textW = GlobalAlloc( GMEM_FIXED, count * sizeof(WCHAR) );
957 if (textW) MultiByteToWideChar( CP_UTF8, 0, lpstr, -1, textW, count );
958 HeapFree(GetProcessHeap(), 0, lpstr);
960 return textW;
964 /**************************************************************************
965 * import_compound_text
967 * Import COMPOUND_TEXT to CF_UNICODE
969 static HANDLE import_compound_text( Atom type, const void *data, size_t size )
971 int i, j;
972 char** srcstr;
973 int count, lcount;
974 int srclen, destlen;
975 WCHAR *deststr;
976 XTextProperty txtprop;
978 txtprop.value = (BYTE *)data;
979 txtprop.nitems = size;
980 txtprop.encoding = x11drv_atom(COMPOUND_TEXT);
981 txtprop.format = 8;
982 if (XmbTextPropertyToTextList( thread_display(), &txtprop, &srcstr, &count ) != Success) return 0;
983 if (!count) return 0;
985 TRACE("Importing %d line(s)\n", count);
987 /* Compute number of lines */
988 srclen = strlen(srcstr[0]);
989 for (i = 0, lcount = 0; i <= srclen; i++)
991 if (srcstr[0][i] == '\n')
992 lcount++;
995 destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
997 TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
999 if ((deststr = GlobalAlloc( GMEM_FIXED, (destlen + lcount + 1) * sizeof(WCHAR) )))
1001 MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1003 if (lcount)
1005 for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1007 deststr[j] = deststr[i];
1009 if (deststr[i] == '\n')
1010 deststr[--j] = '\r';
1015 XFreeStringList(srcstr);
1017 return deststr;
1021 /**************************************************************************
1022 * import_pixmap
1024 * Import XA_PIXMAP, converting the image to CF_DIB.
1026 static HANDLE import_pixmap( Atom type, const void *data, size_t size )
1028 const Pixmap *pPixmap = (const Pixmap *)data;
1029 BYTE *ptr = NULL;
1030 XVisualInfo vis = default_visual;
1031 char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
1032 BITMAPINFO *info = (BITMAPINFO *)buffer;
1033 struct gdi_image_bits bits;
1034 Window root;
1035 int x,y; /* Unused */
1036 unsigned border_width; /* Unused */
1037 unsigned int depth, width, height;
1039 /* Get the Pixmap dimensions and bit depth */
1040 if (!XGetGeometry(gdi_display, *pPixmap, &root, &x, &y, &width, &height,
1041 &border_width, &depth)) depth = 0;
1042 if (!pixmap_formats[depth]) return 0;
1044 TRACE( "pixmap properties: width=%d, height=%d, depth=%d\n", width, height, depth );
1046 if (depth != vis.depth) switch (pixmap_formats[depth]->bits_per_pixel)
1048 case 1:
1049 case 4:
1050 case 8:
1051 break;
1052 case 16: /* assume R5G5B5 */
1053 vis.red_mask = 0x7c00;
1054 vis.green_mask = 0x03e0;
1055 vis.blue_mask = 0x001f;
1056 break;
1057 case 24: /* assume R8G8B8 */
1058 case 32: /* assume A8R8G8B8 */
1059 vis.red_mask = 0xff0000;
1060 vis.green_mask = 0x00ff00;
1061 vis.blue_mask = 0x0000ff;
1062 break;
1063 default:
1064 return 0;
1067 if (!get_pixmap_image( *pPixmap, width, height, &vis, info, &bits ))
1069 DWORD info_size = bitmap_info_size( info, DIB_RGB_COLORS );
1071 ptr = GlobalAlloc( GMEM_FIXED, info_size + info->bmiHeader.biSizeImage );
1072 if (ptr)
1074 memcpy( ptr, info, info_size );
1075 memcpy( ptr + info_size, bits.ptr, info->bmiHeader.biSizeImage );
1077 if (bits.free) bits.free( &bits );
1079 return ptr;
1083 /**************************************************************************
1084 * import_image_bmp
1086 * Import image/bmp, converting the image to CF_DIB.
1088 static HANDLE import_image_bmp( Atom type, const void *data, size_t size )
1090 HANDLE hClipData = 0;
1091 const BITMAPFILEHEADER *bfh = data;
1093 if (size >= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPCOREHEADER) &&
1094 bfh->bfType == 0x4d42 /* "BM" */)
1096 const BITMAPINFO *bmi = (const BITMAPINFO *)(bfh + 1);
1097 HBITMAP hbmp;
1098 HDC hdc = GetDC(0);
1100 if ((hbmp = CreateDIBitmap( hdc, &bmi->bmiHeader, CBM_INIT,
1101 (const BYTE *)data + bfh->bfOffBits, bmi, DIB_RGB_COLORS )))
1103 hClipData = create_dib_from_bitmap( hbmp );
1104 DeleteObject(hbmp);
1106 ReleaseDC(0, hdc);
1108 return hClipData;
1112 /**************************************************************************
1113 * import_metafile
1115 static HANDLE import_metafile( Atom type, const void *data, size_t size )
1117 METAFILEPICT *mf;
1119 if (size < sizeof(METAFILEPICT)) return 0;
1120 if ((mf = GlobalAlloc( GMEM_FIXED, sizeof(METAFILEPICT) )))
1122 memcpy( mf, data, sizeof(METAFILEPICT) );
1123 mf->hMF = SetMetaFileBitsEx( size - sizeof(METAFILEPICT),
1124 (const BYTE *)data + sizeof(METAFILEPICT) );
1126 return mf;
1130 /**************************************************************************
1131 * import_enhmetafile
1133 static HANDLE import_enhmetafile( Atom type, const void *data, size_t size )
1135 return SetEnhMetaFileBits( size, data );
1139 /**************************************************************************
1140 * import_text_uri_list
1142 * Import text/uri-list.
1144 static HANDLE import_text_uri_list( Atom type, const void *data, size_t size )
1146 const char *uriList = data;
1147 char *uri;
1148 WCHAR *path;
1149 WCHAR *out = NULL;
1150 int total = 0;
1151 int capacity = 4096;
1152 int start = 0;
1153 int end = 0;
1154 DROPFILES *dropFiles = NULL;
1156 if (!(out = HeapAlloc(GetProcessHeap(), 0, capacity * sizeof(WCHAR)))) return 0;
1158 while (end < size)
1160 while (end < size && uriList[end] != '\r')
1161 ++end;
1162 if (end < (size - 1) && uriList[end+1] != '\n')
1164 WARN("URI list line doesn't end in \\r\\n\n");
1165 break;
1168 uri = HeapAlloc(GetProcessHeap(), 0, end - start + 1);
1169 if (uri == NULL)
1170 break;
1171 lstrcpynA(uri, &uriList[start], end - start + 1);
1172 path = uri_to_dos(uri);
1173 TRACE("converted URI %s to DOS path %s\n", debugstr_a(uri), debugstr_w(path));
1174 HeapFree(GetProcessHeap(), 0, uri);
1176 if (path)
1178 int pathSize = strlenW(path) + 1;
1179 if (pathSize > capacity - total)
1181 capacity = 2*capacity + pathSize;
1182 out = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, out, (capacity + 1)*sizeof(WCHAR));
1183 if (out == NULL)
1184 goto done;
1186 memcpy(&out[total], path, pathSize * sizeof(WCHAR));
1187 total += pathSize;
1188 done:
1189 HeapFree(GetProcessHeap(), 0, path);
1190 if (out == NULL)
1191 break;
1194 start = end + 2;
1195 end = start;
1197 if (out && end >= size)
1199 if ((dropFiles = GlobalAlloc( GMEM_FIXED, sizeof(DROPFILES) + (total + 1) * sizeof(WCHAR) )))
1201 dropFiles->pFiles = sizeof(DROPFILES);
1202 dropFiles->pt.x = 0;
1203 dropFiles->pt.y = 0;
1204 dropFiles->fNC = 0;
1205 dropFiles->fWide = TRUE;
1206 out[total] = '\0';
1207 memcpy( (char*)dropFiles + dropFiles->pFiles, out, (total + 1) * sizeof(WCHAR) );
1210 HeapFree(GetProcessHeap(), 0, out);
1211 return dropFiles;
1215 /**************************************************************************
1216 * import_data
1218 * Generic import clipboard data routine.
1220 static HANDLE import_data( Atom type, const void *data, size_t size )
1222 void *ret = GlobalAlloc( GMEM_FIXED, size );
1224 if (ret) memcpy( ret, data, size );
1225 return ret;
1229 /**************************************************************************
1230 * import_selection
1232 * Import the specified format from the selection and return a global handle to the data.
1234 static HANDLE import_selection( Display *display, Window win, Atom selection,
1235 struct clipboard_format *format )
1237 unsigned char *data;
1238 unsigned long size;
1239 Atom prop, type;
1240 HANDLE ret;
1242 if (!format->import) return 0;
1244 TRACE( "import %s from %s win %lx to format %s\n",
1245 debugstr_xatom( format->atom ), debugstr_xatom( selection ),
1246 win, debugstr_format( format->id ) );
1248 if ((prop = convert_selection( display, win, selection, format->atom )) == None)
1250 TRACE( "failed to convert selection\n" );
1251 return 0;
1253 if (!X11DRV_CLIPBOARD_ReadProperty( display, win, prop, &type, &data, &size ))
1255 TRACE( "failed to read property\n" );
1256 return 0;
1258 ret = format->import( type, data, size );
1259 HeapFree( GetProcessHeap(), 0, data );
1260 return ret;
1264 /**************************************************************************
1265 * X11DRV_CLIPBOARD_ImportSelection
1267 * Import the X selection into the clipboard format registered for the given X target.
1269 HANDLE X11DRV_CLIPBOARD_ImportSelection( Display *display, Window win, Atom selection,
1270 Atom target, UINT *windowsFormat )
1272 struct clipboard_format *format = X11DRV_CLIPBOARD_LookupProperty( NULL, target );
1273 if (!format) return 0;
1274 *windowsFormat = format->id;
1275 return import_selection( display, win, selection, format );
1279 /**************************************************************************
1280 * export_data
1282 * Generic export clipboard data routine.
1284 static BOOL export_data( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1286 void *ptr = GlobalLock( handle );
1288 if (!ptr) return FALSE;
1289 put_property( display, win, prop, target, 8, ptr, GlobalSize( handle ));
1290 GlobalUnlock( handle );
1291 return TRUE;
1295 /**************************************************************************
1296 * export_string
1298 * Export CF_TEXT converting the string to XA_STRING.
1300 static BOOL export_string( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1302 UINT i, j;
1303 UINT size;
1304 LPSTR text, lpstr = NULL;
1306 text = GlobalLock( handle );
1307 size = strlen(text);
1309 /* remove carriage returns */
1310 lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1311 if (lpstr == NULL)
1313 GlobalUnlock( handle );
1314 return FALSE;
1316 for (i = 0,j = 0; i < size && text[i]; i++)
1318 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1319 continue;
1320 lpstr[j++] = text[i];
1322 put_property( display, win, prop, target, 8, lpstr, j );
1323 HeapFree( GetProcessHeap(), 0, lpstr );
1324 GlobalUnlock( handle );
1325 return TRUE;
1329 /**************************************************************************
1330 * export_utf8_string
1332 * Export CF_UNICODE converting the string to UTF8.
1334 static BOOL export_utf8_string( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1336 UINT i, j;
1337 UINT size;
1338 LPSTR text, lpstr;
1339 LPWSTR uni_text = GlobalLock( handle );
1341 size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1342 text = HeapAlloc(GetProcessHeap(), 0, size);
1343 if (!text)
1345 GlobalUnlock( handle );
1346 return FALSE;
1349 WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1350 GlobalUnlock( handle );
1352 /* remove carriage returns */
1353 lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1354 if (lpstr == NULL)
1356 HeapFree(GetProcessHeap(), 0, text);
1357 return FALSE;
1359 for (i = 0,j = 0; i < size && text[i]; i++)
1361 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1362 continue;
1363 lpstr[j++] = text[i];
1365 put_property( display, win, prop, target, 8, lpstr, j );
1366 HeapFree(GetProcessHeap(), 0, lpstr);
1367 HeapFree(GetProcessHeap(), 0, text);
1368 GlobalUnlock( handle );
1369 return TRUE;
1373 /**************************************************************************
1374 * export_compound_text
1376 * Export CF_UNICODE to COMPOUND_TEXT
1378 static BOOL export_compound_text( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1380 char* lpstr;
1381 XTextProperty textprop;
1382 XICCEncodingStyle style;
1383 UINT i, j;
1384 UINT size;
1385 LPWSTR uni_text = GlobalLock( handle );
1387 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1388 lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1389 if (!lpstr)
1391 GlobalUnlock( handle );
1392 return FALSE;
1395 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1397 /* remove carriage returns */
1398 for (i = 0, j = 0; i < size && lpstr[i]; i++)
1400 if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1401 continue;
1402 lpstr[j++] = lpstr[i];
1404 lpstr[j]='\0';
1406 GlobalUnlock( handle );
1408 if (target == x11drv_atom(COMPOUND_TEXT))
1409 style = XCompoundTextStyle;
1410 else
1411 style = XStdICCTextStyle;
1413 /* Update the X property */
1414 if (XmbTextListToTextProperty( display, &lpstr, 1, style, &textprop ) == Success)
1416 XSetTextProperty( display, win, &textprop, prop );
1417 XFree( textprop.value );
1420 HeapFree(GetProcessHeap(), 0, lpstr);
1421 return TRUE;
1425 /**************************************************************************
1426 * export_pixmap
1428 * Export CF_DIB to XA_PIXMAP.
1430 static BOOL export_pixmap( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1432 Pixmap pixmap;
1433 BITMAPINFO *pbmi;
1434 struct gdi_image_bits bits;
1436 pbmi = GlobalLock( handle );
1437 bits.ptr = (LPBYTE)pbmi + bitmap_info_size( pbmi, DIB_RGB_COLORS );
1438 bits.free = NULL;
1439 bits.is_copy = FALSE;
1440 pixmap = create_pixmap_from_image( 0, &default_visual, pbmi, &bits, DIB_RGB_COLORS );
1441 GlobalUnlock( handle );
1443 put_property( display, win, prop, target, 32, &pixmap, 1 );
1444 /* FIXME: free the pixmap when the property is deleted */
1445 return TRUE;
1449 /**************************************************************************
1450 * export_image_bmp
1452 * Export CF_DIB to image/bmp.
1454 static BOOL export_image_bmp( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1456 LPBYTE dibdata = GlobalLock( handle );
1457 UINT bmpsize;
1458 BITMAPFILEHEADER *bfh;
1460 bmpsize = sizeof(BITMAPFILEHEADER) + GlobalSize( handle );
1461 bfh = HeapAlloc( GetProcessHeap(), 0, bmpsize );
1462 if (bfh)
1464 /* bitmap file header */
1465 bfh->bfType = 0x4d42; /* "BM" */
1466 bfh->bfSize = bmpsize;
1467 bfh->bfReserved1 = 0;
1468 bfh->bfReserved2 = 0;
1469 bfh->bfOffBits = sizeof(BITMAPFILEHEADER) + bitmap_info_size((BITMAPINFO*)dibdata, DIB_RGB_COLORS);
1471 /* rest of bitmap is the same as the packed dib */
1472 memcpy(bfh+1, dibdata, bmpsize-sizeof(BITMAPFILEHEADER));
1474 GlobalUnlock( handle );
1475 put_property( display, win, prop, target, 8, bfh, bmpsize );
1476 HeapFree( GetProcessHeap(), 0, bfh );
1477 return TRUE;
1481 /**************************************************************************
1482 * export_metafile
1484 * Export MetaFilePict.
1486 static BOOL export_metafile( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1488 METAFILEPICT *src, *dst;
1489 unsigned int size;
1491 src = GlobalLock( handle );
1492 size = GetMetaFileBitsEx(src->hMF, 0, NULL);
1494 dst = HeapAlloc( GetProcessHeap(), 0, size + sizeof(*dst) );
1495 if (dst)
1497 *dst = *src;
1498 GetMetaFileBitsEx( src->hMF, size, dst + 1 );
1500 GlobalUnlock( handle );
1501 put_property( display, win, prop, target, 8, dst, size + sizeof(*dst) );
1502 HeapFree( GetProcessHeap(), 0, dst );
1503 return TRUE;
1507 /**************************************************************************
1508 * export_enhmetafile
1510 * Export EnhMetaFile.
1512 static BOOL export_enhmetafile( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1514 unsigned int size;
1515 void *ptr;
1517 if (!(size = GetEnhMetaFileBits( handle, 0, NULL ))) return FALSE;
1518 if (!(ptr = HeapAlloc( GetProcessHeap(), 0, size ))) return FALSE;
1520 GetEnhMetaFileBits( handle, size, ptr );
1521 put_property( display, win, prop, target, 8, ptr, size );
1522 HeapFree( GetProcessHeap(), 0, ptr );
1523 return TRUE;
1527 /**************************************************************************
1528 * get_html_description_field
1530 * Find the value of a field in an HTML Format description.
1532 static LPCSTR get_html_description_field(LPCSTR data, LPCSTR keyword)
1534 LPCSTR pos=data;
1536 while (pos && *pos && *pos != '<')
1538 if (memcmp(pos, keyword, strlen(keyword)) == 0)
1539 return pos+strlen(keyword);
1541 pos = strchr(pos, '\n');
1542 if (pos) pos++;
1545 return NULL;
1549 /**************************************************************************
1550 * export_text_html
1552 * Export HTML Format to text/html.
1554 * FIXME: We should attempt to add an <a base> tag and convert windows paths.
1556 static BOOL export_text_html( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1558 LPCSTR data, field_value;
1559 UINT fragmentstart, fragmentend;
1561 data = GlobalLock( handle );
1563 /* read the important fields */
1564 field_value = get_html_description_field(data, "StartFragment:");
1565 if (!field_value)
1567 ERR("Couldn't find StartFragment value\n");
1568 goto failed;
1570 fragmentstart = atoi(field_value);
1572 field_value = get_html_description_field(data, "EndFragment:");
1573 if (!field_value)
1575 ERR("Couldn't find EndFragment value\n");
1576 goto failed;
1578 fragmentend = atoi(field_value);
1580 /* export only the fragment */
1581 put_property( display, win, prop, target, 8, &data[fragmentstart], fragmentend - fragmentstart );
1582 GlobalUnlock( handle );
1583 return TRUE;
1585 failed:
1586 GlobalUnlock( handle );
1587 return FALSE;
1591 /**************************************************************************
1592 * export_hdrop
1594 * Export CF_HDROP format to text/uri-list.
1596 static BOOL export_hdrop( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1598 UINT i;
1599 UINT numFiles;
1600 char *textUriList;
1601 UINT textUriListSize = 32;
1602 UINT next = 0;
1604 textUriList = HeapAlloc( GetProcessHeap(), 0, textUriListSize );
1605 if (!textUriList) return FALSE;
1606 numFiles = DragQueryFileW( handle, 0xFFFFFFFF, NULL, 0 );
1607 for (i = 0; i < numFiles; i++)
1609 UINT dosFilenameSize;
1610 WCHAR *dosFilename = NULL;
1611 char *unixFilename = NULL;
1612 UINT uriSize;
1613 UINT u;
1615 dosFilenameSize = 1 + DragQueryFileW( handle, i, NULL, 0 );
1616 dosFilename = HeapAlloc(GetProcessHeap(), 0, dosFilenameSize*sizeof(WCHAR));
1617 if (dosFilename == NULL) goto failed;
1618 DragQueryFileW( handle, i, dosFilename, dosFilenameSize );
1619 unixFilename = wine_get_unix_file_name(dosFilename);
1620 HeapFree(GetProcessHeap(), 0, dosFilename);
1621 if (unixFilename == NULL) goto failed;
1622 uriSize = 8 + /* file:/// */
1623 3 * (lstrlenA(unixFilename) - 1) + /* "%xy" per char except first '/' */
1624 2; /* \r\n */
1625 if ((next + uriSize) > textUriListSize)
1627 UINT biggerSize = max( 2 * textUriListSize, next + uriSize );
1628 void *bigger = HeapReAlloc( GetProcessHeap(), 0, textUriList, biggerSize );
1629 if (bigger)
1631 textUriList = bigger;
1632 textUriListSize = biggerSize;
1634 else
1636 HeapFree(GetProcessHeap(), 0, unixFilename);
1637 goto failed;
1640 lstrcpyA(&textUriList[next], "file:///");
1641 next += 8;
1642 /* URL encode everything - unnecessary, but easier/lighter than linking in shlwapi, and can't hurt */
1643 for (u = 1; unixFilename[u]; u++)
1645 static const char hex_table[] = "0123456789abcdef";
1646 textUriList[next++] = '%';
1647 textUriList[next++] = hex_table[unixFilename[u] >> 4];
1648 textUriList[next++] = hex_table[unixFilename[u] & 0xf];
1650 textUriList[next++] = '\r';
1651 textUriList[next++] = '\n';
1652 HeapFree(GetProcessHeap(), 0, unixFilename);
1654 put_property( display, win, prop, target, 8, textUriList, next );
1655 HeapFree( GetProcessHeap(), 0, textUriList );
1656 return TRUE;
1658 failed:
1659 HeapFree( GetProcessHeap(), 0, textUriList );
1660 return FALSE;
1664 /***********************************************************************
1665 * get_clipboard_formats
1667 * Return a list of all formats currently available on the Win32 clipboard.
1668 * Helper for export_targets.
1670 static UINT *get_clipboard_formats( UINT *size )
1672 UINT *ids;
1674 *size = 256;
1675 for (;;)
1677 if (!(ids = HeapAlloc( GetProcessHeap(), 0, *size * sizeof(*ids) ))) return NULL;
1678 if (GetUpdatedClipboardFormats( ids, *size, size )) break;
1679 HeapFree( GetProcessHeap(), 0, ids );
1680 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) return NULL;
1682 return ids;
1686 /***********************************************************************
1687 * is_format_available
1689 * Check if a clipboard format is included in the list.
1690 * Helper for export_targets.
1692 static BOOL is_format_available( UINT format, const UINT *ids, unsigned int count )
1694 while (count--) if (*ids++ == format) return TRUE;
1695 return FALSE;
1699 /***********************************************************************
1700 * export_targets
1702 * Service a TARGETS selection request event
1704 static BOOL export_targets( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1706 struct clipboard_format *format;
1707 UINT pos, count, *formats;
1708 Atom *targets;
1710 intern_atoms();
1712 if (!(formats = get_clipboard_formats( &count ))) return FALSE;
1714 /* the builtin formats contain duplicates, so allocate some extra space */
1715 if (!(targets = HeapAlloc( GetProcessHeap(), 0, (count + NB_BUILTIN_FORMATS) * sizeof(*targets) )))
1717 HeapFree( GetProcessHeap(), 0, formats );
1718 return FALSE;
1721 pos = 0;
1722 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
1724 if (!format->export) continue;
1725 /* formats with id==0 are always exported */
1726 if (format->id && !is_format_available( format->id, formats, count )) continue;
1727 TRACE( "%d: %s -> %s\n", pos, debugstr_format( format->id ), debugstr_xatom( format->atom ));
1728 targets[pos++] = format->atom;
1731 put_property( display, win, prop, XA_ATOM, 32, targets, pos );
1732 HeapFree( GetProcessHeap(), 0, targets );
1733 HeapFree( GetProcessHeap(), 0, formats );
1734 return TRUE;
1738 /**************************************************************************
1739 * export_selection
1741 * Export selection data, depending on the target type.
1743 static BOOL export_selection( Display *display, Window win, Atom prop, Atom target )
1745 struct clipboard_format *format = X11DRV_CLIPBOARD_LookupProperty( NULL, target );
1746 HANDLE handle = 0;
1747 BOOL ret = FALSE;
1749 if (!format || !format->export) return FALSE;
1751 TRACE( "win %lx prop %s target %s exporting %s\n", win,
1752 debugstr_xatom( prop ), debugstr_xatom( target ), debugstr_format( format->id ) );
1754 if (!format->id) return format->export( display, win, prop, target, 0 );
1756 if (!OpenClipboard( 0 ))
1758 ERR( "failed to open clipboard for %s\n", debugstr_format( format->id ));
1759 return FALSE;
1762 if ((handle = GetClipboardData( format->id )))
1763 ret = format->export( display, win, prop, target, handle );
1765 CloseClipboard();
1766 return ret;
1770 /***********************************************************************
1771 * export_multiple
1773 * Service a MULTIPLE selection request event
1774 * prop contains a list of (target,property) atom pairs.
1775 * The first atom names a target and the second names a property.
1776 * The effect is as if we have received a sequence of SelectionRequest events
1777 * (one for each atom pair) except that:
1778 * 1. We reply with a SelectionNotify only when all the requested conversions
1779 * have been performed.
1780 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
1781 * we replace the atom in the property by None.
1783 static BOOL export_multiple( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1785 Atom atype;
1786 int aformat;
1787 Atom *list;
1788 unsigned long i, count, failed, remain;
1790 /* Read the MULTIPLE property contents. This should contain a list of
1791 * (target,property) atom pairs.
1793 if (XGetWindowProperty( display, win, prop, 0, 0x3FFF, False, AnyPropertyType, &atype, &aformat,
1794 &count, &remain, (unsigned char**)&list ))
1795 return FALSE;
1797 TRACE( "type %s format %d count %ld remain %ld\n",
1798 debugstr_xatom( atype ), aformat, count, remain );
1801 * Make sure we got what we expect.
1802 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
1803 * in a MULTIPLE selection request should be of type ATOM_PAIR.
1804 * However some X apps(such as XPaint) are not compliant with this and return
1805 * a user defined atom in atype when XGetWindowProperty is called.
1806 * The data *is* an atom pair but is not denoted as such.
1808 if (aformat == 32 /* atype == xAtomPair */ )
1810 for (i = failed = 0; i < count; i += 2)
1812 if (list[i+1] == None) continue;
1813 if (export_selection( display, win, list[i + 1], list[i] )) continue;
1814 failed++;
1815 list[i + 1] = None;
1817 if (failed) put_property( display, win, prop, atype, 32, list, count );
1819 XFree( list );
1820 return TRUE;
1824 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
1826 return (event->error_code == BadAtom);
1829 static int is_window_error( Display *display, XErrorEvent *event, void *arg )
1831 return (event->error_code == BadWindow);
1834 /**************************************************************************
1835 * X11DRV_CLIPBOARD_InsertSelectionProperties
1837 * Mark properties available for future retrieval.
1839 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
1841 UINT i, nb_atoms = 0;
1842 Atom *atoms = NULL;
1844 /* Cache these formats in the clipboard cache */
1845 for (i = 0; i < count; i++)
1847 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
1849 if (lpFormat)
1851 /* We found at least one Window's format that mapps to the property.
1852 * Continue looking for more.
1854 * If more than one property map to a Window's format then we use the first
1855 * one and ignore the rest.
1857 while (lpFormat)
1859 TRACE( "property %s -> format %s\n",
1860 debugstr_xatom( lpFormat->atom ), debugstr_format( lpFormat->id ));
1861 if (lpFormat->id)
1862 X11DRV_CLIPBOARD_InsertClipboardData( lpFormat->id, 0, lpFormat, FALSE );
1863 lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
1866 else if (properties[i])
1868 /* add it to the list of atoms that we don't know about yet */
1869 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
1870 (count - i) * sizeof(*atoms) );
1871 if (atoms) atoms[nb_atoms++] = properties[i];
1875 /* query all unknown atoms in one go */
1876 if (atoms)
1878 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
1879 if (names)
1881 X11DRV_expect_error( display, is_atom_error, NULL );
1882 if (!XGetAtomNames( display, atoms, nb_atoms, names )) nb_atoms = 0;
1883 if (X11DRV_check_error())
1885 WARN( "got some bad atoms, ignoring\n" );
1886 nb_atoms = 0;
1888 for (i = 0; i < nb_atoms; i++)
1890 WINE_CLIPFORMAT *lpFormat;
1891 LPWSTR wname;
1892 int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
1893 wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1894 MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
1896 lpFormat = register_format( RegisterClipboardFormatW(wname), atoms[i] );
1897 HeapFree(GetProcessHeap(), 0, wname);
1898 if (!lpFormat)
1900 ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
1901 continue;
1903 TRACE( "property %s -> format %s\n",
1904 debugstr_xatom( lpFormat->atom ), debugstr_format( lpFormat->id ));
1905 X11DRV_CLIPBOARD_InsertClipboardData( lpFormat->id, 0, lpFormat, FALSE );
1907 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
1908 HeapFree( GetProcessHeap(), 0, names );
1910 HeapFree( GetProcessHeap(), 0, atoms );
1915 /**************************************************************************
1916 * X11DRV_CLIPBOARD_QueryAvailableData
1918 * Caches the list of data formats available from the current selection.
1919 * This queries the selection owner for the TARGETS property and saves all
1920 * reported property types.
1922 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display)
1924 Atom atype=AnyPropertyType;
1925 int aformat;
1926 unsigned long remain;
1927 Atom* targetList=NULL;
1928 Window w;
1929 unsigned long cSelectionTargets = 0;
1930 Atom prop;
1932 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
1934 ERR("Received request to cache selection but process is owner=(%08x)\n",
1935 (unsigned) selectionWindow);
1936 return -1; /* Prevent self request */
1939 w = thread_selection_wnd();
1940 if (!w)
1942 ERR("No window available to retrieve selection!\n");
1943 return -1;
1947 * Query the selection owner for the TARGETS property
1949 if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
1950 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
1952 if (use_primary_selection && (prop = convert_selection( display, w, XA_PRIMARY, x11drv_atom(TARGETS) )))
1953 selectionCacheSrc = XA_PRIMARY;
1954 else if ((prop = convert_selection( display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS) )))
1955 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1956 else
1958 Atom xstr = XA_STRING;
1960 /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
1961 if (convert_selection( display, w, XA_PRIMARY, XA_STRING ))
1963 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1964 selectionCacheSrc = XA_PRIMARY;
1965 return 1;
1967 else if (convert_selection( display, w, x11drv_atom(CLIPBOARD), XA_STRING ))
1969 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
1970 selectionCacheSrc = x11drv_atom(CLIPBOARD);
1971 return 1;
1973 else
1975 WARN("Failed to query selection owner for available data.\n");
1976 return -1;
1980 else return 0; /* No selection owner so report 0 targets available */
1982 /* Read the TARGETS property contents */
1983 if (!XGetWindowProperty(display, w, prop,
1984 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
1985 &remain, (unsigned char**)&targetList))
1987 TRACE( "type %s format %d count %ld remain %ld\n",
1988 debugstr_xatom( atype ), aformat, cSelectionTargets, remain);
1990 * The TARGETS property should have returned us a list of atoms
1991 * corresponding to each selection target format supported.
1993 if (atype == XA_ATOM || atype == x11drv_atom(TARGETS))
1995 if (aformat == 32)
1997 X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, cSelectionTargets);
1999 else if (aformat == 8) /* work around quartz-wm brain damage */
2001 unsigned long i, count = cSelectionTargets / sizeof(CARD32);
2002 Atom *atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(Atom) );
2003 for (i = 0; i < count; i++)
2004 atoms[i] = ((CARD32 *)targetList)[i]; /* FIXME: byte swapping */
2005 X11DRV_CLIPBOARD_InsertSelectionProperties( display, atoms, count );
2006 HeapFree( GetProcessHeap(), 0, atoms );
2010 /* Free the list of targets */
2011 XFree(targetList);
2013 else WARN("Failed to read TARGETS property\n");
2015 return cSelectionTargets;
2019 /**************************************************************************
2020 * X11DRV_CLIPBOARD_ReadSelectionData
2022 * This method is invoked only when we DO NOT own the X selection
2024 * We always get the data from the selection client each time,
2025 * since we have no way of determining if the data in our cache is stale.
2027 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData)
2029 BOOL bRet = FALSE;
2030 HANDLE hData;
2032 if (!lpData->lpFormat)
2034 ERR("Requesting format %04x but no source format linked to data.\n",
2035 lpData->wFormatID);
2036 return FALSE;
2039 if (!selectionAcquired)
2041 Window w = thread_selection_wnd();
2042 if(!w)
2044 ERR("No window available to read selection data!\n");
2045 return FALSE;
2048 hData = import_selection( display, w, selectionCacheSrc, lpData->lpFormat );
2049 if (hData)
2050 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, hData, lpData->lpFormat, TRUE);
2052 else
2054 ERR("Received request to cache selection data but process is owner\n");
2057 TRACE("Returning %d\n", bRet);
2059 return bRet;
2063 /**************************************************************************
2064 * X11DRV_CLIPBOARD_GetProperty
2065 * Gets type, data and size.
2067 static BOOL X11DRV_CLIPBOARD_GetProperty(Display *display, Window w, Atom prop,
2068 Atom *atype, unsigned char** data, unsigned long* datasize)
2070 int aformat;
2071 unsigned long pos = 0, nitems, remain, count;
2072 unsigned char *val = NULL, *buffer;
2074 for (;;)
2076 if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
2077 AnyPropertyType, atype, &aformat, &nitems, &remain, &buffer))
2079 WARN("Failed to read property\n");
2080 HeapFree( GetProcessHeap(), 0, val );
2081 return FALSE;
2084 count = get_property_size( aformat, nitems );
2085 if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
2086 else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
2088 if (!*data)
2090 XFree( buffer );
2091 HeapFree( GetProcessHeap(), 0, val );
2092 return FALSE;
2094 val = *data;
2095 memcpy( (int *)val + pos, buffer, count );
2096 XFree( buffer );
2097 if (!remain)
2099 *datasize = pos * sizeof(int) + count;
2100 val[*datasize] = 0;
2101 break;
2103 pos += count / sizeof(int);
2106 TRACE( "got property %s type %s format %u len %lu from window %lx\n",
2107 debugstr_xatom( prop ), debugstr_xatom( *atype ), aformat, *datasize, w );
2109 /* Delete the property on the window now that we are done
2110 * This will send a PropertyNotify event to the selection owner. */
2111 XDeleteProperty(display, w, prop);
2112 return TRUE;
2116 struct clipboard_data_packet {
2117 struct list entry;
2118 unsigned long size;
2119 unsigned char *data;
2122 /**************************************************************************
2123 * X11DRV_CLIPBOARD_ReadProperty
2124 * Reads the contents of the X selection property.
2126 static BOOL X11DRV_CLIPBOARD_ReadProperty( Display *display, Window w, Atom prop,
2127 Atom *type, unsigned char** data, unsigned long* datasize )
2129 XEvent xe;
2131 if (prop == None)
2132 return FALSE;
2134 while (XCheckTypedWindowEvent(display, w, PropertyNotify, &xe))
2137 if (!X11DRV_CLIPBOARD_GetProperty(display, w, prop, type, data, datasize))
2138 return FALSE;
2140 if (*type == x11drv_atom(INCR))
2142 unsigned char *buf;
2143 unsigned long bufsize = 0;
2144 struct list packets;
2145 struct clipboard_data_packet *packet, *packet2;
2146 BOOL res;
2148 HeapFree(GetProcessHeap(), 0, *data);
2149 *data = NULL;
2151 list_init(&packets);
2153 for (;;)
2155 int i;
2156 unsigned char *prop_data;
2157 unsigned long prop_size;
2159 /* Wait until PropertyNotify is received */
2160 for (i = 0; i < SELECTION_RETRIES; i++)
2162 Bool res;
2164 res = XCheckTypedWindowEvent(display, w, PropertyNotify, &xe);
2165 if (res && xe.xproperty.atom == prop &&
2166 xe.xproperty.state == PropertyNewValue)
2167 break;
2168 usleep(SELECTION_WAIT);
2171 if (i >= SELECTION_RETRIES ||
2172 !X11DRV_CLIPBOARD_GetProperty(display, w, prop, type, &prop_data, &prop_size))
2174 res = FALSE;
2175 break;
2178 /* Retrieved entire data. */
2179 if (prop_size == 0)
2181 HeapFree(GetProcessHeap(), 0, prop_data);
2182 res = TRUE;
2183 break;
2186 packet = HeapAlloc(GetProcessHeap(), 0, sizeof(*packet));
2187 if (!packet)
2189 HeapFree(GetProcessHeap(), 0, prop_data);
2190 res = FALSE;
2191 break;
2194 packet->size = prop_size;
2195 packet->data = prop_data;
2196 list_add_tail(&packets, &packet->entry);
2197 bufsize += prop_size;
2200 if (res)
2202 buf = HeapAlloc(GetProcessHeap(), 0, bufsize + 1);
2203 if (buf)
2205 unsigned long bytes_copied = 0;
2206 *datasize = bufsize;
2207 LIST_FOR_EACH_ENTRY( packet, &packets, struct clipboard_data_packet, entry)
2209 memcpy(&buf[bytes_copied], packet->data, packet->size);
2210 bytes_copied += packet->size;
2212 buf[bufsize] = 0;
2213 *data = buf;
2215 else
2216 res = FALSE;
2219 LIST_FOR_EACH_ENTRY_SAFE( packet, packet2, &packets, struct clipboard_data_packet, entry)
2221 HeapFree(GetProcessHeap(), 0, packet->data);
2222 HeapFree(GetProcessHeap(), 0, packet);
2225 return res;
2228 return TRUE;
2232 /**************************************************************************
2233 * X11DRV_CLIPBOARD_ReleaseSelection
2235 * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
2237 static void X11DRV_CLIPBOARD_ReleaseSelection(Display *display, Atom selType, Window w, HWND hwnd, Time time)
2239 /* w is the window that lost the selection
2241 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
2242 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
2244 if (selectionAcquired && (w == selectionWindow))
2246 HWND owner;
2248 /* completely give up the selection */
2249 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
2251 if (X11DRV_CLIPBOARD_IsProcessOwner( &owner ))
2253 /* Since we're still the owner, this wasn't initiated by
2254 another Wine process */
2255 if (OpenClipboard(hwnd))
2257 /* Destroy private objects */
2258 SendMessageW(owner, WM_DESTROYCLIPBOARD, 0, 0);
2260 /* Give up ownership of the windows clipboard */
2261 X11DRV_CLIPBOARD_ReleaseOwnership();
2262 CloseClipboard();
2266 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2268 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2270 if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2272 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2273 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2275 else
2276 TRACE("We no longer own PRIMARY\n");
2278 else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2280 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2282 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2284 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2285 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2287 else
2288 TRACE("We no longer own CLIPBOARD\n");
2291 selectionWindow = None;
2293 empty_clipboard();
2295 /* Reset the selection flags now that we are done */
2296 selectionAcquired = S_NOSELECTION;
2301 /**************************************************************************
2302 * X11DRV Clipboard Exports
2303 **************************************************************************/
2306 static void selection_acquire(void)
2308 Window owner;
2309 Display *display;
2311 owner = thread_selection_wnd();
2312 display = thread_display();
2314 selectionAcquired = 0;
2315 selectionWindow = 0;
2317 /* Grab PRIMARY selection if not owned */
2318 if (use_primary_selection)
2319 XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2321 /* Grab CLIPBOARD selection if not owned */
2322 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2324 if (use_primary_selection && XGetSelectionOwner(display, XA_PRIMARY) == owner)
2325 selectionAcquired |= S_PRIMARY;
2327 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2328 selectionAcquired |= S_CLIPBOARD;
2330 if (selectionAcquired)
2332 selectionWindow = owner;
2333 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2337 static DWORD WINAPI selection_thread_proc(LPVOID p)
2339 HANDLE event = p;
2341 TRACE("\n");
2343 selection_acquire();
2344 SetEvent(event);
2346 while (selectionAcquired)
2348 MsgWaitForMultipleObjectsEx(0, NULL, INFINITE, QS_SENDMESSAGE, 0);
2351 return 0;
2354 /**************************************************************************
2355 * X11DRV_AcquireClipboard
2357 void X11DRV_AcquireClipboard(HWND hWndClipWindow)
2359 DWORD procid;
2360 HANDLE selectionThread;
2362 TRACE(" %p\n", hWndClipWindow);
2365 * It's important that the selection get acquired from the thread
2366 * that owns the clipboard window. The primary reason is that we know
2367 * it is running a message loop and therefore can process the
2368 * X selection events.
2370 if (hWndClipWindow &&
2371 GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, &procid))
2373 if (procid != GetCurrentProcessId())
2375 WARN("Setting clipboard owner to other process is not supported\n");
2376 hWndClipWindow = NULL;
2378 else
2380 TRACE("Thread %x is acquiring selection with thread %x's window %p\n",
2381 GetCurrentThreadId(),
2382 GetWindowThreadProcessId(hWndClipWindow, NULL), hWndClipWindow);
2384 SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0);
2385 return;
2389 if (hWndClipWindow)
2391 selection_acquire();
2393 else
2395 HANDLE event = CreateEventW(NULL, FALSE, FALSE, NULL);
2396 selectionThread = CreateThread(NULL, 0, selection_thread_proc, event, 0, NULL);
2398 if (selectionThread)
2400 WaitForSingleObject(event, INFINITE);
2401 CloseHandle(selectionThread);
2403 CloseHandle(event);
2408 static void empty_clipboard(void)
2410 WINE_CLIPDATA *data, *next;
2412 LIST_FOR_EACH_ENTRY_SAFE( data, next, &data_list, WINE_CLIPDATA, entry )
2414 list_remove( &data->entry );
2415 X11DRV_CLIPBOARD_FreeData( data );
2416 HeapFree( GetProcessHeap(), 0, data );
2417 ClipDataCount--;
2420 TRACE(" %d entries remaining in cache.\n", ClipDataCount);
2423 /**************************************************************************
2424 * X11DRV_EmptyClipboard
2426 * Empty cached clipboard data.
2428 void CDECL X11DRV_EmptyClipboard(void)
2430 X11DRV_AcquireClipboard( GetOpenClipboardWindow() );
2431 empty_clipboard();
2434 /**************************************************************************
2435 * X11DRV_SetClipboardData
2437 BOOL CDECL X11DRV_SetClipboardData(UINT wFormat, HANDLE hData, BOOL owner)
2439 if (!owner) X11DRV_CLIPBOARD_UpdateCache();
2441 return X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData, NULL, TRUE);
2445 /**************************************************************************
2446 * CountClipboardFormats
2448 INT CDECL X11DRV_CountClipboardFormats(void)
2450 X11DRV_CLIPBOARD_UpdateCache();
2452 TRACE(" count=%d\n", ClipDataCount);
2454 return ClipDataCount;
2458 /**************************************************************************
2459 * X11DRV_EnumClipboardFormats
2461 UINT CDECL X11DRV_EnumClipboardFormats(UINT wFormat)
2463 struct list *ptr = NULL;
2465 TRACE("(%04X)\n", wFormat);
2467 X11DRV_CLIPBOARD_UpdateCache();
2469 if (!wFormat)
2471 ptr = list_head( &data_list );
2473 else
2475 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
2476 if (lpData) ptr = list_next( &data_list, &lpData->entry );
2479 if (!ptr) return 0;
2480 return LIST_ENTRY( ptr, WINE_CLIPDATA, entry )->wFormatID;
2484 /**************************************************************************
2485 * X11DRV_IsClipboardFormatAvailable
2487 BOOL CDECL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
2489 BOOL bRet = FALSE;
2491 TRACE("(%04X)\n", wFormat);
2493 X11DRV_CLIPBOARD_UpdateCache();
2495 if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
2496 bRet = TRUE;
2498 TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
2500 return bRet;
2504 /**************************************************************************
2505 * GetClipboardData (USER.142)
2507 HANDLE CDECL X11DRV_GetClipboardData(UINT wFormat)
2509 LPWINE_CLIPDATA lpRender;
2511 TRACE("(%04X)\n", wFormat);
2513 X11DRV_CLIPBOARD_UpdateCache();
2515 if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
2517 if ( !lpRender->hData )
2518 X11DRV_CLIPBOARD_RenderFormat(thread_init_display(), lpRender);
2520 TRACE(" returning %p (type %04x)\n", lpRender->hData, lpRender->wFormatID);
2521 return lpRender->hData;
2524 return 0;
2528 /**************************************************************************
2529 * ResetSelectionOwner
2531 * Called when the thread owning the selection is destroyed and we need to
2532 * preserve the selection ownership. We look for another top level window
2533 * in this process and send it a message to acquire the selection.
2535 void X11DRV_ResetSelectionOwner(void)
2537 HWND hwnd;
2538 DWORD procid;
2540 TRACE("\n");
2542 if (!selectionAcquired || thread_selection_wnd() != selectionWindow)
2543 return;
2545 selectionAcquired = S_NOSELECTION;
2546 selectionWindow = 0;
2548 hwnd = GetWindow(GetDesktopWindow(), GW_CHILD);
2551 if (GetCurrentThreadId() != GetWindowThreadProcessId(hwnd, &procid))
2553 if (GetCurrentProcessId() == procid)
2555 if (SendMessageW(hwnd, WM_X11DRV_ACQUIRE_SELECTION, 0, 0))
2556 return;
2559 } while ((hwnd = GetWindow(hwnd, GW_HWNDNEXT)) != NULL);
2561 WARN("Failed to find another thread to take selection ownership. Clipboard data will be lost.\n");
2563 X11DRV_CLIPBOARD_ReleaseOwnership();
2564 empty_clipboard();
2568 /***********************************************************************
2569 * X11DRV_HandleSelectionRequest
2571 BOOL X11DRV_SelectionRequest( HWND hwnd, XEvent *xev )
2573 XSelectionRequestEvent *event = &xev->xselectionrequest;
2574 Display *display = event->display;
2575 XEvent result;
2576 Atom rprop = None;
2578 X11DRV_expect_error( display, is_window_error, NULL );
2581 * We can only handle the selection request if :
2582 * The selection is PRIMARY or CLIPBOARD, AND we can successfully open the clipboard.
2584 if (((event->selection != XA_PRIMARY) && (event->selection != x11drv_atom(CLIPBOARD))))
2585 goto done;
2587 /* If the specified property is None the requestor is an obsolete client.
2588 * We support these by using the specified target atom as the reply property.
2590 rprop = event->property;
2591 if( rprop == None )
2592 rprop = event->target;
2594 if (!export_selection( display, event->requestor, rprop, event->target ))
2595 rprop = None; /* report failure to client */
2597 done:
2598 result.xselection.type = SelectionNotify;
2599 result.xselection.display = display;
2600 result.xselection.requestor = event->requestor;
2601 result.xselection.selection = event->selection;
2602 result.xselection.property = rprop;
2603 result.xselection.target = event->target;
2604 result.xselection.time = event->time;
2605 TRACE( "sending SelectionNotify for %s to %lx\n", debugstr_xatom( rprop ), event->requestor );
2606 XSendEvent( display, event->requestor, False, NoEventMask, &result );
2607 XSync( display, False );
2608 if (X11DRV_check_error()) WARN( "requestor %lx is no longer valid\n", event->requestor );
2609 return FALSE;
2613 /***********************************************************************
2614 * X11DRV_SelectionClear
2616 BOOL X11DRV_SelectionClear( HWND hWnd, XEvent *xev )
2618 XSelectionClearEvent *event = &xev->xselectionclear;
2619 if (event->selection == XA_PRIMARY || event->selection == x11drv_atom(CLIPBOARD))
2620 X11DRV_CLIPBOARD_ReleaseSelection( event->display, event->selection,
2621 event->window, hWnd, event->time );
2622 return FALSE;