winex11: Don't update the clipboard if the X11 selection hasn't changed.
[wine.git] / dlls / winex11.drv / clipboard.c
blob8afe2c2a882c0f2d95071176659424c3e787f81a
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 read_property( 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 UINT rendered_formats;
195 static ULONG64 last_clipboard_update;
196 static struct clipboard_format **current_x11_formats;
197 static unsigned int nb_current_x11_formats;
199 Display *clipboard_display = NULL;
201 static const char *debugstr_format( UINT id )
203 WCHAR buffer[256];
205 if (GetClipboardFormatNameW( id, buffer, 256 ))
206 return wine_dbg_sprintf( "%04x %s", id, debugstr_w(buffer) );
208 switch (id)
210 case 0: return "(none)";
211 #define BUILTIN(id) case id: return #id;
212 BUILTIN(CF_TEXT)
213 BUILTIN(CF_BITMAP)
214 BUILTIN(CF_METAFILEPICT)
215 BUILTIN(CF_SYLK)
216 BUILTIN(CF_DIF)
217 BUILTIN(CF_TIFF)
218 BUILTIN(CF_OEMTEXT)
219 BUILTIN(CF_DIB)
220 BUILTIN(CF_PALETTE)
221 BUILTIN(CF_PENDATA)
222 BUILTIN(CF_RIFF)
223 BUILTIN(CF_WAVE)
224 BUILTIN(CF_UNICODETEXT)
225 BUILTIN(CF_ENHMETAFILE)
226 BUILTIN(CF_HDROP)
227 BUILTIN(CF_LOCALE)
228 BUILTIN(CF_DIBV5)
229 BUILTIN(CF_OWNERDISPLAY)
230 BUILTIN(CF_DSPTEXT)
231 BUILTIN(CF_DSPBITMAP)
232 BUILTIN(CF_DSPMETAFILEPICT)
233 BUILTIN(CF_DSPENHMETAFILE)
234 #undef BUILTIN
235 default: return wine_dbg_sprintf( "%04x", id );
239 static const char *debugstr_xatom( Atom atom )
241 const char *ret;
242 char *name;
244 if (!atom) return "(None)";
245 name = XGetAtomName( thread_display(), atom );
246 ret = debugstr_a( name );
247 XFree( name );
248 return ret;
252 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
254 return (event->error_code == BadAtom);
258 /**************************************************************************
259 * find_win32_format
261 static struct clipboard_format *find_win32_format( UINT id )
263 struct clipboard_format *format;
265 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
266 if (format->id == id) return format;
267 return NULL;
271 /**************************************************************************
272 * find_x11_format
274 static struct clipboard_format *find_x11_format( Atom atom )
276 struct clipboard_format *format;
278 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
279 if (format->atom == atom) return format;
280 return NULL;
284 /**************************************************************************
285 * register_builtin_formats
287 static void register_builtin_formats(void)
289 struct clipboard_format *formats;
290 unsigned int i;
292 if (!(formats = HeapAlloc( GetProcessHeap(), 0, NB_BUILTIN_FORMATS * sizeof(*formats)))) return;
294 for (i = 0; i < NB_BUILTIN_FORMATS; i++)
296 if (builtin_formats[i].name)
297 formats[i].id = RegisterClipboardFormatW( builtin_formats[i].name );
298 else
299 formats[i].id = builtin_formats[i].id;
301 formats[i].atom = GET_ATOM(builtin_formats[i].data);
302 formats[i].import = builtin_formats[i].import;
303 formats[i].export = builtin_formats[i].export;
304 list_add_tail( &format_list, &formats[i].entry );
309 /**************************************************************************
310 * register_formats
312 static void register_formats( const UINT *ids, const Atom *atoms, unsigned int count )
314 struct clipboard_format *formats;
315 unsigned int i;
317 if (!(formats = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*formats)))) return;
319 for (i = 0; i < count; i++)
321 formats[i].id = ids[i];
322 formats[i].atom = atoms[i];
323 formats[i].import = import_data;
324 formats[i].export = export_data;
325 list_add_tail( &format_list, &formats[i].entry );
326 TRACE( "registered %s atom %s\n", debugstr_format( ids[i] ), debugstr_xatom( atoms[i] ));
331 /**************************************************************************
332 * register_win32_formats
334 * Register Win32 clipboard formats the first time we encounter them.
336 static void register_win32_formats( const UINT *ids, UINT size )
338 unsigned int count, len;
339 UINT new_ids[256];
340 char *names[256];
341 Atom atoms[256];
342 WCHAR buffer[256];
344 if (list_empty( &format_list)) register_builtin_formats();
346 while (size)
348 for (count = 0; count < 256 && size; ids++, size--)
350 if (find_win32_format( *ids )) continue; /* it already exists */
351 if (!GetClipboardFormatNameW( *ids, buffer, 256 )) continue; /* not a named format */
352 if (!(len = WideCharToMultiByte( CP_UNIXCP, 0, buffer, -1, NULL, 0, NULL, NULL ))) continue;
353 if (!(names[count] = HeapAlloc( GetProcessHeap(), 0, len ))) continue;
354 WideCharToMultiByte( CP_UNIXCP, 0, buffer, -1, names[count], len, NULL, NULL );
355 new_ids[count++] = *ids;
357 if (!count) return;
359 XInternAtoms( thread_display(), names, count, False, atoms );
360 register_formats( new_ids, atoms, count );
361 while (count) HeapFree( GetProcessHeap(), 0, names[--count] );
366 /**************************************************************************
367 * register_x11_formats
369 * Register X11 atom formats the first time we encounter them.
371 static void register_x11_formats( const Atom *atoms, UINT size )
373 Display *display = thread_display();
374 unsigned int i, pos, count;
375 char *names[256];
376 UINT ids[256];
377 Atom new_atoms[256];
378 WCHAR buffer[256];
380 if (list_empty( &format_list)) register_builtin_formats();
382 while (size)
384 for (count = 0; count < 256 && size; atoms++, size--)
385 if (!find_x11_format( *atoms )) new_atoms[count++] = *atoms;
387 if (!count) return;
389 X11DRV_expect_error( display, is_atom_error, NULL );
390 if (!XGetAtomNames( display, new_atoms, count, names )) count = 0;
391 if (X11DRV_check_error())
393 WARN( "got some bad atoms, ignoring\n" );
394 count = 0;
397 for (i = pos = 0; i < count; i++)
399 if (MultiByteToWideChar( CP_UNIXCP, 0, names[i], -1, buffer, 256 ) &&
400 (ids[pos] = RegisterClipboardFormatW( buffer )))
401 new_atoms[pos++] = new_atoms[i];
402 XFree( names[i] );
404 register_formats( ids, new_atoms, pos );
409 /**************************************************************************
410 * put_property
412 * Put data as a property on the specified window.
414 static void put_property( Display *display, Window win, Atom prop, Atom type, int format,
415 const void *ptr, size_t size )
417 const unsigned char *data = ptr;
418 int mode = PropModeReplace;
419 size_t width = (format == 32) ? sizeof(long) : format / 8;
420 size_t max_size = XExtendedMaxRequestSize( display ) * 4;
422 if (!max_size) max_size = XMaxRequestSize( display ) * 4;
423 max_size -= 64; /* request overhead */
427 size_t count = min( size, max_size / width );
428 XChangeProperty( display, win, prop, type, format, mode, data, count );
429 mode = PropModeAppend;
430 size -= count;
431 data += count * width;
432 } while (size > 0);
436 /**************************************************************************
437 * convert_selection
439 static BOOL convert_selection( Display *display, Window win, Atom selection,
440 struct clipboard_format *format, Atom *type,
441 unsigned char **data, unsigned long *size )
443 int i;
444 XEvent event;
446 TRACE( "import %s from %s win %lx to format %s\n",
447 debugstr_xatom( format->atom ), debugstr_xatom( selection ),
448 win, debugstr_format( format->id ) );
450 XConvertSelection( display, selection, format->atom, x11drv_atom(SELECTION_DATA), win, CurrentTime );
452 for (i = 0; i < SELECTION_RETRIES; i++)
454 Bool res = XCheckTypedWindowEvent( display, win, SelectionNotify, &event );
455 if (res && event.xselection.selection == selection && event.xselection.target == format->atom)
456 return read_property( display, win, event.xselection.property, type, data, size );
457 usleep( SELECTION_WAIT );
459 ERR( "Timed out waiting for SelectionNotify event\n" );
460 return FALSE;
464 /***********************************************************************
465 * bitmap_info_size
467 * Return the size of the bitmap info structure including color table.
469 static int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
471 unsigned int colors, size, masks = 0;
473 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
475 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
476 colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
477 return sizeof(BITMAPCOREHEADER) + colors *
478 ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
480 else /* assume BITMAPINFOHEADER */
482 colors = info->bmiHeader.biClrUsed;
483 if (!colors && (info->bmiHeader.biBitCount <= 8))
484 colors = 1 << info->bmiHeader.biBitCount;
485 if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
486 size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
487 return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
492 /***********************************************************************
493 * create_dib_from_bitmap
495 * Allocates a packed DIB and copies the bitmap data into it.
497 static HGLOBAL create_dib_from_bitmap(HBITMAP hBmp)
499 BITMAP bmp;
500 HDC hdc;
501 HGLOBAL hPackedDIB;
502 LPBYTE pPackedDIB;
503 LPBITMAPINFOHEADER pbmiHeader;
504 unsigned int cDataSize, cPackedSize, OffsetBits;
505 int nLinesCopied;
507 if (!GetObjectW( hBmp, sizeof(bmp), &bmp )) return 0;
510 * A packed DIB contains a BITMAPINFO structure followed immediately by
511 * an optional color palette and the pixel data.
514 /* Calculate the size of the packed DIB */
515 cDataSize = abs( bmp.bmHeight ) * (((bmp.bmWidth * bmp.bmBitsPixel + 31) / 8) & ~3);
516 cPackedSize = sizeof(BITMAPINFOHEADER)
517 + ( (bmp.bmBitsPixel <= 8) ? (sizeof(RGBQUAD) * (1 << bmp.bmBitsPixel)) : 0 )
518 + cDataSize;
519 /* Get the offset to the bits */
520 OffsetBits = cPackedSize - cDataSize;
522 /* Allocate the packed DIB */
523 TRACE("\tAllocating packed DIB of size %d\n", cPackedSize);
524 hPackedDIB = GlobalAlloc( GMEM_FIXED, cPackedSize );
525 if ( !hPackedDIB )
527 WARN("Could not allocate packed DIB!\n");
528 return 0;
531 /* A packed DIB starts with a BITMAPINFOHEADER */
532 pPackedDIB = GlobalLock(hPackedDIB);
533 pbmiHeader = (LPBITMAPINFOHEADER)pPackedDIB;
535 /* Init the BITMAPINFOHEADER */
536 pbmiHeader->biSize = sizeof(BITMAPINFOHEADER);
537 pbmiHeader->biWidth = bmp.bmWidth;
538 pbmiHeader->biHeight = bmp.bmHeight;
539 pbmiHeader->biPlanes = 1;
540 pbmiHeader->biBitCount = bmp.bmBitsPixel;
541 pbmiHeader->biCompression = BI_RGB;
542 pbmiHeader->biSizeImage = 0;
543 pbmiHeader->biXPelsPerMeter = pbmiHeader->biYPelsPerMeter = 0;
544 pbmiHeader->biClrUsed = 0;
545 pbmiHeader->biClrImportant = 0;
547 /* Retrieve the DIB bits from the bitmap and fill in the
548 * DIB color table if present */
549 hdc = GetDC( 0 );
550 nLinesCopied = GetDIBits(hdc, /* Handle to device context */
551 hBmp, /* Handle to bitmap */
552 0, /* First scan line to set in dest bitmap */
553 bmp.bmHeight, /* Number of scan lines to copy */
554 pPackedDIB + OffsetBits, /* [out] Address of array for bitmap bits */
555 (LPBITMAPINFO) pbmiHeader, /* [out] Address of BITMAPINFO structure */
556 0); /* RGB or palette index */
557 GlobalUnlock(hPackedDIB);
558 ReleaseDC( 0, hdc );
560 /* Cleanup if GetDIBits failed */
561 if (nLinesCopied != bmp.bmHeight)
563 TRACE("\tGetDIBits returned %d. Actual lines=%d\n", nLinesCopied, bmp.bmHeight);
564 GlobalFree(hPackedDIB);
565 hPackedDIB = 0;
567 return hPackedDIB;
571 /***********************************************************************
572 * uri_to_dos
574 * Converts a text/uri-list URI to DOS filename.
576 static WCHAR* uri_to_dos(char *encodedURI)
578 WCHAR *ret = NULL;
579 int i;
580 int j = 0;
581 char *uri = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, strlen(encodedURI) + 1);
582 if (uri == NULL)
583 return NULL;
584 for (i = 0; encodedURI[i]; ++i)
586 if (encodedURI[i] == '%')
588 if (encodedURI[i+1] && encodedURI[i+2])
590 char buffer[3];
591 int number;
592 buffer[0] = encodedURI[i+1];
593 buffer[1] = encodedURI[i+2];
594 buffer[2] = '\0';
595 sscanf(buffer, "%x", &number);
596 uri[j++] = number;
597 i += 2;
599 else
601 WARN("invalid URI encoding in %s\n", debugstr_a(encodedURI));
602 HeapFree(GetProcessHeap(), 0, uri);
603 return NULL;
606 else
607 uri[j++] = encodedURI[i];
610 /* Read http://www.freedesktop.org/wiki/Draganddropwarts and cry... */
611 if (strncmp(uri, "file:/", 6) == 0)
613 if (uri[6] == '/')
615 if (uri[7] == '/')
617 /* file:///path/to/file (nautilus, thunar) */
618 ret = wine_get_dos_file_name(&uri[7]);
620 else if (uri[7])
622 /* file://hostname/path/to/file (X file drag spec) */
623 char hostname[256];
624 char *path = strchr(&uri[7], '/');
625 if (path)
627 *path = '\0';
628 if (strcmp(&uri[7], "localhost") == 0)
630 *path = '/';
631 ret = wine_get_dos_file_name(path);
633 else if (gethostname(hostname, sizeof(hostname)) == 0)
635 if (strcmp(hostname, &uri[7]) == 0)
637 *path = '/';
638 ret = wine_get_dos_file_name(path);
644 else if (uri[6])
646 /* file:/path/to/file (konqueror) */
647 ret = wine_get_dos_file_name(&uri[5]);
650 HeapFree(GetProcessHeap(), 0, uri);
651 return ret;
655 /**************************************************************************
656 * unicode_text_from_string
658 * Convert a string in the specified encoding to CF_UNICODETEXT format.
660 static HANDLE unicode_text_from_string( UINT codepage, const void *data, size_t size )
662 DWORD i, j, count;
663 WCHAR *strW;
665 count = MultiByteToWideChar( codepage, 0, data, size, NULL, 0);
667 if (!(strW = GlobalAlloc( GMEM_FIXED, (count * 2 + 1) * sizeof(WCHAR) ))) return 0;
669 MultiByteToWideChar( codepage, 0, data, size, strW + count, count );
670 for (i = j = 0; i < count; i++)
672 if (strW[i + count] == '\n') strW[j++] = '\r';
673 strW[j++] = strW[i + count];
675 strW[j++] = 0;
676 GlobalReAlloc( strW, j * sizeof(WCHAR), GMEM_FIXED ); /* release unused space */
677 TRACE( "returning %s\n", debugstr_wn( strW, j - 1 ));
678 return strW;
682 /**************************************************************************
683 * import_string
685 * Import XA_STRING, converting the string to CF_UNICODETEXT.
687 static HANDLE import_string( Atom type, const void *data, size_t size )
689 return unicode_text_from_string( 28591, data, size );
693 /**************************************************************************
694 * import_utf8_string
696 * Import XA_UTF8_STRING, converting the string to CF_UNICODETEXT.
698 static HANDLE import_utf8_string( Atom type, const void *data, size_t size )
700 return unicode_text_from_string( CP_UTF8, data, size );
704 /**************************************************************************
705 * import_compound_text
707 * Import COMPOUND_TEXT to CF_UNICODETEXT.
709 static HANDLE import_compound_text( Atom type, const void *data, size_t size )
711 char** srcstr;
712 int count;
713 HANDLE ret;
714 XTextProperty txtprop;
716 txtprop.value = (BYTE *)data;
717 txtprop.nitems = size;
718 txtprop.encoding = x11drv_atom(COMPOUND_TEXT);
719 txtprop.format = 8;
720 if (XmbTextPropertyToTextList( thread_display(), &txtprop, &srcstr, &count ) != Success) return 0;
721 if (!count) return 0;
723 ret = unicode_text_from_string( CP_UNIXCP, srcstr[0], strlen(srcstr[0]) + 1 );
724 XFreeStringList(srcstr);
725 return ret;
729 /**************************************************************************
730 * import_text
732 * Import XA_TEXT, converting the string to CF_UNICODETEXT.
734 static HANDLE import_text( Atom type, const void *data, size_t size )
736 if (type == XA_STRING) return import_string( type, data, size );
737 if (type == x11drv_atom(UTF8_STRING)) return import_utf8_string( type, data, size );
738 if (type == x11drv_atom(COMPOUND_TEXT)) return import_compound_text( type, data, size );
739 FIXME( "unsupported TEXT type %s\n", debugstr_xatom( type ));
740 return 0;
744 /**************************************************************************
745 * import_pixmap
747 * Import XA_PIXMAP, converting the image to CF_DIB.
749 static HANDLE import_pixmap( Atom type, const void *data, size_t size )
751 const Pixmap *pPixmap = (const Pixmap *)data;
752 BYTE *ptr = NULL;
753 XVisualInfo vis = default_visual;
754 char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
755 BITMAPINFO *info = (BITMAPINFO *)buffer;
756 struct gdi_image_bits bits;
757 Window root;
758 int x,y; /* Unused */
759 unsigned border_width; /* Unused */
760 unsigned int depth, width, height;
762 /* Get the Pixmap dimensions and bit depth */
763 if (!XGetGeometry(gdi_display, *pPixmap, &root, &x, &y, &width, &height,
764 &border_width, &depth)) depth = 0;
765 if (!pixmap_formats[depth]) return 0;
767 TRACE( "pixmap properties: width=%d, height=%d, depth=%d\n", width, height, depth );
769 if (depth != vis.depth) switch (pixmap_formats[depth]->bits_per_pixel)
771 case 1:
772 case 4:
773 case 8:
774 break;
775 case 16: /* assume R5G5B5 */
776 vis.red_mask = 0x7c00;
777 vis.green_mask = 0x03e0;
778 vis.blue_mask = 0x001f;
779 break;
780 case 24: /* assume R8G8B8 */
781 case 32: /* assume A8R8G8B8 */
782 vis.red_mask = 0xff0000;
783 vis.green_mask = 0x00ff00;
784 vis.blue_mask = 0x0000ff;
785 break;
786 default:
787 return 0;
790 if (!get_pixmap_image( *pPixmap, width, height, &vis, info, &bits ))
792 DWORD info_size = bitmap_info_size( info, DIB_RGB_COLORS );
794 ptr = GlobalAlloc( GMEM_FIXED, info_size + info->bmiHeader.biSizeImage );
795 if (ptr)
797 memcpy( ptr, info, info_size );
798 memcpy( ptr + info_size, bits.ptr, info->bmiHeader.biSizeImage );
800 if (bits.free) bits.free( &bits );
802 return ptr;
806 /**************************************************************************
807 * import_image_bmp
809 * Import image/bmp, converting the image to CF_DIB.
811 static HANDLE import_image_bmp( Atom type, const void *data, size_t size )
813 HANDLE hClipData = 0;
814 const BITMAPFILEHEADER *bfh = data;
816 if (size >= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPCOREHEADER) &&
817 bfh->bfType == 0x4d42 /* "BM" */)
819 const BITMAPINFO *bmi = (const BITMAPINFO *)(bfh + 1);
820 HBITMAP hbmp;
821 HDC hdc = GetDC(0);
823 if ((hbmp = CreateDIBitmap( hdc, &bmi->bmiHeader, CBM_INIT,
824 (const BYTE *)data + bfh->bfOffBits, bmi, DIB_RGB_COLORS )))
826 hClipData = create_dib_from_bitmap( hbmp );
827 DeleteObject(hbmp);
829 ReleaseDC(0, hdc);
831 return hClipData;
835 /**************************************************************************
836 * import_enhmetafile
838 static HANDLE import_enhmetafile( Atom type, const void *data, size_t size )
840 return SetEnhMetaFileBits( size, data );
844 /**************************************************************************
845 * import_text_uri_list
847 * Import text/uri-list.
849 static HANDLE import_text_uri_list( Atom type, const void *data, size_t size )
851 const char *uriList = data;
852 char *uri;
853 WCHAR *path;
854 WCHAR *out = NULL;
855 int total = 0;
856 int capacity = 4096;
857 int start = 0;
858 int end = 0;
859 DROPFILES *dropFiles = NULL;
861 if (!(out = HeapAlloc(GetProcessHeap(), 0, capacity * sizeof(WCHAR)))) return 0;
863 while (end < size)
865 while (end < size && uriList[end] != '\r')
866 ++end;
867 if (end < (size - 1) && uriList[end+1] != '\n')
869 WARN("URI list line doesn't end in \\r\\n\n");
870 break;
873 uri = HeapAlloc(GetProcessHeap(), 0, end - start + 1);
874 if (uri == NULL)
875 break;
876 lstrcpynA(uri, &uriList[start], end - start + 1);
877 path = uri_to_dos(uri);
878 TRACE("converted URI %s to DOS path %s\n", debugstr_a(uri), debugstr_w(path));
879 HeapFree(GetProcessHeap(), 0, uri);
881 if (path)
883 int pathSize = strlenW(path) + 1;
884 if (pathSize > capacity - total)
886 capacity = 2*capacity + pathSize;
887 out = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, out, (capacity + 1)*sizeof(WCHAR));
888 if (out == NULL)
889 goto done;
891 memcpy(&out[total], path, pathSize * sizeof(WCHAR));
892 total += pathSize;
893 done:
894 HeapFree(GetProcessHeap(), 0, path);
895 if (out == NULL)
896 break;
899 start = end + 2;
900 end = start;
902 if (out && end >= size)
904 if ((dropFiles = GlobalAlloc( GMEM_FIXED, sizeof(DROPFILES) + (total + 1) * sizeof(WCHAR) )))
906 dropFiles->pFiles = sizeof(DROPFILES);
907 dropFiles->pt.x = 0;
908 dropFiles->pt.y = 0;
909 dropFiles->fNC = 0;
910 dropFiles->fWide = TRUE;
911 out[total] = '\0';
912 memcpy( (char*)dropFiles + dropFiles->pFiles, out, (total + 1) * sizeof(WCHAR) );
915 HeapFree(GetProcessHeap(), 0, out);
916 return dropFiles;
920 /**************************************************************************
921 * import_targets
923 * Import TARGETS and mark the corresponding clipboard formats as available.
925 static HANDLE import_targets( Atom type, const void *data, size_t size )
927 UINT i, pos, count = size / sizeof(Atom);
928 const Atom *properties = data;
929 struct clipboard_format *format, **formats;
931 if (type != XA_ATOM && type != x11drv_atom(TARGETS)) return 0;
933 register_x11_formats( properties, count );
935 /* the builtin formats contain duplicates, so allocate some extra space */
936 if (!(formats = HeapAlloc( GetProcessHeap(), 0, (count + NB_BUILTIN_FORMATS) * sizeof(*formats ))))
937 return 0;
939 pos = 0;
940 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
942 for (i = 0; i < count; i++) if (properties[i] == format->atom) break;
943 if (i == count) continue;
944 if (format->import && format->id)
946 TRACE( "property %s -> format %s\n",
947 debugstr_xatom( properties[i] ), debugstr_format( format->id ));
948 SetClipboardData( format->id, 0 );
949 formats[pos++] = format;
951 else TRACE( "property %s (ignoring)\n", debugstr_xatom( properties[i] ));
954 HeapFree( GetProcessHeap(), 0, current_x11_formats );
955 current_x11_formats = formats;
956 nb_current_x11_formats = pos;
957 return (HANDLE)1;
961 /**************************************************************************
962 * import_data
964 * Generic import clipboard data routine.
966 static HANDLE import_data( Atom type, const void *data, size_t size )
968 void *ret = GlobalAlloc( GMEM_FIXED, size );
970 if (ret) memcpy( ret, data, size );
971 return ret;
975 /**************************************************************************
976 * import_selection
978 * Import the specified format from the selection and return a global handle to the data.
980 static HANDLE import_selection( Display *display, Window win, Atom selection,
981 struct clipboard_format *format )
983 unsigned char *data;
984 unsigned long size;
985 Atom type;
986 HANDLE ret;
988 if (!format->import) return 0;
990 if (!convert_selection( display, win, selection, format, &type, &data, &size ))
992 TRACE( "failed to convert selection\n" );
993 return 0;
995 ret = format->import( type, data, size );
996 HeapFree( GetProcessHeap(), 0, data );
997 return ret;
1001 /**************************************************************************
1002 * X11DRV_CLIPBOARD_ImportSelection
1004 * Import the X selection into the clipboard format registered for the given X target.
1006 void X11DRV_CLIPBOARD_ImportSelection( Display *display, Window win, Atom selection,
1007 Atom *targets, UINT count,
1008 void (*callback)( Atom, UINT, HANDLE ))
1010 UINT i;
1011 HANDLE handle;
1012 struct clipboard_format *format;
1014 register_x11_formats( targets, count );
1016 for (i = 0; i < count; i++)
1018 if (!(format = find_x11_format( targets[i] ))) continue;
1019 if (!format->id) continue;
1020 if (!(handle = import_selection( display, win, selection, format ))) continue;
1021 callback( targets[i], format->id, handle );
1026 /**************************************************************************
1027 * render_format
1029 static HANDLE render_format( UINT id )
1031 Display *display = thread_display();
1032 unsigned int i;
1033 HANDLE handle = 0;
1035 if (!current_selection) return 0;
1037 for (i = 0; i < nb_current_x11_formats; i++)
1039 if (current_x11_formats[i]->id != id) continue;
1040 handle = import_selection( display, import_window, current_selection, current_x11_formats[i] );
1041 if (handle) SetClipboardData( id, handle );
1042 break;
1044 return handle;
1048 /**************************************************************************
1049 * export_data
1051 * Generic export clipboard data routine.
1053 static BOOL export_data( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1055 void *ptr = GlobalLock( handle );
1057 if (!ptr) return FALSE;
1058 put_property( display, win, prop, target, 8, ptr, GlobalSize( handle ));
1059 GlobalUnlock( handle );
1060 return TRUE;
1064 /**************************************************************************
1065 * string_from_unicode_text
1067 * Convert CF_UNICODETEXT data to a string in the specified codepage.
1069 static char *string_from_unicode_text( UINT codepage, HANDLE handle, UINT *size )
1071 UINT i, j;
1072 char *str;
1073 WCHAR *strW = GlobalLock( handle );
1074 UINT lenW = GlobalSize( handle ) / sizeof(WCHAR);
1075 DWORD len = WideCharToMultiByte( codepage, 0, strW, lenW, NULL, 0, NULL, NULL );
1077 if ((str = HeapAlloc( GetProcessHeap(), 0, len )))
1079 WideCharToMultiByte( codepage, 0, strW, lenW, str, len, NULL, NULL);
1080 GlobalUnlock( handle );
1082 /* remove carriage returns */
1083 for (i = j = 0; i < len; i++)
1085 if (str[i] == '\r' && (i == len - 1 || str[i + 1] == '\n')) continue;
1086 str[j++] = str[i];
1088 if (j && !str[j - 1]) j--; /* remove trailing null */
1089 *size = j;
1090 TRACE( "returning %s\n", debugstr_an( str, j ));
1092 GlobalUnlock( handle );
1093 return str;
1097 /**************************************************************************
1098 * export_string
1100 * Export CF_UNICODETEXT converting the string to XA_STRING.
1102 static BOOL export_string( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1104 UINT size;
1105 char *text = string_from_unicode_text( 28591, handle, &size );
1107 if (!text) return FALSE;
1108 put_property( display, win, prop, target, 8, text, size );
1109 HeapFree( GetProcessHeap(), 0, text );
1110 GlobalUnlock( handle );
1111 return TRUE;
1115 /**************************************************************************
1116 * export_utf8_string
1118 * Export CF_UNICODE converting the string to UTF8.
1120 static BOOL export_utf8_string( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1122 UINT size;
1123 char *text = string_from_unicode_text( CP_UTF8, handle, &size );
1125 if (!text) return FALSE;
1126 put_property( display, win, prop, target, 8, text, size );
1127 HeapFree( GetProcessHeap(), 0, text );
1128 GlobalUnlock( handle );
1129 return TRUE;
1133 /**************************************************************************
1134 * export_text
1136 * Export CF_UNICODE to the polymorphic TEXT type, using UTF8.
1138 static BOOL export_text( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1140 return export_utf8_string( display, win, prop, x11drv_atom(UTF8_STRING), handle );
1144 /**************************************************************************
1145 * export_compound_text
1147 * Export CF_UNICODE to COMPOUND_TEXT
1149 static BOOL export_compound_text( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1151 XTextProperty textprop;
1152 XICCEncodingStyle style;
1153 UINT size;
1154 char *text = string_from_unicode_text( CP_UNIXCP, handle, &size );
1156 if (!text) return FALSE;
1157 if (target == x11drv_atom(COMPOUND_TEXT))
1158 style = XCompoundTextStyle;
1159 else
1160 style = XStdICCTextStyle;
1162 /* Update the X property */
1163 if (XmbTextListToTextProperty( display, &text, 1, style, &textprop ) == Success)
1165 XSetTextProperty( display, win, &textprop, prop );
1166 XFree( textprop.value );
1169 HeapFree( GetProcessHeap(), 0, text );
1170 return TRUE;
1174 /**************************************************************************
1175 * export_pixmap
1177 * Export CF_DIB to XA_PIXMAP.
1179 static BOOL export_pixmap( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1181 Pixmap pixmap;
1182 BITMAPINFO *pbmi;
1183 struct gdi_image_bits bits;
1185 pbmi = GlobalLock( handle );
1186 bits.ptr = (LPBYTE)pbmi + bitmap_info_size( pbmi, DIB_RGB_COLORS );
1187 bits.free = NULL;
1188 bits.is_copy = FALSE;
1189 pixmap = create_pixmap_from_image( 0, &default_visual, pbmi, &bits, DIB_RGB_COLORS );
1190 GlobalUnlock( handle );
1192 put_property( display, win, prop, target, 32, &pixmap, 1 );
1193 /* FIXME: free the pixmap when the property is deleted */
1194 return TRUE;
1198 /**************************************************************************
1199 * export_image_bmp
1201 * Export CF_DIB to image/bmp.
1203 static BOOL export_image_bmp( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1205 LPBYTE dibdata = GlobalLock( handle );
1206 UINT bmpsize;
1207 BITMAPFILEHEADER *bfh;
1209 bmpsize = sizeof(BITMAPFILEHEADER) + GlobalSize( handle );
1210 bfh = HeapAlloc( GetProcessHeap(), 0, bmpsize );
1211 if (bfh)
1213 /* bitmap file header */
1214 bfh->bfType = 0x4d42; /* "BM" */
1215 bfh->bfSize = bmpsize;
1216 bfh->bfReserved1 = 0;
1217 bfh->bfReserved2 = 0;
1218 bfh->bfOffBits = sizeof(BITMAPFILEHEADER) + bitmap_info_size((BITMAPINFO*)dibdata, DIB_RGB_COLORS);
1220 /* rest of bitmap is the same as the packed dib */
1221 memcpy(bfh+1, dibdata, bmpsize-sizeof(BITMAPFILEHEADER));
1223 GlobalUnlock( handle );
1224 put_property( display, win, prop, target, 8, bfh, bmpsize );
1225 HeapFree( GetProcessHeap(), 0, bfh );
1226 return TRUE;
1230 /**************************************************************************
1231 * export_enhmetafile
1233 * Export EnhMetaFile.
1235 static BOOL export_enhmetafile( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1237 unsigned int size;
1238 void *ptr;
1240 if (!(size = GetEnhMetaFileBits( handle, 0, NULL ))) return FALSE;
1241 if (!(ptr = HeapAlloc( GetProcessHeap(), 0, size ))) return FALSE;
1243 GetEnhMetaFileBits( handle, size, ptr );
1244 put_property( display, win, prop, target, 8, ptr, size );
1245 HeapFree( GetProcessHeap(), 0, ptr );
1246 return TRUE;
1250 /**************************************************************************
1251 * get_html_description_field
1253 * Find the value of a field in an HTML Format description.
1255 static LPCSTR get_html_description_field(LPCSTR data, LPCSTR keyword)
1257 LPCSTR pos=data;
1259 while (pos && *pos && *pos != '<')
1261 if (memcmp(pos, keyword, strlen(keyword)) == 0)
1262 return pos+strlen(keyword);
1264 pos = strchr(pos, '\n');
1265 if (pos) pos++;
1268 return NULL;
1272 /**************************************************************************
1273 * export_text_html
1275 * Export HTML Format to text/html.
1277 * FIXME: We should attempt to add an <a base> tag and convert windows paths.
1279 static BOOL export_text_html( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1281 LPCSTR data, field_value;
1282 UINT fragmentstart, fragmentend;
1284 data = GlobalLock( handle );
1286 /* read the important fields */
1287 field_value = get_html_description_field(data, "StartFragment:");
1288 if (!field_value)
1290 ERR("Couldn't find StartFragment value\n");
1291 goto failed;
1293 fragmentstart = atoi(field_value);
1295 field_value = get_html_description_field(data, "EndFragment:");
1296 if (!field_value)
1298 ERR("Couldn't find EndFragment value\n");
1299 goto failed;
1301 fragmentend = atoi(field_value);
1303 /* export only the fragment */
1304 put_property( display, win, prop, target, 8, &data[fragmentstart], fragmentend - fragmentstart );
1305 GlobalUnlock( handle );
1306 return TRUE;
1308 failed:
1309 GlobalUnlock( handle );
1310 return FALSE;
1314 /**************************************************************************
1315 * export_hdrop
1317 * Export CF_HDROP format to text/uri-list.
1319 static BOOL export_hdrop( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1321 UINT i;
1322 UINT numFiles;
1323 char *textUriList;
1324 UINT textUriListSize = 32;
1325 UINT next = 0;
1327 textUriList = HeapAlloc( GetProcessHeap(), 0, textUriListSize );
1328 if (!textUriList) return FALSE;
1329 numFiles = DragQueryFileW( handle, 0xFFFFFFFF, NULL, 0 );
1330 for (i = 0; i < numFiles; i++)
1332 UINT dosFilenameSize;
1333 WCHAR *dosFilename = NULL;
1334 char *unixFilename = NULL;
1335 UINT uriSize;
1336 UINT u;
1338 dosFilenameSize = 1 + DragQueryFileW( handle, i, NULL, 0 );
1339 dosFilename = HeapAlloc(GetProcessHeap(), 0, dosFilenameSize*sizeof(WCHAR));
1340 if (dosFilename == NULL) goto failed;
1341 DragQueryFileW( handle, i, dosFilename, dosFilenameSize );
1342 unixFilename = wine_get_unix_file_name(dosFilename);
1343 HeapFree(GetProcessHeap(), 0, dosFilename);
1344 if (unixFilename == NULL) goto failed;
1345 uriSize = 8 + /* file:/// */
1346 3 * (lstrlenA(unixFilename) - 1) + /* "%xy" per char except first '/' */
1347 2; /* \r\n */
1348 if ((next + uriSize) > textUriListSize)
1350 UINT biggerSize = max( 2 * textUriListSize, next + uriSize );
1351 void *bigger = HeapReAlloc( GetProcessHeap(), 0, textUriList, biggerSize );
1352 if (bigger)
1354 textUriList = bigger;
1355 textUriListSize = biggerSize;
1357 else
1359 HeapFree(GetProcessHeap(), 0, unixFilename);
1360 goto failed;
1363 lstrcpyA(&textUriList[next], "file:///");
1364 next += 8;
1365 /* URL encode everything - unnecessary, but easier/lighter than linking in shlwapi, and can't hurt */
1366 for (u = 1; unixFilename[u]; u++)
1368 static const char hex_table[] = "0123456789abcdef";
1369 textUriList[next++] = '%';
1370 textUriList[next++] = hex_table[unixFilename[u] >> 4];
1371 textUriList[next++] = hex_table[unixFilename[u] & 0xf];
1373 textUriList[next++] = '\r';
1374 textUriList[next++] = '\n';
1375 HeapFree(GetProcessHeap(), 0, unixFilename);
1377 put_property( display, win, prop, target, 8, textUriList, next );
1378 HeapFree( GetProcessHeap(), 0, textUriList );
1379 return TRUE;
1381 failed:
1382 HeapFree( GetProcessHeap(), 0, textUriList );
1383 return FALSE;
1387 /***********************************************************************
1388 * get_clipboard_formats
1390 * Return a list of all formats currently available on the Win32 clipboard.
1391 * Helper for export_targets.
1393 static UINT *get_clipboard_formats( UINT *size )
1395 UINT *ids;
1397 *size = 256;
1398 for (;;)
1400 if (!(ids = HeapAlloc( GetProcessHeap(), 0, *size * sizeof(*ids) ))) return NULL;
1401 if (GetUpdatedClipboardFormats( ids, *size, size )) break;
1402 HeapFree( GetProcessHeap(), 0, ids );
1403 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) return NULL;
1405 register_win32_formats( ids, *size );
1406 return ids;
1410 /***********************************************************************
1411 * is_format_available
1413 * Check if a clipboard format is included in the list.
1414 * Helper for export_targets.
1416 static BOOL is_format_available( UINT format, const UINT *ids, unsigned int count )
1418 while (count--) if (*ids++ == format) return TRUE;
1419 return FALSE;
1423 /***********************************************************************
1424 * export_targets
1426 * Service a TARGETS selection request event
1428 static BOOL export_targets( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1430 struct clipboard_format *format;
1431 UINT pos, count, *formats;
1432 Atom *targets;
1434 if (!(formats = get_clipboard_formats( &count ))) return FALSE;
1436 /* the builtin formats contain duplicates, so allocate some extra space */
1437 if (!(targets = HeapAlloc( GetProcessHeap(), 0, (count + NB_BUILTIN_FORMATS) * sizeof(*targets) )))
1439 HeapFree( GetProcessHeap(), 0, formats );
1440 return FALSE;
1443 pos = 0;
1444 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
1446 if (!format->export) continue;
1447 /* formats with id==0 are always exported */
1448 if (format->id && !is_format_available( format->id, formats, count )) continue;
1449 TRACE( "%d: %s -> %s\n", pos, debugstr_format( format->id ), debugstr_xatom( format->atom ));
1450 targets[pos++] = format->atom;
1453 put_property( display, win, prop, XA_ATOM, 32, targets, pos );
1454 HeapFree( GetProcessHeap(), 0, targets );
1455 HeapFree( GetProcessHeap(), 0, formats );
1456 return TRUE;
1460 /**************************************************************************
1461 * export_selection
1463 * Export selection data, depending on the target type.
1465 static BOOL export_selection( Display *display, Window win, Atom prop, Atom target )
1467 struct clipboard_format *format;
1468 HANDLE handle = 0;
1469 BOOL open = FALSE, ret = FALSE;
1471 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
1473 if (format->atom != target) continue;
1474 if (!format->export) continue;
1475 if (!format->id)
1477 TRACE( "win %lx prop %s target %s\n", win, debugstr_xatom( prop ), debugstr_xatom( target ));
1478 ret = format->export( display, win, prop, target, 0 );
1479 break;
1481 if (!open && !(open = OpenClipboard( clipboard_hwnd )))
1483 ERR( "failed to open clipboard for %s\n", debugstr_xatom( target ));
1484 return FALSE;
1486 if ((handle = GetClipboardData( format->id )))
1488 TRACE( "win %lx prop %s target %s exporting %s %p\n",
1489 win, debugstr_xatom( prop ), debugstr_xatom( target ),
1490 debugstr_format( format->id ), handle );
1492 ret = format->export( display, win, prop, target, handle );
1493 break;
1495 /* keep looking for another Win32 format mapping to the same target */
1497 if (open) CloseClipboard();
1498 return ret;
1502 /***********************************************************************
1503 * export_multiple
1505 * Service a MULTIPLE selection request event
1506 * prop contains a list of (target,property) atom pairs.
1507 * The first atom names a target and the second names a property.
1508 * The effect is as if we have received a sequence of SelectionRequest events
1509 * (one for each atom pair) except that:
1510 * 1. We reply with a SelectionNotify only when all the requested conversions
1511 * have been performed.
1512 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
1513 * we replace the atom in the property by None.
1515 static BOOL export_multiple( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1517 Atom atype;
1518 int aformat;
1519 Atom *list;
1520 unsigned long i, count, failed, remain;
1522 /* Read the MULTIPLE property contents. This should contain a list of
1523 * (target,property) atom pairs.
1525 if (XGetWindowProperty( display, win, prop, 0, 0x3FFF, False, AnyPropertyType, &atype, &aformat,
1526 &count, &remain, (unsigned char**)&list ))
1527 return FALSE;
1529 TRACE( "type %s format %d count %ld remain %ld\n",
1530 debugstr_xatom( atype ), aformat, count, remain );
1533 * Make sure we got what we expect.
1534 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
1535 * in a MULTIPLE selection request should be of type ATOM_PAIR.
1536 * However some X apps(such as XPaint) are not compliant with this and return
1537 * a user defined atom in atype when XGetWindowProperty is called.
1538 * The data *is* an atom pair but is not denoted as such.
1540 if (aformat == 32 /* atype == xAtomPair */ )
1542 for (i = failed = 0; i < count; i += 2)
1544 if (list[i+1] == None) continue;
1545 if (export_selection( display, win, list[i + 1], list[i] )) continue;
1546 failed++;
1547 list[i + 1] = None;
1549 if (failed) put_property( display, win, prop, atype, 32, list, count );
1551 XFree( list );
1552 return TRUE;
1556 /***********************************************************************
1557 * export_timestamp
1559 * Export the timestamp that was used to acquire the selection
1561 static BOOL export_timestamp( Display *display, Window win, Atom prop, Atom target, HANDLE handle )
1563 Time time = CurrentTime; /* FIXME */
1564 put_property( display, win, prop, XA_INTEGER, 32, &time, 1 );
1565 return TRUE;
1569 /**************************************************************************
1570 * X11DRV_CLIPBOARD_GetProperty
1571 * Gets type, data and size.
1573 static BOOL X11DRV_CLIPBOARD_GetProperty(Display *display, Window w, Atom prop,
1574 Atom *atype, unsigned char** data, unsigned long* datasize)
1576 int aformat;
1577 unsigned long pos = 0, nitems, remain, count;
1578 unsigned char *val = NULL, *buffer;
1580 for (;;)
1582 if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
1583 AnyPropertyType, atype, &aformat, &nitems, &remain, &buffer))
1585 WARN("Failed to read property\n");
1586 HeapFree( GetProcessHeap(), 0, val );
1587 return FALSE;
1590 count = get_property_size( aformat, nitems );
1591 if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
1592 else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
1594 if (!*data)
1596 XFree( buffer );
1597 HeapFree( GetProcessHeap(), 0, val );
1598 return FALSE;
1600 val = *data;
1601 memcpy( (int *)val + pos, buffer, count );
1602 XFree( buffer );
1603 if (!remain)
1605 *datasize = pos * sizeof(int) + count;
1606 val[*datasize] = 0;
1607 break;
1609 pos += count / sizeof(int);
1612 TRACE( "got property %s type %s format %u len %lu from window %lx\n",
1613 debugstr_xatom( prop ), debugstr_xatom( *atype ), aformat, *datasize, w );
1615 /* Delete the property on the window now that we are done
1616 * This will send a PropertyNotify event to the selection owner. */
1617 XDeleteProperty(display, w, prop);
1618 return TRUE;
1622 struct clipboard_data_packet {
1623 struct list entry;
1624 unsigned long size;
1625 unsigned char *data;
1628 /**************************************************************************
1629 * read_property
1631 * Reads the contents of the X selection property.
1633 static BOOL read_property( 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 BOOL request_selection_contents( Display *display, BOOL changed )
1785 struct clipboard_format *targets = find_x11_format( x11drv_atom(TARGETS) );
1786 struct clipboard_format *string = find_x11_format( XA_STRING );
1787 struct clipboard_format *format = NULL;
1788 Window owner = 0;
1789 unsigned char *data = NULL;
1790 unsigned long size = 0;
1791 Atom type = 0;
1793 static Atom last_selection;
1794 static Window last_owner;
1795 static struct clipboard_format *last_format;
1796 static Atom last_type;
1797 static unsigned char *last_data;
1798 static unsigned long last_size;
1800 assert( targets );
1801 assert( string );
1803 current_selection = 0;
1804 if (use_primary_selection)
1806 if ((owner = XGetSelectionOwner( display, XA_PRIMARY )))
1807 current_selection = XA_PRIMARY;
1809 if (!current_selection)
1811 if ((owner = XGetSelectionOwner( display, x11drv_atom(CLIPBOARD) )))
1812 current_selection = x11drv_atom(CLIPBOARD);
1815 if (current_selection)
1817 if (convert_selection( display, import_window, current_selection, targets, &type, &data, &size ))
1818 format = targets;
1819 else if (convert_selection( display, import_window, current_selection, string, &type, &data, &size ))
1820 format = string;
1823 changed = (changed ||
1824 rendered_formats ||
1825 last_selection != current_selection ||
1826 last_owner != owner ||
1827 last_format != format ||
1828 last_type != type ||
1829 last_size != size ||
1830 memcmp( last_data, data, size ));
1832 if (!changed)
1834 HeapFree( GetProcessHeap(), 0, data );
1835 return FALSE;
1838 if (!OpenClipboard( clipboard_hwnd )) return FALSE;
1839 TRACE( "selection changed, importing\n" );
1840 EmptyClipboard();
1841 is_clipboard_owner = TRUE;
1842 rendered_formats = 0;
1844 if (format) format->import( type, data, size );
1846 HeapFree( GetProcessHeap(), 0, last_data );
1847 last_selection = current_selection;
1848 last_owner = owner;
1849 last_format = format;
1850 last_type = type;
1851 last_data = data;
1852 last_size = size;
1853 last_clipboard_update = GetTickCount64();
1854 CloseClipboard();
1855 return TRUE;
1859 /**************************************************************************
1860 * update_clipboard
1862 * Periodically update the clipboard while the selection is owned by an X11 app.
1864 BOOL update_clipboard( HWND hwnd )
1866 if (hwnd != clipboard_hwnd) return TRUE;
1867 if (!is_clipboard_owner) return TRUE;
1868 if (GetTickCount64() - last_clipboard_update <= SELECTION_UPDATE_DELAY) return TRUE;
1869 return request_selection_contents( thread_display(), FALSE );
1873 /**************************************************************************
1874 * clipboard_wndproc
1876 * Window procedure for the clipboard manager.
1878 static LRESULT CALLBACK clipboard_wndproc( HWND hwnd, UINT msg, WPARAM wp, LPARAM lp )
1880 switch (msg)
1882 case WM_NCCREATE:
1883 return TRUE;
1884 case WM_CLIPBOARDUPDATE:
1885 if (is_clipboard_owner) break; /* ignore our own changes */
1886 acquire_selection( thread_init_display() );
1887 break;
1888 case WM_RENDERFORMAT:
1889 if (render_format( wp )) rendered_formats++;
1890 break;
1891 case WM_DESTROYCLIPBOARD:
1892 TRACE( "WM_DESTROYCLIPBOARD: lost ownership\n" );
1893 is_clipboard_owner = FALSE;
1894 break;
1896 return DefWindowProcW( hwnd, msg, wp, lp );
1900 /**************************************************************************
1901 * wait_clipboard_mutex
1903 * Make sure that there's only one clipboard thread per window station.
1905 static BOOL wait_clipboard_mutex(void)
1907 static const WCHAR prefix[] = {'_','_','w','i','n','e','_','c','l','i','p','b','o','a','r','d','_'};
1908 WCHAR buffer[MAX_PATH + sizeof(prefix) / sizeof(WCHAR)];
1909 HANDLE mutex;
1911 memcpy( buffer, prefix, sizeof(prefix) );
1912 if (!GetUserObjectInformationW( GetProcessWindowStation(), UOI_NAME,
1913 buffer + sizeof(prefix) / sizeof(WCHAR),
1914 sizeof(buffer) - sizeof(prefix), NULL ))
1916 ERR( "failed to get winstation name\n" );
1917 return FALSE;
1919 mutex = CreateMutexW( NULL, TRUE, buffer );
1920 if (GetLastError() == ERROR_ALREADY_EXISTS)
1922 TRACE( "waiting for mutex %s\n", debugstr_w( buffer ));
1923 WaitForSingleObject( mutex, INFINITE );
1925 return TRUE;
1929 /**************************************************************************
1930 * clipboard_thread
1932 * Thread running inside the desktop process to manage the clipboard
1934 static DWORD WINAPI clipboard_thread( void *arg )
1936 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};
1937 XSetWindowAttributes attr;
1938 WNDCLASSW class;
1939 MSG msg;
1941 if (!wait_clipboard_mutex()) return 0;
1943 clipboard_display = thread_init_display();
1944 attr.event_mask = PropertyChangeMask;
1945 import_window = XCreateWindow( clipboard_display, root_window, 0, 0, 1, 1, 0, CopyFromParent,
1946 InputOutput, CopyFromParent, CWEventMask, &attr );
1947 if (!import_window)
1949 ERR( "failed to create import window\n" );
1950 return 0;
1953 memset( &class, 0, sizeof(class) );
1954 class.lpfnWndProc = clipboard_wndproc;
1955 class.lpszClassName = clipboard_classname;
1957 if (!RegisterClassW( &class ) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS)
1959 ERR( "could not register clipboard window class err %u\n", GetLastError() );
1960 return 0;
1962 if (!(clipboard_hwnd = CreateWindowW( clipboard_classname, NULL, 0, 0, 0, 0, 0,
1963 HWND_MESSAGE, 0, 0, NULL )))
1965 ERR( "failed to create clipboard window err %u\n", GetLastError() );
1966 return 0;
1969 clipboard_thread_id = GetCurrentThreadId();
1970 AddClipboardFormatListener( clipboard_hwnd );
1971 register_builtin_formats();
1972 request_selection_contents( clipboard_display, TRUE );
1974 TRACE( "clipboard thread %04x running\n", GetCurrentThreadId() );
1975 while (GetMessageW( &msg, 0, 0, 0 )) DispatchMessageW( &msg );
1976 return 0;
1980 /**************************************************************************
1981 * X11DRV_UpdateClipboard
1983 void CDECL X11DRV_UpdateClipboard(void)
1985 static ULONG last_update;
1986 ULONG now;
1987 DWORD_PTR ret;
1989 if (GetCurrentThreadId() == clipboard_thread_id) return;
1990 now = GetTickCount();
1991 if ((int)(now - last_update) <= SELECTION_UPDATE_DELAY) return;
1992 if (SendMessageTimeoutW( GetClipboardOwner(), WM_X11DRV_UPDATE_CLIPBOARD, 0, 0,
1993 SMTO_ABORTIFHUNG, 5000, &ret ) && ret)
1994 last_update = now;
1998 /***********************************************************************
1999 * X11DRV_HandleSelectionRequest
2001 BOOL X11DRV_SelectionRequest( HWND hwnd, XEvent *xev )
2003 XSelectionRequestEvent *event = &xev->xselectionrequest;
2004 Display *display = event->display;
2005 XEvent result;
2006 Atom rprop = None;
2008 TRACE( "got request on %lx for selection %s target %s win %lx prop %s\n",
2009 event->owner, debugstr_xatom( event->selection ), debugstr_xatom( event->target ),
2010 event->requestor, debugstr_xatom( event->property ));
2012 if (event->owner != selection_window) goto done;
2013 if ((event->selection != x11drv_atom(CLIPBOARD)) &&
2014 (!use_primary_selection || event->selection != XA_PRIMARY)) goto done;
2016 /* If the specified property is None the requestor is an obsolete client.
2017 * We support these by using the specified target atom as the reply property.
2019 rprop = event->property;
2020 if( rprop == None )
2021 rprop = event->target;
2023 if (!export_selection( display, event->requestor, rprop, event->target ))
2024 rprop = None; /* report failure to client */
2026 done:
2027 result.xselection.type = SelectionNotify;
2028 result.xselection.display = display;
2029 result.xselection.requestor = event->requestor;
2030 result.xselection.selection = event->selection;
2031 result.xselection.property = rprop;
2032 result.xselection.target = event->target;
2033 result.xselection.time = event->time;
2034 TRACE( "sending SelectionNotify for %s to %lx\n", debugstr_xatom( rprop ), event->requestor );
2035 XSendEvent( display, event->requestor, False, NoEventMask, &result );
2036 return FALSE;
2040 /***********************************************************************
2041 * X11DRV_SelectionClear
2043 BOOL X11DRV_SelectionClear( HWND hwnd, XEvent *xev )
2045 XSelectionClearEvent *event = &xev->xselectionclear;
2047 if (event->window != selection_window) return FALSE;
2048 if (event->selection != x11drv_atom(CLIPBOARD)) return FALSE;
2050 release_selection( event->display, event->time );
2051 request_selection_contents( event->display, TRUE );
2052 return FALSE;
2056 /**************************************************************************
2057 * X11DRV_InitClipboard
2059 void X11DRV_InitClipboard(void)
2061 DWORD id;
2062 HANDLE handle = CreateThread( NULL, 0, clipboard_thread, NULL, 0, &id );
2064 if (handle) CloseHandle( handle );
2065 else ERR( "failed to create clipboard thread\n" );