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_html( Atom type
, const void *data
, size_t size
);
120 static HANDLE
import_text_uri_list( Atom type
, const void *data
, size_t size
);
121 static HANDLE
import_targets( Atom type
, const void *data
, size_t size
);
123 static BOOL
export_data( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
124 static BOOL
export_string( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
125 static BOOL
export_utf8_string( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
126 static BOOL
export_text( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
127 static BOOL
export_compound_text( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
128 static BOOL
export_pixmap( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
129 static BOOL
export_image_bmp( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
130 static BOOL
export_enhmetafile( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
131 static BOOL
export_text_html( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
132 static BOOL
export_hdrop( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
133 static BOOL
export_targets( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
134 static BOOL
export_multiple( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
135 static BOOL
export_timestamp( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
137 static BOOL
read_property( Display
*display
, Window w
, Atom prop
,
138 Atom
*type
, unsigned char **data
, unsigned long *datasize
);
140 /* Clipboard formats */
142 static const WCHAR RichTextFormatW
[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
143 static const WCHAR GIFW
[] = {'G','I','F',0};
144 static const WCHAR JFIFW
[] = {'J','F','I','F',0};
145 static const WCHAR PNGW
[] = {'P','N','G',0};
146 static const WCHAR HTMLFormatW
[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
155 } builtin_formats
[] =
157 { 0, CF_UNICODETEXT
, XATOM_UTF8_STRING
, import_utf8_string
, export_utf8_string
},
158 { 0, CF_UNICODETEXT
, XATOM_COMPOUND_TEXT
, import_compound_text
, export_compound_text
},
159 { 0, CF_UNICODETEXT
, XA_STRING
, import_string
, export_string
},
160 { 0, CF_UNICODETEXT
, XATOM_text_plain
, import_string
, export_string
},
161 { 0, CF_UNICODETEXT
, XATOM_TEXT
, import_text
, export_text
},
162 { 0, CF_SYLK
, XATOM_WCF_SYLK
, import_data
, export_data
},
163 { 0, CF_DIF
, XATOM_WCF_DIF
, import_data
, export_data
},
164 { 0, CF_TIFF
, XATOM_WCF_TIFF
, import_data
, export_data
},
165 { 0, CF_DIB
, XA_PIXMAP
, import_pixmap
, export_pixmap
},
166 { 0, CF_PENDATA
, XATOM_WCF_PENDATA
, import_data
, export_data
},
167 { 0, CF_RIFF
, XATOM_WCF_RIFF
, import_data
, export_data
},
168 { 0, CF_WAVE
, XATOM_WCF_WAVE
, import_data
, export_data
},
169 { 0, CF_ENHMETAFILE
, XATOM_WCF_ENHMETAFILE
, import_enhmetafile
, export_enhmetafile
},
170 { 0, CF_HDROP
, XATOM_text_uri_list
, import_text_uri_list
, export_hdrop
},
171 { 0, CF_DIB
, XATOM_image_bmp
, import_image_bmp
, export_image_bmp
},
172 { RichTextFormatW
, 0, XATOM_text_rtf
, import_data
, export_data
},
173 { RichTextFormatW
, 0, XATOM_text_richtext
, import_data
, export_data
},
174 { GIFW
, 0, XATOM_image_gif
, import_data
, export_data
},
175 { JFIFW
, 0, XATOM_image_jpeg
, import_data
, export_data
},
176 { PNGW
, 0, XATOM_image_png
, import_data
, export_data
},
177 { HTMLFormatW
, 0, XATOM_HTML_Format
, import_data
, export_data
},
178 { HTMLFormatW
, 0, XATOM_text_html
, import_text_html
, export_text_html
},
179 { 0, 0, XATOM_TARGETS
, import_targets
, export_targets
},
180 { 0, 0, XATOM_MULTIPLE
, NULL
, export_multiple
},
181 { 0, 0, XATOM_TIMESTAMP
, NULL
, export_timestamp
},
184 static struct list format_list
= LIST_INIT( format_list
);
186 #define NB_BUILTIN_FORMATS (sizeof(builtin_formats) / sizeof(builtin_formats[0]))
187 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
189 static DWORD clipboard_thread_id
;
190 static HWND clipboard_hwnd
;
191 static BOOL is_clipboard_owner
;
192 static Window selection_window
;
193 static Window import_window
;
194 static Atom current_selection
;
195 static UINT rendered_formats
;
196 static ULONG64 last_clipboard_update
;
197 static struct clipboard_format
**current_x11_formats
;
198 static unsigned int nb_current_x11_formats
;
200 Display
*clipboard_display
= NULL
;
202 static const char *debugstr_format( UINT id
)
206 if (GetClipboardFormatNameW( id
, buffer
, 256 ))
207 return wine_dbg_sprintf( "%04x %s", id
, debugstr_w(buffer
) );
211 case 0: return "(none)";
212 #define BUILTIN(id) case id: return #id;
215 BUILTIN(CF_METAFILEPICT
)
225 BUILTIN(CF_UNICODETEXT
)
226 BUILTIN(CF_ENHMETAFILE
)
230 BUILTIN(CF_OWNERDISPLAY
)
232 BUILTIN(CF_DSPBITMAP
)
233 BUILTIN(CF_DSPMETAFILEPICT
)
234 BUILTIN(CF_DSPENHMETAFILE
)
236 default: return wine_dbg_sprintf( "%04x", id
);
240 static const char *debugstr_xatom( Atom atom
)
245 if (!atom
) return "(None)";
246 name
= XGetAtomName( thread_display(), atom
);
247 ret
= debugstr_a( name
);
253 static int is_atom_error( Display
*display
, XErrorEvent
*event
, void *arg
)
255 return (event
->error_code
== BadAtom
);
259 /**************************************************************************
262 static struct clipboard_format
*find_win32_format( UINT id
)
264 struct clipboard_format
*format
;
266 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
267 if (format
->id
== id
) return format
;
272 /**************************************************************************
275 static struct clipboard_format
*find_x11_format( Atom atom
)
277 struct clipboard_format
*format
;
279 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
280 if (format
->atom
== atom
) return format
;
285 /**************************************************************************
286 * register_builtin_formats
288 static void register_builtin_formats(void)
290 struct clipboard_format
*formats
;
293 if (!(formats
= HeapAlloc( GetProcessHeap(), 0, NB_BUILTIN_FORMATS
* sizeof(*formats
)))) return;
295 for (i
= 0; i
< NB_BUILTIN_FORMATS
; i
++)
297 if (builtin_formats
[i
].name
)
298 formats
[i
].id
= RegisterClipboardFormatW( builtin_formats
[i
].name
);
300 formats
[i
].id
= builtin_formats
[i
].id
;
302 formats
[i
].atom
= GET_ATOM(builtin_formats
[i
].data
);
303 formats
[i
].import
= builtin_formats
[i
].import
;
304 formats
[i
].export
= builtin_formats
[i
].export
;
305 list_add_tail( &format_list
, &formats
[i
].entry
);
310 /**************************************************************************
313 static void register_formats( const UINT
*ids
, const Atom
*atoms
, unsigned int count
)
315 struct clipboard_format
*formats
;
318 if (!(formats
= HeapAlloc( GetProcessHeap(), 0, count
* sizeof(*formats
)))) return;
320 for (i
= 0; i
< count
; i
++)
322 formats
[i
].id
= ids
[i
];
323 formats
[i
].atom
= atoms
[i
];
324 formats
[i
].import
= import_data
;
325 formats
[i
].export
= export_data
;
326 list_add_tail( &format_list
, &formats
[i
].entry
);
327 TRACE( "registered %s atom %s\n", debugstr_format( ids
[i
] ), debugstr_xatom( atoms
[i
] ));
332 /**************************************************************************
333 * register_win32_formats
335 * Register Win32 clipboard formats the first time we encounter them.
337 static void register_win32_formats( const UINT
*ids
, UINT size
)
339 unsigned int count
, len
;
345 if (list_empty( &format_list
)) register_builtin_formats();
349 for (count
= 0; count
< 256 && size
; ids
++, size
--)
351 if (find_win32_format( *ids
)) continue; /* it already exists */
352 if (!GetClipboardFormatNameW( *ids
, buffer
, 256 )) continue; /* not a named format */
353 if (!(len
= WideCharToMultiByte( CP_UNIXCP
, 0, buffer
, -1, NULL
, 0, NULL
, NULL
))) continue;
354 if (!(names
[count
] = HeapAlloc( GetProcessHeap(), 0, len
))) continue;
355 WideCharToMultiByte( CP_UNIXCP
, 0, buffer
, -1, names
[count
], len
, NULL
, NULL
);
356 new_ids
[count
++] = *ids
;
360 XInternAtoms( thread_display(), names
, count
, False
, atoms
);
361 register_formats( new_ids
, atoms
, count
);
362 while (count
) HeapFree( GetProcessHeap(), 0, names
[--count
] );
367 /**************************************************************************
368 * register_x11_formats
370 * Register X11 atom formats the first time we encounter them.
372 static void register_x11_formats( const Atom
*atoms
, UINT size
)
374 Display
*display
= thread_display();
375 unsigned int i
, pos
, count
;
381 if (list_empty( &format_list
)) register_builtin_formats();
385 for (count
= 0; count
< 256 && size
; atoms
++, size
--)
386 if (!find_x11_format( *atoms
)) new_atoms
[count
++] = *atoms
;
390 X11DRV_expect_error( display
, is_atom_error
, NULL
);
391 if (!XGetAtomNames( display
, new_atoms
, count
, names
)) count
= 0;
392 if (X11DRV_check_error())
394 WARN( "got some bad atoms, ignoring\n" );
398 for (i
= pos
= 0; i
< count
; i
++)
400 if (MultiByteToWideChar( CP_UNIXCP
, 0, names
[i
], -1, buffer
, 256 ) &&
401 (ids
[pos
] = RegisterClipboardFormatW( buffer
)))
402 new_atoms
[pos
++] = new_atoms
[i
];
405 register_formats( ids
, new_atoms
, pos
);
410 /**************************************************************************
413 * Put data as a property on the specified window.
415 static void put_property( Display
*display
, Window win
, Atom prop
, Atom type
, int format
,
416 const void *ptr
, size_t size
)
418 const unsigned char *data
= ptr
;
419 int mode
= PropModeReplace
;
420 size_t width
= (format
== 32) ? sizeof(long) : format
/ 8;
421 size_t max_size
= XExtendedMaxRequestSize( display
) * 4;
423 if (!max_size
) max_size
= XMaxRequestSize( display
) * 4;
424 max_size
-= 64; /* request overhead */
428 size_t count
= min( size
, max_size
/ width
);
429 XChangeProperty( display
, win
, prop
, type
, format
, mode
, data
, count
);
430 mode
= PropModeAppend
;
432 data
+= count
* width
;
437 /**************************************************************************
440 static BOOL
convert_selection( Display
*display
, Window win
, Atom selection
,
441 struct clipboard_format
*format
, Atom
*type
,
442 unsigned char **data
, unsigned long *size
)
447 TRACE( "import %s from %s win %lx to format %s\n",
448 debugstr_xatom( format
->atom
), debugstr_xatom( selection
),
449 win
, debugstr_format( format
->id
) );
451 XConvertSelection( display
, selection
, format
->atom
, x11drv_atom(SELECTION_DATA
), win
, CurrentTime
);
453 for (i
= 0; i
< SELECTION_RETRIES
; i
++)
455 Bool res
= XCheckTypedWindowEvent( display
, win
, SelectionNotify
, &event
);
456 if (res
&& event
.xselection
.selection
== selection
&& event
.xselection
.target
== format
->atom
)
457 return read_property( display
, win
, event
.xselection
.property
, type
, data
, size
);
458 usleep( SELECTION_WAIT
);
460 ERR( "Timed out waiting for SelectionNotify event\n" );
465 /***********************************************************************
468 * Return the size of the bitmap info structure including color table.
470 static int bitmap_info_size( const BITMAPINFO
* info
, WORD coloruse
)
472 unsigned int colors
, size
, masks
= 0;
474 if (info
->bmiHeader
.biSize
== sizeof(BITMAPCOREHEADER
))
476 const BITMAPCOREHEADER
*core
= (const BITMAPCOREHEADER
*)info
;
477 colors
= (core
->bcBitCount
<= 8) ? 1 << core
->bcBitCount
: 0;
478 return sizeof(BITMAPCOREHEADER
) + colors
*
479 ((coloruse
== DIB_RGB_COLORS
) ? sizeof(RGBTRIPLE
) : sizeof(WORD
));
481 else /* assume BITMAPINFOHEADER */
483 colors
= info
->bmiHeader
.biClrUsed
;
484 if (!colors
&& (info
->bmiHeader
.biBitCount
<= 8))
485 colors
= 1 << info
->bmiHeader
.biBitCount
;
486 if (info
->bmiHeader
.biCompression
== BI_BITFIELDS
) masks
= 3;
487 size
= max( info
->bmiHeader
.biSize
, sizeof(BITMAPINFOHEADER
) + masks
* sizeof(DWORD
) );
488 return size
+ colors
* ((coloruse
== DIB_RGB_COLORS
) ? sizeof(RGBQUAD
) : sizeof(WORD
));
493 /***********************************************************************
494 * create_dib_from_bitmap
496 * Allocates a packed DIB and copies the bitmap data into it.
498 static HGLOBAL
create_dib_from_bitmap(HBITMAP hBmp
)
504 LPBITMAPINFOHEADER pbmiHeader
;
505 unsigned int cDataSize
, cPackedSize
, OffsetBits
;
508 if (!GetObjectW( hBmp
, sizeof(bmp
), &bmp
)) return 0;
511 * A packed DIB contains a BITMAPINFO structure followed immediately by
512 * an optional color palette and the pixel data.
515 /* Calculate the size of the packed DIB */
516 cDataSize
= abs( bmp
.bmHeight
) * (((bmp
.bmWidth
* bmp
.bmBitsPixel
+ 31) / 8) & ~3);
517 cPackedSize
= sizeof(BITMAPINFOHEADER
)
518 + ( (bmp
.bmBitsPixel
<= 8) ? (sizeof(RGBQUAD
) * (1 << bmp
.bmBitsPixel
)) : 0 )
520 /* Get the offset to the bits */
521 OffsetBits
= cPackedSize
- cDataSize
;
523 /* Allocate the packed DIB */
524 TRACE("\tAllocating packed DIB of size %d\n", cPackedSize
);
525 hPackedDIB
= GlobalAlloc( GMEM_FIXED
, cPackedSize
);
528 WARN("Could not allocate packed DIB!\n");
532 /* A packed DIB starts with a BITMAPINFOHEADER */
533 pPackedDIB
= GlobalLock(hPackedDIB
);
534 pbmiHeader
= (LPBITMAPINFOHEADER
)pPackedDIB
;
536 /* Init the BITMAPINFOHEADER */
537 pbmiHeader
->biSize
= sizeof(BITMAPINFOHEADER
);
538 pbmiHeader
->biWidth
= bmp
.bmWidth
;
539 pbmiHeader
->biHeight
= bmp
.bmHeight
;
540 pbmiHeader
->biPlanes
= 1;
541 pbmiHeader
->biBitCount
= bmp
.bmBitsPixel
;
542 pbmiHeader
->biCompression
= BI_RGB
;
543 pbmiHeader
->biSizeImage
= 0;
544 pbmiHeader
->biXPelsPerMeter
= pbmiHeader
->biYPelsPerMeter
= 0;
545 pbmiHeader
->biClrUsed
= 0;
546 pbmiHeader
->biClrImportant
= 0;
548 /* Retrieve the DIB bits from the bitmap and fill in the
549 * DIB color table if present */
551 nLinesCopied
= GetDIBits(hdc
, /* Handle to device context */
552 hBmp
, /* Handle to bitmap */
553 0, /* First scan line to set in dest bitmap */
554 bmp
.bmHeight
, /* Number of scan lines to copy */
555 pPackedDIB
+ OffsetBits
, /* [out] Address of array for bitmap bits */
556 (LPBITMAPINFO
) pbmiHeader
, /* [out] Address of BITMAPINFO structure */
557 0); /* RGB or palette index */
558 GlobalUnlock(hPackedDIB
);
561 /* Cleanup if GetDIBits failed */
562 if (nLinesCopied
!= bmp
.bmHeight
)
564 TRACE("\tGetDIBits returned %d. Actual lines=%d\n", nLinesCopied
, bmp
.bmHeight
);
565 GlobalFree(hPackedDIB
);
572 /***********************************************************************
575 * Converts a text/uri-list URI to DOS filename.
577 static WCHAR
* uri_to_dos(char *encodedURI
)
582 char *uri
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, strlen(encodedURI
) + 1);
585 for (i
= 0; encodedURI
[i
]; ++i
)
587 if (encodedURI
[i
] == '%')
589 if (encodedURI
[i
+1] && encodedURI
[i
+2])
593 buffer
[0] = encodedURI
[i
+1];
594 buffer
[1] = encodedURI
[i
+2];
596 sscanf(buffer
, "%x", &number
);
602 WARN("invalid URI encoding in %s\n", debugstr_a(encodedURI
));
603 HeapFree(GetProcessHeap(), 0, uri
);
608 uri
[j
++] = encodedURI
[i
];
611 /* Read http://www.freedesktop.org/wiki/Draganddropwarts and cry... */
612 if (strncmp(uri
, "file:/", 6) == 0)
618 /* file:///path/to/file (nautilus, thunar) */
619 ret
= wine_get_dos_file_name(&uri
[7]);
623 /* file://hostname/path/to/file (X file drag spec) */
625 char *path
= strchr(&uri
[7], '/');
629 if (strcmp(&uri
[7], "localhost") == 0)
632 ret
= wine_get_dos_file_name(path
);
634 else if (gethostname(hostname
, sizeof(hostname
)) == 0)
636 if (strcmp(hostname
, &uri
[7]) == 0)
639 ret
= wine_get_dos_file_name(path
);
647 /* file:/path/to/file (konqueror) */
648 ret
= wine_get_dos_file_name(&uri
[5]);
651 HeapFree(GetProcessHeap(), 0, uri
);
656 /**************************************************************************
657 * unicode_text_from_string
659 * Convert a string in the specified encoding to CF_UNICODETEXT format.
661 static HANDLE
unicode_text_from_string( UINT codepage
, const void *data
, size_t size
)
666 count
= MultiByteToWideChar( codepage
, 0, data
, size
, NULL
, 0);
668 if (!(strW
= GlobalAlloc( GMEM_FIXED
, (count
* 2 + 1) * sizeof(WCHAR
) ))) return 0;
670 MultiByteToWideChar( codepage
, 0, data
, size
, strW
+ count
, count
);
671 for (i
= j
= 0; i
< count
; i
++)
673 if (strW
[i
+ count
] == '\n') strW
[j
++] = '\r';
674 strW
[j
++] = strW
[i
+ count
];
677 GlobalReAlloc( strW
, j
* sizeof(WCHAR
), GMEM_FIXED
); /* release unused space */
678 TRACE( "returning %s\n", debugstr_wn( strW
, j
- 1 ));
683 /**************************************************************************
686 * Import XA_STRING, converting the string to CF_UNICODETEXT.
688 static HANDLE
import_string( Atom type
, const void *data
, size_t size
)
690 return unicode_text_from_string( 28591, data
, size
);
694 /**************************************************************************
697 * Import XA_UTF8_STRING, converting the string to CF_UNICODETEXT.
699 static HANDLE
import_utf8_string( Atom type
, const void *data
, size_t size
)
701 return unicode_text_from_string( CP_UTF8
, data
, size
);
705 /**************************************************************************
706 * import_compound_text
708 * Import COMPOUND_TEXT to CF_UNICODETEXT.
710 static HANDLE
import_compound_text( Atom type
, const void *data
, size_t size
)
715 XTextProperty txtprop
;
717 txtprop
.value
= (BYTE
*)data
;
718 txtprop
.nitems
= size
;
719 txtprop
.encoding
= x11drv_atom(COMPOUND_TEXT
);
721 if (XmbTextPropertyToTextList( thread_display(), &txtprop
, &srcstr
, &count
) != Success
) return 0;
722 if (!count
) return 0;
724 ret
= unicode_text_from_string( CP_UNIXCP
, srcstr
[0], strlen(srcstr
[0]) + 1 );
725 XFreeStringList(srcstr
);
730 /**************************************************************************
733 * Import XA_TEXT, converting the string to CF_UNICODETEXT.
735 static HANDLE
import_text( Atom type
, const void *data
, size_t size
)
737 if (type
== XA_STRING
) return import_string( type
, data
, size
);
738 if (type
== x11drv_atom(UTF8_STRING
)) return import_utf8_string( type
, data
, size
);
739 if (type
== x11drv_atom(COMPOUND_TEXT
)) return import_compound_text( type
, data
, size
);
740 FIXME( "unsupported TEXT type %s\n", debugstr_xatom( type
));
745 /**************************************************************************
748 * Import XA_PIXMAP, converting the image to CF_DIB.
750 static HANDLE
import_pixmap( Atom type
, const void *data
, size_t size
)
752 const Pixmap
*pPixmap
= (const Pixmap
*)data
;
754 XVisualInfo vis
= default_visual
;
755 char buffer
[FIELD_OFFSET( BITMAPINFO
, bmiColors
[256] )];
756 BITMAPINFO
*info
= (BITMAPINFO
*)buffer
;
757 struct gdi_image_bits bits
;
759 int x
,y
; /* Unused */
760 unsigned border_width
; /* Unused */
761 unsigned int depth
, width
, height
;
763 /* Get the Pixmap dimensions and bit depth */
764 if (!XGetGeometry(gdi_display
, *pPixmap
, &root
, &x
, &y
, &width
, &height
,
765 &border_width
, &depth
)) depth
= 0;
766 if (!pixmap_formats
[depth
]) return 0;
768 TRACE( "pixmap properties: width=%d, height=%d, depth=%d\n", width
, height
, depth
);
770 if (depth
!= vis
.depth
) switch (pixmap_formats
[depth
]->bits_per_pixel
)
776 case 16: /* assume R5G5B5 */
777 vis
.red_mask
= 0x7c00;
778 vis
.green_mask
= 0x03e0;
779 vis
.blue_mask
= 0x001f;
781 case 24: /* assume R8G8B8 */
782 case 32: /* assume A8R8G8B8 */
783 vis
.red_mask
= 0xff0000;
784 vis
.green_mask
= 0x00ff00;
785 vis
.blue_mask
= 0x0000ff;
791 if (!get_pixmap_image( *pPixmap
, width
, height
, &vis
, info
, &bits
))
793 DWORD info_size
= bitmap_info_size( info
, DIB_RGB_COLORS
);
795 ptr
= GlobalAlloc( GMEM_FIXED
, info_size
+ info
->bmiHeader
.biSizeImage
);
798 memcpy( ptr
, info
, info_size
);
799 memcpy( ptr
+ info_size
, bits
.ptr
, info
->bmiHeader
.biSizeImage
);
801 if (bits
.free
) bits
.free( &bits
);
807 /**************************************************************************
810 * Import image/bmp, converting the image to CF_DIB.
812 static HANDLE
import_image_bmp( Atom type
, const void *data
, size_t size
)
814 HANDLE hClipData
= 0;
815 const BITMAPFILEHEADER
*bfh
= data
;
817 if (size
>= sizeof(BITMAPFILEHEADER
)+sizeof(BITMAPCOREHEADER
) &&
818 bfh
->bfType
== 0x4d42 /* "BM" */)
820 const BITMAPINFO
*bmi
= (const BITMAPINFO
*)(bfh
+ 1);
824 if ((hbmp
= CreateDIBitmap( hdc
, &bmi
->bmiHeader
, CBM_INIT
,
825 (const BYTE
*)data
+ bfh
->bfOffBits
, bmi
, DIB_RGB_COLORS
)))
827 hClipData
= create_dib_from_bitmap( hbmp
);
836 /**************************************************************************
839 static HANDLE
import_enhmetafile( Atom type
, const void *data
, size_t size
)
841 return SetEnhMetaFileBits( size
, data
);
845 /**************************************************************************
848 static HANDLE
import_text_html( Atom type
, const void *data
, size_t size
)
850 static const char header
[] =
852 "StartHTML:0000000100\n"
854 "StartFragment:%010lu\n"
855 "EndFragment:%010lu\n"
856 "<!--StartFragment-->";
857 static const char trailer
[] = "\n<!--EndFragment-->";
862 /* Firefox uses UTF-16LE with byte order mark. Convert to UTF-8 without the BOM. */
863 if (size
>= sizeof(WCHAR
) && ((const WCHAR
*)data
)[0] == 0xfeff)
865 len
= WideCharToMultiByte( CP_UTF8
, 0, (const WCHAR
*)data
+ 1, size
/ sizeof(WCHAR
) - 1,
866 NULL
, 0, NULL
, NULL
);
867 if (!(text
= HeapAlloc( GetProcessHeap(), 0, len
))) return 0;
868 WideCharToMultiByte( CP_UTF8
, 0, (const WCHAR
*)data
+ 1, size
/ sizeof(WCHAR
) - 1,
869 text
, len
, NULL
, NULL
);
874 len
= strlen( header
) + 12; /* 3 * 4 extra chars for %010lu */
875 total
= len
+ size
+ sizeof(trailer
);
876 if ((ret
= GlobalAlloc( GMEM_FIXED
, total
)))
879 p
+= sprintf( p
, header
, total
- 1, len
, len
+ size
+ 1 /* include the final \n in the data */ );
880 memcpy( p
, data
, size
);
881 strcpy( p
+ size
, trailer
);
882 TRACE( "returning %s\n", debugstr_a( ret
));
884 HeapFree( GetProcessHeap(), 0, text
);
889 /**************************************************************************
890 * import_text_uri_list
892 * Import text/uri-list.
894 static HANDLE
import_text_uri_list( Atom type
, const void *data
, size_t size
)
896 const char *uriList
= data
;
904 DROPFILES
*dropFiles
= NULL
;
906 if (!(out
= HeapAlloc(GetProcessHeap(), 0, capacity
* sizeof(WCHAR
)))) return 0;
910 while (end
< size
&& uriList
[end
] != '\r')
912 if (end
< (size
- 1) && uriList
[end
+1] != '\n')
914 WARN("URI list line doesn't end in \\r\\n\n");
918 uri
= HeapAlloc(GetProcessHeap(), 0, end
- start
+ 1);
921 lstrcpynA(uri
, &uriList
[start
], end
- start
+ 1);
922 path
= uri_to_dos(uri
);
923 TRACE("converted URI %s to DOS path %s\n", debugstr_a(uri
), debugstr_w(path
));
924 HeapFree(GetProcessHeap(), 0, uri
);
928 int pathSize
= strlenW(path
) + 1;
929 if (pathSize
> capacity
- total
)
931 capacity
= 2*capacity
+ pathSize
;
932 out
= HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, out
, (capacity
+ 1)*sizeof(WCHAR
));
936 memcpy(&out
[total
], path
, pathSize
* sizeof(WCHAR
));
939 HeapFree(GetProcessHeap(), 0, path
);
947 if (out
&& end
>= size
)
949 if ((dropFiles
= GlobalAlloc( GMEM_FIXED
, sizeof(DROPFILES
) + (total
+ 1) * sizeof(WCHAR
) )))
951 dropFiles
->pFiles
= sizeof(DROPFILES
);
955 dropFiles
->fWide
= TRUE
;
957 memcpy( (char*)dropFiles
+ dropFiles
->pFiles
, out
, (total
+ 1) * sizeof(WCHAR
) );
960 HeapFree(GetProcessHeap(), 0, out
);
965 /**************************************************************************
968 * Import TARGETS and mark the corresponding clipboard formats as available.
970 static HANDLE
import_targets( Atom type
, const void *data
, size_t size
)
972 UINT i
, pos
, count
= size
/ sizeof(Atom
);
973 const Atom
*properties
= data
;
974 struct clipboard_format
*format
, **formats
;
976 if (type
!= XA_ATOM
&& type
!= x11drv_atom(TARGETS
)) return 0;
978 register_x11_formats( properties
, count
);
980 /* the builtin formats contain duplicates, so allocate some extra space */
981 if (!(formats
= HeapAlloc( GetProcessHeap(), 0, (count
+ NB_BUILTIN_FORMATS
) * sizeof(*formats
))))
985 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
987 for (i
= 0; i
< count
; i
++) if (properties
[i
] == format
->atom
) break;
988 if (i
== count
) continue;
989 if (format
->import
&& format
->id
)
991 TRACE( "property %s -> format %s\n",
992 debugstr_xatom( properties
[i
] ), debugstr_format( format
->id
));
993 SetClipboardData( format
->id
, 0 );
994 formats
[pos
++] = format
;
996 else TRACE( "property %s (ignoring)\n", debugstr_xatom( properties
[i
] ));
999 HeapFree( GetProcessHeap(), 0, current_x11_formats
);
1000 current_x11_formats
= formats
;
1001 nb_current_x11_formats
= pos
;
1006 /**************************************************************************
1009 * Generic import clipboard data routine.
1011 static HANDLE
import_data( Atom type
, const void *data
, size_t size
)
1013 void *ret
= GlobalAlloc( GMEM_FIXED
, size
);
1015 if (ret
) memcpy( ret
, data
, size
);
1020 /**************************************************************************
1023 * Import the specified format from the selection and return a global handle to the data.
1025 static HANDLE
import_selection( Display
*display
, Window win
, Atom selection
,
1026 struct clipboard_format
*format
)
1028 unsigned char *data
;
1033 if (!format
->import
) return 0;
1035 if (!convert_selection( display
, win
, selection
, format
, &type
, &data
, &size
))
1037 TRACE( "failed to convert selection\n" );
1040 ret
= format
->import( type
, data
, size
);
1041 HeapFree( GetProcessHeap(), 0, data
);
1046 /**************************************************************************
1047 * X11DRV_CLIPBOARD_ImportSelection
1049 * Import the X selection into the clipboard format registered for the given X target.
1051 void X11DRV_CLIPBOARD_ImportSelection( Display
*display
, Window win
, Atom selection
,
1052 Atom
*targets
, UINT count
,
1053 void (*callback
)( Atom
, UINT
, HANDLE
))
1057 struct clipboard_format
*format
;
1059 register_x11_formats( targets
, count
);
1061 for (i
= 0; i
< count
; i
++)
1063 if (!(format
= find_x11_format( targets
[i
] ))) continue;
1064 if (!format
->id
) continue;
1065 if (!(handle
= import_selection( display
, win
, selection
, format
))) continue;
1066 callback( targets
[i
], format
->id
, handle
);
1071 /**************************************************************************
1074 static HANDLE
render_format( UINT id
)
1076 Display
*display
= thread_display();
1080 if (!current_selection
) return 0;
1082 for (i
= 0; i
< nb_current_x11_formats
; i
++)
1084 if (current_x11_formats
[i
]->id
!= id
) continue;
1085 handle
= import_selection( display
, import_window
, current_selection
, current_x11_formats
[i
] );
1086 if (handle
) SetClipboardData( id
, handle
);
1093 /**************************************************************************
1096 * Generic export clipboard data routine.
1098 static BOOL
export_data( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1100 void *ptr
= GlobalLock( handle
);
1102 if (!ptr
) return FALSE
;
1103 put_property( display
, win
, prop
, target
, 8, ptr
, GlobalSize( handle
));
1104 GlobalUnlock( handle
);
1109 /**************************************************************************
1110 * string_from_unicode_text
1112 * Convert CF_UNICODETEXT data to a string in the specified codepage.
1114 static char *string_from_unicode_text( UINT codepage
, HANDLE handle
, UINT
*size
)
1118 WCHAR
*strW
= GlobalLock( handle
);
1119 UINT lenW
= GlobalSize( handle
) / sizeof(WCHAR
);
1120 DWORD len
= WideCharToMultiByte( codepage
, 0, strW
, lenW
, NULL
, 0, NULL
, NULL
);
1122 if ((str
= HeapAlloc( GetProcessHeap(), 0, len
)))
1124 WideCharToMultiByte( codepage
, 0, strW
, lenW
, str
, len
, NULL
, NULL
);
1125 GlobalUnlock( handle
);
1127 /* remove carriage returns */
1128 for (i
= j
= 0; i
< len
; i
++)
1130 if (str
[i
] == '\r' && (i
== len
- 1 || str
[i
+ 1] == '\n')) continue;
1133 if (j
&& !str
[j
- 1]) j
--; /* remove trailing null */
1135 TRACE( "returning %s\n", debugstr_an( str
, j
));
1137 GlobalUnlock( handle
);
1142 /**************************************************************************
1145 * Export CF_UNICODETEXT converting the string to XA_STRING.
1147 static BOOL
export_string( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1150 char *text
= string_from_unicode_text( 28591, handle
, &size
);
1152 if (!text
) return FALSE
;
1153 put_property( display
, win
, prop
, target
, 8, text
, size
);
1154 HeapFree( GetProcessHeap(), 0, text
);
1155 GlobalUnlock( handle
);
1160 /**************************************************************************
1161 * export_utf8_string
1163 * Export CF_UNICODE converting the string to UTF8.
1165 static BOOL
export_utf8_string( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1168 char *text
= string_from_unicode_text( CP_UTF8
, handle
, &size
);
1170 if (!text
) return FALSE
;
1171 put_property( display
, win
, prop
, target
, 8, text
, size
);
1172 HeapFree( GetProcessHeap(), 0, text
);
1173 GlobalUnlock( handle
);
1178 /**************************************************************************
1181 * Export CF_UNICODE to the polymorphic TEXT type, using UTF8.
1183 static BOOL
export_text( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1185 return export_utf8_string( display
, win
, prop
, x11drv_atom(UTF8_STRING
), handle
);
1189 /**************************************************************************
1190 * export_compound_text
1192 * Export CF_UNICODE to COMPOUND_TEXT
1194 static BOOL
export_compound_text( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1196 XTextProperty textprop
;
1197 XICCEncodingStyle style
;
1199 char *text
= string_from_unicode_text( CP_UNIXCP
, handle
, &size
);
1201 if (!text
) return FALSE
;
1202 if (target
== x11drv_atom(COMPOUND_TEXT
))
1203 style
= XCompoundTextStyle
;
1205 style
= XStdICCTextStyle
;
1207 /* Update the X property */
1208 if (XmbTextListToTextProperty( display
, &text
, 1, style
, &textprop
) == Success
)
1210 XSetTextProperty( display
, win
, &textprop
, prop
);
1211 XFree( textprop
.value
);
1214 HeapFree( GetProcessHeap(), 0, text
);
1219 /**************************************************************************
1222 * Export CF_DIB to XA_PIXMAP.
1224 static BOOL
export_pixmap( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1228 struct gdi_image_bits bits
;
1230 pbmi
= GlobalLock( handle
);
1231 bits
.ptr
= (LPBYTE
)pbmi
+ bitmap_info_size( pbmi
, DIB_RGB_COLORS
);
1233 bits
.is_copy
= FALSE
;
1234 pixmap
= create_pixmap_from_image( 0, &default_visual
, pbmi
, &bits
, DIB_RGB_COLORS
);
1235 GlobalUnlock( handle
);
1237 put_property( display
, win
, prop
, target
, 32, &pixmap
, 1 );
1238 /* FIXME: free the pixmap when the property is deleted */
1243 /**************************************************************************
1246 * Export CF_DIB to image/bmp.
1248 static BOOL
export_image_bmp( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1250 LPBYTE dibdata
= GlobalLock( handle
);
1252 BITMAPFILEHEADER
*bfh
;
1254 bmpsize
= sizeof(BITMAPFILEHEADER
) + GlobalSize( handle
);
1255 bfh
= HeapAlloc( GetProcessHeap(), 0, bmpsize
);
1258 /* bitmap file header */
1259 bfh
->bfType
= 0x4d42; /* "BM" */
1260 bfh
->bfSize
= bmpsize
;
1261 bfh
->bfReserved1
= 0;
1262 bfh
->bfReserved2
= 0;
1263 bfh
->bfOffBits
= sizeof(BITMAPFILEHEADER
) + bitmap_info_size((BITMAPINFO
*)dibdata
, DIB_RGB_COLORS
);
1265 /* rest of bitmap is the same as the packed dib */
1266 memcpy(bfh
+1, dibdata
, bmpsize
-sizeof(BITMAPFILEHEADER
));
1268 GlobalUnlock( handle
);
1269 put_property( display
, win
, prop
, target
, 8, bfh
, bmpsize
);
1270 HeapFree( GetProcessHeap(), 0, bfh
);
1275 /**************************************************************************
1276 * export_enhmetafile
1278 * Export EnhMetaFile.
1280 static BOOL
export_enhmetafile( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1285 if (!(size
= GetEnhMetaFileBits( handle
, 0, NULL
))) return FALSE
;
1286 if (!(ptr
= HeapAlloc( GetProcessHeap(), 0, size
))) return FALSE
;
1288 GetEnhMetaFileBits( handle
, size
, ptr
);
1289 put_property( display
, win
, prop
, target
, 8, ptr
, size
);
1290 HeapFree( GetProcessHeap(), 0, ptr
);
1295 /**************************************************************************
1296 * get_html_description_field
1298 * Find the value of a field in an HTML Format description.
1300 static LPCSTR
get_html_description_field(LPCSTR data
, LPCSTR keyword
)
1304 while (pos
&& *pos
&& *pos
!= '<')
1306 if (memcmp(pos
, keyword
, strlen(keyword
)) == 0)
1307 return pos
+strlen(keyword
);
1309 pos
= strchr(pos
, '\n');
1317 /**************************************************************************
1320 * Export HTML Format to text/html.
1322 * FIXME: We should attempt to add an <a base> tag and convert windows paths.
1324 static BOOL
export_text_html( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1326 LPCSTR data
, field_value
;
1327 UINT fragmentstart
, fragmentend
;
1329 data
= GlobalLock( handle
);
1331 /* read the important fields */
1332 field_value
= get_html_description_field(data
, "StartFragment:");
1335 ERR("Couldn't find StartFragment value\n");
1338 fragmentstart
= atoi(field_value
);
1340 field_value
= get_html_description_field(data
, "EndFragment:");
1343 ERR("Couldn't find EndFragment value\n");
1346 fragmentend
= atoi(field_value
);
1348 /* export only the fragment */
1349 put_property( display
, win
, prop
, target
, 8, &data
[fragmentstart
], fragmentend
- fragmentstart
);
1350 GlobalUnlock( handle
);
1354 GlobalUnlock( handle
);
1359 /**************************************************************************
1362 * Export CF_HDROP format to text/uri-list.
1364 static BOOL
export_hdrop( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1369 UINT textUriListSize
= 32;
1372 textUriList
= HeapAlloc( GetProcessHeap(), 0, textUriListSize
);
1373 if (!textUriList
) return FALSE
;
1374 numFiles
= DragQueryFileW( handle
, 0xFFFFFFFF, NULL
, 0 );
1375 for (i
= 0; i
< numFiles
; i
++)
1377 UINT dosFilenameSize
;
1378 WCHAR
*dosFilename
= NULL
;
1379 char *unixFilename
= NULL
;
1383 dosFilenameSize
= 1 + DragQueryFileW( handle
, i
, NULL
, 0 );
1384 dosFilename
= HeapAlloc(GetProcessHeap(), 0, dosFilenameSize
*sizeof(WCHAR
));
1385 if (dosFilename
== NULL
) goto failed
;
1386 DragQueryFileW( handle
, i
, dosFilename
, dosFilenameSize
);
1387 unixFilename
= wine_get_unix_file_name(dosFilename
);
1388 HeapFree(GetProcessHeap(), 0, dosFilename
);
1389 if (unixFilename
== NULL
) goto failed
;
1390 uriSize
= 8 + /* file:/// */
1391 3 * (lstrlenA(unixFilename
) - 1) + /* "%xy" per char except first '/' */
1393 if ((next
+ uriSize
) > textUriListSize
)
1395 UINT biggerSize
= max( 2 * textUriListSize
, next
+ uriSize
);
1396 void *bigger
= HeapReAlloc( GetProcessHeap(), 0, textUriList
, biggerSize
);
1399 textUriList
= bigger
;
1400 textUriListSize
= biggerSize
;
1404 HeapFree(GetProcessHeap(), 0, unixFilename
);
1408 lstrcpyA(&textUriList
[next
], "file:///");
1410 /* URL encode everything - unnecessary, but easier/lighter than linking in shlwapi, and can't hurt */
1411 for (u
= 1; unixFilename
[u
]; u
++)
1413 static const char hex_table
[] = "0123456789abcdef";
1414 textUriList
[next
++] = '%';
1415 textUriList
[next
++] = hex_table
[unixFilename
[u
] >> 4];
1416 textUriList
[next
++] = hex_table
[unixFilename
[u
] & 0xf];
1418 textUriList
[next
++] = '\r';
1419 textUriList
[next
++] = '\n';
1420 HeapFree(GetProcessHeap(), 0, unixFilename
);
1422 put_property( display
, win
, prop
, target
, 8, textUriList
, next
);
1423 HeapFree( GetProcessHeap(), 0, textUriList
);
1427 HeapFree( GetProcessHeap(), 0, textUriList
);
1432 /***********************************************************************
1433 * get_clipboard_formats
1435 * Return a list of all formats currently available on the Win32 clipboard.
1436 * Helper for export_targets.
1438 static UINT
*get_clipboard_formats( UINT
*size
)
1445 if (!(ids
= HeapAlloc( GetProcessHeap(), 0, *size
* sizeof(*ids
) ))) return NULL
;
1446 if (GetUpdatedClipboardFormats( ids
, *size
, size
)) break;
1447 HeapFree( GetProcessHeap(), 0, ids
);
1448 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER
) return NULL
;
1450 register_win32_formats( ids
, *size
);
1455 /***********************************************************************
1456 * is_format_available
1458 * Check if a clipboard format is included in the list.
1459 * Helper for export_targets.
1461 static BOOL
is_format_available( UINT format
, const UINT
*ids
, unsigned int count
)
1463 while (count
--) if (*ids
++ == format
) return TRUE
;
1468 /***********************************************************************
1471 * Service a TARGETS selection request event
1473 static BOOL
export_targets( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1475 struct clipboard_format
*format
;
1476 UINT pos
, count
, *formats
;
1479 if (!(formats
= get_clipboard_formats( &count
))) return FALSE
;
1481 /* the builtin formats contain duplicates, so allocate some extra space */
1482 if (!(targets
= HeapAlloc( GetProcessHeap(), 0, (count
+ NB_BUILTIN_FORMATS
) * sizeof(*targets
) )))
1484 HeapFree( GetProcessHeap(), 0, formats
);
1489 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
1491 if (!format
->export
) continue;
1492 /* formats with id==0 are always exported */
1493 if (format
->id
&& !is_format_available( format
->id
, formats
, count
)) continue;
1494 TRACE( "%d: %s -> %s\n", pos
, debugstr_format( format
->id
), debugstr_xatom( format
->atom
));
1495 targets
[pos
++] = format
->atom
;
1498 put_property( display
, win
, prop
, XA_ATOM
, 32, targets
, pos
);
1499 HeapFree( GetProcessHeap(), 0, targets
);
1500 HeapFree( GetProcessHeap(), 0, formats
);
1505 /**************************************************************************
1508 * Export selection data, depending on the target type.
1510 static BOOL
export_selection( Display
*display
, Window win
, Atom prop
, Atom target
)
1512 struct clipboard_format
*format
;
1514 BOOL open
= FALSE
, ret
= FALSE
;
1516 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
1518 if (format
->atom
!= target
) continue;
1519 if (!format
->export
) continue;
1522 TRACE( "win %lx prop %s target %s\n", win
, debugstr_xatom( prop
), debugstr_xatom( target
));
1523 ret
= format
->export( display
, win
, prop
, target
, 0 );
1526 if (!open
&& !(open
= OpenClipboard( clipboard_hwnd
)))
1528 ERR( "failed to open clipboard for %s\n", debugstr_xatom( target
));
1531 if ((handle
= GetClipboardData( format
->id
)))
1533 TRACE( "win %lx prop %s target %s exporting %s %p\n",
1534 win
, debugstr_xatom( prop
), debugstr_xatom( target
),
1535 debugstr_format( format
->id
), handle
);
1537 ret
= format
->export( display
, win
, prop
, target
, handle
);
1540 /* keep looking for another Win32 format mapping to the same target */
1542 if (open
) CloseClipboard();
1547 /***********************************************************************
1550 * Service a MULTIPLE selection request event
1551 * prop contains a list of (target,property) atom pairs.
1552 * The first atom names a target and the second names a property.
1553 * The effect is as if we have received a sequence of SelectionRequest events
1554 * (one for each atom pair) except that:
1555 * 1. We reply with a SelectionNotify only when all the requested conversions
1556 * have been performed.
1557 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
1558 * we replace the atom in the property by None.
1560 static BOOL
export_multiple( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1565 unsigned long i
, count
, failed
, remain
;
1567 /* Read the MULTIPLE property contents. This should contain a list of
1568 * (target,property) atom pairs.
1570 if (XGetWindowProperty( display
, win
, prop
, 0, 0x3FFF, False
, AnyPropertyType
, &atype
, &aformat
,
1571 &count
, &remain
, (unsigned char**)&list
))
1574 TRACE( "type %s format %d count %ld remain %ld\n",
1575 debugstr_xatom( atype
), aformat
, count
, remain
);
1578 * Make sure we got what we expect.
1579 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
1580 * in a MULTIPLE selection request should be of type ATOM_PAIR.
1581 * However some X apps(such as XPaint) are not compliant with this and return
1582 * a user defined atom in atype when XGetWindowProperty is called.
1583 * The data *is* an atom pair but is not denoted as such.
1585 if (aformat
== 32 /* atype == xAtomPair */ )
1587 for (i
= failed
= 0; i
< count
; i
+= 2)
1589 if (list
[i
+1] == None
) continue;
1590 if (export_selection( display
, win
, list
[i
+ 1], list
[i
] )) continue;
1594 if (failed
) put_property( display
, win
, prop
, atype
, 32, list
, count
);
1601 /***********************************************************************
1604 * Export the timestamp that was used to acquire the selection
1606 static BOOL
export_timestamp( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1608 Time time
= CurrentTime
; /* FIXME */
1609 put_property( display
, win
, prop
, XA_INTEGER
, 32, &time
, 1 );
1614 /**************************************************************************
1615 * X11DRV_CLIPBOARD_GetProperty
1616 * Gets type, data and size.
1618 static BOOL
X11DRV_CLIPBOARD_GetProperty(Display
*display
, Window w
, Atom prop
,
1619 Atom
*atype
, unsigned char** data
, unsigned long* datasize
)
1622 unsigned long pos
= 0, nitems
, remain
, count
;
1623 unsigned char *val
= NULL
, *buffer
;
1627 if (XGetWindowProperty(display
, w
, prop
, pos
, INT_MAX
/ 4, False
,
1628 AnyPropertyType
, atype
, &aformat
, &nitems
, &remain
, &buffer
))
1630 WARN("Failed to read property\n");
1631 HeapFree( GetProcessHeap(), 0, val
);
1635 count
= get_property_size( aformat
, nitems
);
1636 if (!val
) *data
= HeapAlloc( GetProcessHeap(), 0, pos
* sizeof(int) + count
+ 1 );
1637 else *data
= HeapReAlloc( GetProcessHeap(), 0, val
, pos
* sizeof(int) + count
+ 1 );
1642 HeapFree( GetProcessHeap(), 0, val
);
1646 memcpy( (int *)val
+ pos
, buffer
, count
);
1650 *datasize
= pos
* sizeof(int) + count
;
1654 pos
+= count
/ sizeof(int);
1657 TRACE( "got property %s type %s format %u len %lu from window %lx\n",
1658 debugstr_xatom( prop
), debugstr_xatom( *atype
), aformat
, *datasize
, w
);
1660 /* Delete the property on the window now that we are done
1661 * This will send a PropertyNotify event to the selection owner. */
1662 XDeleteProperty(display
, w
, prop
);
1667 struct clipboard_data_packet
{
1670 unsigned char *data
;
1673 /**************************************************************************
1676 * Reads the contents of the X selection property.
1678 static BOOL
read_property( Display
*display
, Window w
, Atom prop
,
1679 Atom
*type
, unsigned char **data
, unsigned long *datasize
)
1686 while (XCheckTypedWindowEvent(display
, w
, PropertyNotify
, &xe
))
1689 if (!X11DRV_CLIPBOARD_GetProperty(display
, w
, prop
, type
, data
, datasize
))
1692 if (*type
== x11drv_atom(INCR
))
1695 unsigned long bufsize
= 0;
1696 struct list packets
;
1697 struct clipboard_data_packet
*packet
, *packet2
;
1700 HeapFree(GetProcessHeap(), 0, *data
);
1703 list_init(&packets
);
1708 unsigned char *prop_data
;
1709 unsigned long prop_size
;
1711 /* Wait until PropertyNotify is received */
1712 for (i
= 0; i
< SELECTION_RETRIES
; i
++)
1716 res
= XCheckTypedWindowEvent(display
, w
, PropertyNotify
, &xe
);
1717 if (res
&& xe
.xproperty
.atom
== prop
&&
1718 xe
.xproperty
.state
== PropertyNewValue
)
1720 usleep(SELECTION_WAIT
);
1723 if (i
>= SELECTION_RETRIES
||
1724 !X11DRV_CLIPBOARD_GetProperty(display
, w
, prop
, type
, &prop_data
, &prop_size
))
1730 /* Retrieved entire data. */
1733 HeapFree(GetProcessHeap(), 0, prop_data
);
1738 packet
= HeapAlloc(GetProcessHeap(), 0, sizeof(*packet
));
1741 HeapFree(GetProcessHeap(), 0, prop_data
);
1746 packet
->size
= prop_size
;
1747 packet
->data
= prop_data
;
1748 list_add_tail(&packets
, &packet
->entry
);
1749 bufsize
+= prop_size
;
1754 buf
= HeapAlloc(GetProcessHeap(), 0, bufsize
+ 1);
1757 unsigned long bytes_copied
= 0;
1758 *datasize
= bufsize
;
1759 LIST_FOR_EACH_ENTRY( packet
, &packets
, struct clipboard_data_packet
, entry
)
1761 memcpy(&buf
[bytes_copied
], packet
->data
, packet
->size
);
1762 bytes_copied
+= packet
->size
;
1771 LIST_FOR_EACH_ENTRY_SAFE( packet
, packet2
, &packets
, struct clipboard_data_packet
, entry
)
1773 HeapFree(GetProcessHeap(), 0, packet
->data
);
1774 HeapFree(GetProcessHeap(), 0, packet
);
1784 /**************************************************************************
1787 * Acquire the X11 selection when the Win32 clipboard has changed.
1789 static void acquire_selection( Display
*display
)
1791 if (selection_window
) XDestroyWindow( display
, selection_window
);
1793 selection_window
= XCreateWindow( display
, root_window
, 0, 0, 1, 1, 0, CopyFromParent
,
1794 InputOutput
, CopyFromParent
, 0, NULL
);
1795 if (!selection_window
) return;
1797 XSetSelectionOwner( display
, x11drv_atom(CLIPBOARD
), selection_window
, CurrentTime
);
1798 if (use_primary_selection
) XSetSelectionOwner( display
, XA_PRIMARY
, selection_window
, CurrentTime
);
1799 TRACE( "win %lx\n", selection_window
);
1803 /**************************************************************************
1806 * Release the X11 selection when some other X11 app has grabbed it.
1808 static void release_selection( Display
*display
, Time time
)
1810 assert( selection_window
);
1812 TRACE( "win %lx\n", selection_window
);
1814 /* release PRIMARY if we still own it */
1815 if (use_primary_selection
&& XGetSelectionOwner( display
, XA_PRIMARY
) == selection_window
)
1816 XSetSelectionOwner( display
, XA_PRIMARY
, None
, time
);
1818 XDestroyWindow( display
, selection_window
);
1819 selection_window
= 0;
1823 /**************************************************************************
1824 * request_selection_contents
1826 * Retrieve the contents of the X11 selection when it's owned by an X11 app.
1828 static BOOL
request_selection_contents( Display
*display
, BOOL changed
)
1830 struct clipboard_format
*targets
= find_x11_format( x11drv_atom(TARGETS
) );
1831 struct clipboard_format
*string
= find_x11_format( XA_STRING
);
1832 struct clipboard_format
*format
= NULL
;
1834 unsigned char *data
= NULL
;
1835 unsigned long size
= 0;
1838 static Atom last_selection
;
1839 static Window last_owner
;
1840 static struct clipboard_format
*last_format
;
1841 static Atom last_type
;
1842 static unsigned char *last_data
;
1843 static unsigned long last_size
;
1848 current_selection
= 0;
1849 if (use_primary_selection
)
1851 if ((owner
= XGetSelectionOwner( display
, XA_PRIMARY
)))
1852 current_selection
= XA_PRIMARY
;
1854 if (!current_selection
)
1856 if ((owner
= XGetSelectionOwner( display
, x11drv_atom(CLIPBOARD
) )))
1857 current_selection
= x11drv_atom(CLIPBOARD
);
1860 if (current_selection
)
1862 if (convert_selection( display
, import_window
, current_selection
, targets
, &type
, &data
, &size
))
1864 else if (convert_selection( display
, import_window
, current_selection
, string
, &type
, &data
, &size
))
1868 changed
= (changed
||
1870 last_selection
!= current_selection
||
1871 last_owner
!= owner
||
1872 last_format
!= format
||
1873 last_type
!= type
||
1874 last_size
!= size
||
1875 memcmp( last_data
, data
, size
));
1879 HeapFree( GetProcessHeap(), 0, data
);
1883 if (!OpenClipboard( clipboard_hwnd
)) return FALSE
;
1884 TRACE( "selection changed, importing\n" );
1886 is_clipboard_owner
= TRUE
;
1887 rendered_formats
= 0;
1889 if (format
) format
->import( type
, data
, size
);
1891 HeapFree( GetProcessHeap(), 0, last_data
);
1892 last_selection
= current_selection
;
1894 last_format
= format
;
1898 last_clipboard_update
= GetTickCount64();
1900 SetTimer( clipboard_hwnd
, 1, SELECTION_UPDATE_DELAY
, NULL
);
1905 /**************************************************************************
1908 * Periodically update the clipboard while the selection is owned by an X11 app.
1910 BOOL
update_clipboard( HWND hwnd
)
1912 if (hwnd
!= clipboard_hwnd
) return TRUE
;
1913 if (!is_clipboard_owner
) return TRUE
;
1914 if (GetTickCount64() - last_clipboard_update
<= SELECTION_UPDATE_DELAY
) return TRUE
;
1915 return request_selection_contents( thread_display(), FALSE
);
1919 /**************************************************************************
1922 * Window procedure for the clipboard manager.
1924 static LRESULT CALLBACK
clipboard_wndproc( HWND hwnd
, UINT msg
, WPARAM wp
, LPARAM lp
)
1930 case WM_CLIPBOARDUPDATE
:
1931 if (is_clipboard_owner
) break; /* ignore our own changes */
1932 acquire_selection( thread_init_display() );
1934 case WM_RENDERFORMAT
:
1935 if (render_format( wp
)) rendered_formats
++;
1938 if (!is_clipboard_owner
) break;
1939 request_selection_contents( thread_display(), FALSE
);
1941 case WM_DESTROYCLIPBOARD
:
1942 TRACE( "WM_DESTROYCLIPBOARD: lost ownership\n" );
1943 is_clipboard_owner
= FALSE
;
1944 KillTimer( hwnd
, 1 );
1947 return DefWindowProcW( hwnd
, msg
, wp
, lp
);
1951 /**************************************************************************
1952 * wait_clipboard_mutex
1954 * Make sure that there's only one clipboard thread per window station.
1956 static BOOL
wait_clipboard_mutex(void)
1958 static const WCHAR prefix
[] = {'_','_','w','i','n','e','_','c','l','i','p','b','o','a','r','d','_'};
1959 WCHAR buffer
[MAX_PATH
+ sizeof(prefix
) / sizeof(WCHAR
)];
1962 memcpy( buffer
, prefix
, sizeof(prefix
) );
1963 if (!GetUserObjectInformationW( GetProcessWindowStation(), UOI_NAME
,
1964 buffer
+ sizeof(prefix
) / sizeof(WCHAR
),
1965 sizeof(buffer
) - sizeof(prefix
), NULL
))
1967 ERR( "failed to get winstation name\n" );
1970 mutex
= CreateMutexW( NULL
, TRUE
, buffer
);
1971 if (GetLastError() == ERROR_ALREADY_EXISTS
)
1973 TRACE( "waiting for mutex %s\n", debugstr_w( buffer
));
1974 WaitForSingleObject( mutex
, INFINITE
);
1980 /**************************************************************************
1983 * Thread running inside the desktop process to manage the clipboard
1985 static DWORD WINAPI
clipboard_thread( void *arg
)
1987 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};
1988 XSetWindowAttributes attr
;
1992 if (!wait_clipboard_mutex()) return 0;
1994 clipboard_display
= thread_init_display();
1995 attr
.event_mask
= PropertyChangeMask
;
1996 import_window
= XCreateWindow( clipboard_display
, root_window
, 0, 0, 1, 1, 0, CopyFromParent
,
1997 InputOutput
, CopyFromParent
, CWEventMask
, &attr
);
2000 ERR( "failed to create import window\n" );
2004 memset( &class, 0, sizeof(class) );
2005 class.lpfnWndProc
= clipboard_wndproc
;
2006 class.lpszClassName
= clipboard_classname
;
2008 if (!RegisterClassW( &class ) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS
)
2010 ERR( "could not register clipboard window class err %u\n", GetLastError() );
2013 if (!(clipboard_hwnd
= CreateWindowW( clipboard_classname
, NULL
, 0, 0, 0, 0, 0,
2014 HWND_MESSAGE
, 0, 0, NULL
)))
2016 ERR( "failed to create clipboard window err %u\n", GetLastError() );
2020 clipboard_thread_id
= GetCurrentThreadId();
2021 AddClipboardFormatListener( clipboard_hwnd
);
2022 register_builtin_formats();
2023 request_selection_contents( clipboard_display
, TRUE
);
2025 TRACE( "clipboard thread %04x running\n", GetCurrentThreadId() );
2026 while (GetMessageW( &msg
, 0, 0, 0 )) DispatchMessageW( &msg
);
2031 /**************************************************************************
2032 * X11DRV_UpdateClipboard
2034 void CDECL
X11DRV_UpdateClipboard(void)
2036 static ULONG last_update
;
2040 if (GetCurrentThreadId() == clipboard_thread_id
) return;
2041 now
= GetTickCount();
2042 if ((int)(now
- last_update
) <= SELECTION_UPDATE_DELAY
) return;
2043 if (SendMessageTimeoutW( GetClipboardOwner(), WM_X11DRV_UPDATE_CLIPBOARD
, 0, 0,
2044 SMTO_ABORTIFHUNG
, 5000, &ret
) && ret
)
2049 /***********************************************************************
2050 * X11DRV_HandleSelectionRequest
2052 BOOL
X11DRV_SelectionRequest( HWND hwnd
, XEvent
*xev
)
2054 XSelectionRequestEvent
*event
= &xev
->xselectionrequest
;
2055 Display
*display
= event
->display
;
2059 TRACE( "got request on %lx for selection %s target %s win %lx prop %s\n",
2060 event
->owner
, debugstr_xatom( event
->selection
), debugstr_xatom( event
->target
),
2061 event
->requestor
, debugstr_xatom( event
->property
));
2063 if (event
->owner
!= selection_window
) goto done
;
2064 if ((event
->selection
!= x11drv_atom(CLIPBOARD
)) &&
2065 (!use_primary_selection
|| event
->selection
!= XA_PRIMARY
)) goto done
;
2067 /* If the specified property is None the requestor is an obsolete client.
2068 * We support these by using the specified target atom as the reply property.
2070 rprop
= event
->property
;
2072 rprop
= event
->target
;
2074 if (!export_selection( display
, event
->requestor
, rprop
, event
->target
))
2075 rprop
= None
; /* report failure to client */
2078 result
.xselection
.type
= SelectionNotify
;
2079 result
.xselection
.display
= display
;
2080 result
.xselection
.requestor
= event
->requestor
;
2081 result
.xselection
.selection
= event
->selection
;
2082 result
.xselection
.property
= rprop
;
2083 result
.xselection
.target
= event
->target
;
2084 result
.xselection
.time
= event
->time
;
2085 TRACE( "sending SelectionNotify for %s to %lx\n", debugstr_xatom( rprop
), event
->requestor
);
2086 XSendEvent( display
, event
->requestor
, False
, NoEventMask
, &result
);
2091 /***********************************************************************
2092 * X11DRV_SelectionClear
2094 BOOL
X11DRV_SelectionClear( HWND hwnd
, XEvent
*xev
)
2096 XSelectionClearEvent
*event
= &xev
->xselectionclear
;
2098 if (event
->window
!= selection_window
) return FALSE
;
2099 if (event
->selection
!= x11drv_atom(CLIPBOARD
)) return FALSE
;
2101 release_selection( event
->display
, event
->time
);
2102 request_selection_contents( event
->display
, TRUE
);
2107 /**************************************************************************
2108 * X11DRV_InitClipboard
2110 void X11DRV_InitClipboard(void)
2113 HANDLE handle
= CreateThread( NULL
, 0, clipboard_thread
, NULL
, 0, &id
);
2115 if (handle
) CloseHandle( handle
);
2116 else ERR( "failed to create clipboard thread\n" );