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