winex11: Remove support for exporting the CF_BITMAP, CF_PALETTE and CF_DIBV5 formats.
[wine.git] / dlls / winex11.drv / clipboard.c
blob776e579009d526d96c3bcb702b0f4b5e2ce36049
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"
91 WINE_DEFAULT_DEBUG_CHANNEL(clipboard);
93 /* Maximum wait time for selection notify */
94 #define SELECTION_RETRIES 500 /* wait for .5 seconds */
95 #define SELECTION_WAIT 1000 /* us */
97 #define SELECTION_UPDATE_DELAY 2000 /* delay between checks of the X11 selection */
99 typedef BOOL (*EXPORTFUNC)( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
100 typedef HANDLE (*IMPORTFUNC)( Atom type, const void *data, size_t size );
102 struct clipboard_format
104 struct list entry;
105 UINT id;
106 Atom atom;
107 IMPORTFUNC import;
108 EXPORTFUNC export;
111 static HANDLE import_data( Atom type, const void *data, size_t size );
112 static HANDLE import_enhmetafile( Atom type, const void *data, size_t size );
113 static HANDLE import_pixmap( Atom type, const void *data, size_t size );
114 static HANDLE import_image_bmp( Atom type, const void *data, size_t size );
115 static HANDLE import_string( Atom type, const void *data, size_t size );
116 static HANDLE import_utf8_string( Atom type, const void *data, size_t size );
117 static HANDLE import_compound_text( Atom type, const void *data, size_t size );
118 static HANDLE import_text_uri_list( Atom type, const void *data, size_t size );
119 static HANDLE import_targets( Atom type, const void *data, size_t size );
121 static BOOL export_data( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
122 static BOOL export_string( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
123 static BOOL export_utf8_string( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
124 static BOOL export_compound_text( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
125 static BOOL export_pixmap( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
126 static BOOL export_image_bmp( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
127 static BOOL export_enhmetafile( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
128 static BOOL export_text_html( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
129 static BOOL export_hdrop( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
130 static BOOL export_targets( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
131 static BOOL export_multiple( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
133 static BOOL X11DRV_CLIPBOARD_ReadProperty( Display *display, Window w, Atom prop,
134 Atom *type, unsigned char **data, unsigned long *datasize );
136 /* Clipboard formats */
138 static const WCHAR RichTextFormatW[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
139 static const WCHAR GIFW[] = {'G','I','F',0};
140 static const WCHAR JFIFW[] = {'J','F','I','F',0};
141 static const WCHAR PNGW[] = {'P','N','G',0};
142 static const WCHAR HTMLFormatW[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
144 static const struct
146 const WCHAR *name;
147 UINT id;
148 UINT data;
149 IMPORTFUNC import;
150 EXPORTFUNC export;
151 } builtin_formats[] =
153 { 0, CF_UNICODETEXT, XATOM_UTF8_STRING, import_utf8_string, export_utf8_string },
154 { 0, CF_UNICODETEXT, XATOM_COMPOUND_TEXT, import_compound_text, export_compound_text },
155 { 0, CF_UNICODETEXT, XA_STRING, import_string, export_string },
156 { 0, CF_UNICODETEXT, XATOM_text_plain, import_string, export_string },
157 { 0, CF_SYLK, XATOM_WCF_SYLK, import_data, export_data },
158 { 0, CF_DIF, XATOM_WCF_DIF, import_data, export_data },
159 { 0, CF_TIFF, XATOM_WCF_TIFF, import_data, export_data },
160 { 0, CF_OEMTEXT, XATOM_WCF_OEMTEXT, import_data, export_data },
161 { 0, CF_DIB, XA_PIXMAP, import_pixmap, export_pixmap },
162 { 0, CF_PENDATA, XATOM_WCF_PENDATA, import_data, export_data },
163 { 0, CF_RIFF, XATOM_WCF_RIFF, import_data, export_data },
164 { 0, CF_WAVE, XATOM_WCF_WAVE, import_data, export_data },
165 { 0, CF_ENHMETAFILE, XATOM_WCF_ENHMETAFILE, import_enhmetafile, export_enhmetafile },
166 { 0, CF_HDROP, XATOM_text_uri_list, import_text_uri_list, export_hdrop },
167 { 0, CF_LOCALE, XATOM_WCF_LOCALE, import_data, export_data },
168 { 0, CF_DIB, XATOM_image_bmp, import_image_bmp, export_image_bmp },
169 { RichTextFormatW, 0, XATOM_text_rtf, import_data, export_data },
170 { RichTextFormatW, 0, XATOM_text_richtext, import_data, export_data },
171 { GIFW, 0, XATOM_image_gif, import_data, export_data },
172 { JFIFW, 0, XATOM_image_jpeg, import_data, export_data },
173 { PNGW, 0, XATOM_image_png, import_data, export_data },
174 { HTMLFormatW, 0, XATOM_HTML_Format, import_data, export_data },
175 { HTMLFormatW, 0, XATOM_text_html, import_data, export_text_html },
176 { 0, 0, XATOM_TARGETS, import_targets, export_targets },
177 { 0, 0, XATOM_MULTIPLE, NULL, export_multiple },
180 static struct list format_list = LIST_INIT( format_list );
182 #define NB_BUILTIN_FORMATS (sizeof(builtin_formats) / sizeof(builtin_formats[0]))
183 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
185 static DWORD clipboard_thread_id;
186 static HWND clipboard_hwnd;
187 static BOOL is_clipboard_owner;
188 static Window selection_window;
189 static Window import_window;
190 static Atom current_selection;
191 static ULONG64 last_clipboard_update;
192 static struct clipboard_format **current_x11_formats;
193 static unsigned int nb_current_x11_formats;
195 Display *clipboard_display = NULL;
197 static const char *debugstr_format( UINT id )
199 WCHAR buffer[256];
201 if (GetClipboardFormatNameW( id, buffer, 256 ))
202 return wine_dbg_sprintf( "%04x %s", id, debugstr_w(buffer) );
204 switch (id)
206 case 0: return "(none)";
207 #define BUILTIN(id) case id: return #id;
208 BUILTIN(CF_TEXT)
209 BUILTIN(CF_BITMAP)
210 BUILTIN(CF_METAFILEPICT)
211 BUILTIN(CF_SYLK)
212 BUILTIN(CF_DIF)
213 BUILTIN(CF_TIFF)
214 BUILTIN(CF_OEMTEXT)
215 BUILTIN(CF_DIB)
216 BUILTIN(CF_PALETTE)
217 BUILTIN(CF_PENDATA)
218 BUILTIN(CF_RIFF)
219 BUILTIN(CF_WAVE)
220 BUILTIN(CF_UNICODETEXT)
221 BUILTIN(CF_ENHMETAFILE)
222 BUILTIN(CF_HDROP)
223 BUILTIN(CF_LOCALE)
224 BUILTIN(CF_DIBV5)
225 BUILTIN(CF_OWNERDISPLAY)
226 BUILTIN(CF_DSPTEXT)
227 BUILTIN(CF_DSPBITMAP)
228 BUILTIN(CF_DSPMETAFILEPICT)
229 BUILTIN(CF_DSPENHMETAFILE)
230 #undef BUILTIN
231 default: return wine_dbg_sprintf( "%04x", id );
235 static const char *debugstr_xatom( Atom atom )
237 const char *ret;
238 char *name;
240 if (!atom) return "(None)";
241 name = XGetAtomName( thread_display(), atom );
242 ret = debugstr_a( name );
243 XFree( name );
244 return ret;
248 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
250 return (event->error_code == BadAtom);
254 /**************************************************************************
255 * find_win32_format
257 static struct clipboard_format *find_win32_format( UINT id )
259 struct clipboard_format *format;
261 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
262 if (format->id == id) return format;
263 return NULL;
267 /**************************************************************************
268 * find_x11_format
270 static struct clipboard_format *find_x11_format( Atom atom )
272 struct clipboard_format *format;
274 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
275 if (format->atom == atom) return format;
276 return NULL;
280 /**************************************************************************
281 * register_builtin_formats
283 static void register_builtin_formats(void)
285 struct clipboard_format *formats;
286 unsigned int i;
288 if (!(formats = HeapAlloc( GetProcessHeap(), 0, NB_BUILTIN_FORMATS * sizeof(*formats)))) return;
290 for (i = 0; i < NB_BUILTIN_FORMATS; i++)
292 if (builtin_formats[i].name)
293 formats[i].id = RegisterClipboardFormatW( builtin_formats[i].name );
294 else
295 formats[i].id = builtin_formats[i].id;
297 formats[i].atom = GET_ATOM(builtin_formats[i].data);
298 formats[i].import = builtin_formats[i].import;
299 formats[i].export = builtin_formats[i].export;
300 list_add_tail( &format_list, &formats[i].entry );
305 /**************************************************************************
306 * register_formats
308 static void register_formats( const UINT *ids, const Atom *atoms, unsigned int count )
310 struct clipboard_format *formats;
311 unsigned int i;
313 if (!(formats = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*formats)))) return;
315 for (i = 0; i < count; i++)
317 formats[i].id = ids[i];
318 formats[i].atom = atoms[i];
319 formats[i].import = import_data;
320 formats[i].export = export_data;
321 list_add_tail( &format_list, &formats[i].entry );
322 TRACE( "registered %s atom %s\n", debugstr_format( ids[i] ), debugstr_xatom( atoms[i] ));
327 /**************************************************************************
328 * register_win32_formats
330 * Register Win32 clipboard formats the first time we encounter them.
332 static void register_win32_formats( const UINT *ids, UINT size )
334 unsigned int count, len;
335 UINT new_ids[256];
336 char *names[256];
337 Atom atoms[256];
338 WCHAR buffer[256];
340 if (list_empty( &format_list)) register_builtin_formats();
342 while (size)
344 for (count = 0; count < 256 && size; ids++, size--)
346 if (find_win32_format( *ids )) continue; /* it already exists */
347 if (!GetClipboardFormatNameW( *ids, buffer, 256 )) continue; /* not a named format */
348 if (!(len = WideCharToMultiByte( CP_UNIXCP, 0, buffer, -1, NULL, 0, NULL, NULL ))) continue;
349 if (!(names[count] = HeapAlloc( GetProcessHeap(), 0, len ))) continue;
350 WideCharToMultiByte( CP_UNIXCP, 0, buffer, -1, names[count], len, NULL, NULL );
351 new_ids[count++] = *ids;
353 if (!count) return;
355 XInternAtoms( thread_display(), names, count, False, atoms );
356 register_formats( new_ids, atoms, count );
357 while (count) HeapFree( GetProcessHeap(), 0, names[--count] );
362 /**************************************************************************
363 * register_x11_formats
365 * Register X11 atom formats the first time we encounter them.
367 static void register_x11_formats( const Atom *atoms, UINT size )
369 Display *display = thread_display();
370 unsigned int i, pos, count;
371 char *names[256];
372 UINT ids[256];
373 Atom new_atoms[256];
374 WCHAR buffer[256];
376 if (list_empty( &format_list)) register_builtin_formats();
378 while (size)
380 for (count = 0; count < 256 && size; atoms++, size--)
381 if (!find_x11_format( *atoms )) new_atoms[count++] = *atoms;
383 if (!count) return;
385 X11DRV_expect_error( display, is_atom_error, NULL );
386 if (!XGetAtomNames( display, new_atoms, count, names )) count = 0;
387 if (X11DRV_check_error())
389 WARN( "got some bad atoms, ignoring\n" );
390 count = 0;
393 for (i = pos = 0; i < count; i++)
395 if (MultiByteToWideChar( CP_UNIXCP, 0, names[i], -1, buffer, 256 ) &&
396 (ids[pos] = RegisterClipboardFormatW( buffer )))
397 new_atoms[pos++] = new_atoms[i];
398 XFree( names[i] );
400 register_formats( ids, new_atoms, pos );
405 /**************************************************************************
406 * put_property
408 * Put data as a property on the specified window.
410 static void put_property( Display *display, Window win, Atom prop, Atom type, int format,
411 const void *ptr, size_t size )
413 const unsigned char *data = ptr;
414 int mode = PropModeReplace;
415 size_t width = (format == 32) ? sizeof(long) : format / 8;
416 size_t max_size = XExtendedMaxRequestSize( display ) * 4;
418 if (!max_size) max_size = XMaxRequestSize( display ) * 4;
419 max_size -= 64; /* request overhead */
423 size_t count = min( size, max_size / width );
424 XChangeProperty( display, win, prop, type, format, mode, data, count );
425 mode = PropModeAppend;
426 size -= count;
427 data += count * width;
428 } while (size > 0);
432 /**************************************************************************
433 * convert_selection
435 static Atom convert_selection( Display *display, Window win, Atom selection, Atom target )
437 int i;
438 XEvent event;
440 XConvertSelection( display, selection, target, x11drv_atom(SELECTION_DATA), win, CurrentTime );
442 for (i = 0; i < SELECTION_RETRIES; i++)
444 Bool res = XCheckTypedWindowEvent( display, win, SelectionNotify, &event );
445 if (res && event.xselection.selection == selection && event.xselection.target == target)
446 return event.xselection.property;
447 usleep( SELECTION_WAIT );
449 ERR( "Timed out waiting for SelectionNotify event\n" );
450 return None;
454 /***********************************************************************
455 * bitmap_info_size
457 * Return the size of the bitmap info structure including color table.
459 static int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
461 unsigned int colors, size, masks = 0;
463 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
465 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
466 colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
467 return sizeof(BITMAPCOREHEADER) + colors *
468 ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
470 else /* assume BITMAPINFOHEADER */
472 colors = info->bmiHeader.biClrUsed;
473 if (!colors && (info->bmiHeader.biBitCount <= 8))
474 colors = 1 << info->bmiHeader.biBitCount;
475 if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
476 size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
477 return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
482 /***********************************************************************
483 * create_dib_from_bitmap
485 * Allocates a packed DIB and copies the bitmap data into it.
487 static HGLOBAL create_dib_from_bitmap(HBITMAP hBmp)
489 BITMAP bmp;
490 HDC hdc;
491 HGLOBAL hPackedDIB;
492 LPBYTE pPackedDIB;
493 LPBITMAPINFOHEADER pbmiHeader;
494 unsigned int cDataSize, cPackedSize, OffsetBits;
495 int nLinesCopied;
497 if (!GetObjectW( hBmp, sizeof(bmp), &bmp )) return 0;
500 * A packed DIB contains a BITMAPINFO structure followed immediately by
501 * an optional color palette and the pixel data.
504 /* Calculate the size of the packed DIB */
505 cDataSize = abs( bmp.bmHeight ) * (((bmp.bmWidth * bmp.bmBitsPixel + 31) / 8) & ~3);
506 cPackedSize = sizeof(BITMAPINFOHEADER)
507 + ( (bmp.bmBitsPixel <= 8) ? (sizeof(RGBQUAD) * (1 << bmp.bmBitsPixel)) : 0 )
508 + cDataSize;
509 /* Get the offset to the bits */
510 OffsetBits = cPackedSize - cDataSize;
512 /* Allocate the packed DIB */
513 TRACE("\tAllocating packed DIB of size %d\n", cPackedSize);
514 hPackedDIB = GlobalAlloc( GMEM_FIXED, cPackedSize );
515 if ( !hPackedDIB )
517 WARN("Could not allocate packed DIB!\n");
518 return 0;
521 /* A packed DIB starts with a BITMAPINFOHEADER */
522 pPackedDIB = GlobalLock(hPackedDIB);
523 pbmiHeader = (LPBITMAPINFOHEADER)pPackedDIB;
525 /* Init the BITMAPINFOHEADER */
526 pbmiHeader->biSize = sizeof(BITMAPINFOHEADER);
527 pbmiHeader->biWidth = bmp.bmWidth;
528 pbmiHeader->biHeight = bmp.bmHeight;
529 pbmiHeader->biPlanes = 1;
530 pbmiHeader->biBitCount = bmp.bmBitsPixel;
531 pbmiHeader->biCompression = BI_RGB;
532 pbmiHeader->biSizeImage = 0;
533 pbmiHeader->biXPelsPerMeter = pbmiHeader->biYPelsPerMeter = 0;
534 pbmiHeader->biClrUsed = 0;
535 pbmiHeader->biClrImportant = 0;
537 /* Retrieve the DIB bits from the bitmap and fill in the
538 * DIB color table if present */
539 hdc = GetDC( 0 );
540 nLinesCopied = GetDIBits(hdc, /* Handle to device context */
541 hBmp, /* Handle to bitmap */
542 0, /* First scan line to set in dest bitmap */
543 bmp.bmHeight, /* Number of scan lines to copy */
544 pPackedDIB + OffsetBits, /* [out] Address of array for bitmap bits */
545 (LPBITMAPINFO) pbmiHeader, /* [out] Address of BITMAPINFO structure */
546 0); /* RGB or palette index */
547 GlobalUnlock(hPackedDIB);
548 ReleaseDC( 0, hdc );
550 /* Cleanup if GetDIBits failed */
551 if (nLinesCopied != bmp.bmHeight)
553 TRACE("\tGetDIBits returned %d. Actual lines=%d\n", nLinesCopied, bmp.bmHeight);
554 GlobalFree(hPackedDIB);
555 hPackedDIB = 0;
557 return hPackedDIB;
561 /***********************************************************************
562 * uri_to_dos
564 * Converts a text/uri-list URI to DOS filename.
566 static WCHAR* uri_to_dos(char *encodedURI)
568 WCHAR *ret = NULL;
569 int i;
570 int j = 0;
571 char *uri = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, strlen(encodedURI) + 1);
572 if (uri == NULL)
573 return NULL;
574 for (i = 0; encodedURI[i]; ++i)
576 if (encodedURI[i] == '%')
578 if (encodedURI[i+1] && encodedURI[i+2])
580 char buffer[3];
581 int number;
582 buffer[0] = encodedURI[i+1];
583 buffer[1] = encodedURI[i+2];
584 buffer[2] = '\0';
585 sscanf(buffer, "%x", &number);
586 uri[j++] = number;
587 i += 2;
589 else
591 WARN("invalid URI encoding in %s\n", debugstr_a(encodedURI));
592 HeapFree(GetProcessHeap(), 0, uri);
593 return NULL;
596 else
597 uri[j++] = encodedURI[i];
600 /* Read http://www.freedesktop.org/wiki/Draganddropwarts and cry... */
601 if (strncmp(uri, "file:/", 6) == 0)
603 if (uri[6] == '/')
605 if (uri[7] == '/')
607 /* file:///path/to/file (nautilus, thunar) */
608 ret = wine_get_dos_file_name(&uri[7]);
610 else if (uri[7])
612 /* file://hostname/path/to/file (X file drag spec) */
613 char hostname[256];
614 char *path = strchr(&uri[7], '/');
615 if (path)
617 *path = '\0';
618 if (strcmp(&uri[7], "localhost") == 0)
620 *path = '/';
621 ret = wine_get_dos_file_name(path);
623 else if (gethostname(hostname, sizeof(hostname)) == 0)
625 if (strcmp(hostname, &uri[7]) == 0)
627 *path = '/';
628 ret = wine_get_dos_file_name(path);
634 else if (uri[6])
636 /* file:/path/to/file (konqueror) */
637 ret = wine_get_dos_file_name(&uri[5]);
640 HeapFree(GetProcessHeap(), 0, uri);
641 return ret;
645 /**************************************************************************
646 * unicode_text_from_string
648 * Convert a string in the specified encoding to CF_UNICODETEXT format.
650 static HANDLE unicode_text_from_string( UINT codepage, const void *data, size_t size )
652 DWORD i, j, count;
653 WCHAR *strW;
655 count = MultiByteToWideChar( codepage, 0, data, size, NULL, 0);
657 if (!(strW = GlobalAlloc( GMEM_FIXED, (count * 2 + 1) * sizeof(WCHAR) ))) return 0;
659 MultiByteToWideChar( codepage, 0, data, size, strW + count, count );
660 for (i = j = 0; i < count; i++)
662 if (strW[i + count] == '\n') strW[j++] = '\r';
663 strW[j++] = strW[i + count];
665 strW[j++] = 0;
666 GlobalReAlloc( strW, j * sizeof(WCHAR), GMEM_FIXED ); /* release unused space */
667 TRACE( "returning %s\n", debugstr_wn( strW, j - 1 ));
668 return strW;
672 /**************************************************************************
673 * import_string
675 * Import XA_STRING, converting the string to CF_UNICODETEXT.
677 static HANDLE import_string( Atom type, const void *data, size_t size )
679 return unicode_text_from_string( 28591, data, size );
683 /**************************************************************************
684 * import_utf8_string
686 * Import XA_UTF8_STRING, converting the string to CF_UNICODETEXT.
688 static HANDLE import_utf8_string( Atom type, const void *data, size_t size )
690 return unicode_text_from_string( CP_UTF8, data, size );
694 /**************************************************************************
695 * import_compound_text
697 * Import COMPOUND_TEXT to CF_UNICODETEXT.
699 static HANDLE import_compound_text( Atom type, const void *data, size_t size )
701 char** srcstr;
702 int count;
703 HANDLE ret;
704 XTextProperty txtprop;
706 txtprop.value = (BYTE *)data;
707 txtprop.nitems = size;
708 txtprop.encoding = x11drv_atom(COMPOUND_TEXT);
709 txtprop.format = 8;
710 if (XmbTextPropertyToTextList( thread_display(), &txtprop, &srcstr, &count ) != Success) return 0;
711 if (!count) return 0;
713 ret = unicode_text_from_string( CP_UNIXCP, srcstr[0], strlen(srcstr[0]) + 1 );
714 XFreeStringList(srcstr);
715 return ret;
719 /**************************************************************************
720 * import_pixmap
722 * Import XA_PIXMAP, converting the image to CF_DIB.
724 static HANDLE import_pixmap( Atom type, const void *data, size_t size )
726 const Pixmap *pPixmap = (const Pixmap *)data;
727 BYTE *ptr = NULL;
728 XVisualInfo vis = default_visual;
729 char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
730 BITMAPINFO *info = (BITMAPINFO *)buffer;
731 struct gdi_image_bits bits;
732 Window root;
733 int x,y; /* Unused */
734 unsigned border_width; /* Unused */
735 unsigned int depth, width, height;
737 /* Get the Pixmap dimensions and bit depth */
738 if (!XGetGeometry(gdi_display, *pPixmap, &root, &x, &y, &width, &height,
739 &border_width, &depth)) depth = 0;
740 if (!pixmap_formats[depth]) return 0;
742 TRACE( "pixmap properties: width=%d, height=%d, depth=%d\n", width, height, depth );
744 if (depth != vis.depth) switch (pixmap_formats[depth]->bits_per_pixel)
746 case 1:
747 case 4:
748 case 8:
749 break;
750 case 16: /* assume R5G5B5 */
751 vis.red_mask = 0x7c00;
752 vis.green_mask = 0x03e0;
753 vis.blue_mask = 0x001f;
754 break;
755 case 24: /* assume R8G8B8 */
756 case 32: /* assume A8R8G8B8 */
757 vis.red_mask = 0xff0000;
758 vis.green_mask = 0x00ff00;
759 vis.blue_mask = 0x0000ff;
760 break;
761 default:
762 return 0;
765 if (!get_pixmap_image( *pPixmap, width, height, &vis, info, &bits ))
767 DWORD info_size = bitmap_info_size( info, DIB_RGB_COLORS );
769 ptr = GlobalAlloc( GMEM_FIXED, info_size + info->bmiHeader.biSizeImage );
770 if (ptr)
772 memcpy( ptr, info, info_size );
773 memcpy( ptr + info_size, bits.ptr, info->bmiHeader.biSizeImage );
775 if (bits.free) bits.free( &bits );
777 return ptr;
781 /**************************************************************************
782 * import_image_bmp
784 * Import image/bmp, converting the image to CF_DIB.
786 static HANDLE import_image_bmp( Atom type, const void *data, size_t size )
788 HANDLE hClipData = 0;
789 const BITMAPFILEHEADER *bfh = data;
791 if (size >= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPCOREHEADER) &&
792 bfh->bfType == 0x4d42 /* "BM" */)
794 const BITMAPINFO *bmi = (const BITMAPINFO *)(bfh + 1);
795 HBITMAP hbmp;
796 HDC hdc = GetDC(0);
798 if ((hbmp = CreateDIBitmap( hdc, &bmi->bmiHeader, CBM_INIT,
799 (const BYTE *)data + bfh->bfOffBits, bmi, DIB_RGB_COLORS )))
801 hClipData = create_dib_from_bitmap( hbmp );
802 DeleteObject(hbmp);
804 ReleaseDC(0, hdc);
806 return hClipData;
810 /**************************************************************************
811 * import_enhmetafile
813 static HANDLE import_enhmetafile( Atom type, const void *data, size_t size )
815 return SetEnhMetaFileBits( size, data );
819 /**************************************************************************
820 * import_text_uri_list
822 * Import text/uri-list.
824 static HANDLE import_text_uri_list( Atom type, const void *data, size_t size )
826 const char *uriList = data;
827 char *uri;
828 WCHAR *path;
829 WCHAR *out = NULL;
830 int total = 0;
831 int capacity = 4096;
832 int start = 0;
833 int end = 0;
834 DROPFILES *dropFiles = NULL;
836 if (!(out = HeapAlloc(GetProcessHeap(), 0, capacity * sizeof(WCHAR)))) return 0;
838 while (end < size)
840 while (end < size && uriList[end] != '\r')
841 ++end;
842 if (end < (size - 1) && uriList[end+1] != '\n')
844 WARN("URI list line doesn't end in \\r\\n\n");
845 break;
848 uri = HeapAlloc(GetProcessHeap(), 0, end - start + 1);
849 if (uri == NULL)
850 break;
851 lstrcpynA(uri, &uriList[start], end - start + 1);
852 path = uri_to_dos(uri);
853 TRACE("converted URI %s to DOS path %s\n", debugstr_a(uri), debugstr_w(path));
854 HeapFree(GetProcessHeap(), 0, uri);
856 if (path)
858 int pathSize = strlenW(path) + 1;
859 if (pathSize > capacity - total)
861 capacity = 2*capacity + pathSize;
862 out = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, out, (capacity + 1)*sizeof(WCHAR));
863 if (out == NULL)
864 goto done;
866 memcpy(&out[total], path, pathSize * sizeof(WCHAR));
867 total += pathSize;
868 done:
869 HeapFree(GetProcessHeap(), 0, path);
870 if (out == NULL)
871 break;
874 start = end + 2;
875 end = start;
877 if (out && end >= size)
879 if ((dropFiles = GlobalAlloc( GMEM_FIXED, sizeof(DROPFILES) + (total + 1) * sizeof(WCHAR) )))
881 dropFiles->pFiles = sizeof(DROPFILES);
882 dropFiles->pt.x = 0;
883 dropFiles->pt.y = 0;
884 dropFiles->fNC = 0;
885 dropFiles->fWide = TRUE;
886 out[total] = '\0';
887 memcpy( (char*)dropFiles + dropFiles->pFiles, out, (total + 1) * sizeof(WCHAR) );
890 HeapFree(GetProcessHeap(), 0, out);
891 return dropFiles;
895 /**************************************************************************
896 * import_targets
898 * Import TARGETS and mark the corresponding clipboard formats as available.
900 static HANDLE import_targets( Atom type, const void *data, size_t size )
902 UINT i, pos, count = size / sizeof(Atom);
903 const Atom *properties = data;
904 struct clipboard_format *format, **formats;
906 if (type != XA_ATOM && type != x11drv_atom(TARGETS)) return 0;
908 register_x11_formats( properties, count );
910 /* the builtin formats contain duplicates, so allocate some extra space */
911 if (!(formats = HeapAlloc( GetProcessHeap(), 0, (count + NB_BUILTIN_FORMATS) * sizeof(*formats ))))
912 return 0;
914 pos = 0;
915 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
917 for (i = 0; i < count; i++) if (properties[i] == format->atom) break;
918 if (i == count) continue;
919 if (format->import && format->id)
921 TRACE( "property %s -> format %s\n",
922 debugstr_xatom( properties[i] ), debugstr_format( format->id ));
923 SetClipboardData( format->id, 0 );
924 formats[pos++] = format;
926 else TRACE( "property %s (ignoring)\n", debugstr_xatom( properties[i] ));
929 HeapFree( GetProcessHeap(), 0, current_x11_formats );
930 current_x11_formats = formats;
931 nb_current_x11_formats = pos;
932 return (HANDLE)1;
936 /**************************************************************************
937 * import_data
939 * Generic import clipboard data routine.
941 static HANDLE import_data( Atom type, const void *data, size_t size )
943 void *ret = GlobalAlloc( GMEM_FIXED, size );
945 if (ret) memcpy( ret, data, size );
946 return ret;
950 /**************************************************************************
951 * import_selection
953 * Import the specified format from the selection and return a global handle to the data.
955 static HANDLE import_selection( Display *display, Window win, Atom selection,
956 struct clipboard_format *format )
958 unsigned char *data;
959 unsigned long size;
960 Atom prop, type;
961 HANDLE ret;
963 if (!format->import) return 0;
965 TRACE( "import %s from %s win %lx to format %s\n",
966 debugstr_xatom( format->atom ), debugstr_xatom( selection ),
967 win, debugstr_format( format->id ) );
969 if ((prop = convert_selection( display, win, selection, format->atom )) == None)
971 TRACE( "failed to convert selection\n" );
972 return 0;
974 if (!X11DRV_CLIPBOARD_ReadProperty( display, win, prop, &type, &data, &size ))
976 TRACE( "failed to read property\n" );
977 return 0;
979 ret = format->import( type, data, size );
980 HeapFree( GetProcessHeap(), 0, data );
981 return ret;
985 /**************************************************************************
986 * X11DRV_CLIPBOARD_ImportSelection
988 * Import the X selection into the clipboard format registered for the given X target.
990 void X11DRV_CLIPBOARD_ImportSelection( Display *display, Window win, Atom selection,
991 Atom *targets, UINT count,
992 void (*callback)( Atom, UINT, HANDLE ))
994 UINT i;
995 HANDLE handle;
996 struct clipboard_format *format;
998 register_x11_formats( targets, count );
1000 for (i = 0; i < count; i++)
1002 if (!(format = find_x11_format( targets[i] ))) continue;
1003 if (!format->id) continue;
1004 if (!(handle = import_selection( display, win, selection, format ))) continue;
1005 callback( targets[i], format->id, handle );
1010 /**************************************************************************
1011 * render_format
1013 static void render_format( UINT id )
1015 Display *display = thread_display();
1016 unsigned int i;
1017 HANDLE handle = 0;
1019 if (!current_selection) return;
1021 for (i = 0; i < nb_current_x11_formats; i++)
1023 if (current_x11_formats[i]->id != id) continue;
1024 handle = import_selection( display, import_window, current_selection, current_x11_formats[i] );
1025 if (handle) SetClipboardData( id, handle );
1026 break;
1031 /**************************************************************************
1032 * export_data
1034 * Generic export clipboard data routine.
1036 static BOOL export_data( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1038 void *ptr = GlobalLock( handle );
1040 if (!ptr) return FALSE;
1041 put_property( display, win, prop, target, 8, ptr, GlobalSize( handle ));
1042 GlobalUnlock( handle );
1043 return TRUE;
1047 /**************************************************************************
1048 * string_from_unicode_text
1050 * Convert CF_UNICODETEXT data to a string in the specified codepage.
1052 static char *string_from_unicode_text( UINT codepage, HANDLE handle, UINT *size )
1054 UINT i, j;
1055 char *str;
1056 WCHAR *strW = GlobalLock( handle );
1057 UINT lenW = GlobalSize( handle ) / sizeof(WCHAR);
1058 DWORD len = WideCharToMultiByte( codepage, 0, strW, lenW, NULL, 0, NULL, NULL );
1060 if ((str = HeapAlloc( GetProcessHeap(), 0, len )))
1062 WideCharToMultiByte( codepage, 0, strW, lenW, str, len, NULL, NULL);
1063 GlobalUnlock( handle );
1065 /* remove carriage returns */
1066 for (i = j = 0; i < len; i++)
1068 if (str[i] == '\r' && (i == len - 1 || str[i + 1] == '\n')) continue;
1069 str[j++] = str[i];
1071 if (j && !str[j - 1]) j--; /* remove trailing null */
1072 *size = j;
1073 TRACE( "returning %s\n", debugstr_an( str, j ));
1075 GlobalUnlock( handle );
1076 return str;
1080 /**************************************************************************
1081 * export_string
1083 * Export CF_UNICODETEXT converting the string to XA_STRING.
1085 static BOOL export_string( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1087 UINT size;
1088 char *text = string_from_unicode_text( 28591, handle, &size );
1090 if (!text) return FALSE;
1091 put_property( display, win, prop, target, 8, text, size );
1092 HeapFree( GetProcessHeap(), 0, text );
1093 GlobalUnlock( handle );
1094 return TRUE;
1098 /**************************************************************************
1099 * export_utf8_string
1101 * Export CF_UNICODE converting the string to UTF8.
1103 static BOOL export_utf8_string( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1105 UINT size;
1106 char *text = string_from_unicode_text( CP_UTF8, handle, &size );
1108 if (!text) return FALSE;
1109 put_property( display, win, prop, target, 8, text, size );
1110 HeapFree( GetProcessHeap(), 0, text );
1111 GlobalUnlock( handle );
1112 return TRUE;
1116 /**************************************************************************
1117 * export_compound_text
1119 * Export CF_UNICODE to COMPOUND_TEXT
1121 static BOOL export_compound_text( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1123 XTextProperty textprop;
1124 XICCEncodingStyle style;
1125 UINT size;
1126 char *text = string_from_unicode_text( CP_UNIXCP, handle, &size );
1128 if (!text) return FALSE;
1129 if (target == x11drv_atom(COMPOUND_TEXT))
1130 style = XCompoundTextStyle;
1131 else
1132 style = XStdICCTextStyle;
1134 /* Update the X property */
1135 if (XmbTextListToTextProperty( display, &text, 1, style, &textprop ) == Success)
1137 XSetTextProperty( display, win, &textprop, prop );
1138 XFree( textprop.value );
1141 HeapFree( GetProcessHeap(), 0, text );
1142 return TRUE;
1146 /**************************************************************************
1147 * export_pixmap
1149 * Export CF_DIB to XA_PIXMAP.
1151 static BOOL export_pixmap( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1153 Pixmap pixmap;
1154 BITMAPINFO *pbmi;
1155 struct gdi_image_bits bits;
1157 pbmi = GlobalLock( handle );
1158 bits.ptr = (LPBYTE)pbmi + bitmap_info_size( pbmi, DIB_RGB_COLORS );
1159 bits.free = NULL;
1160 bits.is_copy = FALSE;
1161 pixmap = create_pixmap_from_image( 0, &default_visual, pbmi, &bits, DIB_RGB_COLORS );
1162 GlobalUnlock( handle );
1164 put_property( display, win, prop, target, 32, &pixmap, 1 );
1165 /* FIXME: free the pixmap when the property is deleted */
1166 return TRUE;
1170 /**************************************************************************
1171 * export_image_bmp
1173 * Export CF_DIB to image/bmp.
1175 static BOOL export_image_bmp( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1177 LPBYTE dibdata = GlobalLock( handle );
1178 UINT bmpsize;
1179 BITMAPFILEHEADER *bfh;
1181 bmpsize = sizeof(BITMAPFILEHEADER) + GlobalSize( handle );
1182 bfh = HeapAlloc( GetProcessHeap(), 0, bmpsize );
1183 if (bfh)
1185 /* bitmap file header */
1186 bfh->bfType = 0x4d42; /* "BM" */
1187 bfh->bfSize = bmpsize;
1188 bfh->bfReserved1 = 0;
1189 bfh->bfReserved2 = 0;
1190 bfh->bfOffBits = sizeof(BITMAPFILEHEADER) + bitmap_info_size((BITMAPINFO*)dibdata, DIB_RGB_COLORS);
1192 /* rest of bitmap is the same as the packed dib */
1193 memcpy(bfh+1, dibdata, bmpsize-sizeof(BITMAPFILEHEADER));
1195 GlobalUnlock( handle );
1196 put_property( display, win, prop, target, 8, bfh, bmpsize );
1197 HeapFree( GetProcessHeap(), 0, bfh );
1198 return TRUE;
1202 /**************************************************************************
1203 * export_enhmetafile
1205 * Export EnhMetaFile.
1207 static BOOL export_enhmetafile( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1209 unsigned int size;
1210 void *ptr;
1212 if (!(size = GetEnhMetaFileBits( handle, 0, NULL ))) return FALSE;
1213 if (!(ptr = HeapAlloc( GetProcessHeap(), 0, size ))) return FALSE;
1215 GetEnhMetaFileBits( handle, size, ptr );
1216 put_property( display, win, prop, target, 8, ptr, size );
1217 HeapFree( GetProcessHeap(), 0, ptr );
1218 return TRUE;
1222 /**************************************************************************
1223 * get_html_description_field
1225 * Find the value of a field in an HTML Format description.
1227 static LPCSTR get_html_description_field(LPCSTR data, LPCSTR keyword)
1229 LPCSTR pos=data;
1231 while (pos && *pos && *pos != '<')
1233 if (memcmp(pos, keyword, strlen(keyword)) == 0)
1234 return pos+strlen(keyword);
1236 pos = strchr(pos, '\n');
1237 if (pos) pos++;
1240 return NULL;
1244 /**************************************************************************
1245 * export_text_html
1247 * Export HTML Format to text/html.
1249 * FIXME: We should attempt to add an <a base> tag and convert windows paths.
1251 static BOOL export_text_html( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1253 LPCSTR data, field_value;
1254 UINT fragmentstart, fragmentend;
1256 data = GlobalLock( handle );
1258 /* read the important fields */
1259 field_value = get_html_description_field(data, "StartFragment:");
1260 if (!field_value)
1262 ERR("Couldn't find StartFragment value\n");
1263 goto failed;
1265 fragmentstart = atoi(field_value);
1267 field_value = get_html_description_field(data, "EndFragment:");
1268 if (!field_value)
1270 ERR("Couldn't find EndFragment value\n");
1271 goto failed;
1273 fragmentend = atoi(field_value);
1275 /* export only the fragment */
1276 put_property( display, win, prop, target, 8, &data[fragmentstart], fragmentend - fragmentstart );
1277 GlobalUnlock( handle );
1278 return TRUE;
1280 failed:
1281 GlobalUnlock( handle );
1282 return FALSE;
1286 /**************************************************************************
1287 * export_hdrop
1289 * Export CF_HDROP format to text/uri-list.
1291 static BOOL export_hdrop( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1293 UINT i;
1294 UINT numFiles;
1295 char *textUriList;
1296 UINT textUriListSize = 32;
1297 UINT next = 0;
1299 textUriList = HeapAlloc( GetProcessHeap(), 0, textUriListSize );
1300 if (!textUriList) return FALSE;
1301 numFiles = DragQueryFileW( handle, 0xFFFFFFFF, NULL, 0 );
1302 for (i = 0; i < numFiles; i++)
1304 UINT dosFilenameSize;
1305 WCHAR *dosFilename = NULL;
1306 char *unixFilename = NULL;
1307 UINT uriSize;
1308 UINT u;
1310 dosFilenameSize = 1 + DragQueryFileW( handle, i, NULL, 0 );
1311 dosFilename = HeapAlloc(GetProcessHeap(), 0, dosFilenameSize*sizeof(WCHAR));
1312 if (dosFilename == NULL) goto failed;
1313 DragQueryFileW( handle, i, dosFilename, dosFilenameSize );
1314 unixFilename = wine_get_unix_file_name(dosFilename);
1315 HeapFree(GetProcessHeap(), 0, dosFilename);
1316 if (unixFilename == NULL) goto failed;
1317 uriSize = 8 + /* file:/// */
1318 3 * (lstrlenA(unixFilename) - 1) + /* "%xy" per char except first '/' */
1319 2; /* \r\n */
1320 if ((next + uriSize) > textUriListSize)
1322 UINT biggerSize = max( 2 * textUriListSize, next + uriSize );
1323 void *bigger = HeapReAlloc( GetProcessHeap(), 0, textUriList, biggerSize );
1324 if (bigger)
1326 textUriList = bigger;
1327 textUriListSize = biggerSize;
1329 else
1331 HeapFree(GetProcessHeap(), 0, unixFilename);
1332 goto failed;
1335 lstrcpyA(&textUriList[next], "file:///");
1336 next += 8;
1337 /* URL encode everything - unnecessary, but easier/lighter than linking in shlwapi, and can't hurt */
1338 for (u = 1; unixFilename[u]; u++)
1340 static const char hex_table[] = "0123456789abcdef";
1341 textUriList[next++] = '%';
1342 textUriList[next++] = hex_table[unixFilename[u] >> 4];
1343 textUriList[next++] = hex_table[unixFilename[u] & 0xf];
1345 textUriList[next++] = '\r';
1346 textUriList[next++] = '\n';
1347 HeapFree(GetProcessHeap(), 0, unixFilename);
1349 put_property( display, win, prop, target, 8, textUriList, next );
1350 HeapFree( GetProcessHeap(), 0, textUriList );
1351 return TRUE;
1353 failed:
1354 HeapFree( GetProcessHeap(), 0, textUriList );
1355 return FALSE;
1359 /***********************************************************************
1360 * get_clipboard_formats
1362 * Return a list of all formats currently available on the Win32 clipboard.
1363 * Helper for export_targets.
1365 static UINT *get_clipboard_formats( UINT *size )
1367 UINT *ids;
1369 *size = 256;
1370 for (;;)
1372 if (!(ids = HeapAlloc( GetProcessHeap(), 0, *size * sizeof(*ids) ))) return NULL;
1373 if (GetUpdatedClipboardFormats( ids, *size, size )) break;
1374 HeapFree( GetProcessHeap(), 0, ids );
1375 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) return NULL;
1377 register_win32_formats( ids, *size );
1378 return ids;
1382 /***********************************************************************
1383 * is_format_available
1385 * Check if a clipboard format is included in the list.
1386 * Helper for export_targets.
1388 static BOOL is_format_available( UINT format, const UINT *ids, unsigned int count )
1390 while (count--) if (*ids++ == format) return TRUE;
1391 return FALSE;
1395 /***********************************************************************
1396 * export_targets
1398 * Service a TARGETS selection request event
1400 static BOOL export_targets( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1402 struct clipboard_format *format;
1403 UINT pos, count, *formats;
1404 Atom *targets;
1406 if (!(formats = get_clipboard_formats( &count ))) return FALSE;
1408 /* the builtin formats contain duplicates, so allocate some extra space */
1409 if (!(targets = HeapAlloc( GetProcessHeap(), 0, (count + NB_BUILTIN_FORMATS) * sizeof(*targets) )))
1411 HeapFree( GetProcessHeap(), 0, formats );
1412 return FALSE;
1415 pos = 0;
1416 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
1418 if (!format->export) continue;
1419 /* formats with id==0 are always exported */
1420 if (format->id && !is_format_available( format->id, formats, count )) continue;
1421 TRACE( "%d: %s -> %s\n", pos, debugstr_format( format->id ), debugstr_xatom( format->atom ));
1422 targets[pos++] = format->atom;
1425 put_property( display, win, prop, XA_ATOM, 32, targets, pos );
1426 HeapFree( GetProcessHeap(), 0, targets );
1427 HeapFree( GetProcessHeap(), 0, formats );
1428 return TRUE;
1432 /**************************************************************************
1433 * export_selection
1435 * Export selection data, depending on the target type.
1437 static BOOL export_selection( Display *display, Window win, Atom prop, Atom target )
1439 struct clipboard_format *format;
1440 HANDLE handle = 0;
1441 BOOL open = FALSE, ret = FALSE;
1443 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
1445 if (format->atom != target) continue;
1446 if (!format->export) continue;
1447 if (!format->id)
1449 TRACE( "win %lx prop %s target %s\n", win, debugstr_xatom( prop ), debugstr_xatom( target ));
1450 ret = format->export( display, win, prop, target, 0 );
1451 break;
1453 if (!open && !(open = OpenClipboard( clipboard_hwnd )))
1455 ERR( "failed to open clipboard for %s\n", debugstr_xatom( target ));
1456 return FALSE;
1458 if ((handle = GetClipboardData( format->id )))
1460 TRACE( "win %lx prop %s target %s exporting %s %p\n",
1461 win, debugstr_xatom( prop ), debugstr_xatom( target ),
1462 debugstr_format( format->id ), handle );
1464 ret = format->export( display, win, prop, target, handle );
1465 break;
1467 /* keep looking for another Win32 format mapping to the same target */
1469 if (open) CloseClipboard();
1470 return ret;
1474 /***********************************************************************
1475 * export_multiple
1477 * Service a MULTIPLE selection request event
1478 * prop contains a list of (target,property) atom pairs.
1479 * The first atom names a target and the second names a property.
1480 * The effect is as if we have received a sequence of SelectionRequest events
1481 * (one for each atom pair) except that:
1482 * 1. We reply with a SelectionNotify only when all the requested conversions
1483 * have been performed.
1484 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
1485 * we replace the atom in the property by None.
1487 static BOOL export_multiple( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1489 Atom atype;
1490 int aformat;
1491 Atom *list;
1492 unsigned long i, count, failed, remain;
1494 /* Read the MULTIPLE property contents. This should contain a list of
1495 * (target,property) atom pairs.
1497 if (XGetWindowProperty( display, win, prop, 0, 0x3FFF, False, AnyPropertyType, &atype, &aformat,
1498 &count, &remain, (unsigned char**)&list ))
1499 return FALSE;
1501 TRACE( "type %s format %d count %ld remain %ld\n",
1502 debugstr_xatom( atype ), aformat, count, remain );
1505 * Make sure we got what we expect.
1506 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
1507 * in a MULTIPLE selection request should be of type ATOM_PAIR.
1508 * However some X apps(such as XPaint) are not compliant with this and return
1509 * a user defined atom in atype when XGetWindowProperty is called.
1510 * The data *is* an atom pair but is not denoted as such.
1512 if (aformat == 32 /* atype == xAtomPair */ )
1514 for (i = failed = 0; i < count; i += 2)
1516 if (list[i+1] == None) continue;
1517 if (export_selection( display, win, list[i + 1], list[i] )) continue;
1518 failed++;
1519 list[i + 1] = None;
1521 if (failed) put_property( display, win, prop, atype, 32, list, count );
1523 XFree( list );
1524 return TRUE;
1528 /**************************************************************************
1529 * X11DRV_CLIPBOARD_GetProperty
1530 * Gets type, data and size.
1532 static BOOL X11DRV_CLIPBOARD_GetProperty(Display *display, Window w, Atom prop,
1533 Atom *atype, unsigned char** data, unsigned long* datasize)
1535 int aformat;
1536 unsigned long pos = 0, nitems, remain, count;
1537 unsigned char *val = NULL, *buffer;
1539 for (;;)
1541 if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
1542 AnyPropertyType, atype, &aformat, &nitems, &remain, &buffer))
1544 WARN("Failed to read property\n");
1545 HeapFree( GetProcessHeap(), 0, val );
1546 return FALSE;
1549 count = get_property_size( aformat, nitems );
1550 if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
1551 else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
1553 if (!*data)
1555 XFree( buffer );
1556 HeapFree( GetProcessHeap(), 0, val );
1557 return FALSE;
1559 val = *data;
1560 memcpy( (int *)val + pos, buffer, count );
1561 XFree( buffer );
1562 if (!remain)
1564 *datasize = pos * sizeof(int) + count;
1565 val[*datasize] = 0;
1566 break;
1568 pos += count / sizeof(int);
1571 TRACE( "got property %s type %s format %u len %lu from window %lx\n",
1572 debugstr_xatom( prop ), debugstr_xatom( *atype ), aformat, *datasize, w );
1574 /* Delete the property on the window now that we are done
1575 * This will send a PropertyNotify event to the selection owner. */
1576 XDeleteProperty(display, w, prop);
1577 return TRUE;
1581 struct clipboard_data_packet {
1582 struct list entry;
1583 unsigned long size;
1584 unsigned char *data;
1587 /**************************************************************************
1588 * X11DRV_CLIPBOARD_ReadProperty
1589 * Reads the contents of the X selection property.
1591 static BOOL X11DRV_CLIPBOARD_ReadProperty( Display *display, Window w, Atom prop,
1592 Atom *type, unsigned char** data, unsigned long* datasize )
1594 XEvent xe;
1596 if (prop == None)
1597 return FALSE;
1599 while (XCheckTypedWindowEvent(display, w, PropertyNotify, &xe))
1602 if (!X11DRV_CLIPBOARD_GetProperty(display, w, prop, type, data, datasize))
1603 return FALSE;
1605 if (*type == x11drv_atom(INCR))
1607 unsigned char *buf;
1608 unsigned long bufsize = 0;
1609 struct list packets;
1610 struct clipboard_data_packet *packet, *packet2;
1611 BOOL res;
1613 HeapFree(GetProcessHeap(), 0, *data);
1614 *data = NULL;
1616 list_init(&packets);
1618 for (;;)
1620 int i;
1621 unsigned char *prop_data;
1622 unsigned long prop_size;
1624 /* Wait until PropertyNotify is received */
1625 for (i = 0; i < SELECTION_RETRIES; i++)
1627 Bool res;
1629 res = XCheckTypedWindowEvent(display, w, PropertyNotify, &xe);
1630 if (res && xe.xproperty.atom == prop &&
1631 xe.xproperty.state == PropertyNewValue)
1632 break;
1633 usleep(SELECTION_WAIT);
1636 if (i >= SELECTION_RETRIES ||
1637 !X11DRV_CLIPBOARD_GetProperty(display, w, prop, type, &prop_data, &prop_size))
1639 res = FALSE;
1640 break;
1643 /* Retrieved entire data. */
1644 if (prop_size == 0)
1646 HeapFree(GetProcessHeap(), 0, prop_data);
1647 res = TRUE;
1648 break;
1651 packet = HeapAlloc(GetProcessHeap(), 0, sizeof(*packet));
1652 if (!packet)
1654 HeapFree(GetProcessHeap(), 0, prop_data);
1655 res = FALSE;
1656 break;
1659 packet->size = prop_size;
1660 packet->data = prop_data;
1661 list_add_tail(&packets, &packet->entry);
1662 bufsize += prop_size;
1665 if (res)
1667 buf = HeapAlloc(GetProcessHeap(), 0, bufsize + 1);
1668 if (buf)
1670 unsigned long bytes_copied = 0;
1671 *datasize = bufsize;
1672 LIST_FOR_EACH_ENTRY( packet, &packets, struct clipboard_data_packet, entry)
1674 memcpy(&buf[bytes_copied], packet->data, packet->size);
1675 bytes_copied += packet->size;
1677 buf[bufsize] = 0;
1678 *data = buf;
1680 else
1681 res = FALSE;
1684 LIST_FOR_EACH_ENTRY_SAFE( packet, packet2, &packets, struct clipboard_data_packet, entry)
1686 HeapFree(GetProcessHeap(), 0, packet->data);
1687 HeapFree(GetProcessHeap(), 0, packet);
1690 return res;
1693 return TRUE;
1697 /**************************************************************************
1698 * acquire_selection
1700 * Acquire the X11 selection when the Win32 clipboard has changed.
1702 static void acquire_selection( Display *display )
1704 if (selection_window) XDestroyWindow( display, selection_window );
1706 selection_window = XCreateWindow( display, root_window, 0, 0, 1, 1, 0, CopyFromParent,
1707 InputOutput, CopyFromParent, 0, NULL );
1708 if (!selection_window) return;
1710 XSetSelectionOwner( display, x11drv_atom(CLIPBOARD), selection_window, CurrentTime );
1711 if (use_primary_selection) XSetSelectionOwner( display, XA_PRIMARY, selection_window, CurrentTime );
1712 TRACE( "win %lx\n", selection_window );
1716 /**************************************************************************
1717 * release_selection
1719 * Release the X11 selection when some other X11 app has grabbed it.
1721 static void release_selection( Display *display, Time time )
1723 assert( selection_window );
1725 TRACE( "win %lx\n", selection_window );
1727 /* release PRIMARY if we still own it */
1728 if (use_primary_selection && XGetSelectionOwner( display, XA_PRIMARY ) == selection_window)
1729 XSetSelectionOwner( display, XA_PRIMARY, None, time );
1731 XDestroyWindow( display, selection_window );
1732 selection_window = 0;
1736 /**************************************************************************
1737 * request_selection_contents
1739 * Retrieve the contents of the X11 selection when it's owned by an X11 app.
1741 static void request_selection_contents( Display *display )
1743 struct clipboard_format *targets = find_x11_format( x11drv_atom(TARGETS) );
1744 struct clipboard_format *string = find_x11_format( XA_STRING );
1746 assert( targets );
1747 assert( string );
1749 current_selection = 0;
1750 if (use_primary_selection && XGetSelectionOwner( display, XA_PRIMARY ))
1752 if (import_selection( display, import_window, XA_PRIMARY, targets ))
1753 current_selection = XA_PRIMARY;
1754 else
1755 import_selection( display, import_window, XA_PRIMARY, string );
1757 else if (XGetSelectionOwner( display, x11drv_atom(CLIPBOARD) ))
1759 if (import_selection( display, import_window, x11drv_atom(CLIPBOARD), targets ))
1760 current_selection = x11drv_atom(CLIPBOARD);
1761 else
1762 import_selection( display, import_window, x11drv_atom(CLIPBOARD), string );
1767 /**************************************************************************
1768 * grab_win32_clipboard
1770 * Grab the Win32 clipboard when an X11 app has grabbed the X11 selection,
1771 * and fill it with the selection contents.
1773 static BOOL grab_win32_clipboard( Display *display )
1775 if (!OpenClipboard( clipboard_hwnd )) return FALSE;
1776 EmptyClipboard();
1777 is_clipboard_owner = TRUE;
1778 last_clipboard_update = GetTickCount64();
1779 request_selection_contents( display );
1780 CloseClipboard();
1781 return TRUE;
1785 /**************************************************************************
1786 * update_clipboard
1788 * Periodically update the clipboard while the selection is owned by an X11 app.
1790 BOOL update_clipboard( HWND hwnd )
1792 if (hwnd != clipboard_hwnd) return TRUE;
1793 if (!is_clipboard_owner) return TRUE;
1794 if (GetTickCount64() - last_clipboard_update <= SELECTION_UPDATE_DELAY) return TRUE;
1795 return grab_win32_clipboard( thread_display() );
1799 /**************************************************************************
1800 * clipboard_wndproc
1802 * Window procedure for the clipboard manager.
1804 static LRESULT CALLBACK clipboard_wndproc( HWND hwnd, UINT msg, WPARAM wp, LPARAM lp )
1806 switch (msg)
1808 case WM_NCCREATE:
1809 return TRUE;
1810 case WM_CLIPBOARDUPDATE:
1811 if (is_clipboard_owner) break; /* ignore our own changes */
1812 acquire_selection( thread_init_display() );
1813 break;
1814 case WM_RENDERFORMAT:
1815 render_format( wp );
1816 break;
1817 case WM_DESTROYCLIPBOARD:
1818 TRACE( "WM_DESTROYCLIPBOARD: lost ownership\n" );
1819 is_clipboard_owner = FALSE;
1820 break;
1822 return DefWindowProcW( hwnd, msg, wp, lp );
1826 /**************************************************************************
1827 * wait_clipboard_mutex
1829 * Make sure that there's only one clipboard thread per window station.
1831 static BOOL wait_clipboard_mutex(void)
1833 static const WCHAR prefix[] = {'_','_','w','i','n','e','_','c','l','i','p','b','o','a','r','d','_'};
1834 WCHAR buffer[MAX_PATH + sizeof(prefix) / sizeof(WCHAR)];
1835 HANDLE mutex;
1837 memcpy( buffer, prefix, sizeof(prefix) );
1838 if (!GetUserObjectInformationW( GetProcessWindowStation(), UOI_NAME,
1839 buffer + sizeof(prefix) / sizeof(WCHAR),
1840 sizeof(buffer) - sizeof(prefix), NULL ))
1842 ERR( "failed to get winstation name\n" );
1843 return FALSE;
1845 mutex = CreateMutexW( NULL, TRUE, buffer );
1846 if (GetLastError() == ERROR_ALREADY_EXISTS)
1848 TRACE( "waiting for mutex %s\n", debugstr_w( buffer ));
1849 WaitForSingleObject( mutex, INFINITE );
1851 return TRUE;
1855 /**************************************************************************
1856 * clipboard_thread
1858 * Thread running inside the desktop process to manage the clipboard
1860 static DWORD WINAPI clipboard_thread( void *arg )
1862 static const WCHAR clipboard_classname[] = {'_','_','w','i','n','e','_','c','l','i','p','b','o','a','r','d','_','m','a','n','a','g','e','r',0};
1863 XSetWindowAttributes attr;
1864 WNDCLASSW class;
1865 MSG msg;
1867 if (!wait_clipboard_mutex()) return 0;
1869 clipboard_display = thread_init_display();
1870 attr.event_mask = PropertyChangeMask;
1871 import_window = XCreateWindow( clipboard_display, root_window, 0, 0, 1, 1, 0, CopyFromParent,
1872 InputOutput, CopyFromParent, CWEventMask, &attr );
1873 if (!import_window)
1875 ERR( "failed to create import window\n" );
1876 return 0;
1879 memset( &class, 0, sizeof(class) );
1880 class.lpfnWndProc = clipboard_wndproc;
1881 class.lpszClassName = clipboard_classname;
1883 if (!RegisterClassW( &class ) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS)
1885 ERR( "could not register clipboard window class err %u\n", GetLastError() );
1886 return 0;
1888 if (!(clipboard_hwnd = CreateWindowW( clipboard_classname, NULL, 0, 0, 0, 0, 0,
1889 HWND_MESSAGE, 0, 0, NULL )))
1891 ERR( "failed to create clipboard window err %u\n", GetLastError() );
1892 return 0;
1895 clipboard_thread_id = GetCurrentThreadId();
1896 AddClipboardFormatListener( clipboard_hwnd );
1897 register_builtin_formats();
1898 grab_win32_clipboard( clipboard_display );
1900 TRACE( "clipboard thread %04x running\n", GetCurrentThreadId() );
1901 while (GetMessageW( &msg, 0, 0, 0 )) DispatchMessageW( &msg );
1902 return 0;
1906 /**************************************************************************
1907 * X11DRV_UpdateClipboard
1909 void CDECL X11DRV_UpdateClipboard(void)
1911 static ULONG last_update;
1912 ULONG now;
1913 DWORD_PTR ret;
1915 if (GetCurrentThreadId() == clipboard_thread_id) return;
1916 now = GetTickCount();
1917 if ((int)(now - last_update) <= SELECTION_UPDATE_DELAY) return;
1918 if (SendMessageTimeoutW( GetClipboardOwner(), WM_X11DRV_UPDATE_CLIPBOARD, 0, 0,
1919 SMTO_ABORTIFHUNG, 5000, &ret ) && ret)
1920 last_update = now;
1924 /***********************************************************************
1925 * X11DRV_HandleSelectionRequest
1927 BOOL X11DRV_SelectionRequest( HWND hwnd, XEvent *xev )
1929 XSelectionRequestEvent *event = &xev->xselectionrequest;
1930 Display *display = event->display;
1931 XEvent result;
1932 Atom rprop = None;
1934 TRACE( "got request on %lx for selection %s target %s win %lx prop %s\n",
1935 event->owner, debugstr_xatom( event->selection ), debugstr_xatom( event->target ),
1936 event->requestor, debugstr_xatom( event->property ));
1938 if (event->owner != selection_window) goto done;
1939 if ((event->selection != x11drv_atom(CLIPBOARD)) &&
1940 (!use_primary_selection || event->selection != XA_PRIMARY)) goto done;
1942 /* If the specified property is None the requestor is an obsolete client.
1943 * We support these by using the specified target atom as the reply property.
1945 rprop = event->property;
1946 if( rprop == None )
1947 rprop = event->target;
1949 if (!export_selection( display, event->requestor, rprop, event->target ))
1950 rprop = None; /* report failure to client */
1952 done:
1953 result.xselection.type = SelectionNotify;
1954 result.xselection.display = display;
1955 result.xselection.requestor = event->requestor;
1956 result.xselection.selection = event->selection;
1957 result.xselection.property = rprop;
1958 result.xselection.target = event->target;
1959 result.xselection.time = event->time;
1960 TRACE( "sending SelectionNotify for %s to %lx\n", debugstr_xatom( rprop ), event->requestor );
1961 XSendEvent( display, event->requestor, False, NoEventMask, &result );
1962 return FALSE;
1966 /***********************************************************************
1967 * X11DRV_SelectionClear
1969 BOOL X11DRV_SelectionClear( HWND hwnd, XEvent *xev )
1971 XSelectionClearEvent *event = &xev->xselectionclear;
1973 if (event->window != selection_window) return FALSE;
1974 if (event->selection != x11drv_atom(CLIPBOARD)) return FALSE;
1976 release_selection( event->display, event->time );
1977 grab_win32_clipboard( event->display );
1978 return FALSE;
1982 /**************************************************************************
1983 * X11DRV_InitClipboard
1985 void X11DRV_InitClipboard(void)
1987 DWORD id;
1988 HANDLE handle = CreateThread( NULL, 0, clipboard_thread, NULL, 0, &id );
1990 if (handle) CloseHandle( handle );
1991 else ERR( "failed to create clipboard thread\n" );