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