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"
83 #ifdef HAVE_X11_EXTENSIONS_XFIXES_H
84 #include <X11/extensions/Xfixes.h>
90 #include "wine/list.h"
91 #include "wine/debug.h"
92 #include "wine/unicode.h"
94 WINE_DEFAULT_DEBUG_CHANNEL(clipboard
);
96 /* Maximum wait time for selection notify */
97 #define SELECTION_RETRIES 500 /* wait for .5 seconds */
98 #define SELECTION_WAIT 1 /* ms */
100 #define SELECTION_UPDATE_DELAY 2000 /* delay between checks of the X11 selection */
102 typedef BOOL (*EXPORTFUNC
)( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
103 typedef HANDLE (*IMPORTFUNC
)( Atom type
, const void *data
, size_t size
);
105 struct clipboard_format
114 static HANDLE
import_data( Atom type
, const void *data
, size_t size
);
115 static HANDLE
import_enhmetafile( Atom type
, const void *data
, size_t size
);
116 static HANDLE
import_pixmap( Atom type
, const void *data
, size_t size
);
117 static HANDLE
import_image_bmp( Atom type
, const void *data
, size_t size
);
118 static HANDLE
import_string( Atom type
, const void *data
, size_t size
);
119 static HANDLE
import_utf8_string( Atom type
, const void *data
, size_t size
);
120 static HANDLE
import_compound_text( Atom type
, const void *data
, size_t size
);
121 static HANDLE
import_text( Atom type
, const void *data
, size_t size
);
122 static HANDLE
import_text_html( Atom type
, const void *data
, size_t size
);
123 static HANDLE
import_text_uri_list( Atom type
, const void *data
, size_t size
);
124 static HANDLE
import_targets( Atom type
, const void *data
, size_t size
);
126 static BOOL
export_data( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
127 static BOOL
export_string( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
128 static BOOL
export_utf8_string( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
129 static BOOL
export_text( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
130 static BOOL
export_compound_text( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
131 static BOOL
export_pixmap( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
132 static BOOL
export_image_bmp( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
133 static BOOL
export_enhmetafile( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
134 static BOOL
export_text_html( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
135 static BOOL
export_hdrop( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
136 static BOOL
export_targets( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
137 static BOOL
export_multiple( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
138 static BOOL
export_timestamp( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
140 static BOOL
read_property( Display
*display
, Window w
, Atom prop
,
141 Atom
*type
, unsigned char **data
, unsigned long *datasize
);
143 /* Clipboard formats */
145 static const WCHAR RichTextFormatW
[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
146 static const WCHAR GIFW
[] = {'G','I','F',0};
147 static const WCHAR JFIFW
[] = {'J','F','I','F',0};
148 static const WCHAR PNGW
[] = {'P','N','G',0};
149 static const WCHAR HTMLFormatW
[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
158 } builtin_formats
[] =
160 { 0, CF_UNICODETEXT
, XATOM_UTF8_STRING
, import_utf8_string
, export_utf8_string
},
161 { 0, CF_UNICODETEXT
, XATOM_COMPOUND_TEXT
, import_compound_text
, export_compound_text
},
162 { 0, CF_UNICODETEXT
, XA_STRING
, import_string
, export_string
},
163 { 0, CF_UNICODETEXT
, XATOM_text_plain
, import_string
, export_string
},
164 { 0, CF_UNICODETEXT
, XATOM_TEXT
, import_text
, export_text
},
165 { 0, CF_SYLK
, XATOM_WCF_SYLK
, import_data
, export_data
},
166 { 0, CF_DIF
, XATOM_WCF_DIF
, import_data
, export_data
},
167 { 0, CF_TIFF
, XATOM_WCF_TIFF
, import_data
, export_data
},
168 { 0, CF_DIB
, XA_PIXMAP
, import_pixmap
, export_pixmap
},
169 { 0, CF_PENDATA
, XATOM_WCF_PENDATA
, import_data
, export_data
},
170 { 0, CF_RIFF
, XATOM_WCF_RIFF
, import_data
, export_data
},
171 { 0, CF_WAVE
, XATOM_WCF_WAVE
, import_data
, export_data
},
172 { 0, CF_ENHMETAFILE
, XATOM_WCF_ENHMETAFILE
, import_enhmetafile
, export_enhmetafile
},
173 { 0, CF_HDROP
, XATOM_text_uri_list
, import_text_uri_list
, export_hdrop
},
174 { 0, CF_DIB
, XATOM_image_bmp
, import_image_bmp
, export_image_bmp
},
175 { RichTextFormatW
, 0, XATOM_text_rtf
, import_data
, export_data
},
176 { RichTextFormatW
, 0, XATOM_text_richtext
, import_data
, export_data
},
177 { GIFW
, 0, XATOM_image_gif
, import_data
, export_data
},
178 { JFIFW
, 0, XATOM_image_jpeg
, import_data
, export_data
},
179 { PNGW
, 0, XATOM_image_png
, import_data
, export_data
},
180 { HTMLFormatW
, 0, XATOM_HTML_Format
, import_data
, export_data
},
181 { HTMLFormatW
, 0, XATOM_text_html
, import_text_html
, export_text_html
},
182 { 0, 0, XATOM_TARGETS
, import_targets
, export_targets
},
183 { 0, 0, XATOM_MULTIPLE
, NULL
, export_multiple
},
184 { 0, 0, XATOM_TIMESTAMP
, NULL
, export_timestamp
},
187 static struct list format_list
= LIST_INIT( format_list
);
189 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
191 static DWORD clipboard_thread_id
;
192 static HWND clipboard_hwnd
;
193 static BOOL is_clipboard_owner
;
194 static Window selection_window
;
195 static Window import_window
;
196 static Atom current_selection
;
197 static UINT rendered_formats
;
198 static ULONG64 last_clipboard_update
;
199 static struct clipboard_format
**current_x11_formats
;
200 static unsigned int nb_current_x11_formats
;
201 static BOOL use_xfixes
;
203 Display
*clipboard_display
= NULL
;
205 static const char *debugstr_format( UINT id
)
209 if (GetClipboardFormatNameW( id
, buffer
, 256 ))
210 return wine_dbg_sprintf( "%04x %s", id
, debugstr_w(buffer
) );
214 case 0: return "(none)";
215 #define BUILTIN(id) case id: return #id;
218 BUILTIN(CF_METAFILEPICT
)
228 BUILTIN(CF_UNICODETEXT
)
229 BUILTIN(CF_ENHMETAFILE
)
233 BUILTIN(CF_OWNERDISPLAY
)
235 BUILTIN(CF_DSPBITMAP
)
236 BUILTIN(CF_DSPMETAFILEPICT
)
237 BUILTIN(CF_DSPENHMETAFILE
)
239 default: return wine_dbg_sprintf( "%04x", id
);
243 static const char *debugstr_xatom( Atom atom
)
248 if (!atom
) return "(None)";
249 name
= XGetAtomName( thread_display(), atom
);
250 ret
= debugstr_a( name
);
256 static int is_atom_error( Display
*display
, XErrorEvent
*event
, void *arg
)
258 return (event
->error_code
== BadAtom
);
262 /**************************************************************************
265 static struct clipboard_format
*find_win32_format( UINT id
)
267 struct clipboard_format
*format
;
269 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
270 if (format
->id
== id
) return format
;
275 /**************************************************************************
278 static struct clipboard_format
*find_x11_format( Atom atom
)
280 struct clipboard_format
*format
;
282 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
283 if (format
->atom
== atom
) return format
;
288 /**************************************************************************
289 * register_builtin_formats
291 static void register_builtin_formats(void)
293 struct clipboard_format
*formats
;
296 if (!(formats
= HeapAlloc( GetProcessHeap(), 0, ARRAY_SIZE(builtin_formats
) * sizeof(*formats
)))) return;
298 for (i
= 0; i
< ARRAY_SIZE(builtin_formats
); i
++)
300 if (builtin_formats
[i
].name
)
301 formats
[i
].id
= RegisterClipboardFormatW( builtin_formats
[i
].name
);
303 formats
[i
].id
= builtin_formats
[i
].id
;
305 formats
[i
].atom
= GET_ATOM(builtin_formats
[i
].data
);
306 formats
[i
].import
= builtin_formats
[i
].import
;
307 formats
[i
].export
= builtin_formats
[i
].export
;
308 list_add_tail( &format_list
, &formats
[i
].entry
);
313 /**************************************************************************
316 static void register_formats( const UINT
*ids
, const Atom
*atoms
, unsigned int count
)
318 struct clipboard_format
*formats
;
321 if (!(formats
= HeapAlloc( GetProcessHeap(), 0, count
* sizeof(*formats
)))) return;
323 for (i
= 0; i
< count
; i
++)
325 formats
[i
].id
= ids
[i
];
326 formats
[i
].atom
= atoms
[i
];
327 formats
[i
].import
= import_data
;
328 formats
[i
].export
= export_data
;
329 list_add_tail( &format_list
, &formats
[i
].entry
);
330 TRACE( "registered %s atom %s\n", debugstr_format( ids
[i
] ), debugstr_xatom( atoms
[i
] ));
335 /**************************************************************************
336 * register_win32_formats
338 * Register Win32 clipboard formats the first time we encounter them.
340 static void register_win32_formats( const UINT
*ids
, UINT size
)
342 unsigned int count
, len
;
348 if (list_empty( &format_list
)) register_builtin_formats();
352 for (count
= 0; count
< 256 && size
; ids
++, size
--)
354 if (find_win32_format( *ids
)) continue; /* it already exists */
355 if (!GetClipboardFormatNameW( *ids
, buffer
, 256 )) continue; /* not a named format */
356 if (!(len
= WideCharToMultiByte( CP_UNIXCP
, 0, buffer
, -1, NULL
, 0, NULL
, NULL
))) continue;
357 if (!(names
[count
] = HeapAlloc( GetProcessHeap(), 0, len
))) continue;
358 WideCharToMultiByte( CP_UNIXCP
, 0, buffer
, -1, names
[count
], len
, NULL
, NULL
);
359 new_ids
[count
++] = *ids
;
363 XInternAtoms( thread_display(), names
, count
, False
, atoms
);
364 register_formats( new_ids
, atoms
, count
);
365 while (count
) HeapFree( GetProcessHeap(), 0, names
[--count
] );
370 /**************************************************************************
371 * register_x11_formats
373 * Register X11 atom formats the first time we encounter them.
375 static void register_x11_formats( const Atom
*atoms
, UINT size
)
377 Display
*display
= thread_display();
378 unsigned int i
, pos
, count
;
384 if (list_empty( &format_list
)) register_builtin_formats();
388 for (count
= 0; count
< 256 && size
; atoms
++, size
--)
389 if (!find_x11_format( *atoms
)) new_atoms
[count
++] = *atoms
;
393 X11DRV_expect_error( display
, is_atom_error
, NULL
);
394 if (!XGetAtomNames( display
, new_atoms
, count
, names
)) count
= 0;
395 if (X11DRV_check_error())
397 WARN( "got some bad atoms, ignoring\n" );
401 for (i
= pos
= 0; i
< count
; i
++)
403 if (MultiByteToWideChar( CP_UNIXCP
, 0, names
[i
], -1, buffer
, 256 ) &&
404 (ids
[pos
] = RegisterClipboardFormatW( buffer
)))
405 new_atoms
[pos
++] = new_atoms
[i
];
408 register_formats( ids
, new_atoms
, pos
);
413 /**************************************************************************
416 * Put data as a property on the specified window.
418 static void put_property( Display
*display
, Window win
, Atom prop
, Atom type
, int format
,
419 const void *ptr
, size_t size
)
421 const unsigned char *data
= ptr
;
422 int mode
= PropModeReplace
;
423 size_t width
= (format
== 32) ? sizeof(long) : format
/ 8;
424 size_t max_size
= XExtendedMaxRequestSize( display
) * 4;
426 if (!max_size
) max_size
= XMaxRequestSize( display
) * 4;
427 max_size
-= 64; /* request overhead */
431 size_t count
= min( size
, max_size
/ width
);
432 XChangeProperty( display
, win
, prop
, type
, format
, mode
, data
, count
);
433 mode
= PropModeAppend
;
435 data
+= count
* width
;
440 /**************************************************************************
443 static BOOL
convert_selection( Display
*display
, Window win
, Atom selection
,
444 struct clipboard_format
*format
, Atom
*type
,
445 unsigned char **data
, unsigned long *size
)
450 TRACE( "import %s from %s win %lx to format %s\n",
451 debugstr_xatom( format
->atom
), debugstr_xatom( selection
),
452 win
, debugstr_format( format
->id
) );
454 XConvertSelection( display
, selection
, format
->atom
, x11drv_atom(SELECTION_DATA
), win
, CurrentTime
);
456 for (i
= 0; i
< SELECTION_RETRIES
; i
++)
458 Bool res
= XCheckTypedWindowEvent( display
, win
, SelectionNotify
, &event
);
459 if (res
&& event
.xselection
.selection
== selection
&& event
.xselection
.target
== format
->atom
)
460 return read_property( display
, win
, event
.xselection
.property
, type
, data
, size
);
461 Sleep( SELECTION_WAIT
);
463 ERR( "Timed out waiting for SelectionNotify event\n" );
468 /***********************************************************************
471 * Return the size of the bitmap info structure including color table.
473 static int bitmap_info_size( const BITMAPINFO
* info
, WORD coloruse
)
475 unsigned int colors
, size
, masks
= 0;
477 if (info
->bmiHeader
.biSize
== sizeof(BITMAPCOREHEADER
))
479 const BITMAPCOREHEADER
*core
= (const BITMAPCOREHEADER
*)info
;
480 colors
= (core
->bcBitCount
<= 8) ? 1 << core
->bcBitCount
: 0;
481 return sizeof(BITMAPCOREHEADER
) + colors
*
482 ((coloruse
== DIB_RGB_COLORS
) ? sizeof(RGBTRIPLE
) : sizeof(WORD
));
484 else /* assume BITMAPINFOHEADER */
486 colors
= info
->bmiHeader
.biClrUsed
;
487 if (!colors
&& (info
->bmiHeader
.biBitCount
<= 8))
488 colors
= 1 << info
->bmiHeader
.biBitCount
;
489 if (info
->bmiHeader
.biCompression
== BI_BITFIELDS
) masks
= 3;
490 size
= max( info
->bmiHeader
.biSize
, sizeof(BITMAPINFOHEADER
) + masks
* sizeof(DWORD
) );
491 return size
+ colors
* ((coloruse
== DIB_RGB_COLORS
) ? sizeof(RGBQUAD
) : sizeof(WORD
));
496 /***********************************************************************
497 * create_dib_from_bitmap
499 * Allocates a packed DIB and copies the bitmap data into it.
501 static HGLOBAL
create_dib_from_bitmap(HBITMAP hBmp
)
507 LPBITMAPINFOHEADER pbmiHeader
;
508 unsigned int cDataSize
, cPackedSize
, OffsetBits
;
511 if (!GetObjectW( hBmp
, sizeof(bmp
), &bmp
)) return 0;
514 * A packed DIB contains a BITMAPINFO structure followed immediately by
515 * an optional color palette and the pixel data.
518 /* Calculate the size of the packed DIB */
519 cDataSize
= abs( bmp
.bmHeight
) * (((bmp
.bmWidth
* bmp
.bmBitsPixel
+ 31) / 8) & ~3);
520 cPackedSize
= sizeof(BITMAPINFOHEADER
)
521 + ( (bmp
.bmBitsPixel
<= 8) ? (sizeof(RGBQUAD
) * (1 << bmp
.bmBitsPixel
)) : 0 )
523 /* Get the offset to the bits */
524 OffsetBits
= cPackedSize
- cDataSize
;
526 /* Allocate the packed DIB */
527 TRACE("\tAllocating packed DIB of size %d\n", cPackedSize
);
528 hPackedDIB
= GlobalAlloc( GMEM_FIXED
, cPackedSize
);
531 WARN("Could not allocate packed DIB!\n");
535 /* A packed DIB starts with a BITMAPINFOHEADER */
536 pPackedDIB
= GlobalLock(hPackedDIB
);
537 pbmiHeader
= (LPBITMAPINFOHEADER
)pPackedDIB
;
539 /* Init the BITMAPINFOHEADER */
540 pbmiHeader
->biSize
= sizeof(BITMAPINFOHEADER
);
541 pbmiHeader
->biWidth
= bmp
.bmWidth
;
542 pbmiHeader
->biHeight
= bmp
.bmHeight
;
543 pbmiHeader
->biPlanes
= 1;
544 pbmiHeader
->biBitCount
= bmp
.bmBitsPixel
;
545 pbmiHeader
->biCompression
= BI_RGB
;
546 pbmiHeader
->biSizeImage
= 0;
547 pbmiHeader
->biXPelsPerMeter
= pbmiHeader
->biYPelsPerMeter
= 0;
548 pbmiHeader
->biClrUsed
= 0;
549 pbmiHeader
->biClrImportant
= 0;
551 /* Retrieve the DIB bits from the bitmap and fill in the
552 * DIB color table if present */
554 nLinesCopied
= GetDIBits(hdc
, /* Handle to device context */
555 hBmp
, /* Handle to bitmap */
556 0, /* First scan line to set in dest bitmap */
557 bmp
.bmHeight
, /* Number of scan lines to copy */
558 pPackedDIB
+ OffsetBits
, /* [out] Address of array for bitmap bits */
559 (LPBITMAPINFO
) pbmiHeader
, /* [out] Address of BITMAPINFO structure */
560 0); /* RGB or palette index */
561 GlobalUnlock(hPackedDIB
);
564 /* Cleanup if GetDIBits failed */
565 if (nLinesCopied
!= bmp
.bmHeight
)
567 TRACE("\tGetDIBits returned %d. Actual lines=%d\n", nLinesCopied
, bmp
.bmHeight
);
568 GlobalFree(hPackedDIB
);
575 /***********************************************************************
578 * Converts a text/uri-list URI to DOS filename.
580 static WCHAR
* uri_to_dos(char *encodedURI
)
585 char *uri
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, strlen(encodedURI
) + 1);
588 for (i
= 0; encodedURI
[i
]; ++i
)
590 if (encodedURI
[i
] == '%')
592 if (encodedURI
[i
+1] && encodedURI
[i
+2])
596 buffer
[0] = encodedURI
[i
+1];
597 buffer
[1] = encodedURI
[i
+2];
599 sscanf(buffer
, "%x", &number
);
605 WARN("invalid URI encoding in %s\n", debugstr_a(encodedURI
));
606 HeapFree(GetProcessHeap(), 0, uri
);
611 uri
[j
++] = encodedURI
[i
];
614 /* Read http://www.freedesktop.org/wiki/Draganddropwarts and cry... */
615 if (strncmp(uri
, "file:/", 6) == 0)
621 /* file:///path/to/file (nautilus, thunar) */
622 ret
= wine_get_dos_file_name(&uri
[7]);
626 /* file://hostname/path/to/file (X file drag spec) */
628 char *path
= strchr(&uri
[7], '/');
632 if (strcmp(&uri
[7], "localhost") == 0)
635 ret
= wine_get_dos_file_name(path
);
637 else if (gethostname(hostname
, sizeof(hostname
)) == 0)
639 if (strcmp(hostname
, &uri
[7]) == 0)
642 ret
= wine_get_dos_file_name(path
);
650 /* file:/path/to/file (konqueror) */
651 ret
= wine_get_dos_file_name(&uri
[5]);
654 HeapFree(GetProcessHeap(), 0, uri
);
659 /**************************************************************************
660 * unicode_text_from_string
662 * Convert a string in the specified encoding to CF_UNICODETEXT format.
664 static HANDLE
unicode_text_from_string( UINT codepage
, const void *data
, size_t size
)
669 count
= MultiByteToWideChar( codepage
, 0, data
, size
, NULL
, 0);
671 if (!(strW
= GlobalAlloc( GMEM_FIXED
, (count
* 2 + 1) * sizeof(WCHAR
) ))) return 0;
673 MultiByteToWideChar( codepage
, 0, data
, size
, strW
+ count
, count
);
674 for (i
= j
= 0; i
< count
; i
++)
676 if (strW
[i
+ count
] == '\n' && (!i
|| strW
[i
+ count
- 1] != '\r')) strW
[j
++] = '\r';
677 strW
[j
++] = strW
[i
+ count
];
680 GlobalReAlloc( strW
, j
* sizeof(WCHAR
), GMEM_FIXED
); /* release unused space */
681 TRACE( "returning %s\n", debugstr_wn( strW
, j
- 1 ));
686 /**************************************************************************
689 * Import XA_STRING, converting the string to CF_UNICODETEXT.
691 static HANDLE
import_string( Atom type
, const void *data
, size_t size
)
693 return unicode_text_from_string( 28591, data
, size
);
697 /**************************************************************************
700 * Import XA_UTF8_STRING, converting the string to CF_UNICODETEXT.
702 static HANDLE
import_utf8_string( Atom type
, const void *data
, size_t size
)
704 return unicode_text_from_string( CP_UTF8
, data
, size
);
708 /**************************************************************************
709 * import_compound_text
711 * Import COMPOUND_TEXT to CF_UNICODETEXT.
713 static HANDLE
import_compound_text( Atom type
, const void *data
, size_t size
)
718 XTextProperty txtprop
;
720 txtprop
.value
= (BYTE
*)data
;
721 txtprop
.nitems
= size
;
722 txtprop
.encoding
= x11drv_atom(COMPOUND_TEXT
);
724 if (XmbTextPropertyToTextList( thread_display(), &txtprop
, &srcstr
, &count
) != Success
) return 0;
725 if (!count
) return 0;
727 ret
= unicode_text_from_string( CP_UNIXCP
, srcstr
[0], strlen(srcstr
[0]) + 1 );
728 XFreeStringList(srcstr
);
733 /**************************************************************************
736 * Import XA_TEXT, converting the string to CF_UNICODETEXT.
738 static HANDLE
import_text( Atom type
, const void *data
, size_t size
)
740 if (type
== XA_STRING
) return import_string( type
, data
, size
);
741 if (type
== x11drv_atom(UTF8_STRING
)) return import_utf8_string( type
, data
, size
);
742 if (type
== x11drv_atom(COMPOUND_TEXT
)) return import_compound_text( type
, data
, size
);
743 FIXME( "unsupported TEXT type %s\n", debugstr_xatom( type
));
748 /**************************************************************************
751 * Import XA_PIXMAP, converting the image to CF_DIB.
753 static HANDLE
import_pixmap( Atom type
, const void *data
, size_t size
)
755 const Pixmap
*pPixmap
= (const Pixmap
*)data
;
757 XVisualInfo vis
= default_visual
;
758 char buffer
[FIELD_OFFSET( BITMAPINFO
, bmiColors
[256] )];
759 BITMAPINFO
*info
= (BITMAPINFO
*)buffer
;
760 struct gdi_image_bits bits
;
762 int x
,y
; /* Unused */
763 unsigned border_width
; /* Unused */
764 unsigned int depth
, width
, height
;
766 /* Get the Pixmap dimensions and bit depth */
767 if (!XGetGeometry(gdi_display
, *pPixmap
, &root
, &x
, &y
, &width
, &height
,
768 &border_width
, &depth
)) depth
= 0;
769 if (!pixmap_formats
[depth
]) return 0;
771 TRACE( "pixmap properties: width=%d, height=%d, depth=%d\n", width
, height
, depth
);
773 if (depth
!= vis
.depth
) switch (pixmap_formats
[depth
]->bits_per_pixel
)
779 case 16: /* assume R5G5B5 */
780 vis
.red_mask
= 0x7c00;
781 vis
.green_mask
= 0x03e0;
782 vis
.blue_mask
= 0x001f;
784 case 24: /* assume R8G8B8 */
785 case 32: /* assume A8R8G8B8 */
786 vis
.red_mask
= 0xff0000;
787 vis
.green_mask
= 0x00ff00;
788 vis
.blue_mask
= 0x0000ff;
794 if (!get_pixmap_image( *pPixmap
, width
, height
, &vis
, info
, &bits
))
796 DWORD info_size
= bitmap_info_size( info
, DIB_RGB_COLORS
);
798 ptr
= GlobalAlloc( GMEM_FIXED
, info_size
+ info
->bmiHeader
.biSizeImage
);
801 memcpy( ptr
, info
, info_size
);
802 memcpy( ptr
+ info_size
, bits
.ptr
, info
->bmiHeader
.biSizeImage
);
804 if (bits
.free
) bits
.free( &bits
);
810 /**************************************************************************
813 * Import image/bmp, converting the image to CF_DIB.
815 static HANDLE
import_image_bmp( Atom type
, const void *data
, size_t size
)
817 HANDLE hClipData
= 0;
818 const BITMAPFILEHEADER
*bfh
= data
;
820 if (size
>= sizeof(BITMAPFILEHEADER
)+sizeof(BITMAPCOREHEADER
) &&
821 bfh
->bfType
== 0x4d42 /* "BM" */)
823 const BITMAPINFO
*bmi
= (const BITMAPINFO
*)(bfh
+ 1);
827 if ((hbmp
= CreateDIBitmap( hdc
, &bmi
->bmiHeader
, CBM_INIT
,
828 (const BYTE
*)data
+ bfh
->bfOffBits
, bmi
, DIB_RGB_COLORS
)))
830 hClipData
= create_dib_from_bitmap( hbmp
);
839 /**************************************************************************
842 static HANDLE
import_enhmetafile( Atom type
, const void *data
, size_t size
)
844 return SetEnhMetaFileBits( size
, data
);
848 /**************************************************************************
851 static HANDLE
import_text_html( Atom type
, const void *data
, size_t size
)
853 static const char header
[] =
855 "StartHTML:0000000100\n"
857 "StartFragment:%010lu\n"
858 "EndFragment:%010lu\n"
859 "<!--StartFragment-->";
860 static const char trailer
[] = "\n<!--EndFragment-->";
865 /* Firefox uses UTF-16LE with byte order mark. Convert to UTF-8 without the BOM. */
866 if (size
>= sizeof(WCHAR
) && ((const WCHAR
*)data
)[0] == 0xfeff)
868 len
= WideCharToMultiByte( CP_UTF8
, 0, (const WCHAR
*)data
+ 1, size
/ sizeof(WCHAR
) - 1,
869 NULL
, 0, NULL
, NULL
);
870 if (!(text
= HeapAlloc( GetProcessHeap(), 0, len
))) return 0;
871 WideCharToMultiByte( CP_UTF8
, 0, (const WCHAR
*)data
+ 1, size
/ sizeof(WCHAR
) - 1,
872 text
, len
, NULL
, NULL
);
877 len
= strlen( header
) + 12; /* 3 * 4 extra chars for %010lu */
878 total
= len
+ size
+ sizeof(trailer
);
879 if ((ret
= GlobalAlloc( GMEM_FIXED
, total
)))
882 p
+= sprintf( p
, header
, total
- 1, len
, len
+ size
+ 1 /* include the final \n in the data */ );
883 memcpy( p
, data
, size
);
884 strcpy( p
+ size
, trailer
);
885 TRACE( "returning %s\n", debugstr_a( ret
));
887 HeapFree( GetProcessHeap(), 0, text
);
892 /**************************************************************************
893 * import_text_uri_list
895 * Import text/uri-list.
897 static HANDLE
import_text_uri_list( Atom type
, const void *data
, size_t size
)
899 const char *uriList
= data
;
907 DROPFILES
*dropFiles
= NULL
;
909 if (!(out
= HeapAlloc(GetProcessHeap(), 0, capacity
* sizeof(WCHAR
)))) return 0;
913 while (end
< size
&& uriList
[end
] != '\r')
915 if (end
< (size
- 1) && uriList
[end
+1] != '\n')
917 WARN("URI list line doesn't end in \\r\\n\n");
921 uri
= HeapAlloc(GetProcessHeap(), 0, end
- start
+ 1);
924 lstrcpynA(uri
, &uriList
[start
], end
- start
+ 1);
925 path
= uri_to_dos(uri
);
926 TRACE("converted URI %s to DOS path %s\n", debugstr_a(uri
), debugstr_w(path
));
927 HeapFree(GetProcessHeap(), 0, uri
);
931 int pathSize
= strlenW(path
) + 1;
932 if (pathSize
> capacity
- total
)
934 capacity
= 2*capacity
+ pathSize
;
935 out
= HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, out
, (capacity
+ 1)*sizeof(WCHAR
));
939 memcpy(&out
[total
], path
, pathSize
* sizeof(WCHAR
));
942 HeapFree(GetProcessHeap(), 0, path
);
950 if (out
&& end
>= size
)
952 if ((dropFiles
= GlobalAlloc( GMEM_FIXED
, sizeof(DROPFILES
) + (total
+ 1) * sizeof(WCHAR
) )))
954 dropFiles
->pFiles
= sizeof(DROPFILES
);
958 dropFiles
->fWide
= TRUE
;
960 memcpy( (char*)dropFiles
+ dropFiles
->pFiles
, out
, (total
+ 1) * sizeof(WCHAR
) );
963 HeapFree(GetProcessHeap(), 0, out
);
968 /**************************************************************************
971 * Import TARGETS and mark the corresponding clipboard formats as available.
973 static HANDLE
import_targets( Atom type
, const void *data
, size_t size
)
975 UINT i
, pos
, count
= size
/ sizeof(Atom
);
976 const Atom
*properties
= data
;
977 struct clipboard_format
*format
, **formats
;
979 if (type
!= XA_ATOM
&& type
!= x11drv_atom(TARGETS
)) return 0;
981 register_x11_formats( properties
, count
);
983 /* the builtin formats contain duplicates, so allocate some extra space */
984 if (!(formats
= HeapAlloc( GetProcessHeap(), 0, (count
+ ARRAY_SIZE(builtin_formats
)) * sizeof(*formats
))))
988 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
990 for (i
= 0; i
< count
; i
++) if (properties
[i
] == format
->atom
) break;
991 if (i
== count
) continue;
992 if (format
->import
&& format
->id
)
994 TRACE( "property %s -> format %s\n",
995 debugstr_xatom( properties
[i
] ), debugstr_format( format
->id
));
996 SetClipboardData( format
->id
, 0 );
997 formats
[pos
++] = format
;
999 else TRACE( "property %s (ignoring)\n", debugstr_xatom( properties
[i
] ));
1002 HeapFree( GetProcessHeap(), 0, current_x11_formats
);
1003 current_x11_formats
= formats
;
1004 nb_current_x11_formats
= pos
;
1009 /**************************************************************************
1012 * Generic import clipboard data routine.
1014 static HANDLE
import_data( Atom type
, const void *data
, size_t size
)
1016 void *ret
= GlobalAlloc( GMEM_FIXED
, size
);
1018 if (ret
) memcpy( ret
, data
, size
);
1023 /**************************************************************************
1026 * Import the specified format from the selection and return a global handle to the data.
1028 static HANDLE
import_selection( Display
*display
, Window win
, Atom selection
,
1029 struct clipboard_format
*format
)
1031 unsigned char *data
;
1036 if (!format
->import
) return 0;
1038 if (!convert_selection( display
, win
, selection
, format
, &type
, &data
, &size
))
1040 TRACE( "failed to convert selection\n" );
1043 ret
= format
->import( type
, data
, size
);
1044 HeapFree( GetProcessHeap(), 0, data
);
1049 /**************************************************************************
1050 * X11DRV_CLIPBOARD_ImportSelection
1052 * Import the X selection into the clipboard format registered for the given X target.
1054 void X11DRV_CLIPBOARD_ImportSelection( Display
*display
, Window win
, Atom selection
,
1055 Atom
*targets
, UINT count
,
1056 void (*callback
)( Atom
, UINT
, HANDLE
))
1060 struct clipboard_format
*format
;
1062 register_x11_formats( targets
, count
);
1064 for (i
= 0; i
< count
; i
++)
1066 if (!(format
= find_x11_format( targets
[i
] ))) continue;
1067 if (!format
->id
) continue;
1068 if (!(handle
= import_selection( display
, win
, selection
, format
))) continue;
1069 callback( targets
[i
], format
->id
, handle
);
1074 /**************************************************************************
1077 static HANDLE
render_format( UINT id
)
1079 Display
*display
= thread_display();
1083 if (!current_selection
) return 0;
1085 for (i
= 0; i
< nb_current_x11_formats
; i
++)
1087 if (current_x11_formats
[i
]->id
!= id
) continue;
1088 if (!(handle
= import_selection( display
, import_window
,
1089 current_selection
, current_x11_formats
[i
] ))) continue;
1090 SetClipboardData( id
, handle
);
1097 /**************************************************************************
1100 * Generic export clipboard data routine.
1102 static BOOL
export_data( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1104 void *ptr
= GlobalLock( handle
);
1106 if (!ptr
) return FALSE
;
1107 put_property( display
, win
, prop
, target
, 8, ptr
, GlobalSize( handle
));
1108 GlobalUnlock( handle
);
1113 /**************************************************************************
1114 * string_from_unicode_text
1116 * Convert CF_UNICODETEXT data to a string in the specified codepage.
1118 static char *string_from_unicode_text( UINT codepage
, HANDLE handle
, UINT
*size
)
1122 WCHAR
*strW
= GlobalLock( handle
);
1123 UINT lenW
= GlobalSize( handle
) / sizeof(WCHAR
);
1124 DWORD len
= WideCharToMultiByte( codepage
, 0, strW
, lenW
, NULL
, 0, NULL
, NULL
);
1126 if ((str
= HeapAlloc( GetProcessHeap(), 0, len
)))
1128 WideCharToMultiByte( codepage
, 0, strW
, lenW
, str
, len
, NULL
, NULL
);
1129 GlobalUnlock( handle
);
1131 /* remove carriage returns */
1132 for (i
= j
= 0; i
< len
; i
++)
1134 if (str
[i
] == '\r' && (i
== len
- 1 || str
[i
+ 1] == '\n')) continue;
1137 while (j
&& !str
[j
- 1]) j
--; /* remove trailing nulls */
1139 TRACE( "returning %s\n", debugstr_an( str
, j
));
1141 GlobalUnlock( handle
);
1146 /**************************************************************************
1149 * Export CF_UNICODETEXT converting the string to XA_STRING.
1151 static BOOL
export_string( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1154 char *text
= string_from_unicode_text( 28591, handle
, &size
);
1156 if (!text
) return FALSE
;
1157 put_property( display
, win
, prop
, target
, 8, text
, size
);
1158 HeapFree( GetProcessHeap(), 0, text
);
1159 GlobalUnlock( handle
);
1164 /**************************************************************************
1165 * export_utf8_string
1167 * Export CF_UNICODE converting the string to UTF8.
1169 static BOOL
export_utf8_string( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1172 char *text
= string_from_unicode_text( CP_UTF8
, handle
, &size
);
1174 if (!text
) return FALSE
;
1175 put_property( display
, win
, prop
, target
, 8, text
, size
);
1176 HeapFree( GetProcessHeap(), 0, text
);
1177 GlobalUnlock( handle
);
1182 /**************************************************************************
1185 * Export CF_UNICODE to the polymorphic TEXT type, using UTF8.
1187 static BOOL
export_text( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1189 return export_utf8_string( display
, win
, prop
, x11drv_atom(UTF8_STRING
), handle
);
1193 /**************************************************************************
1194 * export_compound_text
1196 * Export CF_UNICODE to COMPOUND_TEXT
1198 static BOOL
export_compound_text( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1200 XTextProperty textprop
;
1201 XICCEncodingStyle style
;
1203 char *text
= string_from_unicode_text( CP_UNIXCP
, handle
, &size
);
1205 if (!text
) return FALSE
;
1206 if (target
== x11drv_atom(COMPOUND_TEXT
))
1207 style
= XCompoundTextStyle
;
1209 style
= XStdICCTextStyle
;
1211 /* Update the X property */
1212 if (XmbTextListToTextProperty( display
, &text
, 1, style
, &textprop
) == Success
)
1214 XSetTextProperty( display
, win
, &textprop
, prop
);
1215 XFree( textprop
.value
);
1218 HeapFree( GetProcessHeap(), 0, text
);
1223 /**************************************************************************
1226 * Export CF_DIB to XA_PIXMAP.
1228 static BOOL
export_pixmap( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1232 struct gdi_image_bits bits
;
1234 pbmi
= GlobalLock( handle
);
1235 bits
.ptr
= (LPBYTE
)pbmi
+ bitmap_info_size( pbmi
, DIB_RGB_COLORS
);
1237 bits
.is_copy
= FALSE
;
1238 pixmap
= create_pixmap_from_image( 0, &default_visual
, pbmi
, &bits
, DIB_RGB_COLORS
);
1239 GlobalUnlock( handle
);
1241 put_property( display
, win
, prop
, target
, 32, &pixmap
, 1 );
1242 /* FIXME: free the pixmap when the property is deleted */
1247 /**************************************************************************
1250 * Export CF_DIB to image/bmp.
1252 static BOOL
export_image_bmp( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1254 LPBYTE dibdata
= GlobalLock( handle
);
1256 BITMAPFILEHEADER
*bfh
;
1258 bmpsize
= sizeof(BITMAPFILEHEADER
) + GlobalSize( handle
);
1259 bfh
= HeapAlloc( GetProcessHeap(), 0, bmpsize
);
1262 /* bitmap file header */
1263 bfh
->bfType
= 0x4d42; /* "BM" */
1264 bfh
->bfSize
= bmpsize
;
1265 bfh
->bfReserved1
= 0;
1266 bfh
->bfReserved2
= 0;
1267 bfh
->bfOffBits
= sizeof(BITMAPFILEHEADER
) + bitmap_info_size((BITMAPINFO
*)dibdata
, DIB_RGB_COLORS
);
1269 /* rest of bitmap is the same as the packed dib */
1270 memcpy(bfh
+1, dibdata
, bmpsize
-sizeof(BITMAPFILEHEADER
));
1272 GlobalUnlock( handle
);
1273 put_property( display
, win
, prop
, target
, 8, bfh
, bmpsize
);
1274 HeapFree( GetProcessHeap(), 0, bfh
);
1279 /**************************************************************************
1280 * export_enhmetafile
1282 * Export EnhMetaFile.
1284 static BOOL
export_enhmetafile( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1289 if (!(size
= GetEnhMetaFileBits( handle
, 0, NULL
))) return FALSE
;
1290 if (!(ptr
= HeapAlloc( GetProcessHeap(), 0, size
))) return FALSE
;
1292 GetEnhMetaFileBits( handle
, size
, ptr
);
1293 put_property( display
, win
, prop
, target
, 8, ptr
, size
);
1294 HeapFree( GetProcessHeap(), 0, ptr
);
1299 /**************************************************************************
1302 * Export HTML Format to text/html.
1304 * FIXME: We should attempt to add an <a base> tag and convert windows paths.
1306 static BOOL
export_text_html( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1308 const char *p
, *data
;
1309 UINT start
= 0, end
= 0;
1312 if (!(data
= GlobalLock( handle
))) return FALSE
;
1315 while (*p
&& *p
!= '<')
1317 if (!strncmp( p
, "StartFragment:", 14 )) start
= atoi( p
+ 14 );
1318 else if (!strncmp( p
, "EndFragment:", 12 )) end
= atoi( p
+ 12 );
1319 if (!(p
= strpbrk( p
, "\r\n" ))) break;
1320 while (*p
== '\r' || *p
== '\n') p
++;
1322 if (start
&& start
< end
&& end
<= GlobalSize( handle
))
1323 put_property( display
, win
, prop
, target
, 8, data
+ start
, end
- start
);
1327 GlobalUnlock( handle
);
1332 /**************************************************************************
1335 * Export CF_HDROP format to text/uri-list.
1337 static BOOL
export_hdrop( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1342 UINT textUriListSize
= 32;
1345 textUriList
= HeapAlloc( GetProcessHeap(), 0, textUriListSize
);
1346 if (!textUriList
) return FALSE
;
1347 numFiles
= DragQueryFileW( handle
, 0xFFFFFFFF, NULL
, 0 );
1348 for (i
= 0; i
< numFiles
; i
++)
1350 UINT dosFilenameSize
;
1351 WCHAR
*dosFilename
= NULL
;
1352 char *unixFilename
= NULL
;
1356 dosFilenameSize
= 1 + DragQueryFileW( handle
, i
, NULL
, 0 );
1357 dosFilename
= HeapAlloc(GetProcessHeap(), 0, dosFilenameSize
*sizeof(WCHAR
));
1358 if (dosFilename
== NULL
) goto failed
;
1359 DragQueryFileW( handle
, i
, dosFilename
, dosFilenameSize
);
1360 unixFilename
= wine_get_unix_file_name(dosFilename
);
1361 HeapFree(GetProcessHeap(), 0, dosFilename
);
1362 if (unixFilename
== NULL
) goto failed
;
1363 uriSize
= 8 + /* file:/// */
1364 3 * (lstrlenA(unixFilename
) - 1) + /* "%xy" per char except first '/' */
1366 if ((next
+ uriSize
) > textUriListSize
)
1368 UINT biggerSize
= max( 2 * textUriListSize
, next
+ uriSize
);
1369 void *bigger
= HeapReAlloc( GetProcessHeap(), 0, textUriList
, biggerSize
);
1372 textUriList
= bigger
;
1373 textUriListSize
= biggerSize
;
1377 HeapFree(GetProcessHeap(), 0, unixFilename
);
1381 lstrcpyA(&textUriList
[next
], "file:///");
1383 /* URL encode everything - unnecessary, but easier/lighter than linking in shlwapi, and can't hurt */
1384 for (u
= 1; unixFilename
[u
]; u
++)
1386 static const char hex_table
[] = "0123456789abcdef";
1387 textUriList
[next
++] = '%';
1388 textUriList
[next
++] = hex_table
[unixFilename
[u
] >> 4];
1389 textUriList
[next
++] = hex_table
[unixFilename
[u
] & 0xf];
1391 textUriList
[next
++] = '\r';
1392 textUriList
[next
++] = '\n';
1393 HeapFree(GetProcessHeap(), 0, unixFilename
);
1395 put_property( display
, win
, prop
, target
, 8, textUriList
, next
);
1396 HeapFree( GetProcessHeap(), 0, textUriList
);
1400 HeapFree( GetProcessHeap(), 0, textUriList
);
1405 /***********************************************************************
1406 * get_clipboard_formats
1408 * Return a list of all formats currently available on the Win32 clipboard.
1409 * Helper for export_targets.
1411 static UINT
*get_clipboard_formats( UINT
*size
)
1418 if (!(ids
= HeapAlloc( GetProcessHeap(), 0, *size
* sizeof(*ids
) ))) return NULL
;
1419 if (GetUpdatedClipboardFormats( ids
, *size
, size
)) break;
1420 HeapFree( GetProcessHeap(), 0, ids
);
1421 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER
) return NULL
;
1423 register_win32_formats( ids
, *size
);
1428 /***********************************************************************
1429 * is_format_available
1431 * Check if a clipboard format is included in the list.
1432 * Helper for export_targets.
1434 static BOOL
is_format_available( UINT format
, const UINT
*ids
, unsigned int count
)
1436 while (count
--) if (*ids
++ == format
) return TRUE
;
1441 /***********************************************************************
1444 * Service a TARGETS selection request event
1446 static BOOL
export_targets( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1448 struct clipboard_format
*format
;
1449 UINT pos
, count
, *formats
;
1452 if (!(formats
= get_clipboard_formats( &count
))) return FALSE
;
1454 /* the builtin formats contain duplicates, so allocate some extra space */
1455 if (!(targets
= HeapAlloc( GetProcessHeap(), 0,
1456 (count
+ ARRAY_SIZE(builtin_formats
)) * sizeof(*targets
) )))
1458 HeapFree( GetProcessHeap(), 0, formats
);
1463 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
1465 if (!format
->export
) continue;
1466 /* formats with id==0 are always exported */
1467 if (format
->id
&& !is_format_available( format
->id
, formats
, count
)) continue;
1468 TRACE( "%d: %s -> %s\n", pos
, debugstr_format( format
->id
), debugstr_xatom( format
->atom
));
1469 targets
[pos
++] = format
->atom
;
1472 put_property( display
, win
, prop
, XA_ATOM
, 32, targets
, pos
);
1473 HeapFree( GetProcessHeap(), 0, targets
);
1474 HeapFree( GetProcessHeap(), 0, formats
);
1479 /**************************************************************************
1482 * Export selection data, depending on the target type.
1484 static BOOL
export_selection( Display
*display
, Window win
, Atom prop
, Atom target
)
1486 struct clipboard_format
*format
;
1488 BOOL open
= FALSE
, ret
= FALSE
;
1490 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
1492 if (format
->atom
!= target
) continue;
1493 if (!format
->export
) continue;
1496 TRACE( "win %lx prop %s target %s\n", win
, debugstr_xatom( prop
), debugstr_xatom( target
));
1497 ret
= format
->export( display
, win
, prop
, target
, 0 );
1500 if (!open
&& !(open
= OpenClipboard( clipboard_hwnd
)))
1502 ERR( "failed to open clipboard for %s\n", debugstr_xatom( target
));
1505 if ((handle
= GetClipboardData( format
->id
)))
1507 TRACE( "win %lx prop %s target %s exporting %s %p\n",
1508 win
, debugstr_xatom( prop
), debugstr_xatom( target
),
1509 debugstr_format( format
->id
), handle
);
1511 ret
= format
->export( display
, win
, prop
, target
, handle
);
1514 /* keep looking for another Win32 format mapping to the same target */
1516 if (open
) CloseClipboard();
1521 /***********************************************************************
1524 * Service a MULTIPLE selection request event
1525 * prop contains a list of (target,property) atom pairs.
1526 * The first atom names a target and the second names a property.
1527 * The effect is as if we have received a sequence of SelectionRequest events
1528 * (one for each atom pair) except that:
1529 * 1. We reply with a SelectionNotify only when all the requested conversions
1530 * have been performed.
1531 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
1532 * we replace the atom in the property by None.
1534 static BOOL
export_multiple( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1539 unsigned long i
, count
, failed
, remain
;
1541 /* Read the MULTIPLE property contents. This should contain a list of
1542 * (target,property) atom pairs.
1544 if (XGetWindowProperty( display
, win
, prop
, 0, 0x3FFF, False
, AnyPropertyType
, &atype
, &aformat
,
1545 &count
, &remain
, (unsigned char**)&list
))
1548 TRACE( "type %s format %d count %ld remain %ld\n",
1549 debugstr_xatom( atype
), aformat
, count
, remain
);
1552 * Make sure we got what we expect.
1553 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
1554 * in a MULTIPLE selection request should be of type ATOM_PAIR.
1555 * However some X apps(such as XPaint) are not compliant with this and return
1556 * a user defined atom in atype when XGetWindowProperty is called.
1557 * The data *is* an atom pair but is not denoted as such.
1559 if (aformat
== 32 /* atype == xAtomPair */ )
1561 for (i
= failed
= 0; i
< count
; i
+= 2)
1563 if (list
[i
+1] == None
) continue;
1564 if (export_selection( display
, win
, list
[i
+ 1], list
[i
] )) continue;
1568 if (failed
) put_property( display
, win
, prop
, atype
, 32, list
, count
);
1575 /***********************************************************************
1578 * Export the timestamp that was used to acquire the selection
1580 static BOOL
export_timestamp( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1582 Time time
= CurrentTime
; /* FIXME */
1583 put_property( display
, win
, prop
, XA_INTEGER
, 32, &time
, 1 );
1588 /**************************************************************************
1589 * X11DRV_CLIPBOARD_GetProperty
1590 * Gets type, data and size.
1592 static BOOL
X11DRV_CLIPBOARD_GetProperty(Display
*display
, Window w
, Atom prop
,
1593 Atom
*atype
, unsigned char** data
, unsigned long* datasize
)
1596 unsigned long pos
= 0, nitems
, remain
, count
;
1597 unsigned char *val
= NULL
, *buffer
;
1601 if (XGetWindowProperty(display
, w
, prop
, pos
, INT_MAX
/ 4, False
,
1602 AnyPropertyType
, atype
, &aformat
, &nitems
, &remain
, &buffer
))
1604 WARN("Failed to read property\n");
1605 HeapFree( GetProcessHeap(), 0, val
);
1609 count
= get_property_size( aformat
, nitems
);
1610 if (!val
) *data
= HeapAlloc( GetProcessHeap(), 0, pos
* sizeof(int) + count
+ 1 );
1611 else *data
= HeapReAlloc( GetProcessHeap(), 0, val
, pos
* sizeof(int) + count
+ 1 );
1616 HeapFree( GetProcessHeap(), 0, val
);
1620 memcpy( (int *)val
+ pos
, buffer
, count
);
1624 *datasize
= pos
* sizeof(int) + count
;
1628 pos
+= count
/ sizeof(int);
1631 TRACE( "got property %s type %s format %u len %lu from window %lx\n",
1632 debugstr_xatom( prop
), debugstr_xatom( *atype
), aformat
, *datasize
, w
);
1634 /* Delete the property on the window now that we are done
1635 * This will send a PropertyNotify event to the selection owner. */
1636 XDeleteProperty(display
, w
, prop
);
1641 struct clipboard_data_packet
{
1644 unsigned char *data
;
1647 /**************************************************************************
1650 * Reads the contents of the X selection property.
1652 static BOOL
read_property( Display
*display
, Window w
, Atom prop
,
1653 Atom
*type
, unsigned char **data
, unsigned long *datasize
)
1660 while (XCheckTypedWindowEvent(display
, w
, PropertyNotify
, &xe
))
1663 if (!X11DRV_CLIPBOARD_GetProperty(display
, w
, prop
, type
, data
, datasize
))
1666 if (*type
== x11drv_atom(INCR
))
1669 unsigned long bufsize
= 0;
1670 struct list packets
;
1671 struct clipboard_data_packet
*packet
, *packet2
;
1674 HeapFree(GetProcessHeap(), 0, *data
);
1677 list_init(&packets
);
1682 unsigned char *prop_data
;
1683 unsigned long prop_size
;
1685 /* Wait until PropertyNotify is received */
1686 for (i
= 0; i
< SELECTION_RETRIES
; i
++)
1690 res
= XCheckTypedWindowEvent(display
, w
, PropertyNotify
, &xe
);
1691 if (res
&& xe
.xproperty
.atom
== prop
&&
1692 xe
.xproperty
.state
== PropertyNewValue
)
1694 Sleep(SELECTION_WAIT
);
1697 if (i
>= SELECTION_RETRIES
||
1698 !X11DRV_CLIPBOARD_GetProperty(display
, w
, prop
, type
, &prop_data
, &prop_size
))
1704 /* Retrieved entire data. */
1707 HeapFree(GetProcessHeap(), 0, prop_data
);
1712 packet
= HeapAlloc(GetProcessHeap(), 0, sizeof(*packet
));
1715 HeapFree(GetProcessHeap(), 0, prop_data
);
1720 packet
->size
= prop_size
;
1721 packet
->data
= prop_data
;
1722 list_add_tail(&packets
, &packet
->entry
);
1723 bufsize
+= prop_size
;
1728 buf
= HeapAlloc(GetProcessHeap(), 0, bufsize
+ 1);
1731 unsigned long bytes_copied
= 0;
1732 *datasize
= bufsize
;
1733 LIST_FOR_EACH_ENTRY( packet
, &packets
, struct clipboard_data_packet
, entry
)
1735 memcpy(&buf
[bytes_copied
], packet
->data
, packet
->size
);
1736 bytes_copied
+= packet
->size
;
1745 LIST_FOR_EACH_ENTRY_SAFE( packet
, packet2
, &packets
, struct clipboard_data_packet
, entry
)
1747 HeapFree(GetProcessHeap(), 0, packet
->data
);
1748 HeapFree(GetProcessHeap(), 0, packet
);
1758 /**************************************************************************
1761 * Acquire the X11 selection when the Win32 clipboard has changed.
1763 static void acquire_selection( Display
*display
)
1765 if (selection_window
) XDestroyWindow( display
, selection_window
);
1767 selection_window
= XCreateWindow( display
, root_window
, 0, 0, 1, 1, 0, CopyFromParent
,
1768 InputOutput
, CopyFromParent
, 0, NULL
);
1769 if (!selection_window
) return;
1771 XSetSelectionOwner( display
, x11drv_atom(CLIPBOARD
), selection_window
, CurrentTime
);
1772 if (use_primary_selection
) XSetSelectionOwner( display
, XA_PRIMARY
, selection_window
, CurrentTime
);
1773 TRACE( "win %lx\n", selection_window
);
1777 /**************************************************************************
1780 * Release the X11 selection when some other X11 app has grabbed it.
1782 static void release_selection( Display
*display
, Time time
)
1784 assert( selection_window
);
1786 TRACE( "win %lx\n", selection_window
);
1788 /* release PRIMARY if we still own it */
1789 if (use_primary_selection
&& XGetSelectionOwner( display
, XA_PRIMARY
) == selection_window
)
1790 XSetSelectionOwner( display
, XA_PRIMARY
, None
, time
);
1792 XDestroyWindow( display
, selection_window
);
1793 selection_window
= 0;
1797 /**************************************************************************
1798 * request_selection_contents
1800 * Retrieve the contents of the X11 selection when it's owned by an X11 app.
1802 static BOOL
request_selection_contents( Display
*display
, BOOL changed
)
1804 struct clipboard_format
*targets
= find_x11_format( x11drv_atom(TARGETS
) );
1805 struct clipboard_format
*string
= find_x11_format( XA_STRING
);
1806 struct clipboard_format
*format
= NULL
;
1808 unsigned char *data
= NULL
;
1809 unsigned long size
= 0;
1812 static Atom last_selection
;
1813 static Window last_owner
;
1814 static struct clipboard_format
*last_format
;
1815 static Atom last_type
;
1816 static unsigned char *last_data
;
1817 static unsigned long last_size
;
1822 current_selection
= 0;
1823 if (use_primary_selection
)
1825 if ((owner
= XGetSelectionOwner( display
, XA_PRIMARY
)))
1826 current_selection
= XA_PRIMARY
;
1828 if (!current_selection
)
1830 if ((owner
= XGetSelectionOwner( display
, x11drv_atom(CLIPBOARD
) )))
1831 current_selection
= x11drv_atom(CLIPBOARD
);
1834 if (current_selection
)
1836 if (convert_selection( display
, import_window
, current_selection
, targets
, &type
, &data
, &size
))
1838 else if (convert_selection( display
, import_window
, current_selection
, string
, &type
, &data
, &size
))
1842 changed
= (changed
||
1844 last_selection
!= current_selection
||
1845 last_owner
!= owner
||
1846 last_format
!= format
||
1847 last_type
!= type
||
1848 last_size
!= size
||
1849 memcmp( last_data
, data
, size
));
1851 if (!changed
|| !OpenClipboard( clipboard_hwnd
))
1853 HeapFree( GetProcessHeap(), 0, data
);
1857 TRACE( "selection changed, importing\n" );
1859 is_clipboard_owner
= TRUE
;
1860 rendered_formats
= 0;
1862 if (format
) format
->import( type
, data
, size
);
1864 HeapFree( GetProcessHeap(), 0, last_data
);
1865 last_selection
= current_selection
;
1867 last_format
= format
;
1871 last_clipboard_update
= GetTickCount64();
1874 SetTimer( clipboard_hwnd
, 1, SELECTION_UPDATE_DELAY
, NULL
);
1879 /**************************************************************************
1882 * Periodically update the clipboard while the selection is owned by an X11 app.
1884 BOOL
update_clipboard( HWND hwnd
)
1886 if (use_xfixes
) return TRUE
;
1887 if (hwnd
!= clipboard_hwnd
) return TRUE
;
1888 if (!is_clipboard_owner
) return TRUE
;
1889 if (GetTickCount64() - last_clipboard_update
<= SELECTION_UPDATE_DELAY
) return TRUE
;
1890 return request_selection_contents( thread_display(), FALSE
);
1894 /**************************************************************************
1897 * Window procedure for the clipboard manager.
1899 static LRESULT CALLBACK
clipboard_wndproc( HWND hwnd
, UINT msg
, WPARAM wp
, LPARAM lp
)
1905 case WM_CLIPBOARDUPDATE
:
1906 if (is_clipboard_owner
) break; /* ignore our own changes */
1907 acquire_selection( thread_init_display() );
1909 case WM_RENDERFORMAT
:
1910 if (render_format( wp
)) rendered_formats
++;
1913 if (!is_clipboard_owner
) break;
1914 request_selection_contents( thread_display(), FALSE
);
1916 case WM_DESTROYCLIPBOARD
:
1917 TRACE( "WM_DESTROYCLIPBOARD: lost ownership\n" );
1918 is_clipboard_owner
= FALSE
;
1919 KillTimer( hwnd
, 1 );
1922 return DefWindowProcW( hwnd
, msg
, wp
, lp
);
1926 /**************************************************************************
1927 * wait_clipboard_mutex
1929 * Make sure that there's only one clipboard thread per window station.
1931 static BOOL
wait_clipboard_mutex(void)
1933 static const WCHAR prefix
[] = {'_','_','w','i','n','e','_','c','l','i','p','b','o','a','r','d','_'};
1934 WCHAR buffer
[MAX_PATH
+ ARRAY_SIZE( prefix
)];
1937 memcpy( buffer
, prefix
, sizeof(prefix
) );
1938 if (!GetUserObjectInformationW( GetProcessWindowStation(), UOI_NAME
,
1939 buffer
+ ARRAY_SIZE( prefix
),
1940 sizeof(buffer
) - sizeof(prefix
), NULL
))
1942 ERR( "failed to get winstation name\n" );
1945 mutex
= CreateMutexW( NULL
, TRUE
, buffer
);
1946 if (GetLastError() == ERROR_ALREADY_EXISTS
)
1948 TRACE( "waiting for mutex %s\n", debugstr_w( buffer
));
1949 WaitForSingleObject( mutex
, INFINITE
);
1955 /**************************************************************************
1956 * selection_notify_event
1958 * Called when x11 clipboard content changes
1960 #ifdef SONAME_LIBXFIXES
1961 static BOOL
selection_notify_event( HWND hwnd
, XEvent
*event
)
1963 XFixesSelectionNotifyEvent
*req
= (XFixesSelectionNotifyEvent
*)event
;
1965 if (!is_clipboard_owner
) return FALSE
;
1966 if (req
->owner
== selection_window
) return FALSE
;
1967 request_selection_contents( req
->display
, TRUE
);
1972 /**************************************************************************
1975 * Initialize xfixes to receive clipboard update notifications
1977 static void xfixes_init(void)
1979 #ifdef SONAME_LIBXFIXES
1980 typeof(XFixesSelectSelectionInput
) *pXFixesSelectSelectionInput
;
1981 typeof(XFixesQueryExtension
) *pXFixesQueryExtension
;
1982 typeof(XFixesQueryVersion
) *pXFixesQueryVersion
;
1984 int event_base
, error_base
;
1985 int major
= 3, minor
= 0;
1988 handle
= dlopen(SONAME_LIBXFIXES
, RTLD_NOW
);
1989 if (!handle
) return;
1991 pXFixesQueryExtension
= dlsym(handle
, "XFixesQueryExtension");
1992 if (!pXFixesQueryExtension
) return;
1993 pXFixesQueryVersion
= dlsym(handle
, "XFixesQueryVersion");
1994 if (!pXFixesQueryVersion
) return;
1995 pXFixesSelectSelectionInput
= dlsym(handle
, "XFixesSelectSelectionInput");
1996 if (!pXFixesSelectSelectionInput
) return;
1998 if (!pXFixesQueryExtension(clipboard_display
, &event_base
, &error_base
))
2000 pXFixesQueryVersion(clipboard_display
, &major
, &minor
);
2001 use_xfixes
= (major
>= 1);
2002 if (!use_xfixes
) return;
2004 pXFixesSelectSelectionInput(clipboard_display
, import_window
, x11drv_atom(CLIPBOARD
),
2005 XFixesSetSelectionOwnerNotifyMask
|
2006 XFixesSelectionWindowDestroyNotifyMask
|
2007 XFixesSelectionClientCloseNotifyMask
);
2008 if (use_primary_selection
)
2010 pXFixesSelectSelectionInput(clipboard_display
, import_window
, XA_PRIMARY
,
2011 XFixesSetSelectionOwnerNotifyMask
|
2012 XFixesSelectionWindowDestroyNotifyMask
|
2013 XFixesSelectionClientCloseNotifyMask
);
2015 X11DRV_register_event_handler(event_base
+ XFixesSelectionNotify
,
2016 selection_notify_event
, "XFixesSelectionNotify");
2017 TRACE("xfixes succesully initialized\n");
2019 WARN("xfixes not supported\n");
2024 /**************************************************************************
2027 * Thread running inside the desktop process to manage the clipboard
2029 static DWORD WINAPI
clipboard_thread( void *arg
)
2031 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};
2032 XSetWindowAttributes attr
;
2036 if (!wait_clipboard_mutex()) return 0;
2038 clipboard_display
= thread_init_display();
2039 attr
.event_mask
= PropertyChangeMask
;
2040 import_window
= XCreateWindow( clipboard_display
, root_window
, 0, 0, 1, 1, 0, CopyFromParent
,
2041 InputOutput
, CopyFromParent
, CWEventMask
, &attr
);
2044 ERR( "failed to create import window\n" );
2048 memset( &class, 0, sizeof(class) );
2049 class.lpfnWndProc
= clipboard_wndproc
;
2050 class.lpszClassName
= clipboard_classname
;
2052 if (!RegisterClassW( &class ) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS
)
2054 ERR( "could not register clipboard window class err %u\n", GetLastError() );
2057 if (!(clipboard_hwnd
= CreateWindowW( clipboard_classname
, NULL
, 0, 0, 0, 0, 0,
2058 HWND_MESSAGE
, 0, 0, NULL
)))
2060 ERR( "failed to create clipboard window err %u\n", GetLastError() );
2064 clipboard_thread_id
= GetCurrentThreadId();
2065 AddClipboardFormatListener( clipboard_hwnd
);
2066 register_builtin_formats();
2067 request_selection_contents( clipboard_display
, TRUE
);
2071 TRACE( "clipboard thread %04x running\n", GetCurrentThreadId() );
2072 while (GetMessageW( &msg
, 0, 0, 0 )) DispatchMessageW( &msg
);
2077 /**************************************************************************
2078 * X11DRV_UpdateClipboard
2080 void CDECL
X11DRV_UpdateClipboard(void)
2082 static ULONG last_update
;
2086 if (use_xfixes
) return;
2087 if (GetCurrentThreadId() == clipboard_thread_id
) return;
2088 now
= GetTickCount();
2089 if ((int)(now
- last_update
) <= SELECTION_UPDATE_DELAY
) return;
2090 if (SendMessageTimeoutW( GetClipboardOwner(), WM_X11DRV_UPDATE_CLIPBOARD
, 0, 0,
2091 SMTO_ABORTIFHUNG
, 5000, &ret
) && ret
)
2096 /***********************************************************************
2097 * X11DRV_HandleSelectionRequest
2099 BOOL
X11DRV_SelectionRequest( HWND hwnd
, XEvent
*xev
)
2101 XSelectionRequestEvent
*event
= &xev
->xselectionrequest
;
2102 Display
*display
= event
->display
;
2106 TRACE( "got request on %lx for selection %s target %s win %lx prop %s\n",
2107 event
->owner
, debugstr_xatom( event
->selection
), debugstr_xatom( event
->target
),
2108 event
->requestor
, debugstr_xatom( event
->property
));
2110 if (event
->owner
!= selection_window
) goto done
;
2111 if ((event
->selection
!= x11drv_atom(CLIPBOARD
)) &&
2112 (!use_primary_selection
|| event
->selection
!= XA_PRIMARY
)) goto done
;
2114 /* If the specified property is None the requestor is an obsolete client.
2115 * We support these by using the specified target atom as the reply property.
2117 rprop
= event
->property
;
2119 rprop
= event
->target
;
2121 if (!export_selection( display
, event
->requestor
, rprop
, event
->target
))
2122 rprop
= None
; /* report failure to client */
2125 result
.xselection
.type
= SelectionNotify
;
2126 result
.xselection
.display
= display
;
2127 result
.xselection
.requestor
= event
->requestor
;
2128 result
.xselection
.selection
= event
->selection
;
2129 result
.xselection
.property
= rprop
;
2130 result
.xselection
.target
= event
->target
;
2131 result
.xselection
.time
= event
->time
;
2132 TRACE( "sending SelectionNotify for %s to %lx\n", debugstr_xatom( rprop
), event
->requestor
);
2133 XSendEvent( display
, event
->requestor
, False
, NoEventMask
, &result
);
2138 /***********************************************************************
2139 * X11DRV_SelectionClear
2141 BOOL
X11DRV_SelectionClear( HWND hwnd
, XEvent
*xev
)
2143 XSelectionClearEvent
*event
= &xev
->xselectionclear
;
2145 if (event
->window
!= selection_window
) return FALSE
;
2146 if (event
->selection
!= x11drv_atom(CLIPBOARD
)) return FALSE
;
2148 release_selection( event
->display
, event
->time
);
2149 request_selection_contents( event
->display
, TRUE
);
2154 /**************************************************************************
2155 * X11DRV_InitClipboard
2157 void X11DRV_InitClipboard(void)
2160 HANDLE handle
= CreateThread( NULL
, 0, clipboard_thread
, NULL
, 0, &id
);
2162 if (handle
) CloseHandle( handle
);
2163 else ERR( "failed to create clipboard thread\n" );