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 GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
192 static DWORD clipboard_thread_id
;
193 static HWND clipboard_hwnd
;
194 static BOOL is_clipboard_owner
;
195 static Window selection_window
;
196 static Window import_window
;
197 static Atom current_selection
;
198 static UINT rendered_formats
;
199 static ULONG64 last_clipboard_update
;
200 static struct clipboard_format
**current_x11_formats
;
201 static unsigned int nb_current_x11_formats
;
202 static BOOL use_xfixes
;
204 Display
*clipboard_display
= NULL
;
206 static const char *debugstr_format( UINT id
)
210 if (GetClipboardFormatNameW( id
, buffer
, 256 ))
211 return wine_dbg_sprintf( "%04x %s", id
, debugstr_w(buffer
) );
215 case 0: return "(none)";
216 #define BUILTIN(id) case id: return #id;
219 BUILTIN(CF_METAFILEPICT
)
229 BUILTIN(CF_UNICODETEXT
)
230 BUILTIN(CF_ENHMETAFILE
)
234 BUILTIN(CF_OWNERDISPLAY
)
236 BUILTIN(CF_DSPBITMAP
)
237 BUILTIN(CF_DSPMETAFILEPICT
)
238 BUILTIN(CF_DSPENHMETAFILE
)
240 default: return wine_dbg_sprintf( "%04x", id
);
244 static const char *debugstr_xatom( Atom atom
)
249 if (!atom
) return "(None)";
250 name
= XGetAtomName( thread_display(), atom
);
251 ret
= debugstr_a( name
);
257 static int is_atom_error( Display
*display
, XErrorEvent
*event
, void *arg
)
259 return (event
->error_code
== BadAtom
);
263 /**************************************************************************
266 static struct clipboard_format
*find_win32_format( UINT id
)
268 struct clipboard_format
*format
;
270 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
271 if (format
->id
== id
) return format
;
276 /**************************************************************************
279 static struct clipboard_format
*find_x11_format( Atom atom
)
281 struct clipboard_format
*format
;
283 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
284 if (format
->atom
== atom
) return format
;
289 /**************************************************************************
290 * register_builtin_formats
292 static void register_builtin_formats(void)
294 struct clipboard_format
*formats
;
297 if (!(formats
= HeapAlloc( GetProcessHeap(), 0, ARRAY_SIZE(builtin_formats
) * sizeof(*formats
)))) return;
299 for (i
= 0; i
< ARRAY_SIZE(builtin_formats
); i
++)
301 if (builtin_formats
[i
].name
)
302 formats
[i
].id
= RegisterClipboardFormatW( builtin_formats
[i
].name
);
304 formats
[i
].id
= builtin_formats
[i
].id
;
306 formats
[i
].atom
= GET_ATOM(builtin_formats
[i
].data
);
307 formats
[i
].import
= builtin_formats
[i
].import
;
308 formats
[i
].export
= builtin_formats
[i
].export
;
309 list_add_tail( &format_list
, &formats
[i
].entry
);
314 /**************************************************************************
317 static void register_formats( const UINT
*ids
, const Atom
*atoms
, unsigned int count
)
319 struct clipboard_format
*formats
;
322 if (!(formats
= HeapAlloc( GetProcessHeap(), 0, count
* sizeof(*formats
)))) return;
324 for (i
= 0; i
< count
; i
++)
326 formats
[i
].id
= ids
[i
];
327 formats
[i
].atom
= atoms
[i
];
328 formats
[i
].import
= import_data
;
329 formats
[i
].export
= export_data
;
330 list_add_tail( &format_list
, &formats
[i
].entry
);
331 TRACE( "registered %s atom %s\n", debugstr_format( ids
[i
] ), debugstr_xatom( atoms
[i
] ));
336 /**************************************************************************
337 * register_win32_formats
339 * Register Win32 clipboard formats the first time we encounter them.
341 static void register_win32_formats( const UINT
*ids
, UINT size
)
343 unsigned int count
, len
;
349 if (list_empty( &format_list
)) register_builtin_formats();
353 for (count
= 0; count
< 256 && size
; ids
++, size
--)
355 if (find_win32_format( *ids
)) continue; /* it already exists */
356 if (!GetClipboardFormatNameW( *ids
, buffer
, 256 )) continue; /* not a named format */
357 if (!(len
= WideCharToMultiByte( CP_UNIXCP
, 0, buffer
, -1, NULL
, 0, NULL
, NULL
))) continue;
358 if (!(names
[count
] = HeapAlloc( GetProcessHeap(), 0, len
))) continue;
359 WideCharToMultiByte( CP_UNIXCP
, 0, buffer
, -1, names
[count
], len
, NULL
, NULL
);
360 new_ids
[count
++] = *ids
;
364 XInternAtoms( thread_display(), names
, count
, False
, atoms
);
365 register_formats( new_ids
, atoms
, count
);
366 while (count
) HeapFree( GetProcessHeap(), 0, names
[--count
] );
371 /**************************************************************************
372 * register_x11_formats
374 * Register X11 atom formats the first time we encounter them.
376 static void register_x11_formats( const Atom
*atoms
, UINT size
)
378 Display
*display
= thread_display();
379 unsigned int i
, pos
, count
;
385 if (list_empty( &format_list
)) register_builtin_formats();
389 for (count
= 0; count
< 256 && size
; atoms
++, size
--)
390 if (!find_x11_format( *atoms
)) new_atoms
[count
++] = *atoms
;
394 X11DRV_expect_error( display
, is_atom_error
, NULL
);
395 if (!XGetAtomNames( display
, new_atoms
, count
, names
)) count
= 0;
396 if (X11DRV_check_error())
398 WARN( "got some bad atoms, ignoring\n" );
402 for (i
= pos
= 0; i
< count
; i
++)
404 if (MultiByteToWideChar( CP_UNIXCP
, 0, names
[i
], -1, buffer
, 256 ) &&
405 (ids
[pos
] = RegisterClipboardFormatW( buffer
)))
406 new_atoms
[pos
++] = new_atoms
[i
];
409 register_formats( ids
, new_atoms
, pos
);
414 /**************************************************************************
417 * Put data as a property on the specified window.
419 static void put_property( Display
*display
, Window win
, Atom prop
, Atom type
, int format
,
420 const void *ptr
, size_t size
)
422 const unsigned char *data
= ptr
;
423 int mode
= PropModeReplace
;
424 size_t width
= (format
== 32) ? sizeof(long) : format
/ 8;
425 size_t max_size
= XExtendedMaxRequestSize( display
) * 4;
427 if (!max_size
) max_size
= XMaxRequestSize( display
) * 4;
428 max_size
-= 64; /* request overhead */
432 size_t count
= min( size
, max_size
/ width
);
433 XChangeProperty( display
, win
, prop
, type
, format
, mode
, data
, count
);
434 mode
= PropModeAppend
;
436 data
+= count
* width
;
441 /**************************************************************************
444 static BOOL
convert_selection( Display
*display
, Window win
, Atom selection
,
445 struct clipboard_format
*format
, Atom
*type
,
446 unsigned char **data
, unsigned long *size
)
451 TRACE( "import %s from %s win %lx to format %s\n",
452 debugstr_xatom( format
->atom
), debugstr_xatom( selection
),
453 win
, debugstr_format( format
->id
) );
455 XConvertSelection( display
, selection
, format
->atom
, x11drv_atom(SELECTION_DATA
), win
, CurrentTime
);
457 for (i
= 0; i
< SELECTION_RETRIES
; i
++)
459 Bool res
= XCheckTypedWindowEvent( display
, win
, SelectionNotify
, &event
);
460 if (res
&& event
.xselection
.selection
== selection
&& event
.xselection
.target
== format
->atom
)
461 return read_property( display
, win
, event
.xselection
.property
, type
, data
, size
);
462 usleep( SELECTION_WAIT
);
464 ERR( "Timed out waiting for SelectionNotify event\n" );
469 /***********************************************************************
472 * Return the size of the bitmap info structure including color table.
474 static int bitmap_info_size( const BITMAPINFO
* info
, WORD coloruse
)
476 unsigned int colors
, size
, masks
= 0;
478 if (info
->bmiHeader
.biSize
== sizeof(BITMAPCOREHEADER
))
480 const BITMAPCOREHEADER
*core
= (const BITMAPCOREHEADER
*)info
;
481 colors
= (core
->bcBitCount
<= 8) ? 1 << core
->bcBitCount
: 0;
482 return sizeof(BITMAPCOREHEADER
) + colors
*
483 ((coloruse
== DIB_RGB_COLORS
) ? sizeof(RGBTRIPLE
) : sizeof(WORD
));
485 else /* assume BITMAPINFOHEADER */
487 colors
= info
->bmiHeader
.biClrUsed
;
488 if (!colors
&& (info
->bmiHeader
.biBitCount
<= 8))
489 colors
= 1 << info
->bmiHeader
.biBitCount
;
490 if (info
->bmiHeader
.biCompression
== BI_BITFIELDS
) masks
= 3;
491 size
= max( info
->bmiHeader
.biSize
, sizeof(BITMAPINFOHEADER
) + masks
* sizeof(DWORD
) );
492 return size
+ colors
* ((coloruse
== DIB_RGB_COLORS
) ? sizeof(RGBQUAD
) : sizeof(WORD
));
497 /***********************************************************************
498 * create_dib_from_bitmap
500 * Allocates a packed DIB and copies the bitmap data into it.
502 static HGLOBAL
create_dib_from_bitmap(HBITMAP hBmp
)
508 LPBITMAPINFOHEADER pbmiHeader
;
509 unsigned int cDataSize
, cPackedSize
, OffsetBits
;
512 if (!GetObjectW( hBmp
, sizeof(bmp
), &bmp
)) return 0;
515 * A packed DIB contains a BITMAPINFO structure followed immediately by
516 * an optional color palette and the pixel data.
519 /* Calculate the size of the packed DIB */
520 cDataSize
= abs( bmp
.bmHeight
) * (((bmp
.bmWidth
* bmp
.bmBitsPixel
+ 31) / 8) & ~3);
521 cPackedSize
= sizeof(BITMAPINFOHEADER
)
522 + ( (bmp
.bmBitsPixel
<= 8) ? (sizeof(RGBQUAD
) * (1 << bmp
.bmBitsPixel
)) : 0 )
524 /* Get the offset to the bits */
525 OffsetBits
= cPackedSize
- cDataSize
;
527 /* Allocate the packed DIB */
528 TRACE("\tAllocating packed DIB of size %d\n", cPackedSize
);
529 hPackedDIB
= GlobalAlloc( GMEM_FIXED
, cPackedSize
);
532 WARN("Could not allocate packed DIB!\n");
536 /* A packed DIB starts with a BITMAPINFOHEADER */
537 pPackedDIB
= GlobalLock(hPackedDIB
);
538 pbmiHeader
= (LPBITMAPINFOHEADER
)pPackedDIB
;
540 /* Init the BITMAPINFOHEADER */
541 pbmiHeader
->biSize
= sizeof(BITMAPINFOHEADER
);
542 pbmiHeader
->biWidth
= bmp
.bmWidth
;
543 pbmiHeader
->biHeight
= bmp
.bmHeight
;
544 pbmiHeader
->biPlanes
= 1;
545 pbmiHeader
->biBitCount
= bmp
.bmBitsPixel
;
546 pbmiHeader
->biCompression
= BI_RGB
;
547 pbmiHeader
->biSizeImage
= 0;
548 pbmiHeader
->biXPelsPerMeter
= pbmiHeader
->biYPelsPerMeter
= 0;
549 pbmiHeader
->biClrUsed
= 0;
550 pbmiHeader
->biClrImportant
= 0;
552 /* Retrieve the DIB bits from the bitmap and fill in the
553 * DIB color table if present */
555 nLinesCopied
= GetDIBits(hdc
, /* Handle to device context */
556 hBmp
, /* Handle to bitmap */
557 0, /* First scan line to set in dest bitmap */
558 bmp
.bmHeight
, /* Number of scan lines to copy */
559 pPackedDIB
+ OffsetBits
, /* [out] Address of array for bitmap bits */
560 (LPBITMAPINFO
) pbmiHeader
, /* [out] Address of BITMAPINFO structure */
561 0); /* RGB or palette index */
562 GlobalUnlock(hPackedDIB
);
565 /* Cleanup if GetDIBits failed */
566 if (nLinesCopied
!= bmp
.bmHeight
)
568 TRACE("\tGetDIBits returned %d. Actual lines=%d\n", nLinesCopied
, bmp
.bmHeight
);
569 GlobalFree(hPackedDIB
);
576 /***********************************************************************
579 * Converts a text/uri-list URI to DOS filename.
581 static WCHAR
* uri_to_dos(char *encodedURI
)
586 char *uri
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, strlen(encodedURI
) + 1);
589 for (i
= 0; encodedURI
[i
]; ++i
)
591 if (encodedURI
[i
] == '%')
593 if (encodedURI
[i
+1] && encodedURI
[i
+2])
597 buffer
[0] = encodedURI
[i
+1];
598 buffer
[1] = encodedURI
[i
+2];
600 sscanf(buffer
, "%x", &number
);
606 WARN("invalid URI encoding in %s\n", debugstr_a(encodedURI
));
607 HeapFree(GetProcessHeap(), 0, uri
);
612 uri
[j
++] = encodedURI
[i
];
615 /* Read http://www.freedesktop.org/wiki/Draganddropwarts and cry... */
616 if (strncmp(uri
, "file:/", 6) == 0)
622 /* file:///path/to/file (nautilus, thunar) */
623 ret
= wine_get_dos_file_name(&uri
[7]);
627 /* file://hostname/path/to/file (X file drag spec) */
629 char *path
= strchr(&uri
[7], '/');
633 if (strcmp(&uri
[7], "localhost") == 0)
636 ret
= wine_get_dos_file_name(path
);
638 else if (gethostname(hostname
, sizeof(hostname
)) == 0)
640 if (strcmp(hostname
, &uri
[7]) == 0)
643 ret
= wine_get_dos_file_name(path
);
651 /* file:/path/to/file (konqueror) */
652 ret
= wine_get_dos_file_name(&uri
[5]);
655 HeapFree(GetProcessHeap(), 0, uri
);
660 /**************************************************************************
661 * unicode_text_from_string
663 * Convert a string in the specified encoding to CF_UNICODETEXT format.
665 static HANDLE
unicode_text_from_string( UINT codepage
, const void *data
, size_t size
)
670 count
= MultiByteToWideChar( codepage
, 0, data
, size
, NULL
, 0);
672 if (!(strW
= GlobalAlloc( GMEM_FIXED
, (count
* 2 + 1) * sizeof(WCHAR
) ))) return 0;
674 MultiByteToWideChar( codepage
, 0, data
, size
, strW
+ count
, count
);
675 for (i
= j
= 0; i
< count
; i
++)
677 if (strW
[i
+ count
] == '\n') strW
[j
++] = '\r';
678 strW
[j
++] = strW
[i
+ count
];
681 GlobalReAlloc( strW
, j
* sizeof(WCHAR
), GMEM_FIXED
); /* release unused space */
682 TRACE( "returning %s\n", debugstr_wn( strW
, j
- 1 ));
687 /**************************************************************************
690 * Import XA_STRING, converting the string to CF_UNICODETEXT.
692 static HANDLE
import_string( Atom type
, const void *data
, size_t size
)
694 return unicode_text_from_string( 28591, data
, size
);
698 /**************************************************************************
701 * Import XA_UTF8_STRING, converting the string to CF_UNICODETEXT.
703 static HANDLE
import_utf8_string( Atom type
, const void *data
, size_t size
)
705 return unicode_text_from_string( CP_UTF8
, data
, size
);
709 /**************************************************************************
710 * import_compound_text
712 * Import COMPOUND_TEXT to CF_UNICODETEXT.
714 static HANDLE
import_compound_text( Atom type
, const void *data
, size_t size
)
719 XTextProperty txtprop
;
721 txtprop
.value
= (BYTE
*)data
;
722 txtprop
.nitems
= size
;
723 txtprop
.encoding
= x11drv_atom(COMPOUND_TEXT
);
725 if (XmbTextPropertyToTextList( thread_display(), &txtprop
, &srcstr
, &count
) != Success
) return 0;
726 if (!count
) return 0;
728 ret
= unicode_text_from_string( CP_UNIXCP
, srcstr
[0], strlen(srcstr
[0]) + 1 );
729 XFreeStringList(srcstr
);
734 /**************************************************************************
737 * Import XA_TEXT, converting the string to CF_UNICODETEXT.
739 static HANDLE
import_text( Atom type
, const void *data
, size_t size
)
741 if (type
== XA_STRING
) return import_string( type
, data
, size
);
742 if (type
== x11drv_atom(UTF8_STRING
)) return import_utf8_string( type
, data
, size
);
743 if (type
== x11drv_atom(COMPOUND_TEXT
)) return import_compound_text( type
, data
, size
);
744 FIXME( "unsupported TEXT type %s\n", debugstr_xatom( type
));
749 /**************************************************************************
752 * Import XA_PIXMAP, converting the image to CF_DIB.
754 static HANDLE
import_pixmap( Atom type
, const void *data
, size_t size
)
756 const Pixmap
*pPixmap
= (const Pixmap
*)data
;
758 XVisualInfo vis
= default_visual
;
759 char buffer
[FIELD_OFFSET( BITMAPINFO
, bmiColors
[256] )];
760 BITMAPINFO
*info
= (BITMAPINFO
*)buffer
;
761 struct gdi_image_bits bits
;
763 int x
,y
; /* Unused */
764 unsigned border_width
; /* Unused */
765 unsigned int depth
, width
, height
;
767 /* Get the Pixmap dimensions and bit depth */
768 if (!XGetGeometry(gdi_display
, *pPixmap
, &root
, &x
, &y
, &width
, &height
,
769 &border_width
, &depth
)) depth
= 0;
770 if (!pixmap_formats
[depth
]) return 0;
772 TRACE( "pixmap properties: width=%d, height=%d, depth=%d\n", width
, height
, depth
);
774 if (depth
!= vis
.depth
) switch (pixmap_formats
[depth
]->bits_per_pixel
)
780 case 16: /* assume R5G5B5 */
781 vis
.red_mask
= 0x7c00;
782 vis
.green_mask
= 0x03e0;
783 vis
.blue_mask
= 0x001f;
785 case 24: /* assume R8G8B8 */
786 case 32: /* assume A8R8G8B8 */
787 vis
.red_mask
= 0xff0000;
788 vis
.green_mask
= 0x00ff00;
789 vis
.blue_mask
= 0x0000ff;
795 if (!get_pixmap_image( *pPixmap
, width
, height
, &vis
, info
, &bits
))
797 DWORD info_size
= bitmap_info_size( info
, DIB_RGB_COLORS
);
799 ptr
= GlobalAlloc( GMEM_FIXED
, info_size
+ info
->bmiHeader
.biSizeImage
);
802 memcpy( ptr
, info
, info_size
);
803 memcpy( ptr
+ info_size
, bits
.ptr
, info
->bmiHeader
.biSizeImage
);
805 if (bits
.free
) bits
.free( &bits
);
811 /**************************************************************************
814 * Import image/bmp, converting the image to CF_DIB.
816 static HANDLE
import_image_bmp( Atom type
, const void *data
, size_t size
)
818 HANDLE hClipData
= 0;
819 const BITMAPFILEHEADER
*bfh
= data
;
821 if (size
>= sizeof(BITMAPFILEHEADER
)+sizeof(BITMAPCOREHEADER
) &&
822 bfh
->bfType
== 0x4d42 /* "BM" */)
824 const BITMAPINFO
*bmi
= (const BITMAPINFO
*)(bfh
+ 1);
828 if ((hbmp
= CreateDIBitmap( hdc
, &bmi
->bmiHeader
, CBM_INIT
,
829 (const BYTE
*)data
+ bfh
->bfOffBits
, bmi
, DIB_RGB_COLORS
)))
831 hClipData
= create_dib_from_bitmap( hbmp
);
840 /**************************************************************************
843 static HANDLE
import_enhmetafile( Atom type
, const void *data
, size_t size
)
845 return SetEnhMetaFileBits( size
, data
);
849 /**************************************************************************
852 static HANDLE
import_text_html( Atom type
, const void *data
, size_t size
)
854 static const char header
[] =
856 "StartHTML:0000000100\n"
858 "StartFragment:%010lu\n"
859 "EndFragment:%010lu\n"
860 "<!--StartFragment-->";
861 static const char trailer
[] = "\n<!--EndFragment-->";
866 /* Firefox uses UTF-16LE with byte order mark. Convert to UTF-8 without the BOM. */
867 if (size
>= sizeof(WCHAR
) && ((const WCHAR
*)data
)[0] == 0xfeff)
869 len
= WideCharToMultiByte( CP_UTF8
, 0, (const WCHAR
*)data
+ 1, size
/ sizeof(WCHAR
) - 1,
870 NULL
, 0, NULL
, NULL
);
871 if (!(text
= HeapAlloc( GetProcessHeap(), 0, len
))) return 0;
872 WideCharToMultiByte( CP_UTF8
, 0, (const WCHAR
*)data
+ 1, size
/ sizeof(WCHAR
) - 1,
873 text
, len
, NULL
, NULL
);
878 len
= strlen( header
) + 12; /* 3 * 4 extra chars for %010lu */
879 total
= len
+ size
+ sizeof(trailer
);
880 if ((ret
= GlobalAlloc( GMEM_FIXED
, total
)))
883 p
+= sprintf( p
, header
, total
- 1, len
, len
+ size
+ 1 /* include the final \n in the data */ );
884 memcpy( p
, data
, size
);
885 strcpy( p
+ size
, trailer
);
886 TRACE( "returning %s\n", debugstr_a( ret
));
888 HeapFree( GetProcessHeap(), 0, text
);
893 /**************************************************************************
894 * import_text_uri_list
896 * Import text/uri-list.
898 static HANDLE
import_text_uri_list( Atom type
, const void *data
, size_t size
)
900 const char *uriList
= data
;
908 DROPFILES
*dropFiles
= NULL
;
910 if (!(out
= HeapAlloc(GetProcessHeap(), 0, capacity
* sizeof(WCHAR
)))) return 0;
914 while (end
< size
&& uriList
[end
] != '\r')
916 if (end
< (size
- 1) && uriList
[end
+1] != '\n')
918 WARN("URI list line doesn't end in \\r\\n\n");
922 uri
= HeapAlloc(GetProcessHeap(), 0, end
- start
+ 1);
925 lstrcpynA(uri
, &uriList
[start
], end
- start
+ 1);
926 path
= uri_to_dos(uri
);
927 TRACE("converted URI %s to DOS path %s\n", debugstr_a(uri
), debugstr_w(path
));
928 HeapFree(GetProcessHeap(), 0, uri
);
932 int pathSize
= strlenW(path
) + 1;
933 if (pathSize
> capacity
- total
)
935 capacity
= 2*capacity
+ pathSize
;
936 out
= HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, out
, (capacity
+ 1)*sizeof(WCHAR
));
940 memcpy(&out
[total
], path
, pathSize
* sizeof(WCHAR
));
943 HeapFree(GetProcessHeap(), 0, path
);
951 if (out
&& end
>= size
)
953 if ((dropFiles
= GlobalAlloc( GMEM_FIXED
, sizeof(DROPFILES
) + (total
+ 1) * sizeof(WCHAR
) )))
955 dropFiles
->pFiles
= sizeof(DROPFILES
);
959 dropFiles
->fWide
= TRUE
;
961 memcpy( (char*)dropFiles
+ dropFiles
->pFiles
, out
, (total
+ 1) * sizeof(WCHAR
) );
964 HeapFree(GetProcessHeap(), 0, out
);
969 /**************************************************************************
972 * Import TARGETS and mark the corresponding clipboard formats as available.
974 static HANDLE
import_targets( Atom type
, const void *data
, size_t size
)
976 UINT i
, pos
, count
= size
/ sizeof(Atom
);
977 const Atom
*properties
= data
;
978 struct clipboard_format
*format
, **formats
;
980 if (type
!= XA_ATOM
&& type
!= x11drv_atom(TARGETS
)) return 0;
982 register_x11_formats( properties
, count
);
984 /* the builtin formats contain duplicates, so allocate some extra space */
985 if (!(formats
= HeapAlloc( GetProcessHeap(), 0, (count
+ ARRAY_SIZE(builtin_formats
)) * sizeof(*formats
))))
989 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
991 for (i
= 0; i
< count
; i
++) if (properties
[i
] == format
->atom
) break;
992 if (i
== count
) continue;
993 if (format
->import
&& format
->id
)
995 TRACE( "property %s -> format %s\n",
996 debugstr_xatom( properties
[i
] ), debugstr_format( format
->id
));
997 SetClipboardData( format
->id
, 0 );
998 formats
[pos
++] = format
;
1000 else TRACE( "property %s (ignoring)\n", debugstr_xatom( properties
[i
] ));
1003 HeapFree( GetProcessHeap(), 0, current_x11_formats
);
1004 current_x11_formats
= formats
;
1005 nb_current_x11_formats
= pos
;
1010 /**************************************************************************
1013 * Generic import clipboard data routine.
1015 static HANDLE
import_data( Atom type
, const void *data
, size_t size
)
1017 void *ret
= GlobalAlloc( GMEM_FIXED
, size
);
1019 if (ret
) memcpy( ret
, data
, size
);
1024 /**************************************************************************
1027 * Import the specified format from the selection and return a global handle to the data.
1029 static HANDLE
import_selection( Display
*display
, Window win
, Atom selection
,
1030 struct clipboard_format
*format
)
1032 unsigned char *data
;
1037 if (!format
->import
) return 0;
1039 if (!convert_selection( display
, win
, selection
, format
, &type
, &data
, &size
))
1041 TRACE( "failed to convert selection\n" );
1044 ret
= format
->import( type
, data
, size
);
1045 HeapFree( GetProcessHeap(), 0, data
);
1050 /**************************************************************************
1051 * X11DRV_CLIPBOARD_ImportSelection
1053 * Import the X selection into the clipboard format registered for the given X target.
1055 void X11DRV_CLIPBOARD_ImportSelection( Display
*display
, Window win
, Atom selection
,
1056 Atom
*targets
, UINT count
,
1057 void (*callback
)( Atom
, UINT
, HANDLE
))
1061 struct clipboard_format
*format
;
1063 register_x11_formats( targets
, count
);
1065 for (i
= 0; i
< count
; i
++)
1067 if (!(format
= find_x11_format( targets
[i
] ))) continue;
1068 if (!format
->id
) continue;
1069 if (!(handle
= import_selection( display
, win
, selection
, format
))) continue;
1070 callback( targets
[i
], format
->id
, handle
);
1075 /**************************************************************************
1078 static HANDLE
render_format( UINT id
)
1080 Display
*display
= thread_display();
1084 if (!current_selection
) return 0;
1086 for (i
= 0; i
< nb_current_x11_formats
; i
++)
1088 if (current_x11_formats
[i
]->id
!= id
) continue;
1089 if (!(handle
= import_selection( display
, import_window
,
1090 current_selection
, current_x11_formats
[i
] ))) continue;
1091 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,
1457 (count
+ ARRAY_SIZE(builtin_formats
)) * sizeof(*targets
) )))
1459 HeapFree( GetProcessHeap(), 0, formats
);
1464 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
1466 if (!format
->export
) continue;
1467 /* formats with id==0 are always exported */
1468 if (format
->id
&& !is_format_available( format
->id
, formats
, count
)) continue;
1469 TRACE( "%d: %s -> %s\n", pos
, debugstr_format( format
->id
), debugstr_xatom( format
->atom
));
1470 targets
[pos
++] = format
->atom
;
1473 put_property( display
, win
, prop
, XA_ATOM
, 32, targets
, pos
);
1474 HeapFree( GetProcessHeap(), 0, targets
);
1475 HeapFree( GetProcessHeap(), 0, formats
);
1480 /**************************************************************************
1483 * Export selection data, depending on the target type.
1485 static BOOL
export_selection( Display
*display
, Window win
, Atom prop
, Atom target
)
1487 struct clipboard_format
*format
;
1489 BOOL open
= FALSE
, ret
= FALSE
;
1491 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
1493 if (format
->atom
!= target
) continue;
1494 if (!format
->export
) continue;
1497 TRACE( "win %lx prop %s target %s\n", win
, debugstr_xatom( prop
), debugstr_xatom( target
));
1498 ret
= format
->export( display
, win
, prop
, target
, 0 );
1501 if (!open
&& !(open
= OpenClipboard( clipboard_hwnd
)))
1503 ERR( "failed to open clipboard for %s\n", debugstr_xatom( target
));
1506 if ((handle
= GetClipboardData( format
->id
)))
1508 TRACE( "win %lx prop %s target %s exporting %s %p\n",
1509 win
, debugstr_xatom( prop
), debugstr_xatom( target
),
1510 debugstr_format( format
->id
), handle
);
1512 ret
= format
->export( display
, win
, prop
, target
, handle
);
1515 /* keep looking for another Win32 format mapping to the same target */
1517 if (open
) CloseClipboard();
1522 /***********************************************************************
1525 * Service a MULTIPLE selection request event
1526 * prop contains a list of (target,property) atom pairs.
1527 * The first atom names a target and the second names a property.
1528 * The effect is as if we have received a sequence of SelectionRequest events
1529 * (one for each atom pair) except that:
1530 * 1. We reply with a SelectionNotify only when all the requested conversions
1531 * have been performed.
1532 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
1533 * we replace the atom in the property by None.
1535 static BOOL
export_multiple( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1540 unsigned long i
, count
, failed
, remain
;
1542 /* Read the MULTIPLE property contents. This should contain a list of
1543 * (target,property) atom pairs.
1545 if (XGetWindowProperty( display
, win
, prop
, 0, 0x3FFF, False
, AnyPropertyType
, &atype
, &aformat
,
1546 &count
, &remain
, (unsigned char**)&list
))
1549 TRACE( "type %s format %d count %ld remain %ld\n",
1550 debugstr_xatom( atype
), aformat
, count
, remain
);
1553 * Make sure we got what we expect.
1554 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
1555 * in a MULTIPLE selection request should be of type ATOM_PAIR.
1556 * However some X apps(such as XPaint) are not compliant with this and return
1557 * a user defined atom in atype when XGetWindowProperty is called.
1558 * The data *is* an atom pair but is not denoted as such.
1560 if (aformat
== 32 /* atype == xAtomPair */ )
1562 for (i
= failed
= 0; i
< count
; i
+= 2)
1564 if (list
[i
+1] == None
) continue;
1565 if (export_selection( display
, win
, list
[i
+ 1], list
[i
] )) continue;
1569 if (failed
) put_property( display
, win
, prop
, atype
, 32, list
, count
);
1576 /***********************************************************************
1579 * Export the timestamp that was used to acquire the selection
1581 static BOOL
export_timestamp( Display
*display
, Window win
, Atom prop
, Atom target
, HANDLE handle
)
1583 Time time
= CurrentTime
; /* FIXME */
1584 put_property( display
, win
, prop
, XA_INTEGER
, 32, &time
, 1 );
1589 /**************************************************************************
1590 * X11DRV_CLIPBOARD_GetProperty
1591 * Gets type, data and size.
1593 static BOOL
X11DRV_CLIPBOARD_GetProperty(Display
*display
, Window w
, Atom prop
,
1594 Atom
*atype
, unsigned char** data
, unsigned long* datasize
)
1597 unsigned long pos
= 0, nitems
, remain
, count
;
1598 unsigned char *val
= NULL
, *buffer
;
1602 if (XGetWindowProperty(display
, w
, prop
, pos
, INT_MAX
/ 4, False
,
1603 AnyPropertyType
, atype
, &aformat
, &nitems
, &remain
, &buffer
))
1605 WARN("Failed to read property\n");
1606 HeapFree( GetProcessHeap(), 0, val
);
1610 count
= get_property_size( aformat
, nitems
);
1611 if (!val
) *data
= HeapAlloc( GetProcessHeap(), 0, pos
* sizeof(int) + count
+ 1 );
1612 else *data
= HeapReAlloc( GetProcessHeap(), 0, val
, pos
* sizeof(int) + count
+ 1 );
1617 HeapFree( GetProcessHeap(), 0, val
);
1621 memcpy( (int *)val
+ pos
, buffer
, count
);
1625 *datasize
= pos
* sizeof(int) + count
;
1629 pos
+= count
/ sizeof(int);
1632 TRACE( "got property %s type %s format %u len %lu from window %lx\n",
1633 debugstr_xatom( prop
), debugstr_xatom( *atype
), aformat
, *datasize
, w
);
1635 /* Delete the property on the window now that we are done
1636 * This will send a PropertyNotify event to the selection owner. */
1637 XDeleteProperty(display
, w
, prop
);
1642 struct clipboard_data_packet
{
1645 unsigned char *data
;
1648 /**************************************************************************
1651 * Reads the contents of the X selection property.
1653 static BOOL
read_property( Display
*display
, Window w
, Atom prop
,
1654 Atom
*type
, unsigned char **data
, unsigned long *datasize
)
1661 while (XCheckTypedWindowEvent(display
, w
, PropertyNotify
, &xe
))
1664 if (!X11DRV_CLIPBOARD_GetProperty(display
, w
, prop
, type
, data
, datasize
))
1667 if (*type
== x11drv_atom(INCR
))
1670 unsigned long bufsize
= 0;
1671 struct list packets
;
1672 struct clipboard_data_packet
*packet
, *packet2
;
1675 HeapFree(GetProcessHeap(), 0, *data
);
1678 list_init(&packets
);
1683 unsigned char *prop_data
;
1684 unsigned long prop_size
;
1686 /* Wait until PropertyNotify is received */
1687 for (i
= 0; i
< SELECTION_RETRIES
; i
++)
1691 res
= XCheckTypedWindowEvent(display
, w
, PropertyNotify
, &xe
);
1692 if (res
&& xe
.xproperty
.atom
== prop
&&
1693 xe
.xproperty
.state
== PropertyNewValue
)
1695 usleep(SELECTION_WAIT
);
1698 if (i
>= SELECTION_RETRIES
||
1699 !X11DRV_CLIPBOARD_GetProperty(display
, w
, prop
, type
, &prop_data
, &prop_size
))
1705 /* Retrieved entire data. */
1708 HeapFree(GetProcessHeap(), 0, prop_data
);
1713 packet
= HeapAlloc(GetProcessHeap(), 0, sizeof(*packet
));
1716 HeapFree(GetProcessHeap(), 0, prop_data
);
1721 packet
->size
= prop_size
;
1722 packet
->data
= prop_data
;
1723 list_add_tail(&packets
, &packet
->entry
);
1724 bufsize
+= prop_size
;
1729 buf
= HeapAlloc(GetProcessHeap(), 0, bufsize
+ 1);
1732 unsigned long bytes_copied
= 0;
1733 *datasize
= bufsize
;
1734 LIST_FOR_EACH_ENTRY( packet
, &packets
, struct clipboard_data_packet
, entry
)
1736 memcpy(&buf
[bytes_copied
], packet
->data
, packet
->size
);
1737 bytes_copied
+= packet
->size
;
1746 LIST_FOR_EACH_ENTRY_SAFE( packet
, packet2
, &packets
, struct clipboard_data_packet
, entry
)
1748 HeapFree(GetProcessHeap(), 0, packet
->data
);
1749 HeapFree(GetProcessHeap(), 0, packet
);
1759 /**************************************************************************
1762 * Acquire the X11 selection when the Win32 clipboard has changed.
1764 static void acquire_selection( Display
*display
)
1766 if (selection_window
) XDestroyWindow( display
, selection_window
);
1768 selection_window
= XCreateWindow( display
, root_window
, 0, 0, 1, 1, 0, CopyFromParent
,
1769 InputOutput
, CopyFromParent
, 0, NULL
);
1770 if (!selection_window
) return;
1772 XSetSelectionOwner( display
, x11drv_atom(CLIPBOARD
), selection_window
, CurrentTime
);
1773 if (use_primary_selection
) XSetSelectionOwner( display
, XA_PRIMARY
, selection_window
, CurrentTime
);
1774 TRACE( "win %lx\n", selection_window
);
1778 /**************************************************************************
1781 * Release the X11 selection when some other X11 app has grabbed it.
1783 static void release_selection( Display
*display
, Time time
)
1785 assert( selection_window
);
1787 TRACE( "win %lx\n", selection_window
);
1789 /* release PRIMARY if we still own it */
1790 if (use_primary_selection
&& XGetSelectionOwner( display
, XA_PRIMARY
) == selection_window
)
1791 XSetSelectionOwner( display
, XA_PRIMARY
, None
, time
);
1793 XDestroyWindow( display
, selection_window
);
1794 selection_window
= 0;
1798 /**************************************************************************
1799 * request_selection_contents
1801 * Retrieve the contents of the X11 selection when it's owned by an X11 app.
1803 static BOOL
request_selection_contents( Display
*display
, BOOL changed
)
1805 struct clipboard_format
*targets
= find_x11_format( x11drv_atom(TARGETS
) );
1806 struct clipboard_format
*string
= find_x11_format( XA_STRING
);
1807 struct clipboard_format
*format
= NULL
;
1809 unsigned char *data
= NULL
;
1810 unsigned long size
= 0;
1813 static Atom last_selection
;
1814 static Window last_owner
;
1815 static struct clipboard_format
*last_format
;
1816 static Atom last_type
;
1817 static unsigned char *last_data
;
1818 static unsigned long last_size
;
1823 current_selection
= 0;
1824 if (use_primary_selection
)
1826 if ((owner
= XGetSelectionOwner( display
, XA_PRIMARY
)))
1827 current_selection
= XA_PRIMARY
;
1829 if (!current_selection
)
1831 if ((owner
= XGetSelectionOwner( display
, x11drv_atom(CLIPBOARD
) )))
1832 current_selection
= x11drv_atom(CLIPBOARD
);
1835 if (current_selection
)
1837 if (convert_selection( display
, import_window
, current_selection
, targets
, &type
, &data
, &size
))
1839 else if (convert_selection( display
, import_window
, current_selection
, string
, &type
, &data
, &size
))
1843 changed
= (changed
||
1845 last_selection
!= current_selection
||
1846 last_owner
!= owner
||
1847 last_format
!= format
||
1848 last_type
!= type
||
1849 last_size
!= size
||
1850 memcmp( last_data
, data
, size
));
1852 if (!changed
|| !OpenClipboard( clipboard_hwnd
))
1854 HeapFree( GetProcessHeap(), 0, data
);
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
+ ARRAY_SIZE( prefix
)];
1938 memcpy( buffer
, prefix
, sizeof(prefix
) );
1939 if (!GetUserObjectInformationW( GetProcessWindowStation(), UOI_NAME
,
1940 buffer
+ ARRAY_SIZE( prefix
),
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" );