winebus.sys: Implement IOCTL_HID_GET_DEVICE_ATTRIBUTES for hid devices.
[wine.git] / dlls / winex11.drv / clipboard.c
blobf56fd4f2c0c49811c194c6be2e3d6362ef57adad
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( Atom type, const void *data, size_t size );
119 static HANDLE import_text_uri_list( Atom type, const void *data, size_t size );
120 static HANDLE import_targets( Atom type, const void *data, size_t size );
122 static BOOL export_data( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
123 static BOOL export_string( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
124 static BOOL export_utf8_string( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
125 static BOOL export_text( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
126 static BOOL export_compound_text( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
127 static BOOL export_pixmap( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
128 static BOOL export_image_bmp( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
129 static BOOL export_enhmetafile( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
130 static BOOL export_text_html( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
131 static BOOL export_hdrop( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
132 static BOOL export_targets( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
133 static BOOL export_multiple( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
134 static BOOL export_timestamp( Display *display, Window win, Atom prop, Atom target, HANDLE handle );
136 static BOOL X11DRV_CLIPBOARD_ReadProperty( Display *display, Window w, Atom prop,
137 Atom *type, unsigned char **data, unsigned long *datasize );
139 /* Clipboard formats */
141 static const WCHAR RichTextFormatW[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
142 static const WCHAR GIFW[] = {'G','I','F',0};
143 static const WCHAR JFIFW[] = {'J','F','I','F',0};
144 static const WCHAR PNGW[] = {'P','N','G',0};
145 static const WCHAR HTMLFormatW[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
147 static const struct
149 const WCHAR *name;
150 UINT id;
151 UINT data;
152 IMPORTFUNC import;
153 EXPORTFUNC export;
154 } builtin_formats[] =
156 { 0, CF_UNICODETEXT, XATOM_UTF8_STRING, import_utf8_string, export_utf8_string },
157 { 0, CF_UNICODETEXT, XATOM_COMPOUND_TEXT, import_compound_text, export_compound_text },
158 { 0, CF_UNICODETEXT, XA_STRING, import_string, export_string },
159 { 0, CF_UNICODETEXT, XATOM_text_plain, import_string, export_string },
160 { 0, CF_UNICODETEXT, XATOM_TEXT, import_text, export_text },
161 { 0, CF_SYLK, XATOM_WCF_SYLK, import_data, export_data },
162 { 0, CF_DIF, XATOM_WCF_DIF, import_data, export_data },
163 { 0, CF_TIFF, XATOM_WCF_TIFF, import_data, export_data },
164 { 0, CF_DIB, XA_PIXMAP, import_pixmap, export_pixmap },
165 { 0, CF_PENDATA, XATOM_WCF_PENDATA, import_data, export_data },
166 { 0, CF_RIFF, XATOM_WCF_RIFF, import_data, export_data },
167 { 0, CF_WAVE, XATOM_WCF_WAVE, import_data, export_data },
168 { 0, CF_ENHMETAFILE, XATOM_WCF_ENHMETAFILE, import_enhmetafile, export_enhmetafile },
169 { 0, CF_HDROP, XATOM_text_uri_list, import_text_uri_list, export_hdrop },
170 { 0, CF_DIB, XATOM_image_bmp, import_image_bmp, export_image_bmp },
171 { RichTextFormatW, 0, XATOM_text_rtf, import_data, export_data },
172 { RichTextFormatW, 0, XATOM_text_richtext, import_data, export_data },
173 { GIFW, 0, XATOM_image_gif, import_data, export_data },
174 { JFIFW, 0, XATOM_image_jpeg, import_data, export_data },
175 { PNGW, 0, XATOM_image_png, import_data, export_data },
176 { HTMLFormatW, 0, XATOM_HTML_Format, import_data, export_data },
177 { HTMLFormatW, 0, XATOM_text_html, import_data, export_text_html },
178 { 0, 0, XATOM_TARGETS, import_targets, export_targets },
179 { 0, 0, XATOM_MULTIPLE, NULL, export_multiple },
180 { 0, 0, XATOM_TIMESTAMP, NULL, export_timestamp },
183 static struct list format_list = LIST_INIT( format_list );
185 #define NB_BUILTIN_FORMATS (sizeof(builtin_formats) / sizeof(builtin_formats[0]))
186 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
188 static DWORD clipboard_thread_id;
189 static HWND clipboard_hwnd;
190 static BOOL is_clipboard_owner;
191 static Window selection_window;
192 static Window import_window;
193 static Atom current_selection;
194 static ULONG64 last_clipboard_update;
195 static struct clipboard_format **current_x11_formats;
196 static unsigned int nb_current_x11_formats;
198 Display *clipboard_display = NULL;
200 static const char *debugstr_format( UINT id )
202 WCHAR buffer[256];
204 if (GetClipboardFormatNameW( id, buffer, 256 ))
205 return wine_dbg_sprintf( "%04x %s", id, debugstr_w(buffer) );
207 switch (id)
209 case 0: return "(none)";
210 #define BUILTIN(id) case id: return #id;
211 BUILTIN(CF_TEXT)
212 BUILTIN(CF_BITMAP)
213 BUILTIN(CF_METAFILEPICT)
214 BUILTIN(CF_SYLK)
215 BUILTIN(CF_DIF)
216 BUILTIN(CF_TIFF)
217 BUILTIN(CF_OEMTEXT)
218 BUILTIN(CF_DIB)
219 BUILTIN(CF_PALETTE)
220 BUILTIN(CF_PENDATA)
221 BUILTIN(CF_RIFF)
222 BUILTIN(CF_WAVE)
223 BUILTIN(CF_UNICODETEXT)
224 BUILTIN(CF_ENHMETAFILE)
225 BUILTIN(CF_HDROP)
226 BUILTIN(CF_LOCALE)
227 BUILTIN(CF_DIBV5)
228 BUILTIN(CF_OWNERDISPLAY)
229 BUILTIN(CF_DSPTEXT)
230 BUILTIN(CF_DSPBITMAP)
231 BUILTIN(CF_DSPMETAFILEPICT)
232 BUILTIN(CF_DSPENHMETAFILE)
233 #undef BUILTIN
234 default: return wine_dbg_sprintf( "%04x", id );
238 static const char *debugstr_xatom( Atom atom )
240 const char *ret;
241 char *name;
243 if (!atom) return "(None)";
244 name = XGetAtomName( thread_display(), atom );
245 ret = debugstr_a( name );
246 XFree( name );
247 return ret;
251 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
253 return (event->error_code == BadAtom);
257 /**************************************************************************
258 * find_win32_format
260 static struct clipboard_format *find_win32_format( UINT id )
262 struct clipboard_format *format;
264 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
265 if (format->id == id) return format;
266 return NULL;
270 /**************************************************************************
271 * find_x11_format
273 static struct clipboard_format *find_x11_format( Atom atom )
275 struct clipboard_format *format;
277 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
278 if (format->atom == atom) return format;
279 return NULL;
283 /**************************************************************************
284 * register_builtin_formats
286 static void register_builtin_formats(void)
288 struct clipboard_format *formats;
289 unsigned int i;
291 if (!(formats = HeapAlloc( GetProcessHeap(), 0, NB_BUILTIN_FORMATS * sizeof(*formats)))) return;
293 for (i = 0; i < NB_BUILTIN_FORMATS; i++)
295 if (builtin_formats[i].name)
296 formats[i].id = RegisterClipboardFormatW( builtin_formats[i].name );
297 else
298 formats[i].id = builtin_formats[i].id;
300 formats[i].atom = GET_ATOM(builtin_formats[i].data);
301 formats[i].import = builtin_formats[i].import;
302 formats[i].export = builtin_formats[i].export;
303 list_add_tail( &format_list, &formats[i].entry );
308 /**************************************************************************
309 * register_formats
311 static void register_formats( const UINT *ids, const Atom *atoms, unsigned int count )
313 struct clipboard_format *formats;
314 unsigned int i;
316 if (!(formats = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*formats)))) return;
318 for (i = 0; i < count; i++)
320 formats[i].id = ids[i];
321 formats[i].atom = atoms[i];
322 formats[i].import = import_data;
323 formats[i].export = export_data;
324 list_add_tail( &format_list, &formats[i].entry );
325 TRACE( "registered %s atom %s\n", debugstr_format( ids[i] ), debugstr_xatom( atoms[i] ));
330 /**************************************************************************
331 * register_win32_formats
333 * Register Win32 clipboard formats the first time we encounter them.
335 static void register_win32_formats( const UINT *ids, UINT size )
337 unsigned int count, len;
338 UINT new_ids[256];
339 char *names[256];
340 Atom atoms[256];
341 WCHAR buffer[256];
343 if (list_empty( &format_list)) register_builtin_formats();
345 while (size)
347 for (count = 0; count < 256 && size; ids++, size--)
349 if (find_win32_format( *ids )) continue; /* it already exists */
350 if (!GetClipboardFormatNameW( *ids, buffer, 256 )) continue; /* not a named format */
351 if (!(len = WideCharToMultiByte( CP_UNIXCP, 0, buffer, -1, NULL, 0, NULL, NULL ))) continue;
352 if (!(names[count] = HeapAlloc( GetProcessHeap(), 0, len ))) continue;
353 WideCharToMultiByte( CP_UNIXCP, 0, buffer, -1, names[count], len, NULL, NULL );
354 new_ids[count++] = *ids;
356 if (!count) return;
358 XInternAtoms( thread_display(), names, count, False, atoms );
359 register_formats( new_ids, atoms, count );
360 while (count) HeapFree( GetProcessHeap(), 0, names[--count] );
365 /**************************************************************************
366 * register_x11_formats
368 * Register X11 atom formats the first time we encounter them.
370 static void register_x11_formats( const Atom *atoms, UINT size )
372 Display *display = thread_display();
373 unsigned int i, pos, count;
374 char *names[256];
375 UINT ids[256];
376 Atom new_atoms[256];
377 WCHAR buffer[256];
379 if (list_empty( &format_list)) register_builtin_formats();
381 while (size)
383 for (count = 0; count < 256 && size; atoms++, size--)
384 if (!find_x11_format( *atoms )) new_atoms[count++] = *atoms;
386 if (!count) return;
388 X11DRV_expect_error( display, is_atom_error, NULL );
389 if (!XGetAtomNames( display, new_atoms, count, names )) count = 0;
390 if (X11DRV_check_error())
392 WARN( "got some bad atoms, ignoring\n" );
393 count = 0;
396 for (i = pos = 0; i < count; i++)
398 if (MultiByteToWideChar( CP_UNIXCP, 0, names[i], -1, buffer, 256 ) &&
399 (ids[pos] = RegisterClipboardFormatW( buffer )))
400 new_atoms[pos++] = new_atoms[i];
401 XFree( names[i] );
403 register_formats( ids, new_atoms, pos );
408 /**************************************************************************
409 * put_property
411 * Put data as a property on the specified window.
413 static void put_property( Display *display, Window win, Atom prop, Atom type, int format,
414 const void *ptr, size_t size )
416 const unsigned char *data = ptr;
417 int mode = PropModeReplace;
418 size_t width = (format == 32) ? sizeof(long) : format / 8;
419 size_t max_size = XExtendedMaxRequestSize( display ) * 4;
421 if (!max_size) max_size = XMaxRequestSize( display ) * 4;
422 max_size -= 64; /* request overhead */
426 size_t count = min( size, max_size / width );
427 XChangeProperty( display, win, prop, type, format, mode, data, count );
428 mode = PropModeAppend;
429 size -= count;
430 data += count * width;
431 } while (size > 0);
435 /**************************************************************************
436 * convert_selection
438 static Atom convert_selection( Display *display, Window win, Atom selection, Atom target )
440 int i;
441 XEvent event;
443 XConvertSelection( display, selection, target, x11drv_atom(SELECTION_DATA), win, CurrentTime );
445 for (i = 0; i < SELECTION_RETRIES; i++)
447 Bool res = XCheckTypedWindowEvent( display, win, SelectionNotify, &event );
448 if (res && event.xselection.selection == selection && event.xselection.target == target)
449 return event.xselection.property;
450 usleep( SELECTION_WAIT );
452 ERR( "Timed out waiting for SelectionNotify event\n" );
453 return None;
457 /***********************************************************************
458 * bitmap_info_size
460 * Return the size of the bitmap info structure including color table.
462 static int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
464 unsigned int colors, size, masks = 0;
466 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
468 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
469 colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
470 return sizeof(BITMAPCOREHEADER) + colors *
471 ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
473 else /* assume BITMAPINFOHEADER */
475 colors = info->bmiHeader.biClrUsed;
476 if (!colors && (info->bmiHeader.biBitCount <= 8))
477 colors = 1 << info->bmiHeader.biBitCount;
478 if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
479 size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
480 return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
485 /***********************************************************************
486 * create_dib_from_bitmap
488 * Allocates a packed DIB and copies the bitmap data into it.
490 static HGLOBAL create_dib_from_bitmap(HBITMAP hBmp)
492 BITMAP bmp;
493 HDC hdc;
494 HGLOBAL hPackedDIB;
495 LPBYTE pPackedDIB;
496 LPBITMAPINFOHEADER pbmiHeader;
497 unsigned int cDataSize, cPackedSize, OffsetBits;
498 int nLinesCopied;
500 if (!GetObjectW( hBmp, sizeof(bmp), &bmp )) return 0;
503 * A packed DIB contains a BITMAPINFO structure followed immediately by
504 * an optional color palette and the pixel data.
507 /* Calculate the size of the packed DIB */
508 cDataSize = abs( bmp.bmHeight ) * (((bmp.bmWidth * bmp.bmBitsPixel + 31) / 8) & ~3);
509 cPackedSize = sizeof(BITMAPINFOHEADER)
510 + ( (bmp.bmBitsPixel <= 8) ? (sizeof(RGBQUAD) * (1 << bmp.bmBitsPixel)) : 0 )
511 + cDataSize;
512 /* Get the offset to the bits */
513 OffsetBits = cPackedSize - cDataSize;
515 /* Allocate the packed DIB */
516 TRACE("\tAllocating packed DIB of size %d\n", cPackedSize);
517 hPackedDIB = GlobalAlloc( GMEM_FIXED, cPackedSize );
518 if ( !hPackedDIB )
520 WARN("Could not allocate packed DIB!\n");
521 return 0;
524 /* A packed DIB starts with a BITMAPINFOHEADER */
525 pPackedDIB = GlobalLock(hPackedDIB);
526 pbmiHeader = (LPBITMAPINFOHEADER)pPackedDIB;
528 /* Init the BITMAPINFOHEADER */
529 pbmiHeader->biSize = sizeof(BITMAPINFOHEADER);
530 pbmiHeader->biWidth = bmp.bmWidth;
531 pbmiHeader->biHeight = bmp.bmHeight;
532 pbmiHeader->biPlanes = 1;
533 pbmiHeader->biBitCount = bmp.bmBitsPixel;
534 pbmiHeader->biCompression = BI_RGB;
535 pbmiHeader->biSizeImage = 0;
536 pbmiHeader->biXPelsPerMeter = pbmiHeader->biYPelsPerMeter = 0;
537 pbmiHeader->biClrUsed = 0;
538 pbmiHeader->biClrImportant = 0;
540 /* Retrieve the DIB bits from the bitmap and fill in the
541 * DIB color table if present */
542 hdc = GetDC( 0 );
543 nLinesCopied = GetDIBits(hdc, /* Handle to device context */
544 hBmp, /* Handle to bitmap */
545 0, /* First scan line to set in dest bitmap */
546 bmp.bmHeight, /* Number of scan lines to copy */
547 pPackedDIB + OffsetBits, /* [out] Address of array for bitmap bits */
548 (LPBITMAPINFO) pbmiHeader, /* [out] Address of BITMAPINFO structure */
549 0); /* RGB or palette index */
550 GlobalUnlock(hPackedDIB);
551 ReleaseDC( 0, hdc );
553 /* Cleanup if GetDIBits failed */
554 if (nLinesCopied != bmp.bmHeight)
556 TRACE("\tGetDIBits returned %d. Actual lines=%d\n", nLinesCopied, bmp.bmHeight);
557 GlobalFree(hPackedDIB);
558 hPackedDIB = 0;
560 return hPackedDIB;
564 /***********************************************************************
565 * uri_to_dos
567 * Converts a text/uri-list URI to DOS filename.
569 static WCHAR* uri_to_dos(char *encodedURI)
571 WCHAR *ret = NULL;
572 int i;
573 int j = 0;
574 char *uri = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, strlen(encodedURI) + 1);
575 if (uri == NULL)
576 return NULL;
577 for (i = 0; encodedURI[i]; ++i)
579 if (encodedURI[i] == '%')
581 if (encodedURI[i+1] && encodedURI[i+2])
583 char buffer[3];
584 int number;
585 buffer[0] = encodedURI[i+1];
586 buffer[1] = encodedURI[i+2];
587 buffer[2] = '\0';
588 sscanf(buffer, "%x", &number);
589 uri[j++] = number;
590 i += 2;
592 else
594 WARN("invalid URI encoding in %s\n", debugstr_a(encodedURI));
595 HeapFree(GetProcessHeap(), 0, uri);
596 return NULL;
599 else
600 uri[j++] = encodedURI[i];
603 /* Read http://www.freedesktop.org/wiki/Draganddropwarts and cry... */
604 if (strncmp(uri, "file:/", 6) == 0)
606 if (uri[6] == '/')
608 if (uri[7] == '/')
610 /* file:///path/to/file (nautilus, thunar) */
611 ret = wine_get_dos_file_name(&uri[7]);
613 else if (uri[7])
615 /* file://hostname/path/to/file (X file drag spec) */
616 char hostname[256];
617 char *path = strchr(&uri[7], '/');
618 if (path)
620 *path = '\0';
621 if (strcmp(&uri[7], "localhost") == 0)
623 *path = '/';
624 ret = wine_get_dos_file_name(path);
626 else if (gethostname(hostname, sizeof(hostname)) == 0)
628 if (strcmp(hostname, &uri[7]) == 0)
630 *path = '/';
631 ret = wine_get_dos_file_name(path);
637 else if (uri[6])
639 /* file:/path/to/file (konqueror) */
640 ret = wine_get_dos_file_name(&uri[5]);
643 HeapFree(GetProcessHeap(), 0, uri);
644 return ret;
648 /**************************************************************************
649 * unicode_text_from_string
651 * Convert a string in the specified encoding to CF_UNICODETEXT format.
653 static HANDLE unicode_text_from_string( UINT codepage, const void *data, size_t size )
655 DWORD i, j, count;
656 WCHAR *strW;
658 count = MultiByteToWideChar( codepage, 0, data, size, NULL, 0);
660 if (!(strW = GlobalAlloc( GMEM_FIXED, (count * 2 + 1) * sizeof(WCHAR) ))) return 0;
662 MultiByteToWideChar( codepage, 0, data, size, strW + count, count );
663 for (i = j = 0; i < count; i++)
665 if (strW[i + count] == '\n') strW[j++] = '\r';
666 strW[j++] = strW[i + count];
668 strW[j++] = 0;
669 GlobalReAlloc( strW, j * sizeof(WCHAR), GMEM_FIXED ); /* release unused space */
670 TRACE( "returning %s\n", debugstr_wn( strW, j - 1 ));
671 return strW;
675 /**************************************************************************
676 * import_string
678 * Import XA_STRING, converting the string to CF_UNICODETEXT.
680 static HANDLE import_string( Atom type, const void *data, size_t size )
682 return unicode_text_from_string( 28591, data, size );
686 /**************************************************************************
687 * import_utf8_string
689 * Import XA_UTF8_STRING, converting the string to CF_UNICODETEXT.
691 static HANDLE import_utf8_string( Atom type, const void *data, size_t size )
693 return unicode_text_from_string( CP_UTF8, data, size );
697 /**************************************************************************
698 * import_compound_text
700 * Import COMPOUND_TEXT to CF_UNICODETEXT.
702 static HANDLE import_compound_text( Atom type, const void *data, size_t size )
704 char** srcstr;
705 int count;
706 HANDLE ret;
707 XTextProperty txtprop;
709 txtprop.value = (BYTE *)data;
710 txtprop.nitems = size;
711 txtprop.encoding = x11drv_atom(COMPOUND_TEXT);
712 txtprop.format = 8;
713 if (XmbTextPropertyToTextList( thread_display(), &txtprop, &srcstr, &count ) != Success) return 0;
714 if (!count) return 0;
716 ret = unicode_text_from_string( CP_UNIXCP, srcstr[0], strlen(srcstr[0]) + 1 );
717 XFreeStringList(srcstr);
718 return ret;
722 /**************************************************************************
723 * import_text
725 * Import XA_TEXT, converting the string to CF_UNICODETEXT.
727 static HANDLE import_text( Atom type, const void *data, size_t size )
729 if (type == XA_STRING) return import_string( type, data, size );
730 if (type == x11drv_atom(UTF8_STRING)) return import_utf8_string( type, data, size );
731 if (type == x11drv_atom(COMPOUND_TEXT)) return import_compound_text( type, data, size );
732 FIXME( "unsupported TEXT type %s\n", debugstr_xatom( type ));
733 return 0;
737 /**************************************************************************
738 * import_pixmap
740 * Import XA_PIXMAP, converting the image to CF_DIB.
742 static HANDLE import_pixmap( Atom type, const void *data, size_t size )
744 const Pixmap *pPixmap = (const Pixmap *)data;
745 BYTE *ptr = NULL;
746 XVisualInfo vis = default_visual;
747 char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
748 BITMAPINFO *info = (BITMAPINFO *)buffer;
749 struct gdi_image_bits bits;
750 Window root;
751 int x,y; /* Unused */
752 unsigned border_width; /* Unused */
753 unsigned int depth, width, height;
755 /* Get the Pixmap dimensions and bit depth */
756 if (!XGetGeometry(gdi_display, *pPixmap, &root, &x, &y, &width, &height,
757 &border_width, &depth)) depth = 0;
758 if (!pixmap_formats[depth]) return 0;
760 TRACE( "pixmap properties: width=%d, height=%d, depth=%d\n", width, height, depth );
762 if (depth != vis.depth) switch (pixmap_formats[depth]->bits_per_pixel)
764 case 1:
765 case 4:
766 case 8:
767 break;
768 case 16: /* assume R5G5B5 */
769 vis.red_mask = 0x7c00;
770 vis.green_mask = 0x03e0;
771 vis.blue_mask = 0x001f;
772 break;
773 case 24: /* assume R8G8B8 */
774 case 32: /* assume A8R8G8B8 */
775 vis.red_mask = 0xff0000;
776 vis.green_mask = 0x00ff00;
777 vis.blue_mask = 0x0000ff;
778 break;
779 default:
780 return 0;
783 if (!get_pixmap_image( *pPixmap, width, height, &vis, info, &bits ))
785 DWORD info_size = bitmap_info_size( info, DIB_RGB_COLORS );
787 ptr = GlobalAlloc( GMEM_FIXED, info_size + info->bmiHeader.biSizeImage );
788 if (ptr)
790 memcpy( ptr, info, info_size );
791 memcpy( ptr + info_size, bits.ptr, info->bmiHeader.biSizeImage );
793 if (bits.free) bits.free( &bits );
795 return ptr;
799 /**************************************************************************
800 * import_image_bmp
802 * Import image/bmp, converting the image to CF_DIB.
804 static HANDLE import_image_bmp( Atom type, const void *data, size_t size )
806 HANDLE hClipData = 0;
807 const BITMAPFILEHEADER *bfh = data;
809 if (size >= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPCOREHEADER) &&
810 bfh->bfType == 0x4d42 /* "BM" */)
812 const BITMAPINFO *bmi = (const BITMAPINFO *)(bfh + 1);
813 HBITMAP hbmp;
814 HDC hdc = GetDC(0);
816 if ((hbmp = CreateDIBitmap( hdc, &bmi->bmiHeader, CBM_INIT,
817 (const BYTE *)data + bfh->bfOffBits, bmi, DIB_RGB_COLORS )))
819 hClipData = create_dib_from_bitmap( hbmp );
820 DeleteObject(hbmp);
822 ReleaseDC(0, hdc);
824 return hClipData;
828 /**************************************************************************
829 * import_enhmetafile
831 static HANDLE import_enhmetafile( Atom type, const void *data, size_t size )
833 return SetEnhMetaFileBits( size, data );
837 /**************************************************************************
838 * import_text_uri_list
840 * Import text/uri-list.
842 static HANDLE import_text_uri_list( Atom type, const void *data, size_t size )
844 const char *uriList = data;
845 char *uri;
846 WCHAR *path;
847 WCHAR *out = NULL;
848 int total = 0;
849 int capacity = 4096;
850 int start = 0;
851 int end = 0;
852 DROPFILES *dropFiles = NULL;
854 if (!(out = HeapAlloc(GetProcessHeap(), 0, capacity * sizeof(WCHAR)))) return 0;
856 while (end < size)
858 while (end < size && uriList[end] != '\r')
859 ++end;
860 if (end < (size - 1) && uriList[end+1] != '\n')
862 WARN("URI list line doesn't end in \\r\\n\n");
863 break;
866 uri = HeapAlloc(GetProcessHeap(), 0, end - start + 1);
867 if (uri == NULL)
868 break;
869 lstrcpynA(uri, &uriList[start], end - start + 1);
870 path = uri_to_dos(uri);
871 TRACE("converted URI %s to DOS path %s\n", debugstr_a(uri), debugstr_w(path));
872 HeapFree(GetProcessHeap(), 0, uri);
874 if (path)
876 int pathSize = strlenW(path) + 1;
877 if (pathSize > capacity - total)
879 capacity = 2*capacity + pathSize;
880 out = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, out, (capacity + 1)*sizeof(WCHAR));
881 if (out == NULL)
882 goto done;
884 memcpy(&out[total], path, pathSize * sizeof(WCHAR));
885 total += pathSize;
886 done:
887 HeapFree(GetProcessHeap(), 0, path);
888 if (out == NULL)
889 break;
892 start = end + 2;
893 end = start;
895 if (out && end >= size)
897 if ((dropFiles = GlobalAlloc( GMEM_FIXED, sizeof(DROPFILES) + (total + 1) * sizeof(WCHAR) )))
899 dropFiles->pFiles = sizeof(DROPFILES);
900 dropFiles->pt.x = 0;
901 dropFiles->pt.y = 0;
902 dropFiles->fNC = 0;
903 dropFiles->fWide = TRUE;
904 out[total] = '\0';
905 memcpy( (char*)dropFiles + dropFiles->pFiles, out, (total + 1) * sizeof(WCHAR) );
908 HeapFree(GetProcessHeap(), 0, out);
909 return dropFiles;
913 /**************************************************************************
914 * import_targets
916 * Import TARGETS and mark the corresponding clipboard formats as available.
918 static HANDLE import_targets( Atom type, const void *data, size_t size )
920 UINT i, pos, count = size / sizeof(Atom);
921 const Atom *properties = data;
922 struct clipboard_format *format, **formats;
924 if (type != XA_ATOM && type != x11drv_atom(TARGETS)) return 0;
926 register_x11_formats( properties, count );
928 /* the builtin formats contain duplicates, so allocate some extra space */
929 if (!(formats = HeapAlloc( GetProcessHeap(), 0, (count + NB_BUILTIN_FORMATS) * sizeof(*formats ))))
930 return 0;
932 pos = 0;
933 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
935 for (i = 0; i < count; i++) if (properties[i] == format->atom) break;
936 if (i == count) continue;
937 if (format->import && format->id)
939 TRACE( "property %s -> format %s\n",
940 debugstr_xatom( properties[i] ), debugstr_format( format->id ));
941 SetClipboardData( format->id, 0 );
942 formats[pos++] = format;
944 else TRACE( "property %s (ignoring)\n", debugstr_xatom( properties[i] ));
947 HeapFree( GetProcessHeap(), 0, current_x11_formats );
948 current_x11_formats = formats;
949 nb_current_x11_formats = pos;
950 return (HANDLE)1;
954 /**************************************************************************
955 * import_data
957 * Generic import clipboard data routine.
959 static HANDLE import_data( Atom type, const void *data, size_t size )
961 void *ret = GlobalAlloc( GMEM_FIXED, size );
963 if (ret) memcpy( ret, data, size );
964 return ret;
968 /**************************************************************************
969 * import_selection
971 * Import the specified format from the selection and return a global handle to the data.
973 static HANDLE import_selection( Display *display, Window win, Atom selection,
974 struct clipboard_format *format )
976 unsigned char *data;
977 unsigned long size;
978 Atom prop, type;
979 HANDLE ret;
981 if (!format->import) return 0;
983 TRACE( "import %s from %s win %lx to format %s\n",
984 debugstr_xatom( format->atom ), debugstr_xatom( selection ),
985 win, debugstr_format( format->id ) );
987 if ((prop = convert_selection( display, win, selection, format->atom )) == None)
989 TRACE( "failed to convert selection\n" );
990 return 0;
992 if (!X11DRV_CLIPBOARD_ReadProperty( display, win, prop, &type, &data, &size ))
994 TRACE( "failed to read property\n" );
995 return 0;
997 ret = format->import( type, data, size );
998 HeapFree( GetProcessHeap(), 0, data );
999 return ret;
1003 /**************************************************************************
1004 * X11DRV_CLIPBOARD_ImportSelection
1006 * Import the X selection into the clipboard format registered for the given X target.
1008 void X11DRV_CLIPBOARD_ImportSelection( Display *display, Window win, Atom selection,
1009 Atom *targets, UINT count,
1010 void (*callback)( Atom, UINT, HANDLE ))
1012 UINT i;
1013 HANDLE handle;
1014 struct clipboard_format *format;
1016 register_x11_formats( targets, count );
1018 for (i = 0; i < count; i++)
1020 if (!(format = find_x11_format( targets[i] ))) continue;
1021 if (!format->id) continue;
1022 if (!(handle = import_selection( display, win, selection, format ))) continue;
1023 callback( targets[i], format->id, handle );
1028 /**************************************************************************
1029 * render_format
1031 static void render_format( UINT id )
1033 Display *display = thread_display();
1034 unsigned int i;
1035 HANDLE handle = 0;
1037 if (!current_selection) return;
1039 for (i = 0; i < nb_current_x11_formats; i++)
1041 if (current_x11_formats[i]->id != id) continue;
1042 handle = import_selection( display, import_window, current_selection, current_x11_formats[i] );
1043 if (handle) SetClipboardData( id, handle );
1044 break;
1049 /**************************************************************************
1050 * export_data
1052 * Generic export clipboard data routine.
1054 static BOOL export_data( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1056 void *ptr = GlobalLock( handle );
1058 if (!ptr) return FALSE;
1059 put_property( display, win, prop, target, 8, ptr, GlobalSize( handle ));
1060 GlobalUnlock( handle );
1061 return TRUE;
1065 /**************************************************************************
1066 * string_from_unicode_text
1068 * Convert CF_UNICODETEXT data to a string in the specified codepage.
1070 static char *string_from_unicode_text( UINT codepage, HANDLE handle, UINT *size )
1072 UINT i, j;
1073 char *str;
1074 WCHAR *strW = GlobalLock( handle );
1075 UINT lenW = GlobalSize( handle ) / sizeof(WCHAR);
1076 DWORD len = WideCharToMultiByte( codepage, 0, strW, lenW, NULL, 0, NULL, NULL );
1078 if ((str = HeapAlloc( GetProcessHeap(), 0, len )))
1080 WideCharToMultiByte( codepage, 0, strW, lenW, str, len, NULL, NULL);
1081 GlobalUnlock( handle );
1083 /* remove carriage returns */
1084 for (i = j = 0; i < len; i++)
1086 if (str[i] == '\r' && (i == len - 1 || str[i + 1] == '\n')) continue;
1087 str[j++] = str[i];
1089 if (j && !str[j - 1]) j--; /* remove trailing null */
1090 *size = j;
1091 TRACE( "returning %s\n", debugstr_an( str, j ));
1093 GlobalUnlock( handle );
1094 return str;
1098 /**************************************************************************
1099 * export_string
1101 * Export CF_UNICODETEXT converting the string to XA_STRING.
1103 static BOOL export_string( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1105 UINT size;
1106 char *text = string_from_unicode_text( 28591, 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_utf8_string
1119 * Export CF_UNICODE converting the string to UTF8.
1121 static BOOL export_utf8_string( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1123 UINT size;
1124 char *text = string_from_unicode_text( CP_UTF8, handle, &size );
1126 if (!text) return FALSE;
1127 put_property( display, win, prop, target, 8, text, size );
1128 HeapFree( GetProcessHeap(), 0, text );
1129 GlobalUnlock( handle );
1130 return TRUE;
1134 /**************************************************************************
1135 * export_text
1137 * Export CF_UNICODE to the polymorphic TEXT type, using UTF8.
1139 static BOOL export_text( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1141 return export_utf8_string( display, win, prop, x11drv_atom(UTF8_STRING), handle );
1145 /**************************************************************************
1146 * export_compound_text
1148 * Export CF_UNICODE to COMPOUND_TEXT
1150 static BOOL export_compound_text( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1152 XTextProperty textprop;
1153 XICCEncodingStyle style;
1154 UINT size;
1155 char *text = string_from_unicode_text( CP_UNIXCP, handle, &size );
1157 if (!text) return FALSE;
1158 if (target == x11drv_atom(COMPOUND_TEXT))
1159 style = XCompoundTextStyle;
1160 else
1161 style = XStdICCTextStyle;
1163 /* Update the X property */
1164 if (XmbTextListToTextProperty( display, &text, 1, style, &textprop ) == Success)
1166 XSetTextProperty( display, win, &textprop, prop );
1167 XFree( textprop.value );
1170 HeapFree( GetProcessHeap(), 0, text );
1171 return TRUE;
1175 /**************************************************************************
1176 * export_pixmap
1178 * Export CF_DIB to XA_PIXMAP.
1180 static BOOL export_pixmap( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1182 Pixmap pixmap;
1183 BITMAPINFO *pbmi;
1184 struct gdi_image_bits bits;
1186 pbmi = GlobalLock( handle );
1187 bits.ptr = (LPBYTE)pbmi + bitmap_info_size( pbmi, DIB_RGB_COLORS );
1188 bits.free = NULL;
1189 bits.is_copy = FALSE;
1190 pixmap = create_pixmap_from_image( 0, &default_visual, pbmi, &bits, DIB_RGB_COLORS );
1191 GlobalUnlock( handle );
1193 put_property( display, win, prop, target, 32, &pixmap, 1 );
1194 /* FIXME: free the pixmap when the property is deleted */
1195 return TRUE;
1199 /**************************************************************************
1200 * export_image_bmp
1202 * Export CF_DIB to image/bmp.
1204 static BOOL export_image_bmp( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1206 LPBYTE dibdata = GlobalLock( handle );
1207 UINT bmpsize;
1208 BITMAPFILEHEADER *bfh;
1210 bmpsize = sizeof(BITMAPFILEHEADER) + GlobalSize( handle );
1211 bfh = HeapAlloc( GetProcessHeap(), 0, bmpsize );
1212 if (bfh)
1214 /* bitmap file header */
1215 bfh->bfType = 0x4d42; /* "BM" */
1216 bfh->bfSize = bmpsize;
1217 bfh->bfReserved1 = 0;
1218 bfh->bfReserved2 = 0;
1219 bfh->bfOffBits = sizeof(BITMAPFILEHEADER) + bitmap_info_size((BITMAPINFO*)dibdata, DIB_RGB_COLORS);
1221 /* rest of bitmap is the same as the packed dib */
1222 memcpy(bfh+1, dibdata, bmpsize-sizeof(BITMAPFILEHEADER));
1224 GlobalUnlock( handle );
1225 put_property( display, win, prop, target, 8, bfh, bmpsize );
1226 HeapFree( GetProcessHeap(), 0, bfh );
1227 return TRUE;
1231 /**************************************************************************
1232 * export_enhmetafile
1234 * Export EnhMetaFile.
1236 static BOOL export_enhmetafile( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1238 unsigned int size;
1239 void *ptr;
1241 if (!(size = GetEnhMetaFileBits( handle, 0, NULL ))) return FALSE;
1242 if (!(ptr = HeapAlloc( GetProcessHeap(), 0, size ))) return FALSE;
1244 GetEnhMetaFileBits( handle, size, ptr );
1245 put_property( display, win, prop, target, 8, ptr, size );
1246 HeapFree( GetProcessHeap(), 0, ptr );
1247 return TRUE;
1251 /**************************************************************************
1252 * get_html_description_field
1254 * Find the value of a field in an HTML Format description.
1256 static LPCSTR get_html_description_field(LPCSTR data, LPCSTR keyword)
1258 LPCSTR pos=data;
1260 while (pos && *pos && *pos != '<')
1262 if (memcmp(pos, keyword, strlen(keyword)) == 0)
1263 return pos+strlen(keyword);
1265 pos = strchr(pos, '\n');
1266 if (pos) pos++;
1269 return NULL;
1273 /**************************************************************************
1274 * export_text_html
1276 * Export HTML Format to text/html.
1278 * FIXME: We should attempt to add an <a base> tag and convert windows paths.
1280 static BOOL export_text_html( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1282 LPCSTR data, field_value;
1283 UINT fragmentstart, fragmentend;
1285 data = GlobalLock( handle );
1287 /* read the important fields */
1288 field_value = get_html_description_field(data, "StartFragment:");
1289 if (!field_value)
1291 ERR("Couldn't find StartFragment value\n");
1292 goto failed;
1294 fragmentstart = atoi(field_value);
1296 field_value = get_html_description_field(data, "EndFragment:");
1297 if (!field_value)
1299 ERR("Couldn't find EndFragment value\n");
1300 goto failed;
1302 fragmentend = atoi(field_value);
1304 /* export only the fragment */
1305 put_property( display, win, prop, target, 8, &data[fragmentstart], fragmentend - fragmentstart );
1306 GlobalUnlock( handle );
1307 return TRUE;
1309 failed:
1310 GlobalUnlock( handle );
1311 return FALSE;
1315 /**************************************************************************
1316 * export_hdrop
1318 * Export CF_HDROP format to text/uri-list.
1320 static BOOL export_hdrop( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1322 UINT i;
1323 UINT numFiles;
1324 char *textUriList;
1325 UINT textUriListSize = 32;
1326 UINT next = 0;
1328 textUriList = HeapAlloc( GetProcessHeap(), 0, textUriListSize );
1329 if (!textUriList) return FALSE;
1330 numFiles = DragQueryFileW( handle, 0xFFFFFFFF, NULL, 0 );
1331 for (i = 0; i < numFiles; i++)
1333 UINT dosFilenameSize;
1334 WCHAR *dosFilename = NULL;
1335 char *unixFilename = NULL;
1336 UINT uriSize;
1337 UINT u;
1339 dosFilenameSize = 1 + DragQueryFileW( handle, i, NULL, 0 );
1340 dosFilename = HeapAlloc(GetProcessHeap(), 0, dosFilenameSize*sizeof(WCHAR));
1341 if (dosFilename == NULL) goto failed;
1342 DragQueryFileW( handle, i, dosFilename, dosFilenameSize );
1343 unixFilename = wine_get_unix_file_name(dosFilename);
1344 HeapFree(GetProcessHeap(), 0, dosFilename);
1345 if (unixFilename == NULL) goto failed;
1346 uriSize = 8 + /* file:/// */
1347 3 * (lstrlenA(unixFilename) - 1) + /* "%xy" per char except first '/' */
1348 2; /* \r\n */
1349 if ((next + uriSize) > textUriListSize)
1351 UINT biggerSize = max( 2 * textUriListSize, next + uriSize );
1352 void *bigger = HeapReAlloc( GetProcessHeap(), 0, textUriList, biggerSize );
1353 if (bigger)
1355 textUriList = bigger;
1356 textUriListSize = biggerSize;
1358 else
1360 HeapFree(GetProcessHeap(), 0, unixFilename);
1361 goto failed;
1364 lstrcpyA(&textUriList[next], "file:///");
1365 next += 8;
1366 /* URL encode everything - unnecessary, but easier/lighter than linking in shlwapi, and can't hurt */
1367 for (u = 1; unixFilename[u]; u++)
1369 static const char hex_table[] = "0123456789abcdef";
1370 textUriList[next++] = '%';
1371 textUriList[next++] = hex_table[unixFilename[u] >> 4];
1372 textUriList[next++] = hex_table[unixFilename[u] & 0xf];
1374 textUriList[next++] = '\r';
1375 textUriList[next++] = '\n';
1376 HeapFree(GetProcessHeap(), 0, unixFilename);
1378 put_property( display, win, prop, target, 8, textUriList, next );
1379 HeapFree( GetProcessHeap(), 0, textUriList );
1380 return TRUE;
1382 failed:
1383 HeapFree( GetProcessHeap(), 0, textUriList );
1384 return FALSE;
1388 /***********************************************************************
1389 * get_clipboard_formats
1391 * Return a list of all formats currently available on the Win32 clipboard.
1392 * Helper for export_targets.
1394 static UINT *get_clipboard_formats( UINT *size )
1396 UINT *ids;
1398 *size = 256;
1399 for (;;)
1401 if (!(ids = HeapAlloc( GetProcessHeap(), 0, *size * sizeof(*ids) ))) return NULL;
1402 if (GetUpdatedClipboardFormats( ids, *size, size )) break;
1403 HeapFree( GetProcessHeap(), 0, ids );
1404 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) return NULL;
1406 register_win32_formats( ids, *size );
1407 return ids;
1411 /***********************************************************************
1412 * is_format_available
1414 * Check if a clipboard format is included in the list.
1415 * Helper for export_targets.
1417 static BOOL is_format_available( UINT format, const UINT *ids, unsigned int count )
1419 while (count--) if (*ids++ == format) return TRUE;
1420 return FALSE;
1424 /***********************************************************************
1425 * export_targets
1427 * Service a TARGETS selection request event
1429 static BOOL export_targets( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1431 struct clipboard_format *format;
1432 UINT pos, count, *formats;
1433 Atom *targets;
1435 if (!(formats = get_clipboard_formats( &count ))) return FALSE;
1437 /* the builtin formats contain duplicates, so allocate some extra space */
1438 if (!(targets = HeapAlloc( GetProcessHeap(), 0, (count + NB_BUILTIN_FORMATS) * sizeof(*targets) )))
1440 HeapFree( GetProcessHeap(), 0, formats );
1441 return FALSE;
1444 pos = 0;
1445 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
1447 if (!format->export) continue;
1448 /* formats with id==0 are always exported */
1449 if (format->id && !is_format_available( format->id, formats, count )) continue;
1450 TRACE( "%d: %s -> %s\n", pos, debugstr_format( format->id ), debugstr_xatom( format->atom ));
1451 targets[pos++] = format->atom;
1454 put_property( display, win, prop, XA_ATOM, 32, targets, pos );
1455 HeapFree( GetProcessHeap(), 0, targets );
1456 HeapFree( GetProcessHeap(), 0, formats );
1457 return TRUE;
1461 /**************************************************************************
1462 * export_selection
1464 * Export selection data, depending on the target type.
1466 static BOOL export_selection( Display *display, Window win, Atom prop, Atom target )
1468 struct clipboard_format *format;
1469 HANDLE handle = 0;
1470 BOOL open = FALSE, ret = FALSE;
1472 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
1474 if (format->atom != target) continue;
1475 if (!format->export) continue;
1476 if (!format->id)
1478 TRACE( "win %lx prop %s target %s\n", win, debugstr_xatom( prop ), debugstr_xatom( target ));
1479 ret = format->export( display, win, prop, target, 0 );
1480 break;
1482 if (!open && !(open = OpenClipboard( clipboard_hwnd )))
1484 ERR( "failed to open clipboard for %s\n", debugstr_xatom( target ));
1485 return FALSE;
1487 if ((handle = GetClipboardData( format->id )))
1489 TRACE( "win %lx prop %s target %s exporting %s %p\n",
1490 win, debugstr_xatom( prop ), debugstr_xatom( target ),
1491 debugstr_format( format->id ), handle );
1493 ret = format->export( display, win, prop, target, handle );
1494 break;
1496 /* keep looking for another Win32 format mapping to the same target */
1498 if (open) CloseClipboard();
1499 return ret;
1503 /***********************************************************************
1504 * export_multiple
1506 * Service a MULTIPLE selection request event
1507 * prop contains a list of (target,property) atom pairs.
1508 * The first atom names a target and the second names a property.
1509 * The effect is as if we have received a sequence of SelectionRequest events
1510 * (one for each atom pair) except that:
1511 * 1. We reply with a SelectionNotify only when all the requested conversions
1512 * have been performed.
1513 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
1514 * we replace the atom in the property by None.
1516 static BOOL export_multiple( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1518 Atom atype;
1519 int aformat;
1520 Atom *list;
1521 unsigned long i, count, failed, remain;
1523 /* Read the MULTIPLE property contents. This should contain a list of
1524 * (target,property) atom pairs.
1526 if (XGetWindowProperty( display, win, prop, 0, 0x3FFF, False, AnyPropertyType, &atype, &aformat,
1527 &count, &remain, (unsigned char**)&list ))
1528 return FALSE;
1530 TRACE( "type %s format %d count %ld remain %ld\n",
1531 debugstr_xatom( atype ), aformat, count, remain );
1534 * Make sure we got what we expect.
1535 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
1536 * in a MULTIPLE selection request should be of type ATOM_PAIR.
1537 * However some X apps(such as XPaint) are not compliant with this and return
1538 * a user defined atom in atype when XGetWindowProperty is called.
1539 * The data *is* an atom pair but is not denoted as such.
1541 if (aformat == 32 /* atype == xAtomPair */ )
1543 for (i = failed = 0; i < count; i += 2)
1545 if (list[i+1] == None) continue;
1546 if (export_selection( display, win, list[i + 1], list[i] )) continue;
1547 failed++;
1548 list[i + 1] = None;
1550 if (failed) put_property( display, win, prop, atype, 32, list, count );
1552 XFree( list );
1553 return TRUE;
1557 /***********************************************************************
1558 * export_timestamp
1560 * Export the timestamp that was used to acquire the selection
1562 static BOOL export_timestamp( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1564 Time time = CurrentTime; /* FIXME */
1565 put_property( display, win, prop, XA_INTEGER, 32, &time, 1 );
1566 return TRUE;
1570 /**************************************************************************
1571 * X11DRV_CLIPBOARD_GetProperty
1572 * Gets type, data and size.
1574 static BOOL X11DRV_CLIPBOARD_GetProperty(Display *display, Window w, Atom prop,
1575 Atom *atype, unsigned char** data, unsigned long* datasize)
1577 int aformat;
1578 unsigned long pos = 0, nitems, remain, count;
1579 unsigned char *val = NULL, *buffer;
1581 for (;;)
1583 if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
1584 AnyPropertyType, atype, &aformat, &nitems, &remain, &buffer))
1586 WARN("Failed to read property\n");
1587 HeapFree( GetProcessHeap(), 0, val );
1588 return FALSE;
1591 count = get_property_size( aformat, nitems );
1592 if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
1593 else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
1595 if (!*data)
1597 XFree( buffer );
1598 HeapFree( GetProcessHeap(), 0, val );
1599 return FALSE;
1601 val = *data;
1602 memcpy( (int *)val + pos, buffer, count );
1603 XFree( buffer );
1604 if (!remain)
1606 *datasize = pos * sizeof(int) + count;
1607 val[*datasize] = 0;
1608 break;
1610 pos += count / sizeof(int);
1613 TRACE( "got property %s type %s format %u len %lu from window %lx\n",
1614 debugstr_xatom( prop ), debugstr_xatom( *atype ), aformat, *datasize, w );
1616 /* Delete the property on the window now that we are done
1617 * This will send a PropertyNotify event to the selection owner. */
1618 XDeleteProperty(display, w, prop);
1619 return TRUE;
1623 struct clipboard_data_packet {
1624 struct list entry;
1625 unsigned long size;
1626 unsigned char *data;
1629 /**************************************************************************
1630 * X11DRV_CLIPBOARD_ReadProperty
1631 * Reads the contents of the X selection property.
1633 static BOOL X11DRV_CLIPBOARD_ReadProperty( Display *display, Window w, Atom prop,
1634 Atom *type, unsigned char** data, unsigned long* datasize )
1636 XEvent xe;
1638 if (prop == None)
1639 return FALSE;
1641 while (XCheckTypedWindowEvent(display, w, PropertyNotify, &xe))
1644 if (!X11DRV_CLIPBOARD_GetProperty(display, w, prop, type, data, datasize))
1645 return FALSE;
1647 if (*type == x11drv_atom(INCR))
1649 unsigned char *buf;
1650 unsigned long bufsize = 0;
1651 struct list packets;
1652 struct clipboard_data_packet *packet, *packet2;
1653 BOOL res;
1655 HeapFree(GetProcessHeap(), 0, *data);
1656 *data = NULL;
1658 list_init(&packets);
1660 for (;;)
1662 int i;
1663 unsigned char *prop_data;
1664 unsigned long prop_size;
1666 /* Wait until PropertyNotify is received */
1667 for (i = 0; i < SELECTION_RETRIES; i++)
1669 Bool res;
1671 res = XCheckTypedWindowEvent(display, w, PropertyNotify, &xe);
1672 if (res && xe.xproperty.atom == prop &&
1673 xe.xproperty.state == PropertyNewValue)
1674 break;
1675 usleep(SELECTION_WAIT);
1678 if (i >= SELECTION_RETRIES ||
1679 !X11DRV_CLIPBOARD_GetProperty(display, w, prop, type, &prop_data, &prop_size))
1681 res = FALSE;
1682 break;
1685 /* Retrieved entire data. */
1686 if (prop_size == 0)
1688 HeapFree(GetProcessHeap(), 0, prop_data);
1689 res = TRUE;
1690 break;
1693 packet = HeapAlloc(GetProcessHeap(), 0, sizeof(*packet));
1694 if (!packet)
1696 HeapFree(GetProcessHeap(), 0, prop_data);
1697 res = FALSE;
1698 break;
1701 packet->size = prop_size;
1702 packet->data = prop_data;
1703 list_add_tail(&packets, &packet->entry);
1704 bufsize += prop_size;
1707 if (res)
1709 buf = HeapAlloc(GetProcessHeap(), 0, bufsize + 1);
1710 if (buf)
1712 unsigned long bytes_copied = 0;
1713 *datasize = bufsize;
1714 LIST_FOR_EACH_ENTRY( packet, &packets, struct clipboard_data_packet, entry)
1716 memcpy(&buf[bytes_copied], packet->data, packet->size);
1717 bytes_copied += packet->size;
1719 buf[bufsize] = 0;
1720 *data = buf;
1722 else
1723 res = FALSE;
1726 LIST_FOR_EACH_ENTRY_SAFE( packet, packet2, &packets, struct clipboard_data_packet, entry)
1728 HeapFree(GetProcessHeap(), 0, packet->data);
1729 HeapFree(GetProcessHeap(), 0, packet);
1732 return res;
1735 return TRUE;
1739 /**************************************************************************
1740 * acquire_selection
1742 * Acquire the X11 selection when the Win32 clipboard has changed.
1744 static void acquire_selection( Display *display )
1746 if (selection_window) XDestroyWindow( display, selection_window );
1748 selection_window = XCreateWindow( display, root_window, 0, 0, 1, 1, 0, CopyFromParent,
1749 InputOutput, CopyFromParent, 0, NULL );
1750 if (!selection_window) return;
1752 XSetSelectionOwner( display, x11drv_atom(CLIPBOARD), selection_window, CurrentTime );
1753 if (use_primary_selection) XSetSelectionOwner( display, XA_PRIMARY, selection_window, CurrentTime );
1754 TRACE( "win %lx\n", selection_window );
1758 /**************************************************************************
1759 * release_selection
1761 * Release the X11 selection when some other X11 app has grabbed it.
1763 static void release_selection( Display *display, Time time )
1765 assert( selection_window );
1767 TRACE( "win %lx\n", selection_window );
1769 /* release PRIMARY if we still own it */
1770 if (use_primary_selection && XGetSelectionOwner( display, XA_PRIMARY ) == selection_window)
1771 XSetSelectionOwner( display, XA_PRIMARY, None, time );
1773 XDestroyWindow( display, selection_window );
1774 selection_window = 0;
1778 /**************************************************************************
1779 * request_selection_contents
1781 * Retrieve the contents of the X11 selection when it's owned by an X11 app.
1783 static void request_selection_contents( Display *display )
1785 struct clipboard_format *targets = find_x11_format( x11drv_atom(TARGETS) );
1786 struct clipboard_format *string = find_x11_format( XA_STRING );
1788 assert( targets );
1789 assert( string );
1791 current_selection = 0;
1792 if (use_primary_selection && XGetSelectionOwner( display, XA_PRIMARY ))
1794 if (import_selection( display, import_window, XA_PRIMARY, targets ))
1795 current_selection = XA_PRIMARY;
1796 else
1797 import_selection( display, import_window, XA_PRIMARY, string );
1799 else if (XGetSelectionOwner( display, x11drv_atom(CLIPBOARD) ))
1801 if (import_selection( display, import_window, x11drv_atom(CLIPBOARD), targets ))
1802 current_selection = x11drv_atom(CLIPBOARD);
1803 else
1804 import_selection( display, import_window, x11drv_atom(CLIPBOARD), string );
1809 /**************************************************************************
1810 * grab_win32_clipboard
1812 * Grab the Win32 clipboard when an X11 app has grabbed the X11 selection,
1813 * and fill it with the selection contents.
1815 static BOOL grab_win32_clipboard( Display *display )
1817 if (!OpenClipboard( clipboard_hwnd )) return FALSE;
1818 EmptyClipboard();
1819 is_clipboard_owner = TRUE;
1820 last_clipboard_update = GetTickCount64();
1821 request_selection_contents( display );
1822 CloseClipboard();
1823 return TRUE;
1827 /**************************************************************************
1828 * update_clipboard
1830 * Periodically update the clipboard while the selection is owned by an X11 app.
1832 BOOL update_clipboard( HWND hwnd )
1834 if (hwnd != clipboard_hwnd) return TRUE;
1835 if (!is_clipboard_owner) return TRUE;
1836 if (GetTickCount64() - last_clipboard_update <= SELECTION_UPDATE_DELAY) return TRUE;
1837 return grab_win32_clipboard( thread_display() );
1841 /**************************************************************************
1842 * clipboard_wndproc
1844 * Window procedure for the clipboard manager.
1846 static LRESULT CALLBACK clipboard_wndproc( HWND hwnd, UINT msg, WPARAM wp, LPARAM lp )
1848 switch (msg)
1850 case WM_NCCREATE:
1851 return TRUE;
1852 case WM_CLIPBOARDUPDATE:
1853 if (is_clipboard_owner) break; /* ignore our own changes */
1854 acquire_selection( thread_init_display() );
1855 break;
1856 case WM_RENDERFORMAT:
1857 render_format( wp );
1858 break;
1859 case WM_DESTROYCLIPBOARD:
1860 TRACE( "WM_DESTROYCLIPBOARD: lost ownership\n" );
1861 is_clipboard_owner = FALSE;
1862 break;
1864 return DefWindowProcW( hwnd, msg, wp, lp );
1868 /**************************************************************************
1869 * wait_clipboard_mutex
1871 * Make sure that there's only one clipboard thread per window station.
1873 static BOOL wait_clipboard_mutex(void)
1875 static const WCHAR prefix[] = {'_','_','w','i','n','e','_','c','l','i','p','b','o','a','r','d','_'};
1876 WCHAR buffer[MAX_PATH + sizeof(prefix) / sizeof(WCHAR)];
1877 HANDLE mutex;
1879 memcpy( buffer, prefix, sizeof(prefix) );
1880 if (!GetUserObjectInformationW( GetProcessWindowStation(), UOI_NAME,
1881 buffer + sizeof(prefix) / sizeof(WCHAR),
1882 sizeof(buffer) - sizeof(prefix), NULL ))
1884 ERR( "failed to get winstation name\n" );
1885 return FALSE;
1887 mutex = CreateMutexW( NULL, TRUE, buffer );
1888 if (GetLastError() == ERROR_ALREADY_EXISTS)
1890 TRACE( "waiting for mutex %s\n", debugstr_w( buffer ));
1891 WaitForSingleObject( mutex, INFINITE );
1893 return TRUE;
1897 /**************************************************************************
1898 * clipboard_thread
1900 * Thread running inside the desktop process to manage the clipboard
1902 static DWORD WINAPI clipboard_thread( void *arg )
1904 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};
1905 XSetWindowAttributes attr;
1906 WNDCLASSW class;
1907 MSG msg;
1909 if (!wait_clipboard_mutex()) return 0;
1911 clipboard_display = thread_init_display();
1912 attr.event_mask = PropertyChangeMask;
1913 import_window = XCreateWindow( clipboard_display, root_window, 0, 0, 1, 1, 0, CopyFromParent,
1914 InputOutput, CopyFromParent, CWEventMask, &attr );
1915 if (!import_window)
1917 ERR( "failed to create import window\n" );
1918 return 0;
1921 memset( &class, 0, sizeof(class) );
1922 class.lpfnWndProc = clipboard_wndproc;
1923 class.lpszClassName = clipboard_classname;
1925 if (!RegisterClassW( &class ) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS)
1927 ERR( "could not register clipboard window class err %u\n", GetLastError() );
1928 return 0;
1930 if (!(clipboard_hwnd = CreateWindowW( clipboard_classname, NULL, 0, 0, 0, 0, 0,
1931 HWND_MESSAGE, 0, 0, NULL )))
1933 ERR( "failed to create clipboard window err %u\n", GetLastError() );
1934 return 0;
1937 clipboard_thread_id = GetCurrentThreadId();
1938 AddClipboardFormatListener( clipboard_hwnd );
1939 register_builtin_formats();
1940 grab_win32_clipboard( clipboard_display );
1942 TRACE( "clipboard thread %04x running\n", GetCurrentThreadId() );
1943 while (GetMessageW( &msg, 0, 0, 0 )) DispatchMessageW( &msg );
1944 return 0;
1948 /**************************************************************************
1949 * X11DRV_UpdateClipboard
1951 void CDECL X11DRV_UpdateClipboard(void)
1953 static ULONG last_update;
1954 ULONG now;
1955 DWORD_PTR ret;
1957 if (GetCurrentThreadId() == clipboard_thread_id) return;
1958 now = GetTickCount();
1959 if ((int)(now - last_update) <= SELECTION_UPDATE_DELAY) return;
1960 if (SendMessageTimeoutW( GetClipboardOwner(), WM_X11DRV_UPDATE_CLIPBOARD, 0, 0,
1961 SMTO_ABORTIFHUNG, 5000, &ret ) && ret)
1962 last_update = now;
1966 /***********************************************************************
1967 * X11DRV_HandleSelectionRequest
1969 BOOL X11DRV_SelectionRequest( HWND hwnd, XEvent *xev )
1971 XSelectionRequestEvent *event = &xev->xselectionrequest;
1972 Display *display = event->display;
1973 XEvent result;
1974 Atom rprop = None;
1976 TRACE( "got request on %lx for selection %s target %s win %lx prop %s\n",
1977 event->owner, debugstr_xatom( event->selection ), debugstr_xatom( event->target ),
1978 event->requestor, debugstr_xatom( event->property ));
1980 if (event->owner != selection_window) goto done;
1981 if ((event->selection != x11drv_atom(CLIPBOARD)) &&
1982 (!use_primary_selection || event->selection != XA_PRIMARY)) goto done;
1984 /* If the specified property is None the requestor is an obsolete client.
1985 * We support these by using the specified target atom as the reply property.
1987 rprop = event->property;
1988 if( rprop == None )
1989 rprop = event->target;
1991 if (!export_selection( display, event->requestor, rprop, event->target ))
1992 rprop = None; /* report failure to client */
1994 done:
1995 result.xselection.type = SelectionNotify;
1996 result.xselection.display = display;
1997 result.xselection.requestor = event->requestor;
1998 result.xselection.selection = event->selection;
1999 result.xselection.property = rprop;
2000 result.xselection.target = event->target;
2001 result.xselection.time = event->time;
2002 TRACE( "sending SelectionNotify for %s to %lx\n", debugstr_xatom( rprop ), event->requestor );
2003 XSendEvent( display, event->requestor, False, NoEventMask, &result );
2004 return FALSE;
2008 /***********************************************************************
2009 * X11DRV_SelectionClear
2011 BOOL X11DRV_SelectionClear( HWND hwnd, XEvent *xev )
2013 XSelectionClearEvent *event = &xev->xselectionclear;
2015 if (event->window != selection_window) return FALSE;
2016 if (event->selection != x11drv_atom(CLIPBOARD)) return FALSE;
2018 release_selection( event->display, event->time );
2019 grab_win32_clipboard( event->display );
2020 return FALSE;
2024 /**************************************************************************
2025 * X11DRV_InitClipboard
2027 void X11DRV_InitClipboard(void)
2029 DWORD id;
2030 HANDLE handle = CreateThread( NULL, 0, clipboard_thread, NULL, 0, &id );
2032 if (handle) CloseHandle( handle );
2033 else ERR( "failed to create clipboard thread\n" );