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/library.h"
91 #include "wine/list.h"
92 #include "wine/debug.h"
93 #include "wine/unicode.h"
95 WINE_DEFAULT_DEBUG_CHANNEL(clipboard
);
97 /* Maximum wait time for selection notify */
98 #define SELECTION_RETRIES 500 /* wait for .5 seconds */
99 #define SELECTION_WAIT 1000 /* us */
101 #define SELECTION_UPDATE_DELAY 2000 /* delay between checks of the X11 selection */
103 typedef BOOL (*EXPORTFUNC
)( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
104 typedef HANDLE (*IMPORTFUNC
)( Atom type
, const void *data
, size_t size
);
106 struct clipboard_format
115 static HANDLE
import_data( Atom type
, const void *data
, size_t size
);
116 static HANDLE
import_enhmetafile( Atom type
, const void *data
, size_t size
);
117 static HANDLE
import_pixmap( Atom type
, const void *data
, size_t size
);
118 static HANDLE
import_image_bmp( Atom type
, const void *data
, size_t size
);
119 static HANDLE
import_string( Atom type
, const void *data
, size_t size
);
120 static HANDLE
import_utf8_string( Atom type
, const void *data
, size_t size
);
121 static HANDLE
import_compound_text( Atom type
, const void *data
, size_t size
);
122 static HANDLE
import_text( Atom type
, const void *data
, size_t size
);
123 static HANDLE
import_text_html( Atom type
, const void *data
, size_t size
);
124 static HANDLE
import_text_uri_list( Atom type
, const void *data
, size_t size
);
125 static HANDLE
import_targets( Atom type
, const void *data
, size_t size
);
127 static BOOL
export_data( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
128 static BOOL
export_string( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
129 static BOOL
export_utf8_string( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
130 static BOOL
export_text( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
131 static BOOL
export_compound_text( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
132 static BOOL
export_pixmap( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
133 static BOOL
export_image_bmp( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
134 static BOOL
export_enhmetafile( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
135 static BOOL
export_text_html( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
136 static BOOL
export_hdrop( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
137 static BOOL
export_targets( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
138 static BOOL
export_multiple( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
139 static BOOL
export_timestamp( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
);
141 static BOOL
read_property( Display
*display
, Window w
, Atom prop
,
142 Atom
*type
, unsigned char **data
, unsigned long *datasize
);
144 /* Clipboard formats */
146 static const WCHAR RichTextFormatW
[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
147 static const WCHAR GIFW
[] = {'G','I','F',0};
148 static const WCHAR JFIFW
[] = {'J','F','I','F',0};
149 static const WCHAR PNGW
[] = {'P','N','G',0};
150 static const WCHAR HTMLFormatW
[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
159 } builtin_formats
[] =
161 { 0, CF_UNICODETEXT
, XATOM_UTF8_STRING
, import_utf8_string
, export_utf8_string
},
162 { 0, CF_UNICODETEXT
, XATOM_COMPOUND_TEXT
, import_compound_text
, export_compound_text
},
163 { 0, CF_UNICODETEXT
, XA_STRING
, import_string
, export_string
},
164 { 0, CF_UNICODETEXT
, XATOM_text_plain
, import_string
, export_string
},
165 { 0, CF_UNICODETEXT
, XATOM_TEXT
, import_text
, export_text
},
166 { 0, CF_SYLK
, XATOM_WCF_SYLK
, import_data
, export_data
},
167 { 0, CF_DIF
, XATOM_WCF_DIF
, import_data
, export_data
},
168 { 0, CF_TIFF
, XATOM_WCF_TIFF
, import_data
, export_data
},
169 { 0, CF_DIB
, XA_PIXMAP
, import_pixmap
, export_pixmap
},
170 { 0, CF_PENDATA
, XATOM_WCF_PENDATA
, import_data
, export_data
},
171 { 0, CF_RIFF
, XATOM_WCF_RIFF
, import_data
, export_data
},
172 { 0, CF_WAVE
, XATOM_WCF_WAVE
, import_data
, export_data
},
173 { 0, CF_ENHMETAFILE
, XATOM_WCF_ENHMETAFILE
, import_enhmetafile
, export_enhmetafile
},
174 { 0, CF_HDROP
, XATOM_text_uri_list
, import_text_uri_list
, export_hdrop
},
175 { 0, CF_DIB
, XATOM_image_bmp
, import_image_bmp
, export_image_bmp
},
176 { RichTextFormatW
, 0, XATOM_text_rtf
, import_data
, export_data
},
177 { RichTextFormatW
, 0, XATOM_text_richtext
, import_data
, export_data
},
178 { GIFW
, 0, XATOM_image_gif
, import_data
, export_data
},
179 { JFIFW
, 0, XATOM_image_jpeg
, import_data
, export_data
},
180 { PNGW
, 0, XATOM_image_png
, import_data
, export_data
},
181 { HTMLFormatW
, 0, XATOM_HTML_Format
, import_data
, export_data
},
182 { HTMLFormatW
, 0, XATOM_text_html
, import_text_html
, export_text_html
},
183 { 0, 0, XATOM_TARGETS
, import_targets
, export_targets
},
184 { 0, 0, XATOM_MULTIPLE
, NULL
, export_multiple
},
185 { 0, 0, XATOM_TIMESTAMP
, NULL
, export_timestamp
},
188 static struct list format_list
= LIST_INIT( format_list
);
190 #define NB_BUILTIN_FORMATS (sizeof(builtin_formats) / sizeof(builtin_formats[0]))
191 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
193 static DWORD clipboard_thread_id
;
194 static HWND clipboard_hwnd
;
195 static BOOL is_clipboard_owner
;
196 static Window selection_window
;
197 static Window import_window
;
198 static Atom current_selection
;
199 static UINT rendered_formats
;
200 static ULONG64 last_clipboard_update
;
201 static struct clipboard_format
**current_x11_formats
;
202 static unsigned int nb_current_x11_formats
;
203 static BOOL use_xfixes
;
205 Display
*clipboard_display
= NULL
;
207 static const char *debugstr_format( UINT id
)
211 if (GetClipboardFormatNameW( id
, buffer
, 256 ))
212 return wine_dbg_sprintf( "%04x %s", id
, debugstr_w(buffer
) );
216 case 0: return "(none)";
217 #define BUILTIN(id) case id: return #id;
220 BUILTIN(CF_METAFILEPICT
)
230 BUILTIN(CF_UNICODETEXT
)
231 BUILTIN(CF_ENHMETAFILE
)
235 BUILTIN(CF_OWNERDISPLAY
)
237 BUILTIN(CF_DSPBITMAP
)
238 BUILTIN(CF_DSPMETAFILEPICT
)
239 BUILTIN(CF_DSPENHMETAFILE
)
241 default: return wine_dbg_sprintf( "%04x", id
);
245 static const char *debugstr_xatom( Atom atom
)
250 if (!atom
) return "(None)";
251 name
= XGetAtomName( thread_display(), atom
);
252 ret
= debugstr_a( name
);
258 static int is_atom_error( Display
*display
, XErrorEvent
*event
, void *arg
)
260 return (event
->error_code
== BadAtom
);
264 /**************************************************************************
267 static struct clipboard_format
*find_win32_format( UINT id
)
269 struct clipboard_format
*format
;
271 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
272 if (format
->id
== id
) return format
;
277 /**************************************************************************
280 static struct clipboard_format
*find_x11_format( Atom atom
)
282 struct clipboard_format
*format
;
284 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
285 if (format
->atom
== atom
) return format
;
290 /**************************************************************************
291 * register_builtin_formats
293 static void register_builtin_formats(void)
295 struct clipboard_format
*formats
;
298 if (!(formats
= HeapAlloc( GetProcessHeap(), 0, NB_BUILTIN_FORMATS
* sizeof(*formats
)))) return;
300 for (i
= 0; i
< NB_BUILTIN_FORMATS
; i
++)
302 if (builtin_formats
[i
].name
)
303 formats
[i
].id
= RegisterClipboardFormatW( builtin_formats
[i
].name
);
305 formats
[i
].id
= builtin_formats
[i
].id
;
307 formats
[i
].atom
= GET_ATOM(builtin_formats
[i
].data
);
308 formats
[i
].import
= builtin_formats
[i
].import
;
309 formats
[i
].export
= builtin_formats
[i
].export
;
310 list_add_tail( &format_list
, &formats
[i
].entry
);
315 /**************************************************************************
318 static void register_formats( const UINT
*ids
, const Atom
*atoms
, unsigned int count
)
320 struct clipboard_format
*formats
;
323 if (!(formats
= HeapAlloc( GetProcessHeap(), 0, count
* sizeof(*formats
)))) return;
325 for (i
= 0; i
< count
; i
++)
327 formats
[i
].id
= ids
[i
];
328 formats
[i
].atom
= atoms
[i
];
329 formats
[i
].import
= import_data
;
330 formats
[i
].export
= export_data
;
331 list_add_tail( &format_list
, &formats
[i
].entry
);
332 TRACE( "registered %s atom %s\n", debugstr_format( ids
[i
] ), debugstr_xatom( atoms
[i
] ));
337 /**************************************************************************
338 * register_win32_formats
340 * Register Win32 clipboard formats the first time we encounter them.
342 static void register_win32_formats( const UINT
*ids
, UINT size
)
344 unsigned int count
, len
;
350 if (list_empty( &format_list
)) register_builtin_formats();
354 for (count
= 0; count
< 256 && size
; ids
++, size
--)
356 if (find_win32_format( *ids
)) continue; /* it already exists */
357 if (!GetClipboardFormatNameW( *ids
, buffer
, 256 )) continue; /* not a named format */
358 if (!(len
= WideCharToMultiByte( CP_UNIXCP
, 0, buffer
, -1, NULL
, 0, NULL
, NULL
))) continue;
359 if (!(names
[count
] = HeapAlloc( GetProcessHeap(), 0, len
))) continue;
360 WideCharToMultiByte( CP_UNIXCP
, 0, buffer
, -1, names
[count
], len
, NULL
, NULL
);
361 new_ids
[count
++] = *ids
;
365 XInternAtoms( thread_display(), names
, count
, False
, atoms
);
366 register_formats( new_ids
, atoms
, count
);
367 while (count
) HeapFree( GetProcessHeap(), 0, names
[--count
] );
372 /**************************************************************************
373 * register_x11_formats
375 * Register X11 atom formats the first time we encounter them.
377 static void register_x11_formats( const Atom
*atoms
, UINT size
)
379 Display
*display
= thread_display();
380 unsigned int i
, pos
, count
;
386 if (list_empty( &format_list
)) register_builtin_formats();
390 for (count
= 0; count
< 256 && size
; atoms
++, size
--)
391 if (!find_x11_format( *atoms
)) new_atoms
[count
++] = *atoms
;
395 X11DRV_expect_error( display
, is_atom_error
, NULL
);
396 if (!XGetAtomNames( display
, new_atoms
, count
, names
)) count
= 0;
397 if (X11DRV_check_error())
399 WARN( "got some bad atoms, ignoring\n" );
403 for (i
= pos
= 0; i
< count
; i
++)
405 if (MultiByteToWideChar( CP_UNIXCP
, 0, names
[i
], -1, buffer
, 256 ) &&
406 (ids
[pos
] = RegisterClipboardFormatW( buffer
)))
407 new_atoms
[pos
++] = new_atoms
[i
];
410 register_formats( ids
, new_atoms
, pos
);
415 /**************************************************************************
418 * Put data as a property on the specified window.
420 static void put_property( Display
*display
, Window win
, Atom prop
, Atom type
, int format
,
421 const void *ptr
, size_t size
)
423 const unsigned char *data
= ptr
;
424 int mode
= PropModeReplace
;
425 size_t width
= (format
== 32) ? sizeof(long) : format
/ 8;
426 size_t max_size
= XExtendedMaxRequestSize( display
) * 4;
428 if (!max_size
) max_size
= XMaxRequestSize( display
) * 4;
429 max_size
-= 64; /* request overhead */
433 size_t count
= min( size
, max_size
/ width
);
434 XChangeProperty( display
, win
, prop
, type
, format
, mode
, data
, count
);
435 mode
= PropModeAppend
;
437 data
+= count
* width
;
442 /**************************************************************************
445 static BOOL
convert_selection( Display
*display
, Window win
, Atom selection
,
446 struct clipboard_format
*format
, Atom
*type
,
447 unsigned char **data
, unsigned long *size
)
452 TRACE( "import %s from %s win %lx to format %s\n",
453 debugstr_xatom( format
->atom
), debugstr_xatom( selection
),
454 win
, debugstr_format( format
->id
) );
456 XConvertSelection( display
, selection
, format
->atom
, x11drv_atom(SELECTION_DATA
), win
, CurrentTime
);
458 for (i
= 0; i
< SELECTION_RETRIES
; i
++)
460 Bool res
= XCheckTypedWindowEvent( display
, win
, SelectionNotify
, &event
);
461 if (res
&& event
.xselection
.selection
== selection
&& event
.xselection
.target
== format
->atom
)
462 return read_property( display
, win
, event
.xselection
.property
, type
, data
, size
);
463 usleep( SELECTION_WAIT
);
465 ERR( "Timed out waiting for SelectionNotify event\n" );
470 /***********************************************************************
473 * Return the size of the bitmap info structure including color table.
475 static int bitmap_info_size( const BITMAPINFO
* info
, WORD coloruse
)
477 unsigned int colors
, size
, masks
= 0;
479 if (info
->bmiHeader
.biSize
== sizeof(BITMAPCOREHEADER
))
481 const BITMAPCOREHEADER
*core
= (const BITMAPCOREHEADER
*)info
;
482 colors
= (core
->bcBitCount
<= 8) ? 1 << core
->bcBitCount
: 0;
483 return sizeof(BITMAPCOREHEADER
) + colors
*
484 ((coloruse
== DIB_RGB_COLORS
) ? sizeof(RGBTRIPLE
) : sizeof(WORD
));
486 else /* assume BITMAPINFOHEADER */
488 colors
= info
->bmiHeader
.biClrUsed
;
489 if (!colors
&& (info
->bmiHeader
.biBitCount
<= 8))
490 colors
= 1 << info
->bmiHeader
.biBitCount
;
491 if (info
->bmiHeader
.biCompression
== BI_BITFIELDS
) masks
= 3;
492 size
= max( info
->bmiHeader
.biSize
, sizeof(BITMAPINFOHEADER
) + masks
* sizeof(DWORD
) );
493 return size
+ colors
* ((coloruse
== DIB_RGB_COLORS
) ? sizeof(RGBQUAD
) : sizeof(WORD
));
498 /***********************************************************************
499 * create_dib_from_bitmap
501 * Allocates a packed DIB and copies the bitmap data into it.
503 static HGLOBAL
create_dib_from_bitmap(HBITMAP hBmp
)
509 LPBITMAPINFOHEADER pbmiHeader
;
510 unsigned int cDataSize
, cPackedSize
, OffsetBits
;
513 if (!GetObjectW( hBmp
, sizeof(bmp
), &bmp
)) return 0;
516 * A packed DIB contains a BITMAPINFO structure followed immediately by
517 * an optional color palette and the pixel data.
520 /* Calculate the size of the packed DIB */
521 cDataSize
= abs( bmp
.bmHeight
) * (((bmp
.bmWidth
* bmp
.bmBitsPixel
+ 31) / 8) & ~3);
522 cPackedSize
= sizeof(BITMAPINFOHEADER
)
523 + ( (bmp
.bmBitsPixel
<= 8) ? (sizeof(RGBQUAD
) * (1 << bmp
.bmBitsPixel
)) : 0 )
525 /* Get the offset to the bits */
526 OffsetBits
= cPackedSize
- cDataSize
;
528 /* Allocate the packed DIB */
529 TRACE("\tAllocating packed DIB of size %d\n", cPackedSize
);
530 hPackedDIB
= GlobalAlloc( GMEM_FIXED
, cPackedSize
);
533 WARN("Could not allocate packed DIB!\n");
537 /* A packed DIB starts with a BITMAPINFOHEADER */
538 pPackedDIB
= GlobalLock(hPackedDIB
);
539 pbmiHeader
= (LPBITMAPINFOHEADER
)pPackedDIB
;
541 /* Init the BITMAPINFOHEADER */
542 pbmiHeader
->biSize
= sizeof(BITMAPINFOHEADER
);
543 pbmiHeader
->biWidth
= bmp
.bmWidth
;
544 pbmiHeader
->biHeight
= bmp
.bmHeight
;
545 pbmiHeader
->biPlanes
= 1;
546 pbmiHeader
->biBitCount
= bmp
.bmBitsPixel
;
547 pbmiHeader
->biCompression
= BI_RGB
;
548 pbmiHeader
->biSizeImage
= 0;
549 pbmiHeader
->biXPelsPerMeter
= pbmiHeader
->biYPelsPerMeter
= 0;
550 pbmiHeader
->biClrUsed
= 0;
551 pbmiHeader
->biClrImportant
= 0;
553 /* Retrieve the DIB bits from the bitmap and fill in the
554 * DIB color table if present */
556 nLinesCopied
= GetDIBits(hdc
, /* Handle to device context */
557 hBmp
, /* Handle to bitmap */
558 0, /* First scan line to set in dest bitmap */
559 bmp
.bmHeight
, /* Number of scan lines to copy */
560 pPackedDIB
+ OffsetBits
, /* [out] Address of array for bitmap bits */
561 (LPBITMAPINFO
) pbmiHeader
, /* [out] Address of BITMAPINFO structure */
562 0); /* RGB or palette index */
563 GlobalUnlock(hPackedDIB
);
566 /* Cleanup if GetDIBits failed */
567 if (nLinesCopied
!= bmp
.bmHeight
)
569 TRACE("\tGetDIBits returned %d. Actual lines=%d\n", nLinesCopied
, bmp
.bmHeight
);
570 GlobalFree(hPackedDIB
);
577 /***********************************************************************
580 * Converts a text/uri-list URI to DOS filename.
582 static WCHAR
* uri_to_dos(char *encodedURI
)
587 char *uri
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, strlen(encodedURI
) + 1);
590 for (i
= 0; encodedURI
[i
]; ++i
)
592 if (encodedURI
[i
] == '%')
594 if (encodedURI
[i
+1] && encodedURI
[i
+2])
598 buffer
[0] = encodedURI
[i
+1];
599 buffer
[1] = encodedURI
[i
+2];
601 sscanf(buffer
, "%x", &number
);
607 WARN("invalid URI encoding in %s\n", debugstr_a(encodedURI
));
608 HeapFree(GetProcessHeap(), 0, uri
);
613 uri
[j
++] = encodedURI
[i
];
616 /* Read http://www.freedesktop.org/wiki/Draganddropwarts and cry... */
617 if (strncmp(uri
, "file:/", 6) == 0)
623 /* file:///path/to/file (nautilus, thunar) */
624 ret
= wine_get_dos_file_name(&uri
[7]);
628 /* file://hostname/path/to/file (X file drag spec) */
630 char *path
= strchr(&uri
[7], '/');
634 if (strcmp(&uri
[7], "localhost") == 0)
637 ret
= wine_get_dos_file_name(path
);
639 else if (gethostname(hostname
, sizeof(hostname
)) == 0)
641 if (strcmp(hostname
, &uri
[7]) == 0)
644 ret
= wine_get_dos_file_name(path
);
652 /* file:/path/to/file (konqueror) */
653 ret
= wine_get_dos_file_name(&uri
[5]);
656 HeapFree(GetProcessHeap(), 0, uri
);
661 /**************************************************************************
662 * unicode_text_from_string
664 * Convert a string in the specified encoding to CF_UNICODETEXT format.
666 static HANDLE
unicode_text_from_string( UINT codepage
, const void *data
, size_t size
)
671 count
= MultiByteToWideChar( codepage
, 0, data
, size
, NULL
, 0);
673 if (!(strW
= GlobalAlloc( GMEM_FIXED
, (count
* 2 + 1) * sizeof(WCHAR
) ))) return 0;
675 MultiByteToWideChar( codepage
, 0, data
, size
, strW
+ count
, count
);
676 for (i
= j
= 0; i
< count
; i
++)
678 if (strW
[i
+ count
] == '\n') strW
[j
++] = '\r';
679 strW
[j
++] = strW
[i
+ count
];
682 GlobalReAlloc( strW
, j
* sizeof(WCHAR
), GMEM_FIXED
); /* release unused space */
683 TRACE( "returning %s\n", debugstr_wn( strW
, j
- 1 ));
688 /**************************************************************************
691 * Import XA_STRING, converting the string to CF_UNICODETEXT.
693 static HANDLE
import_string( Atom type
, const void *data
, size_t size
)
695 return unicode_text_from_string( 28591, data
, size
);
699 /**************************************************************************
702 * Import XA_UTF8_STRING, converting the string to CF_UNICODETEXT.
704 static HANDLE
import_utf8_string( Atom type
, const void *data
, size_t size
)
706 return unicode_text_from_string( CP_UTF8
, data
, size
);
710 /**************************************************************************
711 * import_compound_text
713 * Import COMPOUND_TEXT to CF_UNICODETEXT.
715 static HANDLE
import_compound_text( Atom type
, const void *data
, size_t size
)
720 XTextProperty txtprop
;
722 txtprop
.value
= (BYTE
*)data
;
723 txtprop
.nitems
= size
;
724 txtprop
.encoding
= x11drv_atom(COMPOUND_TEXT
);
726 if (XmbTextPropertyToTextList( thread_display(), &txtprop
, &srcstr
, &count
) != Success
) return 0;
727 if (!count
) return 0;
729 ret
= unicode_text_from_string( CP_UNIXCP
, srcstr
[0], strlen(srcstr
[0]) + 1 );
730 XFreeStringList(srcstr
);
735 /**************************************************************************
738 * Import XA_TEXT, converting the string to CF_UNICODETEXT.
740 static HANDLE
import_text( Atom type
, const void *data
, size_t size
)
742 if (type
== XA_STRING
) return import_string( type
, data
, size
);
743 if (type
== x11drv_atom(UTF8_STRING
)) return import_utf8_string( type
, data
, size
);
744 if (type
== x11drv_atom(COMPOUND_TEXT
)) return import_compound_text( type
, data
, size
);
745 FIXME( "unsupported TEXT type %s\n", debugstr_xatom( type
));
750 /**************************************************************************
753 * Import XA_PIXMAP, converting the image to CF_DIB.
755 static HANDLE
import_pixmap( Atom type
, const void *data
, size_t size
)
757 const Pixmap
*pPixmap
= (const Pixmap
*)data
;
759 XVisualInfo vis
= default_visual
;
760 char buffer
[FIELD_OFFSET( BITMAPINFO
, bmiColors
[256] )];
761 BITMAPINFO
*info
= (BITMAPINFO
*)buffer
;
762 struct gdi_image_bits bits
;
764 int x
,y
; /* Unused */
765 unsigned border_width
; /* Unused */
766 unsigned int depth
, width
, height
;
768 /* Get the Pixmap dimensions and bit depth */
769 if (!XGetGeometry(gdi_display
, *pPixmap
, &root
, &x
, &y
, &width
, &height
,
770 &border_width
, &depth
)) depth
= 0;
771 if (!pixmap_formats
[depth
]) return 0;
773 TRACE( "pixmap properties: width=%d, height=%d, depth=%d\n", width
, height
, depth
);
775 if (depth
!= vis
.depth
) switch (pixmap_formats
[depth
]->bits_per_pixel
)
781 case 16: /* assume R5G5B5 */
782 vis
.red_mask
= 0x7c00;
783 vis
.green_mask
= 0x03e0;
784 vis
.blue_mask
= 0x001f;
786 case 24: /* assume R8G8B8 */
787 case 32: /* assume A8R8G8B8 */
788 vis
.red_mask
= 0xff0000;
789 vis
.green_mask
= 0x00ff00;
790 vis
.blue_mask
= 0x0000ff;
796 if (!get_pixmap_image( *pPixmap
, width
, height
, &vis
, info
, &bits
))
798 DWORD info_size
= bitmap_info_size( info
, DIB_RGB_COLORS
);
800 ptr
= GlobalAlloc( GMEM_FIXED
, info_size
+ info
->bmiHeader
.biSizeImage
);
803 memcpy( ptr
, info
, info_size
);
804 memcpy( ptr
+ info_size
, bits
.ptr
, info
->bmiHeader
.biSizeImage
);
806 if (bits
.free
) bits
.free( &bits
);
812 /**************************************************************************
815 * Import image/bmp, converting the image to CF_DIB.
817 static HANDLE
import_image_bmp( Atom type
, const void *data
, size_t size
)
819 HANDLE hClipData
= 0;
820 const BITMAPFILEHEADER
*bfh
= data
;
822 if (size
>= sizeof(BITMAPFILEHEADER
)+sizeof(BITMAPCOREHEADER
) &&
823 bfh
->bfType
== 0x4d42 /* "BM" */)
825 const BITMAPINFO
*bmi
= (const BITMAPINFO
*)(bfh
+ 1);
829 if ((hbmp
= CreateDIBitmap( hdc
, &bmi
->bmiHeader
, CBM_INIT
,
830 (const BYTE
*)data
+ bfh
->bfOffBits
, bmi
, DIB_RGB_COLORS
)))
832 hClipData
= create_dib_from_bitmap( hbmp
);
841 /**************************************************************************
844 static HANDLE
import_enhmetafile( Atom type
, const void *data
, size_t size
)
846 return SetEnhMetaFileBits( size
, data
);
850 /**************************************************************************
853 static HANDLE
import_text_html( Atom type
, const void *data
, size_t size
)
855 static const char header
[] =
857 "StartHTML:0000000100\n"
859 "StartFragment:%010lu\n"
860 "EndFragment:%010lu\n"
861 "<!--StartFragment-->";
862 static const char trailer
[] = "\n<!--EndFragment-->";
867 /* Firefox uses UTF-16LE with byte order mark. Convert to UTF-8 without the BOM. */
868 if (size
>= sizeof(WCHAR
) && ((const WCHAR
*)data
)[0] == 0xfeff)
870 len
= WideCharToMultiByte( CP_UTF8
, 0, (const WCHAR
*)data
+ 1, size
/ sizeof(WCHAR
) - 1,
871 NULL
, 0, NULL
, NULL
);
872 if (!(text
= HeapAlloc( GetProcessHeap(), 0, len
))) return 0;
873 WideCharToMultiByte( CP_UTF8
, 0, (const WCHAR
*)data
+ 1, size
/ sizeof(WCHAR
) - 1,
874 text
, len
, NULL
, NULL
);
879 len
= strlen( header
) + 12; /* 3 * 4 extra chars for %010lu */
880 total
= len
+ size
+ sizeof(trailer
);
881 if ((ret
= GlobalAlloc( GMEM_FIXED
, total
)))
884 p
+= sprintf( p
, header
, total
- 1, len
, len
+ size
+ 1 /* include the final \n in the data */ );
885 memcpy( p
, data
, size
);
886 strcpy( p
+ size
, trailer
);
887 TRACE( "returning %s\n", debugstr_a( ret
));
889 HeapFree( GetProcessHeap(), 0, text
);
894 /**************************************************************************
895 * import_text_uri_list
897 * Import text/uri-list.
899 static HANDLE
import_text_uri_list( Atom type
, const void *data
, size_t size
)
901 const char *uriList
= data
;
909 DROPFILES
*dropFiles
= NULL
;
911 if (!(out
= HeapAlloc(GetProcessHeap(), 0, capacity
* sizeof(WCHAR
)))) return 0;
915 while (end
< size
&& uriList
[end
] != '\r')
917 if (end
< (size
- 1) && uriList
[end
+1] != '\n')
919 WARN("URI list line doesn't end in \\r\\n\n");
923 uri
= HeapAlloc(GetProcessHeap(), 0, end
- start
+ 1);
926 lstrcpynA(uri
, &uriList
[start
], end
- start
+ 1);
927 path
= uri_to_dos(uri
);
928 TRACE("converted URI %s to DOS path %s\n", debugstr_a(uri
), debugstr_w(path
));
929 HeapFree(GetProcessHeap(), 0, uri
);
933 int pathSize
= strlenW(path
) + 1;
934 if (pathSize
> capacity
- total
)
936 capacity
= 2*capacity
+ pathSize
;
937 out
= HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, out
, (capacity
+ 1)*sizeof(WCHAR
));
941 memcpy(&out
[total
], path
, pathSize
* sizeof(WCHAR
));
944 HeapFree(GetProcessHeap(), 0, path
);
952 if (out
&& end
>= size
)
954 if ((dropFiles
= GlobalAlloc( GMEM_FIXED
, sizeof(DROPFILES
) + (total
+ 1) * sizeof(WCHAR
) )))
956 dropFiles
->pFiles
= sizeof(DROPFILES
);
960 dropFiles
->fWide
= TRUE
;
962 memcpy( (char*)dropFiles
+ dropFiles
->pFiles
, out
, (total
+ 1) * sizeof(WCHAR
) );
965 HeapFree(GetProcessHeap(), 0, out
);
970 /**************************************************************************
973 * Import TARGETS and mark the corresponding clipboard formats as available.
975 static HANDLE
import_targets( Atom type
, const void *data
, size_t size
)
977 UINT i
, pos
, count
= size
/ sizeof(Atom
);
978 const Atom
*properties
= data
;
979 struct clipboard_format
*format
, **formats
;
981 if (type
!= XA_ATOM
&& type
!= x11drv_atom(TARGETS
)) return 0;
983 register_x11_formats( properties
, count
);
985 /* the builtin formats contain duplicates, so allocate some extra space */
986 if (!(formats
= HeapAlloc( GetProcessHeap(), 0, (count
+ NB_BUILTIN_FORMATS
) * sizeof(*formats
))))
990 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
992 for (i
= 0; i
< count
; i
++) if (properties
[i
] == format
->atom
) break;
993 if (i
== count
) continue;
994 if (format
->import
&& format
->id
)
996 TRACE( "property %s -> format %s\n",
997 debugstr_xatom( properties
[i
] ), debugstr_format( format
->id
));
998 SetClipboardData( format
->id
, 0 );
999 formats
[pos
++] = format
;
1001 else TRACE( "property %s (ignoring)\n", debugstr_xatom( properties
[i
] ));
1004 HeapFree( GetProcessHeap(), 0, current_x11_formats
);
1005 current_x11_formats
= formats
;
1006 nb_current_x11_formats
= pos
;
1011 /**************************************************************************
1014 * Generic import clipboard data routine.
1016 static HANDLE
import_data( Atom type
, const void *data
, size_t size
)
1018 void *ret
= GlobalAlloc( GMEM_FIXED
, size
);
1020 if (ret
) memcpy( ret
, data
, size
);
1025 /**************************************************************************
1028 * Import the specified format from the selection and return a global handle to the data.
1030 static HANDLE
import_selection( Display
*display
, Window win
, Atom selection
,
1031 struct clipboard_format
*format
)
1033 unsigned char *data
;
1038 if (!format
->import
) return 0;
1040 if (!convert_selection( display
, win
, selection
, format
, &type
, &data
, &size
))
1042 TRACE( "failed to convert selection\n" );
1045 ret
= format
->import( type
, data
, size
);
1046 HeapFree( GetProcessHeap(), 0, data
);
1051 /**************************************************************************
1052 * X11DRV_CLIPBOARD_ImportSelection
1054 * Import the X selection into the clipboard format registered for the given X target.
1056 void X11DRV_CLIPBOARD_ImportSelection( Display
*display
, Window win
, Atom selection
,
1057 Atom
*targets
, UINT count
,
1058 void (*callback
)( Atom
, UINT
, HANDLE
))
1062 struct clipboard_format
*format
;
1064 register_x11_formats( targets
, count
);
1066 for (i
= 0; i
< count
; i
++)
1068 if (!(format
= find_x11_format( targets
[i
] ))) continue;
1069 if (!format
->id
) continue;
1070 if (!(handle
= import_selection( display
, win
, selection
, format
))) continue;
1071 callback( targets
[i
], format
->id
, handle
);
1076 /**************************************************************************
1079 static HANDLE
render_format( UINT id
)
1081 Display
*display
= thread_display();
1085 if (!current_selection
) return 0;
1087 for (i
= 0; i
< nb_current_x11_formats
; i
++)
1089 if (current_x11_formats
[i
]->id
!= id
) continue;
1090 handle
= import_selection( display
, import_window
, current_selection
, current_x11_formats
[i
] );
1091 if (handle
) SetClipboardData( id
, handle
);
1098 /**************************************************************************
1101 * Generic export clipboard data routine.
1103 static BOOL
export_data( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1105 void *ptr
= GlobalLock( handle
);
1107 if (!ptr
) return FALSE
;
1108 put_property( display
, win
, prop
, target
, 8, ptr
, GlobalSize( handle
));
1109 GlobalUnlock( handle
);
1114 /**************************************************************************
1115 * string_from_unicode_text
1117 * Convert CF_UNICODETEXT data to a string in the specified codepage.
1119 static char *string_from_unicode_text( UINT codepage
, HANDLE handle
, UINT
*size
)
1123 WCHAR
*strW
= GlobalLock( handle
);
1124 UINT lenW
= GlobalSize( handle
) / sizeof(WCHAR
);
1125 DWORD len
= WideCharToMultiByte( codepage
, 0, strW
, lenW
, NULL
, 0, NULL
, NULL
);
1127 if ((str
= HeapAlloc( GetProcessHeap(), 0, len
)))
1129 WideCharToMultiByte( codepage
, 0, strW
, lenW
, str
, len
, NULL
, NULL
);
1130 GlobalUnlock( handle
);
1132 /* remove carriage returns */
1133 for (i
= j
= 0; i
< len
; i
++)
1135 if (str
[i
] == '\r' && (i
== len
- 1 || str
[i
+ 1] == '\n')) continue;
1138 while (j
&& !str
[j
- 1]) j
--; /* remove trailing nulls */
1140 TRACE( "returning %s\n", debugstr_an( str
, j
));
1142 GlobalUnlock( handle
);
1147 /**************************************************************************
1150 * Export CF_UNICODETEXT converting the string to XA_STRING.
1152 static BOOL
export_string( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1155 char *text
= string_from_unicode_text( 28591, handle
, &size
);
1157 if (!text
) return FALSE
;
1158 put_property( display
, win
, prop
, target
, 8, text
, size
);
1159 HeapFree( GetProcessHeap(), 0, text
);
1160 GlobalUnlock( handle
);
1165 /**************************************************************************
1166 * export_utf8_string
1168 * Export CF_UNICODE converting the string to UTF8.
1170 static BOOL
export_utf8_string( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1173 char *text
= string_from_unicode_text( CP_UTF8
, handle
, &size
);
1175 if (!text
) return FALSE
;
1176 put_property( display
, win
, prop
, target
, 8, text
, size
);
1177 HeapFree( GetProcessHeap(), 0, text
);
1178 GlobalUnlock( handle
);
1183 /**************************************************************************
1186 * Export CF_UNICODE to the polymorphic TEXT type, using UTF8.
1188 static BOOL
export_text( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1190 return export_utf8_string( display
, win
, prop
, x11drv_atom(UTF8_STRING
), handle
);
1194 /**************************************************************************
1195 * export_compound_text
1197 * Export CF_UNICODE to COMPOUND_TEXT
1199 static BOOL
export_compound_text( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1201 XTextProperty textprop
;
1202 XICCEncodingStyle style
;
1204 char *text
= string_from_unicode_text( CP_UNIXCP
, handle
, &size
);
1206 if (!text
) return FALSE
;
1207 if (target
== x11drv_atom(COMPOUND_TEXT
))
1208 style
= XCompoundTextStyle
;
1210 style
= XStdICCTextStyle
;
1212 /* Update the X property */
1213 if (XmbTextListToTextProperty( display
, &text
, 1, style
, &textprop
) == Success
)
1215 XSetTextProperty( display
, win
, &textprop
, prop
);
1216 XFree( textprop
.value
);
1219 HeapFree( GetProcessHeap(), 0, text
);
1224 /**************************************************************************
1227 * Export CF_DIB to XA_PIXMAP.
1229 static BOOL
export_pixmap( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1233 struct gdi_image_bits bits
;
1235 pbmi
= GlobalLock( handle
);
1236 bits
.ptr
= (LPBYTE
)pbmi
+ bitmap_info_size( pbmi
, DIB_RGB_COLORS
);
1238 bits
.is_copy
= FALSE
;
1239 pixmap
= create_pixmap_from_image( 0, &default_visual
, pbmi
, &bits
, DIB_RGB_COLORS
);
1240 GlobalUnlock( handle
);
1242 put_property( display
, win
, prop
, target
, 32, &pixmap
, 1 );
1243 /* FIXME: free the pixmap when the property is deleted */
1248 /**************************************************************************
1251 * Export CF_DIB to image/bmp.
1253 static BOOL
export_image_bmp( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1255 LPBYTE dibdata
= GlobalLock( handle
);
1257 BITMAPFILEHEADER
*bfh
;
1259 bmpsize
= sizeof(BITMAPFILEHEADER
) + GlobalSize( handle
);
1260 bfh
= HeapAlloc( GetProcessHeap(), 0, bmpsize
);
1263 /* bitmap file header */
1264 bfh
->bfType
= 0x4d42; /* "BM" */
1265 bfh
->bfSize
= bmpsize
;
1266 bfh
->bfReserved1
= 0;
1267 bfh
->bfReserved2
= 0;
1268 bfh
->bfOffBits
= sizeof(BITMAPFILEHEADER
) + bitmap_info_size((BITMAPINFO
*)dibdata
, DIB_RGB_COLORS
);
1270 /* rest of bitmap is the same as the packed dib */
1271 memcpy(bfh
+1, dibdata
, bmpsize
-sizeof(BITMAPFILEHEADER
));
1273 GlobalUnlock( handle
);
1274 put_property( display
, win
, prop
, target
, 8, bfh
, bmpsize
);
1275 HeapFree( GetProcessHeap(), 0, bfh
);
1280 /**************************************************************************
1281 * export_enhmetafile
1283 * Export EnhMetaFile.
1285 static BOOL
export_enhmetafile( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1290 if (!(size
= GetEnhMetaFileBits( handle
, 0, NULL
))) return FALSE
;
1291 if (!(ptr
= HeapAlloc( GetProcessHeap(), 0, size
))) return FALSE
;
1293 GetEnhMetaFileBits( handle
, size
, ptr
);
1294 put_property( display
, win
, prop
, target
, 8, ptr
, size
);
1295 HeapFree( GetProcessHeap(), 0, ptr
);
1300 /**************************************************************************
1303 * Export HTML Format to text/html.
1305 * FIXME: We should attempt to add an <a base> tag and convert windows paths.
1307 static BOOL
export_text_html( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1309 const char *p
, *data
;
1310 UINT start
= 0, end
= 0;
1313 if (!(data
= GlobalLock( handle
))) return FALSE
;
1316 while (*p
&& *p
!= '<')
1318 if (!strncmp( p
, "StartFragment:", 14 )) start
= atoi( p
+ 14 );
1319 else if (!strncmp( p
, "EndFragment:", 12 )) end
= atoi( p
+ 12 );
1320 if (!(p
= strpbrk( p
, "\r\n" ))) break;
1321 while (*p
== '\r' || *p
== '\n') p
++;
1323 if (start
&& start
< end
&& end
<= GlobalSize( handle
))
1324 put_property( display
, win
, prop
, target
, 8, data
+ start
, end
- start
);
1328 GlobalUnlock( handle
);
1333 /**************************************************************************
1336 * Export CF_HDROP format to text/uri-list.
1338 static BOOL
export_hdrop( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1343 UINT textUriListSize
= 32;
1346 textUriList
= HeapAlloc( GetProcessHeap(), 0, textUriListSize
);
1347 if (!textUriList
) return FALSE
;
1348 numFiles
= DragQueryFileW( handle
, 0xFFFFFFFF, NULL
, 0 );
1349 for (i
= 0; i
< numFiles
; i
++)
1351 UINT dosFilenameSize
;
1352 WCHAR
*dosFilename
= NULL
;
1353 char *unixFilename
= NULL
;
1357 dosFilenameSize
= 1 + DragQueryFileW( handle
, i
, NULL
, 0 );
1358 dosFilename
= HeapAlloc(GetProcessHeap(), 0, dosFilenameSize
*sizeof(WCHAR
));
1359 if (dosFilename
== NULL
) goto failed
;
1360 DragQueryFileW( handle
, i
, dosFilename
, dosFilenameSize
);
1361 unixFilename
= wine_get_unix_file_name(dosFilename
);
1362 HeapFree(GetProcessHeap(), 0, dosFilename
);
1363 if (unixFilename
== NULL
) goto failed
;
1364 uriSize
= 8 + /* file:/// */
1365 3 * (lstrlenA(unixFilename
) - 1) + /* "%xy" per char except first '/' */
1367 if ((next
+ uriSize
) > textUriListSize
)
1369 UINT biggerSize
= max( 2 * textUriListSize
, next
+ uriSize
);
1370 void *bigger
= HeapReAlloc( GetProcessHeap(), 0, textUriList
, biggerSize
);
1373 textUriList
= bigger
;
1374 textUriListSize
= biggerSize
;
1378 HeapFree(GetProcessHeap(), 0, unixFilename
);
1382 lstrcpyA(&textUriList
[next
], "file:///");
1384 /* URL encode everything - unnecessary, but easier/lighter than linking in shlwapi, and can't hurt */
1385 for (u
= 1; unixFilename
[u
]; u
++)
1387 static const char hex_table
[] = "0123456789abcdef";
1388 textUriList
[next
++] = '%';
1389 textUriList
[next
++] = hex_table
[unixFilename
[u
] >> 4];
1390 textUriList
[next
++] = hex_table
[unixFilename
[u
] & 0xf];
1392 textUriList
[next
++] = '\r';
1393 textUriList
[next
++] = '\n';
1394 HeapFree(GetProcessHeap(), 0, unixFilename
);
1396 put_property( display
, win
, prop
, target
, 8, textUriList
, next
);
1397 HeapFree( GetProcessHeap(), 0, textUriList
);
1401 HeapFree( GetProcessHeap(), 0, textUriList
);
1406 /***********************************************************************
1407 * get_clipboard_formats
1409 * Return a list of all formats currently available on the Win32 clipboard.
1410 * Helper for export_targets.
1412 static UINT
*get_clipboard_formats( UINT
*size
)
1419 if (!(ids
= HeapAlloc( GetProcessHeap(), 0, *size
* sizeof(*ids
) ))) return NULL
;
1420 if (GetUpdatedClipboardFormats( ids
, *size
, size
)) break;
1421 HeapFree( GetProcessHeap(), 0, ids
);
1422 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER
) return NULL
;
1424 register_win32_formats( ids
, *size
);
1429 /***********************************************************************
1430 * is_format_available
1432 * Check if a clipboard format is included in the list.
1433 * Helper for export_targets.
1435 static BOOL
is_format_available( UINT format
, const UINT
*ids
, unsigned int count
)
1437 while (count
--) if (*ids
++ == format
) return TRUE
;
1442 /***********************************************************************
1445 * Service a TARGETS selection request event
1447 static BOOL
export_targets( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1449 struct clipboard_format
*format
;
1450 UINT pos
, count
, *formats
;
1453 if (!(formats
= get_clipboard_formats( &count
))) return FALSE
;
1455 /* the builtin formats contain duplicates, so allocate some extra space */
1456 if (!(targets
= HeapAlloc( GetProcessHeap(), 0, (count
+ NB_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 usleep(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
));
1853 HeapFree( GetProcessHeap(), 0, data
);
1857 if (!OpenClipboard( clipboard_hwnd
)) return FALSE
;
1858 TRACE( "selection changed, importing\n" );
1860 is_clipboard_owner
= TRUE
;
1861 rendered_formats
= 0;
1863 if (format
) format
->import( type
, data
, size
);
1865 HeapFree( GetProcessHeap(), 0, last_data
);
1866 last_selection
= current_selection
;
1868 last_format
= format
;
1872 last_clipboard_update
= GetTickCount64();
1875 SetTimer( clipboard_hwnd
, 1, SELECTION_UPDATE_DELAY
, NULL
);
1880 /**************************************************************************
1883 * Periodically update the clipboard while the selection is owned by an X11 app.
1885 BOOL
update_clipboard( HWND hwnd
)
1887 if (use_xfixes
) return TRUE
;
1888 if (hwnd
!= clipboard_hwnd
) return TRUE
;
1889 if (!is_clipboard_owner
) return TRUE
;
1890 if (GetTickCount64() - last_clipboard_update
<= SELECTION_UPDATE_DELAY
) return TRUE
;
1891 return request_selection_contents( thread_display(), FALSE
);
1895 /**************************************************************************
1898 * Window procedure for the clipboard manager.
1900 static LRESULT CALLBACK
clipboard_wndproc( HWND hwnd
, UINT msg
, WPARAM wp
, LPARAM lp
)
1906 case WM_CLIPBOARDUPDATE
:
1907 if (is_clipboard_owner
) break; /* ignore our own changes */
1908 acquire_selection( thread_init_display() );
1910 case WM_RENDERFORMAT
:
1911 if (render_format( wp
)) rendered_formats
++;
1914 if (!is_clipboard_owner
) break;
1915 request_selection_contents( thread_display(), FALSE
);
1917 case WM_DESTROYCLIPBOARD
:
1918 TRACE( "WM_DESTROYCLIPBOARD: lost ownership\n" );
1919 is_clipboard_owner
= FALSE
;
1920 KillTimer( hwnd
, 1 );
1923 return DefWindowProcW( hwnd
, msg
, wp
, lp
);
1927 /**************************************************************************
1928 * wait_clipboard_mutex
1930 * Make sure that there's only one clipboard thread per window station.
1932 static BOOL
wait_clipboard_mutex(void)
1934 static const WCHAR prefix
[] = {'_','_','w','i','n','e','_','c','l','i','p','b','o','a','r','d','_'};
1935 WCHAR buffer
[MAX_PATH
+ sizeof(prefix
) / sizeof(WCHAR
)];
1938 memcpy( buffer
, prefix
, sizeof(prefix
) );
1939 if (!GetUserObjectInformationW( GetProcessWindowStation(), UOI_NAME
,
1940 buffer
+ sizeof(prefix
) / sizeof(WCHAR
),
1941 sizeof(buffer
) - sizeof(prefix
), NULL
))
1943 ERR( "failed to get winstation name\n" );
1946 mutex
= CreateMutexW( NULL
, TRUE
, buffer
);
1947 if (GetLastError() == ERROR_ALREADY_EXISTS
)
1949 TRACE( "waiting for mutex %s\n", debugstr_w( buffer
));
1950 WaitForSingleObject( mutex
, INFINITE
);
1956 /**************************************************************************
1957 * selection_notify_event
1959 * Called when x11 clipboard content changes
1961 #ifdef SONAME_LIBXFIXES
1962 static BOOL
selection_notify_event( HWND hwnd
, XEvent
*event
)
1964 XFixesSelectionNotifyEvent
*req
= (XFixesSelectionNotifyEvent
*)event
;
1966 if (!is_clipboard_owner
) return FALSE
;
1967 if (req
->owner
== selection_window
) return FALSE
;
1968 request_selection_contents( req
->display
, TRUE
);
1973 /**************************************************************************
1976 * Initialize xfixes to receive clipboard update notifications
1978 static void xfixes_init(void)
1980 #ifdef SONAME_LIBXFIXES
1981 typeof(XFixesSelectSelectionInput
) *pXFixesSelectSelectionInput
;
1982 typeof(XFixesQueryExtension
) *pXFixesQueryExtension
;
1983 typeof(XFixesQueryVersion
) *pXFixesQueryVersion
;
1985 int event_base
, error_base
;
1986 int major
= 3, minor
= 0;
1989 handle
= wine_dlopen(SONAME_LIBXFIXES
, RTLD_NOW
, NULL
, 0);
1990 if (!handle
) return;
1992 pXFixesQueryExtension
= wine_dlsym(handle
, "XFixesQueryExtension", NULL
, 0);
1993 if (!pXFixesQueryExtension
) return;
1994 pXFixesQueryVersion
= wine_dlsym(handle
, "XFixesQueryVersion", NULL
, 0);
1995 if (!pXFixesQueryVersion
) return;
1996 pXFixesSelectSelectionInput
= wine_dlsym(handle
, "XFixesSelectSelectionInput", NULL
, 0);
1997 if (!pXFixesSelectSelectionInput
) return;
1999 if (!pXFixesQueryExtension(clipboard_display
, &event_base
, &error_base
))
2001 pXFixesQueryVersion(clipboard_display
, &major
, &minor
);
2002 use_xfixes
= (major
>= 1);
2003 if (!use_xfixes
) return;
2005 pXFixesSelectSelectionInput(clipboard_display
, import_window
, x11drv_atom(CLIPBOARD
),
2006 XFixesSetSelectionOwnerNotifyMask
|
2007 XFixesSelectionWindowDestroyNotifyMask
|
2008 XFixesSelectionClientCloseNotifyMask
);
2009 if (use_primary_selection
)
2011 pXFixesSelectSelectionInput(clipboard_display
, import_window
, XA_PRIMARY
,
2012 XFixesSetSelectionOwnerNotifyMask
|
2013 XFixesSelectionWindowDestroyNotifyMask
|
2014 XFixesSelectionClientCloseNotifyMask
);
2016 X11DRV_register_event_handler(event_base
+ XFixesSelectionNotify
,
2017 selection_notify_event
, "XFixesSelectionNotify");
2018 TRACE("xfixes succesully initialized\n");
2020 WARN("xfixes not supported\n");
2025 /**************************************************************************
2028 * Thread running inside the desktop process to manage the clipboard
2030 static DWORD WINAPI
clipboard_thread( void *arg
)
2032 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};
2033 XSetWindowAttributes attr
;
2037 if (!wait_clipboard_mutex()) return 0;
2039 clipboard_display
= thread_init_display();
2040 attr
.event_mask
= PropertyChangeMask
;
2041 import_window
= XCreateWindow( clipboard_display
, root_window
, 0, 0, 1, 1, 0, CopyFromParent
,
2042 InputOutput
, CopyFromParent
, CWEventMask
, &attr
);
2045 ERR( "failed to create import window\n" );
2049 memset( &class, 0, sizeof(class) );
2050 class.lpfnWndProc
= clipboard_wndproc
;
2051 class.lpszClassName
= clipboard_classname
;
2053 if (!RegisterClassW( &class ) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS
)
2055 ERR( "could not register clipboard window class err %u\n", GetLastError() );
2058 if (!(clipboard_hwnd
= CreateWindowW( clipboard_classname
, NULL
, 0, 0, 0, 0, 0,
2059 HWND_MESSAGE
, 0, 0, NULL
)))
2061 ERR( "failed to create clipboard window err %u\n", GetLastError() );
2065 clipboard_thread_id
= GetCurrentThreadId();
2066 AddClipboardFormatListener( clipboard_hwnd
);
2067 register_builtin_formats();
2068 request_selection_contents( clipboard_display
, TRUE
);
2072 TRACE( "clipboard thread %04x running\n", GetCurrentThreadId() );
2073 while (GetMessageW( &msg
, 0, 0, 0 )) DispatchMessageW( &msg
);
2078 /**************************************************************************
2079 * X11DRV_UpdateClipboard
2081 void CDECL
X11DRV_UpdateClipboard(void)
2083 static ULONG last_update
;
2087 if (use_xfixes
) return;
2088 if (GetCurrentThreadId() == clipboard_thread_id
) return;
2089 now
= GetTickCount();
2090 if ((int)(now
- last_update
) <= SELECTION_UPDATE_DELAY
) return;
2091 if (SendMessageTimeoutW( GetClipboardOwner(), WM_X11DRV_UPDATE_CLIPBOARD
, 0, 0,
2092 SMTO_ABORTIFHUNG
, 5000, &ret
) && ret
)
2097 /***********************************************************************
2098 * X11DRV_HandleSelectionRequest
2100 BOOL
X11DRV_SelectionRequest( HWND hwnd
, XEvent
*xev
)
2102 XSelectionRequestEvent
*event
= &xev
->xselectionrequest
;
2103 Display
*display
= event
->display
;
2107 TRACE( "got request on %lx for selection %s target %s win %lx prop %s\n",
2108 event
->owner
, debugstr_xatom( event
->selection
), debugstr_xatom( event
->target
),
2109 event
->requestor
, debugstr_xatom( event
->property
));
2111 if (event
->owner
!= selection_window
) goto done
;
2112 if ((event
->selection
!= x11drv_atom(CLIPBOARD
)) &&
2113 (!use_primary_selection
|| event
->selection
!= XA_PRIMARY
)) goto done
;
2115 /* If the specified property is None the requestor is an obsolete client.
2116 * We support these by using the specified target atom as the reply property.
2118 rprop
= event
->property
;
2120 rprop
= event
->target
;
2122 if (!export_selection( display
, event
->requestor
, rprop
, event
->target
))
2123 rprop
= None
; /* report failure to client */
2126 result
.xselection
.type
= SelectionNotify
;
2127 result
.xselection
.display
= display
;
2128 result
.xselection
.requestor
= event
->requestor
;
2129 result
.xselection
.selection
= event
->selection
;
2130 result
.xselection
.property
= rprop
;
2131 result
.xselection
.target
= event
->target
;
2132 result
.xselection
.time
= event
->time
;
2133 TRACE( "sending SelectionNotify for %s to %lx\n", debugstr_xatom( rprop
), event
->requestor
);
2134 XSendEvent( display
, event
->requestor
, False
, NoEventMask
, &result
);
2139 /***********************************************************************
2140 * X11DRV_SelectionClear
2142 BOOL
X11DRV_SelectionClear( HWND hwnd
, XEvent
*xev
)
2144 XSelectionClearEvent
*event
= &xev
->xselectionclear
;
2146 if (event
->window
!= selection_window
) return FALSE
;
2147 if (event
->selection
!= x11drv_atom(CLIPBOARD
)) return FALSE
;
2149 release_selection( event
->display
, event
->time
);
2150 request_selection_contents( event
->display
, TRUE
);
2155 /**************************************************************************
2156 * X11DRV_InitClipboard
2158 void X11DRV_InitClipboard(void)
2161 HANDLE handle
= CreateThread( NULL
, 0, clipboard_thread
, NULL
, 0, &id
);
2163 if (handle
) CloseHandle( handle
);
2164 else ERR( "failed to create clipboard thread\n" );