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
81 #ifdef HAVE_X11_EXTENSIONS_XFIXES_H
82 #include <X11/extensions/Xfixes.h>
88 #include "wine/list.h"
89 #include "wine/debug.h"
90 #include "wine/unicode.h"
92 WINE_DEFAULT_DEBUG_CHANNEL(clipboard
);
94 /* Maximum wait time for selection notify */
95 #define SELECTION_RETRIES 500 /* wait for .5 seconds */
96 #define SELECTION_WAIT 1 /* ms */
98 #define SELECTION_UPDATE_DELAY 2000 /* delay between checks of the X11 selection */
100 typedef BOOL (*EXPORTFUNC
)( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
);
101 typedef void *(*IMPORTFUNC
)( Atom type
, const void *data
, size_t size
, size_t *ret_size
);
103 struct clipboard_format
112 static void *import_data( Atom type
, const void *data
, size_t size
, size_t *ret_size
);
113 static void *import_pixmap( Atom type
, const void *data
, size_t size
, size_t *ret_size
);
114 static void *import_image_bmp( Atom type
, const void *data
, size_t size
, size_t *ret_size
);
115 static void *import_string( Atom type
, const void *data
, size_t size
, size_t *ret_size
);
116 static void *import_utf8_string( Atom type
, const void *data
, size_t size
, size_t *ret_size
);
117 static void *import_compound_text( Atom type
, const void *data
, size_t size
, size_t *ret_size
);
118 static void *import_text( Atom type
, const void *data
, size_t size
, size_t *ret_size
);
119 static void *import_text_html( Atom type
, const void *data
, size_t size
, size_t *ret_size
);
120 static void *import_text_uri_list( Atom type
, const void *data
, size_t size
, size_t *ret_size
);
121 static void *import_targets( Atom type
, const void *data
, size_t size
, size_t *ret_size
);
123 static BOOL
export_data( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
);
124 static BOOL
export_string( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
);
125 static BOOL
export_utf8_string( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
);
126 static BOOL
export_text( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
);
127 static BOOL
export_compound_text( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
);
128 static BOOL
export_pixmap( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
);
129 static BOOL
export_image_bmp( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
);
130 static BOOL
export_text_html( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
);
131 static BOOL
export_hdrop( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
);
132 static BOOL
export_targets( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
);
133 static BOOL
export_multiple( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
);
134 static BOOL
export_timestamp( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
);
136 static BOOL
read_property( Display
*display
, Window w
, Atom prop
,
137 Atom
*type
, unsigned char **data
, size_t *datasize
);
139 /* Clipboard formats */
141 static const WCHAR RichTextFormatW
[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
142 static const WCHAR GIFW
[] = {'G','I','F',0};
143 static const WCHAR JFIFW
[] = {'J','F','I','F',0};
144 static const WCHAR PNGW
[] = {'P','N','G',0};
145 static const WCHAR HTMLFormatW
[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
154 } builtin_formats
[] =
156 { 0, CF_UNICODETEXT
, XATOM_UTF8_STRING
, import_utf8_string
, export_utf8_string
},
157 { 0, CF_UNICODETEXT
, XATOM_COMPOUND_TEXT
, import_compound_text
, export_compound_text
},
158 { 0, CF_UNICODETEXT
, XA_STRING
, import_string
, export_string
},
159 { 0, CF_UNICODETEXT
, XATOM_text_plain
, import_string
, export_string
},
160 { 0, CF_UNICODETEXT
, XATOM_TEXT
, import_text
, export_text
},
161 { 0, CF_SYLK
, XATOM_WCF_SYLK
, import_data
, export_data
},
162 { 0, CF_DIF
, XATOM_WCF_DIF
, import_data
, export_data
},
163 { 0, CF_TIFF
, XATOM_WCF_TIFF
, import_data
, export_data
},
164 { 0, CF_DIB
, XA_PIXMAP
, import_pixmap
, export_pixmap
},
165 { 0, CF_PENDATA
, XATOM_WCF_PENDATA
, import_data
, export_data
},
166 { 0, CF_RIFF
, XATOM_WCF_RIFF
, import_data
, export_data
},
167 { 0, CF_WAVE
, XATOM_WCF_WAVE
, import_data
, export_data
},
168 { 0, CF_ENHMETAFILE
, XATOM_WCF_ENHMETAFILE
, import_data
, export_data
},
169 { 0, CF_HDROP
, XATOM_text_uri_list
, import_text_uri_list
, export_hdrop
},
170 { 0, CF_DIB
, XATOM_image_bmp
, import_image_bmp
, export_image_bmp
},
171 { RichTextFormatW
, 0, XATOM_text_rtf
, import_data
, export_data
},
172 { RichTextFormatW
, 0, XATOM_text_richtext
, import_data
, export_data
},
173 { GIFW
, 0, XATOM_image_gif
, import_data
, export_data
},
174 { JFIFW
, 0, XATOM_image_jpeg
, import_data
, export_data
},
175 { PNGW
, 0, XATOM_image_png
, import_data
, export_data
},
176 { HTMLFormatW
, 0, XATOM_HTML_Format
, import_data
, export_data
},
177 { HTMLFormatW
, 0, XATOM_text_html
, import_text_html
, export_text_html
},
178 { 0, 0, XATOM_TARGETS
, import_targets
, export_targets
},
179 { 0, 0, XATOM_MULTIPLE
, NULL
, export_multiple
},
180 { 0, 0, XATOM_TIMESTAMP
, NULL
, export_timestamp
},
183 static struct list format_list
= LIST_INIT( format_list
);
185 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
187 static DWORD clipboard_thread_id
;
188 static HWND clipboard_hwnd
;
189 static BOOL is_clipboard_owner
;
190 static Window selection_window
;
191 static Window import_window
;
192 static Atom current_selection
;
193 static UINT rendered_formats
;
194 static ULONG64 last_clipboard_update
;
195 static struct clipboard_format
**current_x11_formats
;
196 static unsigned int nb_current_x11_formats
;
197 static BOOL use_xfixes
;
199 Display
*clipboard_display
= NULL
;
201 static const char *debugstr_format( UINT id
)
205 if (NtUserGetClipboardFormatName( id
, buffer
, ARRAYSIZE(buffer
) ))
206 return wine_dbg_sprintf( "%04x %s", id
, debugstr_w(buffer
) );
210 case 0: return "(none)";
211 #define BUILTIN(id) case id: return #id;
214 BUILTIN(CF_METAFILEPICT
)
224 BUILTIN(CF_UNICODETEXT
)
225 BUILTIN(CF_ENHMETAFILE
)
229 BUILTIN(CF_OWNERDISPLAY
)
231 BUILTIN(CF_DSPBITMAP
)
232 BUILTIN(CF_DSPMETAFILEPICT
)
233 BUILTIN(CF_DSPENHMETAFILE
)
235 default: return wine_dbg_sprintf( "%04x", id
);
239 static const char *debugstr_xatom( Atom atom
)
244 if (!atom
) return "(None)";
245 name
= XGetAtomName( thread_display(), atom
);
246 ret
= debugstr_a( name
);
252 static int is_atom_error( Display
*display
, XErrorEvent
*event
, void *arg
)
254 return (event
->error_code
== BadAtom
);
258 /**************************************************************************
261 static struct clipboard_format
*find_win32_format( UINT id
)
263 struct clipboard_format
*format
;
265 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
266 if (format
->id
== id
) return format
;
271 /**************************************************************************
274 static struct clipboard_format
*find_x11_format( Atom atom
)
276 struct clipboard_format
*format
;
278 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
279 if (format
->atom
== atom
) return format
;
284 /**************************************************************************
285 * register_builtin_formats
287 static void register_builtin_formats(void)
289 struct clipboard_format
*formats
;
292 if (!(formats
= malloc( ARRAY_SIZE(builtin_formats
) * sizeof(*formats
)))) return;
294 for (i
= 0; i
< ARRAY_SIZE(builtin_formats
); i
++)
296 if (builtin_formats
[i
].name
)
297 formats
[i
].id
= RegisterClipboardFormatW( builtin_formats
[i
].name
);
299 formats
[i
].id
= builtin_formats
[i
].id
;
301 formats
[i
].atom
= GET_ATOM(builtin_formats
[i
].data
);
302 formats
[i
].import
= builtin_formats
[i
].import
;
303 formats
[i
].export
= builtin_formats
[i
].export
;
304 list_add_tail( &format_list
, &formats
[i
].entry
);
309 /**************************************************************************
312 static void register_formats( const UINT
*ids
, const Atom
*atoms
, unsigned int count
)
314 struct clipboard_format
*formats
;
317 if (!(formats
= malloc( count
* sizeof(*formats
)))) return;
319 for (i
= 0; i
< count
; i
++)
321 formats
[i
].id
= ids
[i
];
322 formats
[i
].atom
= atoms
[i
];
323 formats
[i
].import
= import_data
;
324 formats
[i
].export
= export_data
;
325 list_add_tail( &format_list
, &formats
[i
].entry
);
326 TRACE( "registered %s atom %s\n", debugstr_format( ids
[i
] ), debugstr_xatom( atoms
[i
] ));
331 /**************************************************************************
332 * register_win32_formats
334 * Register Win32 clipboard formats the first time we encounter them.
336 static void register_win32_formats( const UINT
*ids
, UINT size
)
338 unsigned int count
, len
;
344 if (list_empty( &format_list
)) register_builtin_formats();
348 for (count
= 0; count
< 256 && size
; ids
++, size
--)
350 if (find_win32_format( *ids
)) continue; /* it already exists */
351 if (!NtUserGetClipboardFormatName( *ids
, buffer
, ARRAYSIZE(buffer
) ))
352 continue; /* not a named format */
353 if (!(len
= WideCharToMultiByte( CP_UNIXCP
, 0, buffer
, -1, NULL
, 0, NULL
, NULL
))) continue;
354 if (!(names
[count
] = malloc( len
))) continue;
355 WideCharToMultiByte( CP_UNIXCP
, 0, buffer
, -1, names
[count
], len
, NULL
, NULL
);
356 new_ids
[count
++] = *ids
;
360 XInternAtoms( thread_display(), names
, count
, False
, atoms
);
361 register_formats( new_ids
, atoms
, count
);
362 while (count
) free( names
[--count
] );
367 /**************************************************************************
368 * register_x11_formats
370 * Register X11 atom formats the first time we encounter them.
372 static void register_x11_formats( const Atom
*atoms
, UINT size
)
374 Display
*display
= thread_display();
375 unsigned int i
, pos
, count
;
381 if (list_empty( &format_list
)) register_builtin_formats();
385 for (count
= 0; count
< 256 && size
; atoms
++, size
--)
386 if (!find_x11_format( *atoms
)) new_atoms
[count
++] = *atoms
;
390 X11DRV_expect_error( display
, is_atom_error
, NULL
);
391 if (!XGetAtomNames( display
, new_atoms
, count
, names
)) count
= 0;
392 if (X11DRV_check_error())
394 WARN( "got some bad atoms, ignoring\n" );
398 for (i
= pos
= 0; i
< count
; i
++)
400 if (MultiByteToWideChar( CP_UNIXCP
, 0, names
[i
], -1, buffer
, 256 ) &&
401 (ids
[pos
] = RegisterClipboardFormatW( buffer
)))
402 new_atoms
[pos
++] = new_atoms
[i
];
405 register_formats( ids
, new_atoms
, pos
);
410 /**************************************************************************
413 * Put data as a property on the specified window.
415 static void put_property( Display
*display
, Window win
, Atom prop
, Atom type
, int format
,
416 const void *ptr
, size_t size
)
418 const unsigned char *data
= ptr
;
419 int mode
= PropModeReplace
;
420 size_t width
= (format
== 32) ? sizeof(long) : format
/ 8;
421 size_t max_size
= XExtendedMaxRequestSize( display
) * 4;
423 if (!max_size
) max_size
= XMaxRequestSize( display
) * 4;
424 max_size
-= 64; /* request overhead */
428 size_t count
= min( size
, max_size
/ width
);
429 XChangeProperty( display
, win
, prop
, type
, format
, mode
, data
, count
);
430 mode
= PropModeAppend
;
432 data
+= count
* width
;
437 static void selection_sleep(void)
439 LARGE_INTEGER timeout
;
440 timeout
.QuadPart
= (ULONGLONG
)SELECTION_WAIT
* -10000;
441 NtDelayExecution( FALSE
, &timeout
);
444 /**************************************************************************
447 static BOOL
convert_selection( Display
*display
, Window win
, Atom selection
,
448 struct clipboard_format
*format
, Atom
*type
,
449 unsigned char **data
, size_t *size
)
454 TRACE( "import %s from %s win %lx to format %s\n",
455 debugstr_xatom( format
->atom
), debugstr_xatom( selection
),
456 win
, debugstr_format( format
->id
) );
458 XConvertSelection( display
, selection
, format
->atom
, x11drv_atom(SELECTION_DATA
), win
, CurrentTime
);
460 for (i
= 0; i
< SELECTION_RETRIES
; i
++)
462 Bool res
= XCheckTypedWindowEvent( display
, win
, SelectionNotify
, &event
);
463 if (res
&& event
.xselection
.selection
== selection
&& event
.xselection
.target
== format
->atom
)
464 return read_property( display
, win
, event
.xselection
.property
, type
, data
, size
);
467 ERR( "Timed out waiting for SelectionNotify event\n" );
472 /***********************************************************************
475 * Return the size of the bitmap info structure including color table.
477 static int bitmap_info_size( const BITMAPINFO
* info
, WORD coloruse
)
479 unsigned int colors
, size
, masks
= 0;
481 if (info
->bmiHeader
.biSize
== sizeof(BITMAPCOREHEADER
))
483 const BITMAPCOREHEADER
*core
= (const BITMAPCOREHEADER
*)info
;
484 colors
= (core
->bcBitCount
<= 8) ? 1 << core
->bcBitCount
: 0;
485 return sizeof(BITMAPCOREHEADER
) + colors
*
486 ((coloruse
== DIB_RGB_COLORS
) ? sizeof(RGBTRIPLE
) : sizeof(WORD
));
488 else /* assume BITMAPINFOHEADER */
490 colors
= info
->bmiHeader
.biClrUsed
;
491 if (!colors
&& (info
->bmiHeader
.biBitCount
<= 8))
492 colors
= 1 << info
->bmiHeader
.biBitCount
;
493 if (info
->bmiHeader
.biCompression
== BI_BITFIELDS
) masks
= 3;
494 size
= max( info
->bmiHeader
.biSize
, sizeof(BITMAPINFOHEADER
) + masks
* sizeof(DWORD
) );
495 return size
+ colors
* ((coloruse
== DIB_RGB_COLORS
) ? sizeof(RGBQUAD
) : sizeof(WORD
));
500 /***********************************************************************
501 * create_dib_from_bitmap
503 * Allocates a packed DIB and copies the bitmap data into it.
505 static void *create_dib_from_bitmap( HBITMAP hBmp
, size_t *size
)
509 LPBITMAPINFOHEADER pbmiHeader
;
510 unsigned int cDataSize
, OffsetBits
;
514 if (!NtGdiExtGetObjectW( hBmp
, sizeof(bmp
), &bmp
)) return 0;
517 * A packed DIB contains a BITMAPINFO structure followed immediately by
518 * an optional color palette and the pixel data.
521 /* Calculate the size of the packed DIB */
522 cDataSize
= abs( bmp
.bmHeight
) * (((bmp
.bmWidth
* bmp
.bmBitsPixel
+ 31) / 8) & ~3);
523 *size
= sizeof(BITMAPINFOHEADER
)
524 + ( (bmp
.bmBitsPixel
<= 8) ? (sizeof(RGBQUAD
) * (1 << bmp
.bmBitsPixel
)) : 0 )
526 /* Get the offset to the bits */
527 OffsetBits
= *size
- cDataSize
;
529 /* Allocate the packed DIB */
530 TRACE( "\tAllocating packed DIB\n" );
531 if (!(ret
= malloc( *size
)))
533 WARN( "Could not allocate packed DIB!\n" );
537 /* A packed DIB starts with a BITMAPINFOHEADER */
538 pbmiHeader
= (LPBITMAPINFOHEADER
)ret
;
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 */
554 hdc
= NtUserGetDCEx( 0, 0, DCX_CACHE
| DCX_WINDOW
);
555 nLinesCopied
= NtGdiGetDIBitsInternal( hdc
, hBmp
, 0, bmp
.bmHeight
, ret
+ OffsetBits
,
556 (LPBITMAPINFO
) pbmiHeader
, 0, 0, 0 );
557 NtUserReleaseDC( 0, hdc
);
559 /* Cleanup if GetDIBits failed */
560 if (nLinesCopied
!= bmp
.bmHeight
)
562 TRACE("\tGetDIBits returned %d. Actual lines=%d\n", nLinesCopied
, bmp
.bmHeight
);
570 /* based on wine_get_dos_file_name */
571 static WCHAR
*get_dos_file_name( const char *path
)
573 ULONG len
= strlen( path
) + 9; /* \??\unix prefix */
576 if (!(ret
= malloc( len
* sizeof(WCHAR
) ))) return NULL
;
577 if (wine_unix_to_nt_file_name( path
, ret
, &len
))
585 /* get rid of the \??\ prefix */
586 memmove( ret
, ret
+ 4, (len
- 4) * sizeof(WCHAR
) );
593 /***********************************************************************
596 * Converts a text/uri-list URI to DOS filename.
598 static WCHAR
* uri_to_dos(char *encodedURI
)
603 char *uri
= calloc( 1, strlen(encodedURI
) + 1 );
606 for (i
= 0; encodedURI
[i
]; ++i
)
608 if (encodedURI
[i
] == '%')
610 if (encodedURI
[i
+1] && encodedURI
[i
+2])
614 buffer
[0] = encodedURI
[i
+1];
615 buffer
[1] = encodedURI
[i
+2];
617 sscanf(buffer
, "%x", &number
);
623 WARN("invalid URI encoding in %s\n", debugstr_a(encodedURI
));
629 uri
[j
++] = encodedURI
[i
];
632 /* Read http://www.freedesktop.org/wiki/Draganddropwarts and cry... */
633 if (strncmp(uri
, "file:/", 6) == 0)
639 /* file:///path/to/file (nautilus, thunar) */
640 ret
= get_dos_file_name( &uri
[7] );
644 /* file://hostname/path/to/file (X file drag spec) */
646 char *path
= strchr(&uri
[7], '/');
650 if (strcmp(&uri
[7], "localhost") == 0)
653 ret
= get_dos_file_name( path
);
655 else if (gethostname(hostname
, sizeof(hostname
)) == 0)
657 if (strcmp(hostname
, &uri
[7]) == 0)
660 ret
= get_dos_file_name( path
);
668 /* file:/path/to/file (konqueror) */
669 ret
= get_dos_file_name( &uri
[5] );
677 /**************************************************************************
678 * unicode_text_from_string
680 * Convert a string in the specified encoding to CF_UNICODETEXT format.
682 static WCHAR
*unicode_text_from_string( UINT codepage
, const void *data
, size_t size
, size_t *ret_size
)
687 count
= MultiByteToWideChar( codepage
, 0, data
, size
, NULL
, 0);
689 if (!(strW
= malloc( (count
* 2 + 1) * sizeof(WCHAR
) ))) return 0;
691 MultiByteToWideChar( codepage
, 0, data
, size
, strW
+ count
, count
);
692 for (i
= j
= 0; i
< count
; i
++)
694 if (strW
[i
+ count
] == '\n' && (!i
|| strW
[i
+ count
- 1] != '\r')) strW
[j
++] = '\r';
695 strW
[j
++] = strW
[i
+ count
];
698 *ret_size
= j
* sizeof(WCHAR
);
699 TRACE( "returning %s\n", debugstr_wn( strW
, j
- 1 ));
704 /**************************************************************************
707 * Import XA_STRING, converting the string to CF_UNICODETEXT.
709 static void *import_string( Atom type
, const void *data
, size_t size
, size_t *ret_size
)
711 return unicode_text_from_string( 28591, data
, size
, ret_size
);
715 /**************************************************************************
718 * Import XA_UTF8_STRING, converting the string to CF_UNICODETEXT.
720 static void *import_utf8_string( Atom type
, const void *data
, size_t size
, size_t *ret_size
)
722 return unicode_text_from_string( CP_UTF8
, data
, size
, ret_size
);
726 /**************************************************************************
727 * import_compound_text
729 * Import COMPOUND_TEXT to CF_UNICODETEXT.
731 static void *import_compound_text( Atom type
, const void *data
, size_t size
, size_t *ret_size
)
735 XTextProperty txtprop
;
738 txtprop
.value
= (BYTE
*)data
;
739 txtprop
.nitems
= size
;
740 txtprop
.encoding
= x11drv_atom(COMPOUND_TEXT
);
742 if (XmbTextPropertyToTextList( thread_display(), &txtprop
, &srcstr
, &count
) != Success
) return 0;
743 if (!count
) return 0;
745 ret
= unicode_text_from_string( CP_UNIXCP
, srcstr
[0], strlen(srcstr
[0]) + 1, ret_size
);
746 XFreeStringList(srcstr
);
751 /**************************************************************************
754 * Import XA_TEXT, converting the string to CF_UNICODETEXT.
756 static void *import_text( Atom type
, const void *data
, size_t size
, size_t *ret_size
)
758 if (type
== XA_STRING
) return import_string( type
, data
, size
, ret_size
);
759 if (type
== x11drv_atom(UTF8_STRING
)) return import_utf8_string( type
, data
, size
, ret_size
);
760 if (type
== x11drv_atom(COMPOUND_TEXT
)) return import_compound_text( type
, data
, size
, ret_size
);
761 FIXME( "unsupported TEXT type %s\n", debugstr_xatom( type
));
766 /**************************************************************************
769 * Import XA_PIXMAP, converting the image to CF_DIB.
771 static void *import_pixmap( Atom type
, const void *data
, size_t size
, size_t *ret_size
)
773 const Pixmap
*pPixmap
= (const Pixmap
*)data
;
775 XVisualInfo vis
= default_visual
;
776 char buffer
[FIELD_OFFSET( BITMAPINFO
, bmiColors
[256] )];
777 BITMAPINFO
*info
= (BITMAPINFO
*)buffer
;
778 struct gdi_image_bits bits
;
780 int x
,y
; /* Unused */
781 unsigned border_width
; /* Unused */
782 unsigned int depth
, width
, height
;
784 /* Get the Pixmap dimensions and bit depth */
785 if (!XGetGeometry(gdi_display
, *pPixmap
, &root
, &x
, &y
, &width
, &height
,
786 &border_width
, &depth
)) depth
= 0;
787 if (!pixmap_formats
[depth
]) return 0;
789 TRACE( "pixmap properties: width=%d, height=%d, depth=%d\n", width
, height
, depth
);
791 if (depth
!= vis
.depth
) switch (pixmap_formats
[depth
]->bits_per_pixel
)
797 case 16: /* assume R5G5B5 */
798 vis
.red_mask
= 0x7c00;
799 vis
.green_mask
= 0x03e0;
800 vis
.blue_mask
= 0x001f;
802 case 24: /* assume R8G8B8 */
803 case 32: /* assume A8R8G8B8 */
804 vis
.red_mask
= 0xff0000;
805 vis
.green_mask
= 0x00ff00;
806 vis
.blue_mask
= 0x0000ff;
812 if (!get_pixmap_image( *pPixmap
, width
, height
, &vis
, info
, &bits
))
814 DWORD info_size
= bitmap_info_size( info
, DIB_RGB_COLORS
);
816 ptr
= malloc( info_size
+ info
->bmiHeader
.biSizeImage
);
819 memcpy( ptr
, info
, info_size
);
820 memcpy( ptr
+ info_size
, bits
.ptr
, info
->bmiHeader
.biSizeImage
);
821 *ret_size
= info_size
+ info
->bmiHeader
.biSizeImage
;
823 if (bits
.free
) bits
.free( &bits
);
829 /**************************************************************************
832 * Import image/bmp, converting the image to CF_DIB.
834 static void *import_image_bmp( Atom type
, const void *data
, size_t size
, size_t *ret_size
)
836 const BITMAPFILEHEADER
*bfh
= data
;
839 if (size
>= sizeof(BITMAPFILEHEADER
)+sizeof(BITMAPCOREHEADER
) &&
840 bfh
->bfType
== 0x4d42 /* "BM" */)
842 const BITMAPINFO
*bmi
= (const BITMAPINFO
*)(bfh
+ 1);
847 if (bmi
->bmiHeader
.biSize
== sizeof(BITMAPCOREHEADER
))
849 const BITMAPCOREHEADER
*core
= (const BITMAPCOREHEADER
*)bmi
;
850 width
= core
->bcWidth
;
851 height
= core
->bcHeight
;
853 else if (bmi
->bmiHeader
.biSize
>= sizeof(BITMAPINFOHEADER
))
855 const BITMAPINFOHEADER
*header
= &bmi
->bmiHeader
;
856 if (header
->biCompression
== BI_JPEG
|| header
->biCompression
== BI_PNG
) return 0;
857 width
= header
->biWidth
;
858 height
= header
->biHeight
;
861 if (!width
|| !height
) return NULL
;
863 hdc
= NtUserGetDCEx( 0, 0, DCX_CACHE
| DCX_WINDOW
);
865 if ((hbmp
= NtGdiCreateDIBitmapInternal( hdc
, width
, height
, CBM_INIT
,
866 (const BYTE
*)data
+ bfh
->bfOffBits
, bmi
,
867 DIB_RGB_COLORS
, 0, 0, 0, 0 )))
869 ret
= create_dib_from_bitmap( hbmp
, ret_size
);
870 NtGdiDeleteObjectApp( hbmp
);
872 NtUserReleaseDC(0, hdc
);
878 /**************************************************************************
881 static void *import_text_html( Atom type
, const void *data
, size_t size
, size_t *ret_size
)
883 static const char header
[] =
885 "StartHTML:0000000100\n"
887 "StartFragment:%010lu\n"
888 "EndFragment:%010lu\n"
889 "<!--StartFragment-->";
890 static const char trailer
[] = "\n<!--EndFragment-->";
895 /* Firefox uses UTF-16LE with byte order mark. Convert to UTF-8 without the BOM. */
896 if (size
>= sizeof(WCHAR
) && ((const WCHAR
*)data
)[0] == 0xfeff)
898 len
= WideCharToMultiByte( CP_UTF8
, 0, (const WCHAR
*)data
+ 1, size
/ sizeof(WCHAR
) - 1,
899 NULL
, 0, NULL
, NULL
);
900 if (!(text
= malloc( len
))) return 0;
901 WideCharToMultiByte( CP_UTF8
, 0, (const WCHAR
*)data
+ 1, size
/ sizeof(WCHAR
) - 1,
902 text
, len
, NULL
, NULL
);
907 len
= strlen( header
) + 12; /* 3 * 4 extra chars for %010lu */
908 total
= len
+ size
+ sizeof(trailer
);
909 if ((ret
= malloc( total
)))
912 p
+= sprintf( p
, header
, total
- 1, len
, len
+ size
+ 1 /* include the final \n in the data */ );
913 memcpy( p
, data
, size
);
914 strcpy( p
+ size
, trailer
);
916 TRACE( "returning %s\n", debugstr_a( ret
));
923 /**************************************************************************
924 * import_text_uri_list
926 * Import text/uri-list.
928 static void *import_text_uri_list( Atom type
, const void *data
, size_t size
, size_t *ret_size
)
930 const char *uriList
= data
;
938 DROPFILES
*dropFiles
= NULL
;
940 if (!(out
= malloc( capacity
* sizeof(WCHAR
) ))) return 0;
944 while (end
< size
&& uriList
[end
] != '\r')
946 if (end
< (size
- 1) && uriList
[end
+1] != '\n')
948 WARN("URI list line doesn't end in \\r\\n\n");
952 uri
= malloc( end
- start
+ 1 );
955 lstrcpynA(uri
, &uriList
[start
], end
- start
+ 1);
956 path
= uri_to_dos(uri
);
957 TRACE("converted URI %s to DOS path %s\n", debugstr_a(uri
), debugstr_w(path
));
962 int pathSize
= strlenW(path
) + 1;
963 if (pathSize
> capacity
- total
)
966 capacity
= 2*capacity
+ pathSize
;
967 new_out
= realloc( out
, (capacity
+ 1) * sizeof(WCHAR
) );
972 memcpy(&out
[total
], path
, pathSize
* sizeof(WCHAR
));
983 if (out
&& end
>= size
)
985 *ret_size
= sizeof(DROPFILES
) + (total
+ 1) * sizeof(WCHAR
);
986 if ((dropFiles
= malloc( *ret_size
)))
988 dropFiles
->pFiles
= sizeof(DROPFILES
);
992 dropFiles
->fWide
= TRUE
;
994 memcpy( (char*)dropFiles
+ dropFiles
->pFiles
, out
, (total
+ 1) * sizeof(WCHAR
) );
1002 /**************************************************************************
1005 * Import TARGETS and mark the corresponding clipboard formats as available.
1007 static void *import_targets( Atom type
, const void *data
, size_t size
, size_t *ret_size
)
1009 UINT i
, pos
, count
= size
/ sizeof(Atom
);
1010 const Atom
*properties
= data
;
1011 struct clipboard_format
*format
, **formats
;
1013 if (type
!= XA_ATOM
&& type
!= x11drv_atom(TARGETS
)) return 0;
1015 register_x11_formats( properties
, count
);
1017 /* the builtin formats contain duplicates, so allocate some extra space */
1018 if (!(formats
= malloc( (count
+ ARRAY_SIZE(builtin_formats
)) * sizeof(*formats
))))
1022 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
1024 for (i
= 0; i
< count
; i
++) if (properties
[i
] == format
->atom
) break;
1025 if (i
== count
) continue;
1026 if (format
->import
&& format
->id
)
1028 struct set_clipboard_params params
= { .data
= NULL
};
1030 TRACE( "property %s -> format %s\n",
1031 debugstr_xatom( properties
[i
] ), debugstr_format( format
->id
));
1033 NtUserSetClipboardData( format
->id
, 0, ¶ms
);
1034 formats
[pos
++] = format
;
1036 else TRACE( "property %s (ignoring)\n", debugstr_xatom( properties
[i
] ));
1039 free( current_x11_formats
);
1040 current_x11_formats
= formats
;
1041 nb_current_x11_formats
= pos
;
1047 /**************************************************************************
1050 * Generic import clipboard data routine.
1052 static void *import_data( Atom type
, const void *data
, size_t size
, size_t *ret_size
)
1054 void *ret
= malloc( size
);
1057 memcpy( ret
, data
, size
);
1064 /**************************************************************************
1067 * Import the specified format from the selection and return a global handle to the data.
1069 static void *import_selection( Display
*display
, Window win
, Atom selection
,
1070 struct clipboard_format
*format
, size_t *ret_size
)
1072 unsigned char *data
;
1077 if (!format
->import
) return 0;
1079 if (!convert_selection( display
, win
, selection
, format
, &type
, &data
, &size
))
1081 TRACE( "failed to convert selection\n" );
1084 ret
= format
->import( type
, data
, size
, ret_size
);
1090 /**************************************************************************
1091 * X11DRV_CLIPBOARD_ImportSelection
1093 * Import the X selection into the clipboard format registered for the given X target.
1095 void X11DRV_CLIPBOARD_ImportSelection( Display
*display
, Window win
, Atom selection
,
1096 Atom
*targets
, UINT count
,
1097 void (*callback
)( UINT
, HANDLE
))
1103 struct clipboard_format
*format
;
1105 register_x11_formats( targets
, count
);
1107 for (i
= 0; i
< count
; i
++)
1109 if (!(format
= find_x11_format( targets
[i
] ))) continue;
1110 if (!format
->id
) continue;
1111 if (!(data
= import_selection( display
, win
, selection
, format
, &size
))) continue;
1113 if ((handle
= GlobalAlloc( GMEM_FIXED
, size
)))
1116 ptr
= GlobalLock( handle
);
1117 memcpy( ptr
, data
, size
);
1118 GlobalUnlock( handle
);
1119 callback( format
->id
, handle
);
1126 /**************************************************************************
1129 static BOOL
render_format( UINT id
)
1131 Display
*display
= thread_display();
1134 if (!current_selection
) return 0;
1136 for (i
= 0; i
< nb_current_x11_formats
; i
++)
1138 struct set_clipboard_params params
;
1139 if (current_x11_formats
[i
]->id
!= id
) continue;
1140 if (!(params
.data
= import_selection( display
, import_window
, current_selection
,
1141 current_x11_formats
[i
], ¶ms
.size
))) continue;
1143 NtUserSetClipboardData( id
, 0, ¶ms
);
1144 if (params
.size
) free( params
.data
);
1151 /**************************************************************************
1154 * Generic export clipboard data routine.
1156 static BOOL
export_data( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
)
1158 put_property( display
, win
, prop
, target
, 8, data
, size
);
1163 /**************************************************************************
1164 * string_from_unicode_text
1166 * Convert CF_UNICODETEXT data to a string in the specified codepage.
1168 static char *string_from_unicode_text( UINT codepage
, const WCHAR
*string
, size_t string_size
, size_t *size
)
1172 UINT lenW
= string_size
/ sizeof(WCHAR
);
1175 if (!string_size
) return NULL
;
1177 len
= WideCharToMultiByte( codepage
, 0, string
, lenW
, NULL
, 0, NULL
, NULL
);
1178 if ((str
= malloc( len
)))
1180 WideCharToMultiByte( codepage
, 0, string
, lenW
, str
, len
, NULL
, NULL
);
1182 /* remove carriage returns */
1183 for (i
= j
= 0; i
< len
; i
++)
1185 if (str
[i
] == '\r' && (i
== len
- 1 || str
[i
+ 1] == '\n')) continue;
1188 while (j
&& !str
[j
- 1]) j
--; /* remove trailing nulls */
1190 TRACE( "returning %s\n", debugstr_an( str
, j
));
1196 /**************************************************************************
1199 * Export CF_UNICODETEXT converting the string to XA_STRING.
1201 static BOOL
export_string( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
)
1203 char *text
= string_from_unicode_text( 28591, data
, size
, &size
);
1205 if (!text
) return FALSE
;
1206 put_property( display
, win
, prop
, target
, 8, text
, size
);
1212 /**************************************************************************
1213 * export_utf8_string
1215 * Export CF_UNICODE converting the string to UTF8.
1217 static BOOL
export_utf8_string( Display
*display
, Window win
, Atom prop
, Atom target
,
1218 void *data
, size_t size
)
1220 char *text
= string_from_unicode_text( CP_UTF8
, data
, size
, &size
);
1222 if (!text
) return FALSE
;
1223 put_property( display
, win
, prop
, target
, 8, text
, size
);
1229 /**************************************************************************
1232 * Export CF_UNICODE to the polymorphic TEXT type, using UTF8.
1234 static BOOL
export_text( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
)
1236 return export_utf8_string( display
, win
, prop
, x11drv_atom(UTF8_STRING
), data
, size
);
1240 /**************************************************************************
1241 * export_compound_text
1243 * Export CF_UNICODE to COMPOUND_TEXT
1245 static BOOL
export_compound_text( Display
*display
, Window win
, Atom prop
, Atom target
,
1246 void *data
, size_t size
)
1248 XTextProperty textprop
;
1249 XICCEncodingStyle style
;
1250 char *text
= string_from_unicode_text( CP_UNIXCP
, data
, size
, &size
);
1252 if (!text
) return FALSE
;
1253 if (target
== x11drv_atom(COMPOUND_TEXT
))
1254 style
= XCompoundTextStyle
;
1256 style
= XStdICCTextStyle
;
1258 /* Update the X property */
1259 if (XmbTextListToTextProperty( display
, &text
, 1, style
, &textprop
) == Success
)
1261 XSetTextProperty( display
, win
, &textprop
, prop
);
1262 XFree( textprop
.value
);
1270 /**************************************************************************
1273 * Export CF_DIB to XA_PIXMAP.
1275 static BOOL
export_pixmap( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
)
1278 BITMAPINFO
*pbmi
= data
;
1279 struct gdi_image_bits bits
;
1281 bits
.ptr
= (LPBYTE
)pbmi
+ bitmap_info_size( pbmi
, DIB_RGB_COLORS
);
1283 bits
.is_copy
= FALSE
;
1284 pixmap
= create_pixmap_from_image( 0, &default_visual
, pbmi
, &bits
, DIB_RGB_COLORS
);
1286 put_property( display
, win
, prop
, target
, 32, &pixmap
, 1 );
1287 /* FIXME: free the pixmap when the property is deleted */
1292 /**************************************************************************
1295 * Export CF_DIB to image/bmp.
1297 static BOOL
export_image_bmp( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
)
1299 LPBYTE dibdata
= data
;
1301 BITMAPFILEHEADER
*bfh
;
1303 bmpsize
= sizeof(BITMAPFILEHEADER
) + size
;
1304 bfh
= malloc( bmpsize
);
1307 /* bitmap file header */
1308 bfh
->bfType
= 0x4d42; /* "BM" */
1309 bfh
->bfSize
= bmpsize
;
1310 bfh
->bfReserved1
= 0;
1311 bfh
->bfReserved2
= 0;
1312 bfh
->bfOffBits
= sizeof(BITMAPFILEHEADER
) + bitmap_info_size((BITMAPINFO
*)dibdata
, DIB_RGB_COLORS
);
1314 /* rest of bitmap is the same as the packed dib */
1315 memcpy(bfh
+1, dibdata
, bmpsize
-sizeof(BITMAPFILEHEADER
));
1317 put_property( display
, win
, prop
, target
, 8, bfh
, bmpsize
);
1323 /**************************************************************************
1326 * Export HTML Format to text/html.
1328 * FIXME: We should attempt to add an <a base> tag and convert windows paths.
1330 static BOOL
export_text_html( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
)
1333 UINT start
= 0, end
= 0;
1337 while (*p
&& *p
!= '<')
1339 if (!strncmp( p
, "StartFragment:", 14 )) start
= atoi( p
+ 14 );
1340 else if (!strncmp( p
, "EndFragment:", 12 )) end
= atoi( p
+ 12 );
1341 if (!(p
= strpbrk( p
, "\r\n" ))) break;
1342 while (*p
== '\r' || *p
== '\n') p
++;
1344 if (start
&& start
< end
&& end
<= size
)
1345 put_property( display
, win
, prop
, target
, 8, (char *)data
+ start
, end
- start
);
1353 /**************************************************************************
1356 * Export CF_HDROP format to text/uri-list.
1358 static BOOL
export_hdrop( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
)
1360 char *textUriList
= NULL
;
1361 UINT textUriListSize
= 32;
1364 WCHAR
*unicode_data
= NULL
;
1365 DROPFILES
*drop_files
= data
;
1367 if (!drop_files
->fWide
)
1369 char *p
, *files
= (char *)data
+ drop_files
->pFiles
;
1371 while (*p
) p
+= strlen( p
) + 1;
1374 if (!(unicode_data
= malloc( (p
- files
) * sizeof(WCHAR
) ))) goto failed
;
1375 MultiByteToWideChar( CP_ACP
, 0, files
, p
- files
, unicode_data
, p
- files
);
1378 else ptr
= (const WCHAR
*)((char *)data
+ drop_files
->pFiles
);
1380 if (!(textUriList
= malloc( textUriListSize
))) goto failed
;
1384 char *unixFilename
= NULL
;
1388 unixFilename
= wine_get_unix_file_name( ptr
);
1389 if (unixFilename
== NULL
) goto failed
;
1390 ptr
+= lstrlenW( ptr
) + 1;
1392 uriSize
= 8 + /* file:/// */
1393 3 * (lstrlenA(unixFilename
) - 1) + /* "%xy" per char except first '/' */
1395 if ((next
+ uriSize
) > textUriListSize
)
1397 UINT biggerSize
= max( 2 * textUriListSize
, next
+ uriSize
);
1398 void *bigger
= realloc( textUriList
, biggerSize
);
1401 textUriList
= bigger
;
1402 textUriListSize
= biggerSize
;
1406 HeapFree(GetProcessHeap(), 0, unixFilename
);
1410 lstrcpyA(&textUriList
[next
], "file:///");
1412 /* URL encode everything - unnecessary, but easier/lighter than linking in shlwapi, and can't hurt */
1413 for (u
= 1; unixFilename
[u
]; u
++)
1415 static const char hex_table
[] = "0123456789abcdef";
1416 textUriList
[next
++] = '%';
1417 textUriList
[next
++] = hex_table
[unixFilename
[u
] >> 4];
1418 textUriList
[next
++] = hex_table
[unixFilename
[u
] & 0xf];
1420 textUriList
[next
++] = '\r';
1421 textUriList
[next
++] = '\n';
1422 HeapFree(GetProcessHeap(), 0, unixFilename
);
1424 put_property( display
, win
, prop
, target
, 8, textUriList
, next
);
1425 free( textUriList
);
1429 free( unicode_data
);
1430 free( textUriList
);
1435 /***********************************************************************
1436 * get_clipboard_formats
1438 * Return a list of all formats currently available on the Win32 clipboard.
1439 * Helper for export_targets.
1441 static UINT
*get_clipboard_formats( UINT
*size
)
1448 if (!(ids
= malloc( *size
* sizeof(*ids
) ))) return NULL
;
1449 if (NtUserGetUpdatedClipboardFormats( ids
, *size
, size
)) break;
1451 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER
) return NULL
;
1453 register_win32_formats( ids
, *size
);
1458 /***********************************************************************
1459 * is_format_available
1461 * Check if a clipboard format is included in the list.
1462 * Helper for export_targets.
1464 static BOOL
is_format_available( UINT format
, const UINT
*ids
, unsigned int count
)
1466 while (count
--) if (*ids
++ == format
) return TRUE
;
1471 /***********************************************************************
1474 * Service a TARGETS selection request event
1476 static BOOL
export_targets( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
)
1478 struct clipboard_format
*format
;
1479 UINT pos
, count
, *formats
;
1482 if (!(formats
= get_clipboard_formats( &count
))) return FALSE
;
1484 /* the builtin formats contain duplicates, so allocate some extra space */
1485 if (!(targets
= malloc( (count
+ ARRAY_SIZE(builtin_formats
)) * sizeof(*targets
) )))
1492 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
1494 if (!format
->export
) continue;
1495 /* formats with id==0 are always exported */
1496 if (format
->id
&& !is_format_available( format
->id
, formats
, count
)) continue;
1497 TRACE( "%d: %s -> %s\n", pos
, debugstr_format( format
->id
), debugstr_xatom( format
->atom
));
1498 targets
[pos
++] = format
->atom
;
1501 put_property( display
, win
, prop
, XA_ATOM
, 32, targets
, pos
);
1508 /**************************************************************************
1511 * Export selection data, depending on the target type.
1513 static BOOL
export_selection( Display
*display
, Window win
, Atom prop
, Atom target
)
1515 struct get_clipboard_params params
= { .data_only
= TRUE
};
1516 struct clipboard_format
*format
;
1517 BOOL open
= FALSE
, ret
= FALSE
;
1518 size_t buffer_size
= 0;
1520 LIST_FOR_EACH_ENTRY( format
, &format_list
, struct clipboard_format
, entry
)
1522 if (format
->atom
!= target
) continue;
1523 if (!format
->export
) continue;
1526 TRACE( "win %lx prop %s target %s\n", win
, debugstr_xatom( prop
), debugstr_xatom( target
));
1527 ret
= format
->export( display
, win
, prop
, target
, NULL
, 0 );
1530 if (!open
&& !(open
= NtUserOpenClipboard( clipboard_hwnd
, 0 )))
1532 ERR( "failed to open clipboard for %s\n", debugstr_xatom( target
));
1539 if (!(params
.data
= malloc( buffer_size
))) break;
1544 params
.size
= buffer_size
;
1545 if (NtUserGetClipboardData( format
->id
, ¶ms
))
1547 TRACE( "win %lx prop %s target %s exporting %s\n",
1548 win
, debugstr_xatom( prop
), debugstr_xatom( target
),
1549 debugstr_format( format
->id
) );
1551 ret
= format
->export( display
, win
, prop
, target
, params
.data
, params
.size
);
1554 if (!params
.data_size
) break;
1555 free( params
.data
);
1556 if (!(params
.data
= malloc( params
.data_size
))) goto done
;
1557 buffer_size
= params
.data_size
;
1558 params
.data_size
= 0;
1560 /* keep looking for another Win32 format mapping to the same target */
1563 free( params
.data
);
1564 if (open
) NtUserCloseClipboard();
1569 /***********************************************************************
1572 * Service a MULTIPLE selection request event
1573 * prop contains a list of (target,property) atom pairs.
1574 * The first atom names a target and the second names a property.
1575 * The effect is as if we have received a sequence of SelectionRequest events
1576 * (one for each atom pair) except that:
1577 * 1. We reply with a SelectionNotify only when all the requested conversions
1578 * have been performed.
1579 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
1580 * we replace the atom in the property by None.
1582 static BOOL
export_multiple( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
)
1587 unsigned long i
, count
, failed
, remain
;
1589 /* Read the MULTIPLE property contents. This should contain a list of
1590 * (target,property) atom pairs.
1592 if (XGetWindowProperty( display
, win
, prop
, 0, 0x3FFF, False
, AnyPropertyType
, &atype
, &aformat
,
1593 &count
, &remain
, (unsigned char**)&list
))
1596 TRACE( "type %s format %d count %ld remain %ld\n",
1597 debugstr_xatom( atype
), aformat
, count
, remain
);
1600 * Make sure we got what we expect.
1601 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
1602 * in a MULTIPLE selection request should be of type ATOM_PAIR.
1603 * However some X apps(such as XPaint) are not compliant with this and return
1604 * a user defined atom in atype when XGetWindowProperty is called.
1605 * The data *is* an atom pair but is not denoted as such.
1607 if (aformat
== 32 /* atype == xAtomPair */ )
1609 for (i
= failed
= 0; i
< count
; i
+= 2)
1611 if (list
[i
+1] == None
) continue;
1612 if (export_selection( display
, win
, list
[i
+ 1], list
[i
] )) continue;
1616 if (failed
) put_property( display
, win
, prop
, atype
, 32, list
, count
);
1623 /***********************************************************************
1626 * Export the timestamp that was used to acquire the selection
1628 static BOOL
export_timestamp( Display
*display
, Window win
, Atom prop
, Atom target
, void *data
, size_t size
)
1630 Time time
= CurrentTime
; /* FIXME */
1631 put_property( display
, win
, prop
, XA_INTEGER
, 32, &time
, 1 );
1636 /**************************************************************************
1637 * X11DRV_CLIPBOARD_GetProperty
1638 * Gets type, data and size.
1640 static BOOL
X11DRV_CLIPBOARD_GetProperty(Display
*display
, Window w
, Atom prop
,
1641 Atom
*atype
, unsigned char **data
, size_t *datasize
)
1644 unsigned long pos
= 0, nitems
, remain
, count
;
1645 unsigned char *val
= NULL
, *buffer
;
1649 if (XGetWindowProperty(display
, w
, prop
, pos
, INT_MAX
/ 4, False
,
1650 AnyPropertyType
, atype
, &aformat
, &nitems
, &remain
, &buffer
))
1652 WARN("Failed to read property\n");
1657 count
= get_property_size( aformat
, nitems
);
1658 *data
= realloc( val
, pos
* sizeof(int) + count
+ 1 );
1667 memcpy( (int *)val
+ pos
, buffer
, count
);
1671 *datasize
= pos
* sizeof(int) + count
;
1675 pos
+= count
/ sizeof(int);
1678 TRACE( "got property %s type %s format %u len %zu from window %lx\n",
1679 debugstr_xatom( prop
), debugstr_xatom( *atype
), aformat
, *datasize
, w
);
1681 /* Delete the property on the window now that we are done
1682 * This will send a PropertyNotify event to the selection owner. */
1683 XDeleteProperty(display
, w
, prop
);
1688 struct clipboard_data_packet
{
1691 unsigned char *data
;
1694 /**************************************************************************
1697 * Reads the contents of the X selection property.
1699 static BOOL
read_property( Display
*display
, Window w
, Atom prop
,
1700 Atom
*type
, unsigned char **data
, size_t *datasize
)
1707 while (XCheckTypedWindowEvent(display
, w
, PropertyNotify
, &xe
))
1710 if (!X11DRV_CLIPBOARD_GetProperty(display
, w
, prop
, type
, data
, datasize
))
1713 if (*type
== x11drv_atom(INCR
))
1716 unsigned long bufsize
= 0;
1717 struct list packets
;
1718 struct clipboard_data_packet
*packet
, *packet2
;
1724 list_init(&packets
);
1729 unsigned char *prop_data
;
1732 /* Wait until PropertyNotify is received */
1733 for (i
= 0; i
< SELECTION_RETRIES
; i
++)
1737 res
= XCheckTypedWindowEvent(display
, w
, PropertyNotify
, &xe
);
1738 if (res
&& xe
.xproperty
.atom
== prop
&&
1739 xe
.xproperty
.state
== PropertyNewValue
)
1744 if (i
>= SELECTION_RETRIES
||
1745 !X11DRV_CLIPBOARD_GetProperty(display
, w
, prop
, type
, &prop_data
, &prop_size
))
1751 /* Retrieved entire data. */
1759 packet
= malloc( sizeof(*packet
) );
1767 packet
->size
= prop_size
;
1768 packet
->data
= prop_data
;
1769 list_add_tail(&packets
, &packet
->entry
);
1770 bufsize
+= prop_size
;
1775 buf
= malloc( bufsize
+ 1 );
1778 unsigned long bytes_copied
= 0;
1779 *datasize
= bufsize
;
1780 LIST_FOR_EACH_ENTRY( packet
, &packets
, struct clipboard_data_packet
, entry
)
1782 memcpy(&buf
[bytes_copied
], packet
->data
, packet
->size
);
1783 bytes_copied
+= packet
->size
;
1792 LIST_FOR_EACH_ENTRY_SAFE( packet
, packet2
, &packets
, struct clipboard_data_packet
, entry
)
1794 free( packet
->data
);
1805 /**************************************************************************
1808 * Acquire the X11 selection when the Win32 clipboard has changed.
1810 static void acquire_selection( Display
*display
)
1812 if (selection_window
) XDestroyWindow( display
, selection_window
);
1814 selection_window
= XCreateWindow( display
, root_window
, 0, 0, 1, 1, 0, CopyFromParent
,
1815 InputOutput
, CopyFromParent
, 0, NULL
);
1816 if (!selection_window
) return;
1818 XSetSelectionOwner( display
, x11drv_atom(CLIPBOARD
), selection_window
, CurrentTime
);
1819 if (use_primary_selection
) XSetSelectionOwner( display
, XA_PRIMARY
, selection_window
, CurrentTime
);
1820 TRACE( "win %lx\n", selection_window
);
1824 /**************************************************************************
1827 * Release the X11 selection when some other X11 app has grabbed it.
1829 static void release_selection( Display
*display
, Time time
)
1831 assert( selection_window
);
1833 TRACE( "win %lx\n", selection_window
);
1835 /* release PRIMARY if we still own it */
1836 if (use_primary_selection
&& XGetSelectionOwner( display
, XA_PRIMARY
) == selection_window
)
1837 XSetSelectionOwner( display
, XA_PRIMARY
, None
, time
);
1839 XDestroyWindow( display
, selection_window
);
1840 selection_window
= 0;
1844 /**************************************************************************
1845 * request_selection_contents
1847 * Retrieve the contents of the X11 selection when it's owned by an X11 app.
1849 static BOOL
request_selection_contents( Display
*display
, BOOL changed
)
1851 struct clipboard_format
*targets
= find_x11_format( x11drv_atom(TARGETS
) );
1852 struct clipboard_format
*string
= find_x11_format( XA_STRING
);
1853 struct clipboard_format
*format
= NULL
;
1855 unsigned char *data
= NULL
;
1856 size_t import_size
, size
= 0;
1859 static Atom last_selection
;
1860 static Window last_owner
;
1861 static struct clipboard_format
*last_format
;
1862 static Atom last_type
;
1863 static unsigned char *last_data
;
1864 static unsigned long last_size
;
1869 current_selection
= 0;
1870 if (use_primary_selection
)
1872 if ((owner
= XGetSelectionOwner( display
, XA_PRIMARY
)))
1873 current_selection
= XA_PRIMARY
;
1875 if (!current_selection
)
1877 if ((owner
= XGetSelectionOwner( display
, x11drv_atom(CLIPBOARD
) )))
1878 current_selection
= x11drv_atom(CLIPBOARD
);
1881 if (current_selection
)
1883 if (convert_selection( display
, import_window
, current_selection
, targets
, &type
, &data
, &size
))
1885 else if (convert_selection( display
, import_window
, current_selection
, string
, &type
, &data
, &size
))
1889 changed
= (changed
||
1891 last_selection
!= current_selection
||
1892 last_owner
!= owner
||
1893 last_format
!= format
||
1894 last_type
!= type
||
1895 last_size
!= size
||
1896 memcmp( last_data
, data
, size
));
1898 if (!changed
|| !NtUserOpenClipboard( clipboard_hwnd
, 0 ))
1904 TRACE( "selection changed, importing\n" );
1905 NtUserEmptyClipboard();
1906 is_clipboard_owner
= TRUE
;
1907 rendered_formats
= 0;
1909 if (format
) format
->import( type
, data
, size
, &import_size
);
1912 last_selection
= current_selection
;
1914 last_format
= format
;
1918 last_clipboard_update
= GetTickCount64();
1919 NtUserCloseClipboard();
1921 NtUserSetTimer( clipboard_hwnd
, 1, SELECTION_UPDATE_DELAY
, NULL
, TIMERV_DEFAULT_COALESCING
);
1926 /**************************************************************************
1929 * Periodically update the clipboard while the selection is owned by an X11 app.
1931 BOOL
update_clipboard( HWND hwnd
)
1933 if (use_xfixes
) return TRUE
;
1934 if (hwnd
!= clipboard_hwnd
) return TRUE
;
1935 if (!is_clipboard_owner
) return TRUE
;
1936 if (GetTickCount64() - last_clipboard_update
<= SELECTION_UPDATE_DELAY
) return TRUE
;
1937 return request_selection_contents( thread_display(), FALSE
);
1941 /**************************************************************************
1944 * Window procedure for the clipboard manager.
1946 static LRESULT CALLBACK
clipboard_wndproc( HWND hwnd
, UINT msg
, WPARAM wp
, LPARAM lp
)
1952 case WM_CLIPBOARDUPDATE
:
1953 if (is_clipboard_owner
) break; /* ignore our own changes */
1954 acquire_selection( thread_init_display() );
1956 case WM_RENDERFORMAT
:
1957 if (render_format( wp
)) rendered_formats
++;
1960 if (!is_clipboard_owner
) break;
1961 request_selection_contents( thread_display(), FALSE
);
1963 case WM_DESTROYCLIPBOARD
:
1964 TRACE( "WM_DESTROYCLIPBOARD: lost ownership\n" );
1965 is_clipboard_owner
= FALSE
;
1966 KillTimer( hwnd
, 1 );
1969 return DefWindowProcW( hwnd
, msg
, wp
, lp
);
1973 /**************************************************************************
1974 * wait_clipboard_mutex
1976 * Make sure that there's only one clipboard thread per window station.
1978 static BOOL
wait_clipboard_mutex(void)
1980 static const WCHAR prefix
[] = {'_','_','w','i','n','e','_','c','l','i','p','b','o','a','r','d','_'};
1981 WCHAR buffer
[MAX_PATH
+ ARRAY_SIZE( prefix
)];
1984 memcpy( buffer
, prefix
, sizeof(prefix
) );
1985 if (!GetUserObjectInformationW( GetProcessWindowStation(), UOI_NAME
,
1986 buffer
+ ARRAY_SIZE( prefix
),
1987 sizeof(buffer
) - sizeof(prefix
), NULL
))
1989 ERR( "failed to get winstation name\n" );
1992 mutex
= CreateMutexW( NULL
, TRUE
, buffer
);
1993 if (GetLastError() == ERROR_ALREADY_EXISTS
)
1995 TRACE( "waiting for mutex %s\n", debugstr_w( buffer
));
1996 WaitForSingleObject( mutex
, INFINITE
);
2002 /**************************************************************************
2003 * selection_notify_event
2005 * Called when x11 clipboard content changes
2007 #ifdef SONAME_LIBXFIXES
2008 static BOOL
selection_notify_event( HWND hwnd
, XEvent
*event
)
2010 XFixesSelectionNotifyEvent
*req
= (XFixesSelectionNotifyEvent
*)event
;
2012 if (!is_clipboard_owner
) return FALSE
;
2013 if (req
->owner
== selection_window
) return FALSE
;
2014 request_selection_contents( req
->display
, TRUE
);
2019 /**************************************************************************
2022 * Initialize xfixes to receive clipboard update notifications
2024 static void xfixes_init(void)
2026 #ifdef SONAME_LIBXFIXES
2027 typeof(XFixesSelectSelectionInput
) *pXFixesSelectSelectionInput
;
2028 typeof(XFixesQueryExtension
) *pXFixesQueryExtension
;
2029 typeof(XFixesQueryVersion
) *pXFixesQueryVersion
;
2031 int event_base
, error_base
;
2032 int major
= 3, minor
= 0;
2035 handle
= dlopen(SONAME_LIBXFIXES
, RTLD_NOW
);
2036 if (!handle
) return;
2038 pXFixesQueryExtension
= dlsym(handle
, "XFixesQueryExtension");
2039 if (!pXFixesQueryExtension
) return;
2040 pXFixesQueryVersion
= dlsym(handle
, "XFixesQueryVersion");
2041 if (!pXFixesQueryVersion
) return;
2042 pXFixesSelectSelectionInput
= dlsym(handle
, "XFixesSelectSelectionInput");
2043 if (!pXFixesSelectSelectionInput
) return;
2045 if (!pXFixesQueryExtension(clipboard_display
, &event_base
, &error_base
))
2047 pXFixesQueryVersion(clipboard_display
, &major
, &minor
);
2048 use_xfixes
= (major
>= 1);
2049 if (!use_xfixes
) return;
2051 pXFixesSelectSelectionInput(clipboard_display
, import_window
, x11drv_atom(CLIPBOARD
),
2052 XFixesSetSelectionOwnerNotifyMask
|
2053 XFixesSelectionWindowDestroyNotifyMask
|
2054 XFixesSelectionClientCloseNotifyMask
);
2055 if (use_primary_selection
)
2057 pXFixesSelectSelectionInput(clipboard_display
, import_window
, XA_PRIMARY
,
2058 XFixesSetSelectionOwnerNotifyMask
|
2059 XFixesSelectionWindowDestroyNotifyMask
|
2060 XFixesSelectionClientCloseNotifyMask
);
2062 X11DRV_register_event_handler(event_base
+ XFixesSelectionNotify
,
2063 selection_notify_event
, "XFixesSelectionNotify");
2064 TRACE("xfixes succesully initialized\n");
2066 WARN("xfixes not supported\n");
2071 /**************************************************************************
2074 * Thread running inside the desktop process to manage the clipboard
2076 static DWORD WINAPI
clipboard_thread( void *arg
)
2078 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};
2079 XSetWindowAttributes attr
;
2083 if (!wait_clipboard_mutex()) return 0;
2085 clipboard_display
= thread_init_display();
2086 attr
.event_mask
= PropertyChangeMask
;
2087 import_window
= XCreateWindow( clipboard_display
, root_window
, 0, 0, 1, 1, 0, CopyFromParent
,
2088 InputOutput
, CopyFromParent
, CWEventMask
, &attr
);
2091 ERR( "failed to create import window\n" );
2095 memset( &class, 0, sizeof(class) );
2096 class.lpfnWndProc
= clipboard_wndproc
;
2097 class.lpszClassName
= clipboard_classname
;
2099 if (!RegisterClassW( &class ) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS
)
2101 ERR( "could not register clipboard window class err %u\n", GetLastError() );
2104 if (!(clipboard_hwnd
= CreateWindowW( clipboard_classname
, NULL
, 0, 0, 0, 0, 0,
2105 HWND_MESSAGE
, 0, 0, NULL
)))
2107 ERR( "failed to create clipboard window err %u\n", GetLastError() );
2111 clipboard_thread_id
= GetCurrentThreadId();
2112 AddClipboardFormatListener( clipboard_hwnd
);
2113 register_builtin_formats();
2115 request_selection_contents( clipboard_display
, TRUE
);
2117 TRACE( "clipboard thread %04x running\n", GetCurrentThreadId() );
2118 while (GetMessageW( &msg
, 0, 0, 0 )) DispatchMessageW( &msg
);
2123 /**************************************************************************
2124 * X11DRV_UpdateClipboard
2126 void X11DRV_UpdateClipboard(void)
2128 static ULONG last_update
;
2132 if (use_xfixes
) return;
2133 if (GetCurrentThreadId() == clipboard_thread_id
) return;
2134 now
= GetTickCount();
2135 if ((int)(now
- last_update
) <= SELECTION_UPDATE_DELAY
) return;
2136 if (SendMessageTimeoutW( GetClipboardOwner(), WM_X11DRV_UPDATE_CLIPBOARD
, 0, 0,
2137 SMTO_ABORTIFHUNG
, 5000, &ret
) && ret
)
2142 /***********************************************************************
2143 * X11DRV_HandleSelectionRequest
2145 BOOL
X11DRV_SelectionRequest( HWND hwnd
, XEvent
*xev
)
2147 XSelectionRequestEvent
*event
= &xev
->xselectionrequest
;
2148 Display
*display
= event
->display
;
2152 TRACE( "got request on %lx for selection %s target %s win %lx prop %s\n",
2153 event
->owner
, debugstr_xatom( event
->selection
), debugstr_xatom( event
->target
),
2154 event
->requestor
, debugstr_xatom( event
->property
));
2156 if (event
->owner
!= selection_window
) goto done
;
2157 if ((event
->selection
!= x11drv_atom(CLIPBOARD
)) &&
2158 (!use_primary_selection
|| event
->selection
!= XA_PRIMARY
)) goto done
;
2160 /* If the specified property is None the requestor is an obsolete client.
2161 * We support these by using the specified target atom as the reply property.
2163 rprop
= event
->property
;
2165 rprop
= event
->target
;
2167 if (!export_selection( display
, event
->requestor
, rprop
, event
->target
))
2168 rprop
= None
; /* report failure to client */
2171 result
.xselection
.type
= SelectionNotify
;
2172 result
.xselection
.display
= display
;
2173 result
.xselection
.requestor
= event
->requestor
;
2174 result
.xselection
.selection
= event
->selection
;
2175 result
.xselection
.property
= rprop
;
2176 result
.xselection
.target
= event
->target
;
2177 result
.xselection
.time
= event
->time
;
2178 TRACE( "sending SelectionNotify for %s to %lx\n", debugstr_xatom( rprop
), event
->requestor
);
2179 XSendEvent( display
, event
->requestor
, False
, NoEventMask
, &result
);
2184 /***********************************************************************
2185 * X11DRV_SelectionClear
2187 BOOL
X11DRV_SelectionClear( HWND hwnd
, XEvent
*xev
)
2189 XSelectionClearEvent
*event
= &xev
->xselectionclear
;
2191 if (event
->window
!= selection_window
) return FALSE
;
2192 if (event
->selection
!= x11drv_atom(CLIPBOARD
)) return FALSE
;
2194 release_selection( event
->display
, event
->time
);
2195 request_selection_contents( event
->display
, TRUE
);
2200 /**************************************************************************
2201 * X11DRV_InitClipboard
2203 void X11DRV_InitClipboard(void)
2206 HANDLE handle
= CreateThread( NULL
, 0, clipboard_thread
, NULL
, 0, &id
);
2208 if (handle
) CloseHandle( handle
);
2209 else ERR( "failed to create clipboard thread\n" );