include: Update the PEB and TEB structures.
[wine.git] / dlls / winex11.drv / clipboard.c
blob959b59825e16c40c5122817cefa1a1c9a0c04d06
1 /*
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
25 * NOTES:
26 * This file contains the X specific implementation for the windows
27 * Clipboard API.
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)
33 * 2. CLIPBOARD
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
49 * running WINE apps.
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
66 #if 0
67 #pragma makedep unix
68 #endif
70 #include "config.h"
72 #include <string.h>
73 #include <stdarg.h>
74 #include <stdio.h>
75 #include <stdlib.h>
76 #include <unistd.h>
77 #include <fcntl.h>
78 #include <dlfcn.h>
79 #include <limits.h>
80 #include <time.h>
81 #include <assert.h>
83 #include "ntstatus.h"
84 #define WIN32_NO_STATUS
85 #include "x11drv.h"
87 #ifdef HAVE_X11_EXTENSIONS_XFIXES_H
88 #include <X11/extensions/Xfixes.h>
89 #endif
91 #include "shlobj.h"
92 #include "shellapi.h"
93 #include "shlwapi.h"
94 #include "wine/list.h"
95 #include "wine/debug.h"
97 WINE_DEFAULT_DEBUG_CHANNEL(clipboard);
99 /* Maximum wait time for selection notify */
100 #define SELECTION_RETRIES 500 /* wait for .5 seconds */
101 #define SELECTION_WAIT 1 /* ms */
103 #define SELECTION_UPDATE_DELAY 2000 /* delay between checks of the X11 selection */
105 typedef BOOL (*EXPORTFUNC)( Display *display, Window win, Atom prop, Atom target, void *data, size_t size );
106 typedef void *(*IMPORTFUNC)( Atom type, const void *data, size_t size, size_t *ret_size );
108 struct clipboard_format
110 struct list entry;
111 UINT id;
112 Atom atom;
113 IMPORTFUNC import;
114 EXPORTFUNC export;
117 static void *import_data( Atom type, const void *data, size_t size, size_t *ret_size );
118 static void *import_pixmap( Atom type, const void *data, size_t size, size_t *ret_size );
119 static void *import_image_bmp( Atom type, const void *data, size_t size, size_t *ret_size );
120 static void *import_string( Atom type, const void *data, size_t size, size_t *ret_size );
121 static void *import_utf8_string( Atom type, const void *data, size_t size, size_t *ret_size );
122 static void *import_compound_text( Atom type, const void *data, size_t size, size_t *ret_size );
123 static void *import_text( Atom type, const void *data, size_t size, size_t *ret_size );
124 static void *import_text_html( Atom type, const void *data, size_t size, size_t *ret_size );
125 static void *import_text_uri_list( Atom type, const void *data, size_t size, size_t *ret_size );
126 static void *import_targets( Atom type, const void *data, size_t size, size_t *ret_size );
128 static BOOL export_data( Display *display, Window win, Atom prop, Atom target, void *data, size_t size );
129 static BOOL export_string( Display *display, Window win, Atom prop, Atom target, void *data, size_t size );
130 static BOOL export_utf8_string( Display *display, Window win, Atom prop, Atom target, void *data, size_t size );
131 static BOOL export_text( Display *display, Window win, Atom prop, Atom target, void *data, size_t size );
132 static BOOL export_compound_text( Display *display, Window win, Atom prop, Atom target, void *data, size_t size );
133 static BOOL export_pixmap( Display *display, Window win, Atom prop, Atom target, void *data, size_t size );
134 static BOOL export_image_bmp( Display *display, Window win, Atom prop, Atom target, void *data, size_t size );
135 static BOOL export_text_html( Display *display, Window win, Atom prop, Atom target, void *data, size_t size );
136 static BOOL export_hdrop( Display *display, Window win, Atom prop, Atom target, void *data, size_t size );
137 static BOOL export_targets( Display *display, Window win, Atom prop, Atom target, void *data, size_t size );
138 static BOOL export_multiple( Display *display, Window win, Atom prop, Atom target, void *data, size_t size );
139 static BOOL export_timestamp( Display *display, Window win, Atom prop, Atom target, void *data, size_t size );
141 static BOOL read_property( Display *display, Window w, Atom prop,
142 Atom *type, unsigned char **data, size_t *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};
152 static const struct
154 const WCHAR *name;
155 UINT id;
156 UINT data;
157 IMPORTFUNC import;
158 EXPORTFUNC export;
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_data, export_data },
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 ULONG 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 )
208 WCHAR buffer[256];
210 if (NtUserGetClipboardFormatName( id, buffer, ARRAYSIZE(buffer) ))
211 return wine_dbg_sprintf( "%04x %s", id, debugstr_w(buffer) );
213 switch (id)
215 case 0: return "(none)";
216 #define BUILTIN(id) case id: return #id;
217 BUILTIN(CF_TEXT)
218 BUILTIN(CF_BITMAP)
219 BUILTIN(CF_METAFILEPICT)
220 BUILTIN(CF_SYLK)
221 BUILTIN(CF_DIF)
222 BUILTIN(CF_TIFF)
223 BUILTIN(CF_OEMTEXT)
224 BUILTIN(CF_DIB)
225 BUILTIN(CF_PALETTE)
226 BUILTIN(CF_PENDATA)
227 BUILTIN(CF_RIFF)
228 BUILTIN(CF_WAVE)
229 BUILTIN(CF_UNICODETEXT)
230 BUILTIN(CF_ENHMETAFILE)
231 BUILTIN(CF_HDROP)
232 BUILTIN(CF_LOCALE)
233 BUILTIN(CF_DIBV5)
234 BUILTIN(CF_OWNERDISPLAY)
235 BUILTIN(CF_DSPTEXT)
236 BUILTIN(CF_DSPBITMAP)
237 BUILTIN(CF_DSPMETAFILEPICT)
238 BUILTIN(CF_DSPENHMETAFILE)
239 #undef BUILTIN
240 default: return wine_dbg_sprintf( "%04x", id );
244 static const char *debugstr_xatom( Atom atom )
246 const char *ret;
247 char *name;
249 if (!atom) return "(None)";
250 name = XGetAtomName( thread_display(), atom );
251 ret = debugstr_a( name );
252 XFree( name );
253 return ret;
257 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
259 return (event->error_code == BadAtom);
263 /**************************************************************************
264 * find_win32_format
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;
272 return NULL;
276 /**************************************************************************
277 * find_x11_format
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;
285 return NULL;
289 static ATOM register_clipboard_format( const WCHAR *name )
291 ATOM atom;
292 if (NtAddAtom( name, lstrlenW( name ) * sizeof(WCHAR), &atom )) return 0;
293 return atom;
297 /**************************************************************************
298 * register_builtin_formats
300 static void register_builtin_formats(void)
302 struct clipboard_format *formats;
303 unsigned int i;
305 if (!(formats = malloc( ARRAY_SIZE(builtin_formats) * sizeof(*formats)))) return;
307 for (i = 0; i < ARRAY_SIZE(builtin_formats); i++)
309 if (builtin_formats[i].name)
310 formats[i].id = register_clipboard_format( builtin_formats[i].name );
311 else
312 formats[i].id = builtin_formats[i].id;
314 formats[i].atom = GET_ATOM(builtin_formats[i].data);
315 formats[i].import = builtin_formats[i].import;
316 formats[i].export = builtin_formats[i].export;
317 list_add_tail( &format_list, &formats[i].entry );
322 /**************************************************************************
323 * register_formats
325 static void register_formats( const UINT *ids, const Atom *atoms, unsigned int count )
327 struct clipboard_format *formats;
328 unsigned int i;
330 if (!(formats = malloc( count * sizeof(*formats)))) return;
332 for (i = 0; i < count; i++)
334 formats[i].id = ids[i];
335 formats[i].atom = atoms[i];
336 formats[i].import = import_data;
337 formats[i].export = export_data;
338 list_add_tail( &format_list, &formats[i].entry );
339 TRACE( "registered %s atom %s\n", debugstr_format( ids[i] ), debugstr_xatom( atoms[i] ));
344 /**************************************************************************
345 * register_win32_formats
347 * Register Win32 clipboard formats the first time we encounter them.
349 static void register_win32_formats( const UINT *ids, UINT size )
351 unsigned int count, len;
352 UINT new_ids[256];
353 char *names[256];
354 Atom atoms[256];
355 WCHAR buffer[256];
357 if (list_empty( &format_list)) register_builtin_formats();
359 while (size)
361 for (count = 0; count < 256 && size; ids++, size--)
363 if (find_win32_format( *ids )) continue; /* it already exists */
364 if (!NtUserGetClipboardFormatName( *ids, buffer, ARRAYSIZE(buffer) ))
365 continue; /* not a named format */
366 len = lstrlenW( buffer );
367 if (!(names[count] = malloc( len * 3 + 1 ))) continue;
368 ntdll_wcstoumbs( buffer, len + 1, names[count], len * 3 + 1, FALSE );
369 new_ids[count++] = *ids;
371 if (!count) return;
373 XInternAtoms( thread_display(), names, count, False, atoms );
374 register_formats( new_ids, atoms, count );
375 while (count) free( names[--count] );
380 /**************************************************************************
381 * register_x11_formats
383 * Register X11 atom formats the first time we encounter them.
385 static void register_x11_formats( const Atom *atoms, UINT size )
387 Display *display = thread_display();
388 unsigned int i, pos, count;
389 char *names[256];
390 UINT ids[256];
391 Atom new_atoms[256];
392 WCHAR buffer[256];
394 if (list_empty( &format_list)) register_builtin_formats();
396 while (size)
398 for (count = 0; count < 256 && size; atoms++, size--)
399 if (!find_x11_format( *atoms )) new_atoms[count++] = *atoms;
401 if (!count) return;
403 X11DRV_expect_error( display, is_atom_error, NULL );
404 if (!XGetAtomNames( display, new_atoms, count, names )) count = 0;
405 if (X11DRV_check_error())
407 WARN( "got some bad atoms, ignoring\n" );
408 count = 0;
411 for (i = pos = 0; i < count; i++)
413 if (ntdll_umbstowcs( names[i], strlen( names[i] ) + 1, buffer, ARRAYSIZE(buffer) ) &&
414 (ids[pos] = register_clipboard_format( buffer )))
415 new_atoms[pos++] = new_atoms[i];
416 XFree( names[i] );
418 register_formats( ids, new_atoms, pos );
423 /**************************************************************************
424 * put_property
426 * Put data as a property on the specified window.
428 static void put_property( Display *display, Window win, Atom prop, Atom type, int format,
429 const void *ptr, size_t size )
431 const unsigned char *data = ptr;
432 int mode = PropModeReplace;
433 size_t width = (format == 32) ? sizeof(long) : format / 8;
434 size_t max_size = XExtendedMaxRequestSize( display ) * 4;
436 if (!max_size) max_size = XMaxRequestSize( display ) * 4;
437 max_size -= 64; /* request overhead */
441 size_t count = min( size, max_size / width );
442 XChangeProperty( display, win, prop, type, format, mode, data, count );
443 mode = PropModeAppend;
444 size -= count;
445 data += count * width;
446 } while (size > 0);
450 static void selection_sleep(void)
452 LARGE_INTEGER timeout;
453 timeout.QuadPart = (ULONGLONG)SELECTION_WAIT * -10000;
454 NtDelayExecution( FALSE, &timeout );
457 /**************************************************************************
458 * convert_selection
460 static BOOL convert_selection( Display *display, Window win, Atom selection,
461 struct clipboard_format *format, Atom *type,
462 unsigned char **data, size_t *size )
464 int i;
465 XEvent event;
467 TRACE( "import %s from %s win %lx to format %s\n",
468 debugstr_xatom( format->atom ), debugstr_xatom( selection ),
469 win, debugstr_format( format->id ) );
471 XConvertSelection( display, selection, format->atom, x11drv_atom(SELECTION_DATA), win, CurrentTime );
473 for (i = 0; i < SELECTION_RETRIES; i++)
475 Bool res = XCheckTypedWindowEvent( display, win, SelectionNotify, &event );
476 if (res && event.xselection.selection == selection && event.xselection.target == format->atom)
477 return read_property( display, win, event.xselection.property, type, data, size );
478 selection_sleep();
480 ERR( "Timed out waiting for SelectionNotify event\n" );
481 return FALSE;
485 /***********************************************************************
486 * bitmap_info_size
488 * Return the size of the bitmap info structure including color table.
490 static int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
492 unsigned int colors, size, masks = 0;
494 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
496 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
497 colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
498 return sizeof(BITMAPCOREHEADER) + colors *
499 ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
501 else /* assume BITMAPINFOHEADER */
503 colors = info->bmiHeader.biClrUsed;
504 if (!colors && (info->bmiHeader.biBitCount <= 8))
505 colors = 1 << info->bmiHeader.biBitCount;
506 if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
507 size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
508 return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
513 /***********************************************************************
514 * create_dib_from_bitmap
516 * Allocates a packed DIB and copies the bitmap data into it.
518 static void *create_dib_from_bitmap( HBITMAP hBmp, size_t *size )
520 BITMAP bmp;
521 HDC hdc;
522 LPBITMAPINFOHEADER pbmiHeader;
523 unsigned int cDataSize, OffsetBits;
524 int nLinesCopied;
525 char *ret;
527 if (!NtGdiExtGetObjectW( hBmp, sizeof(bmp), &bmp )) return 0;
530 * A packed DIB contains a BITMAPINFO structure followed immediately by
531 * an optional color palette and the pixel data.
534 /* Calculate the size of the packed DIB */
535 cDataSize = abs( bmp.bmHeight ) * (((bmp.bmWidth * bmp.bmBitsPixel + 31) / 8) & ~3);
536 *size = sizeof(BITMAPINFOHEADER)
537 + ( (bmp.bmBitsPixel <= 8) ? (sizeof(RGBQUAD) * (1 << bmp.bmBitsPixel)) : 0 )
538 + cDataSize;
539 /* Get the offset to the bits */
540 OffsetBits = *size - cDataSize;
542 /* Allocate the packed DIB */
543 TRACE( "\tAllocating packed DIB\n" );
544 if (!(ret = malloc( *size )))
546 WARN( "Could not allocate packed DIB!\n" );
547 return 0;
550 /* A packed DIB starts with a BITMAPINFOHEADER */
551 pbmiHeader = (LPBITMAPINFOHEADER)ret;
553 /* Init the BITMAPINFOHEADER */
554 pbmiHeader->biSize = sizeof(BITMAPINFOHEADER);
555 pbmiHeader->biWidth = bmp.bmWidth;
556 pbmiHeader->biHeight = bmp.bmHeight;
557 pbmiHeader->biPlanes = 1;
558 pbmiHeader->biBitCount = bmp.bmBitsPixel;
559 pbmiHeader->biCompression = BI_RGB;
560 pbmiHeader->biSizeImage = 0;
561 pbmiHeader->biXPelsPerMeter = pbmiHeader->biYPelsPerMeter = 0;
562 pbmiHeader->biClrUsed = 0;
563 pbmiHeader->biClrImportant = 0;
565 /* Retrieve the DIB bits from the bitmap and fill in the
566 * DIB color table if present */
567 hdc = NtUserGetDC( 0 );
568 nLinesCopied = NtGdiGetDIBitsInternal( hdc, hBmp, 0, bmp.bmHeight, ret + OffsetBits,
569 (LPBITMAPINFO) pbmiHeader, 0, 0, 0 );
570 NtUserReleaseDC( 0, hdc );
572 /* Cleanup if GetDIBits failed */
573 if (nLinesCopied != bmp.bmHeight)
575 TRACE("\tGetDIBits returned %d. Actual lines=%d\n", nLinesCopied, bmp.bmHeight);
576 free( ret );
577 ret = NULL;
579 return ret;
583 /* based on wine_get_dos_file_name */
584 static WCHAR *get_dos_file_name( const char *path )
586 ULONG len = strlen( path ) + 9; /* \??\unix prefix */
587 WCHAR *ret;
589 if (!(ret = malloc( len * sizeof(WCHAR) ))) return NULL;
590 if (wine_unix_to_nt_file_name( path, ret, &len ))
592 free( ret );
593 return NULL;
596 if (ret[5] == ':')
598 /* get rid of the \??\ prefix */
599 memmove( ret, ret + 4, (len - 4) * sizeof(WCHAR) );
601 else ret[1] = '\\';
602 return ret;
606 /***********************************************************************
607 * get_nt_pathname
609 * Simplified version of RtlDosPathNameToNtPathName_U.
611 static BOOL get_nt_pathname( const WCHAR *name, UNICODE_STRING *nt_name )
613 static const WCHAR ntprefixW[] = {'\\','?','?','\\'};
614 static const WCHAR uncprefixW[] = {'U','N','C','\\'};
615 size_t len = lstrlenW( name );
616 WCHAR *ptr;
618 nt_name->MaximumLength = (len + 8) * sizeof(WCHAR);
619 if (!(ptr = malloc( nt_name->MaximumLength ))) return FALSE;
620 nt_name->Buffer = ptr;
622 memcpy( ptr, ntprefixW, sizeof(ntprefixW) );
623 ptr += ARRAYSIZE(ntprefixW);
624 if (name[0] == '\\' && name[1] == '\\')
626 if ((name[2] == '.' || name[2] == '?') && name[3] == '\\')
628 name += 4;
629 len -= 4;
631 else
633 memcpy( ptr, uncprefixW, sizeof(uncprefixW) );
634 ptr += ARRAYSIZE(uncprefixW);
635 name += 2;
636 len -= 2;
639 memcpy( ptr, name, (len + 1) * sizeof(WCHAR) );
640 ptr += len;
641 nt_name->Length = (ptr - nt_name->Buffer) * sizeof(WCHAR);
642 return TRUE;
646 /* based on wine_get_unix_file_name */
647 static char *get_unix_file_name( const WCHAR *dosW )
649 UNICODE_STRING nt_name;
650 OBJECT_ATTRIBUTES attr;
651 NTSTATUS status;
652 ULONG size = 256;
653 char *buffer;
655 if (!get_nt_pathname( dosW, &nt_name )) return NULL;
656 InitializeObjectAttributes( &attr, &nt_name, 0, 0, NULL );
657 for (;;)
659 if (!(buffer = malloc( size )))
661 free( nt_name.Buffer );
662 return NULL;
664 status = wine_nt_to_unix_file_name( &attr, buffer, &size, FILE_OPEN_IF );
665 if (status != STATUS_BUFFER_TOO_SMALL) break;
666 free( buffer );
668 free( nt_name.Buffer );
669 if (status)
671 free( buffer );
672 return NULL;
674 return buffer;
678 static CPTABLEINFO *get_xstring_cp(void)
680 static CPTABLEINFO cp;
681 if (!cp.CodePage)
683 USHORT *ptr;
684 SIZE_T nls_size;
685 if (NtGetNlsSectionPtr( 11, 28591, NULL, (void **)&ptr, &nls_size )) return NULL;
686 RtlInitCodePageTable( ptr, &cp );
688 return &cp;
692 static CPTABLEINFO *get_ansi_cp(void)
694 USHORT utf8_hdr[2] = { 0, CP_UTF8 };
695 static CPTABLEINFO cp;
696 if (!cp.CodePage)
698 if (NtCurrentTeb()->Peb->AnsiCodePageData)
699 RtlInitCodePageTable( NtCurrentTeb()->Peb->AnsiCodePageData, &cp );
700 else
701 RtlInitCodePageTable( utf8_hdr, &cp );
703 return &cp;
707 /***********************************************************************
708 * uri_to_dos
710 * Converts a text/uri-list URI to DOS filename.
712 static WCHAR* uri_to_dos(char *encodedURI)
714 WCHAR *ret = NULL;
715 int i;
716 int j = 0;
717 char *uri = calloc( 1, strlen(encodedURI) + 1 );
718 if (uri == NULL)
719 return NULL;
720 for (i = 0; encodedURI[i]; ++i)
722 if (encodedURI[i] == '%')
724 if (encodedURI[i+1] && encodedURI[i+2])
726 char buffer[3];
727 int number;
728 buffer[0] = encodedURI[i+1];
729 buffer[1] = encodedURI[i+2];
730 buffer[2] = '\0';
731 sscanf(buffer, "%x", &number);
732 uri[j++] = number;
733 i += 2;
735 else
737 WARN("invalid URI encoding in %s\n", debugstr_a(encodedURI));
738 free( uri );
739 return NULL;
742 else
743 uri[j++] = encodedURI[i];
746 /* Read http://www.freedesktop.org/wiki/Draganddropwarts and cry... */
747 if (strncmp(uri, "file:/", 6) == 0)
749 if (uri[6] == '/')
751 if (uri[7] == '/')
753 /* file:///path/to/file (nautilus, thunar) */
754 ret = get_dos_file_name( &uri[7] );
756 else if (uri[7])
758 /* file://hostname/path/to/file (X file drag spec) */
759 char hostname[256];
760 char *path = strchr(&uri[7], '/');
761 if (path)
763 *path = '\0';
764 if (strcmp(&uri[7], "localhost") == 0)
766 *path = '/';
767 ret = get_dos_file_name( path );
769 else if (gethostname(hostname, sizeof(hostname)) == 0)
771 if (strcmp(hostname, &uri[7]) == 0)
773 *path = '/';
774 ret = get_dos_file_name( path );
780 else if (uri[6])
782 /* file:/path/to/file (konqueror) */
783 ret = get_dos_file_name( &uri[5] );
786 free( uri );
787 return ret;
791 /**************************************************************************
792 * unicode_text_from_string
794 * Convert a string in the specified encoding to CF_UNICODETEXT format.
796 static void *unicode_text_from_string( WCHAR *ret, const WCHAR *string, DWORD count, size_t *size )
798 DWORD i, j;
800 for (i = j = 0; i < count; i++)
802 if (string[i] == '\n' && (!i || string[i - 1] != '\r')) ret[j++] = '\r';
803 ret[j++] = string[i];
805 ret[j++] = 0;
806 *size = j * sizeof(WCHAR);
807 TRACE( "returning %s\n", debugstr_wn( ret, j - 1 ));
808 return ret;
812 /**************************************************************************
813 * import_string
815 * Import XA_STRING, converting the string to CF_UNICODETEXT.
817 static void *import_string( Atom type, const void *data, size_t size, size_t *ret_size )
819 DWORD str_size;
820 WCHAR *ret;
822 if (!(ret = malloc( (size * 2 + 1) * sizeof(WCHAR) ))) return NULL;
823 RtlCustomCPToUnicodeN( get_xstring_cp(), ret + size, size * sizeof(WCHAR), &str_size, data, size );
824 return unicode_text_from_string( ret, ret + size, str_size / sizeof(WCHAR), ret_size );
828 /**************************************************************************
829 * import_utf8_string
831 * Import XA_UTF8_STRING, converting the string to CF_UNICODETEXT.
833 static void *import_utf8_string( Atom type, const void *data, size_t size, size_t *ret_size )
835 DWORD str_size;
836 WCHAR *ret;
838 RtlUTF8ToUnicodeN( NULL, 0, &str_size, data, size );
839 if (!(ret = malloc( str_size * 2 + sizeof(WCHAR) ))) return NULL;
840 RtlUTF8ToUnicodeN( ret + str_size / sizeof(WCHAR), str_size, &str_size, data, size );
841 return unicode_text_from_string( ret, ret + str_size / sizeof(WCHAR),
842 str_size / sizeof(WCHAR), ret_size );
846 /**************************************************************************
847 * import_compound_text
849 * Import COMPOUND_TEXT to CF_UNICODETEXT.
851 static void *import_compound_text( Atom type, const void *data, size_t size, size_t *ret_size )
853 char** srcstr;
854 int count;
855 XTextProperty txtprop;
856 DWORD len;
857 WCHAR *ret;
859 txtprop.value = (BYTE *)data;
860 txtprop.nitems = size;
861 txtprop.encoding = x11drv_atom(COMPOUND_TEXT);
862 txtprop.format = 8;
863 if (XmbTextPropertyToTextList( thread_display(), &txtprop, &srcstr, &count ) != Success) return 0;
864 if (!count) return 0;
866 len = strlen(srcstr[0]) + 1;
867 if (!(ret = malloc( (len * 2 + 1) * sizeof(WCHAR) ))) return NULL;
869 count = ntdll_umbstowcs( srcstr[0], len, ret + len, len );
870 ret = unicode_text_from_string( ret, ret + len, count, ret_size );
872 XFreeStringList(srcstr);
873 return ret;
877 /**************************************************************************
878 * import_text
880 * Import XA_TEXT, converting the string to CF_UNICODETEXT.
882 static void *import_text( Atom type, const void *data, size_t size, size_t *ret_size )
884 if (type == XA_STRING) return import_string( type, data, size, ret_size );
885 if (type == x11drv_atom(UTF8_STRING)) return import_utf8_string( type, data, size, ret_size );
886 if (type == x11drv_atom(COMPOUND_TEXT)) return import_compound_text( type, data, size, ret_size );
887 FIXME( "unsupported TEXT type %s\n", debugstr_xatom( type ));
888 return 0;
892 /**************************************************************************
893 * import_pixmap
895 * Import XA_PIXMAP, converting the image to CF_DIB.
897 static void *import_pixmap( Atom type, const void *data, size_t size, size_t *ret_size )
899 const Pixmap *pPixmap = (const Pixmap *)data;
900 BYTE *ptr = NULL;
901 XVisualInfo vis = default_visual;
902 char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
903 BITMAPINFO *info = (BITMAPINFO *)buffer;
904 struct gdi_image_bits bits;
905 Window root;
906 int x,y; /* Unused */
907 unsigned border_width; /* Unused */
908 unsigned int depth, width, height;
910 /* Get the Pixmap dimensions and bit depth */
911 if (!XGetGeometry(gdi_display, *pPixmap, &root, &x, &y, &width, &height,
912 &border_width, &depth)) depth = 0;
913 if (!pixmap_formats[depth]) return 0;
915 TRACE( "pixmap properties: width=%d, height=%d, depth=%d\n", width, height, depth );
917 if (depth != vis.depth) switch (pixmap_formats[depth]->bits_per_pixel)
919 case 1:
920 case 4:
921 case 8:
922 break;
923 case 16: /* assume R5G5B5 */
924 vis.red_mask = 0x7c00;
925 vis.green_mask = 0x03e0;
926 vis.blue_mask = 0x001f;
927 break;
928 case 24: /* assume R8G8B8 */
929 case 32: /* assume A8R8G8B8 */
930 vis.red_mask = 0xff0000;
931 vis.green_mask = 0x00ff00;
932 vis.blue_mask = 0x0000ff;
933 break;
934 default:
935 return 0;
938 if (!get_pixmap_image( *pPixmap, width, height, &vis, info, &bits ))
940 DWORD info_size = bitmap_info_size( info, DIB_RGB_COLORS );
942 ptr = malloc( info_size + info->bmiHeader.biSizeImage );
943 if (ptr)
945 memcpy( ptr, info, info_size );
946 memcpy( ptr + info_size, bits.ptr, info->bmiHeader.biSizeImage );
947 *ret_size = info_size + info->bmiHeader.biSizeImage;
949 if (bits.free) bits.free( &bits );
951 return ptr;
955 /**************************************************************************
956 * import_image_bmp
958 * Import image/bmp, converting the image to CF_DIB.
960 static void *import_image_bmp( Atom type, const void *data, size_t size, size_t *ret_size )
962 const BITMAPFILEHEADER *bfh = data;
963 void *ret = NULL;
965 if (size >= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPCOREHEADER) &&
966 bfh->bfType == 0x4d42 /* "BM" */)
968 const BITMAPINFO *bmi = (const BITMAPINFO *)(bfh + 1);
969 int width, height;
970 HBITMAP hbmp;
971 HDC hdc;
973 if (bmi->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
975 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)bmi;
976 width = core->bcWidth;
977 height = core->bcHeight;
979 else if (bmi->bmiHeader.biSize >= sizeof(BITMAPINFOHEADER))
981 const BITMAPINFOHEADER *header = &bmi->bmiHeader;
982 if (header->biCompression == BI_JPEG || header->biCompression == BI_PNG) return 0;
983 width = header->biWidth;
984 height = header->biHeight;
986 else return NULL;
987 if (!width || !height) return NULL;
989 hdc = NtUserGetDC( 0 );
991 if ((hbmp = NtGdiCreateDIBitmapInternal( hdc, width, height, CBM_INIT,
992 (const BYTE *)data + bfh->bfOffBits, bmi,
993 DIB_RGB_COLORS, 0, 0, 0, 0 )))
995 ret = create_dib_from_bitmap( hbmp, ret_size );
996 NtGdiDeleteObjectApp( hbmp );
998 NtUserReleaseDC(0, hdc);
1000 return ret;
1004 /**************************************************************************
1005 * import_text_html
1007 static void *import_text_html( Atom type, const void *data, size_t size, size_t *ret_size )
1009 static const char header[] =
1010 "Version:0.9\n"
1011 "StartHTML:0000000100\n"
1012 "EndHTML:%010lu\n"
1013 "StartFragment:%010lu\n"
1014 "EndFragment:%010lu\n"
1015 "<!--StartFragment-->";
1016 static const char trailer[] = "\n<!--EndFragment-->";
1017 char *text = NULL;
1018 HANDLE ret;
1019 SIZE_T len, total;
1021 /* Firefox uses UTF-16LE with byte order mark. Convert to UTF-8 without the BOM. */
1022 if (size >= sizeof(WCHAR) && ((const WCHAR *)data)[0] == 0xfeff)
1024 DWORD str_len;
1025 RtlUnicodeToUTF8N( NULL, 0, &str_len, (const WCHAR *)data + 1, size - sizeof(WCHAR) );
1026 if (!(text = malloc( str_len ))) return NULL;
1027 RtlUnicodeToUTF8N( text, str_len, &str_len, (const WCHAR *)data + 1, size - sizeof(WCHAR) );
1028 size = str_len;
1029 data = text;
1032 len = strlen( header ) + 12; /* 3 * 4 extra chars for %010lu */
1033 total = len + size + sizeof(trailer);
1034 if ((ret = malloc( total )))
1036 char *p = ret;
1037 p += sprintf( p, header, total - 1, len, len + size + 1 /* include the final \n in the data */ );
1038 memcpy( p, data, size );
1039 strcpy( p + size, trailer );
1040 *ret_size = total;
1041 TRACE( "returning %s\n", debugstr_a( ret ));
1043 free( text );
1044 return ret;
1048 /**************************************************************************
1049 * file_list_to_drop_files
1051 void *file_list_to_drop_files( const void *data, size_t size, size_t *ret_size )
1053 size_t buf_size = 4096, path_size;
1054 DROPFILES *drop = NULL;
1055 const char *ptr;
1056 WCHAR *path;
1058 for (ptr = data; ptr < (const char *)data + size; ptr += strlen( ptr ) + 1)
1060 path = get_dos_file_name( ptr );
1062 TRACE( "converted URI %s to DOS path %s\n", debugstr_a(ptr), debugstr_w(path) );
1064 if (!path) continue;
1066 if (!drop)
1068 if (!(drop = malloc( buf_size ))) return NULL;
1069 drop->pFiles = sizeof(*drop);
1070 drop->pt.x = drop->pt.y = 0;
1071 drop->fNC = FALSE;
1072 drop->fWide = TRUE;
1073 *ret_size = sizeof(*drop);
1076 path_size = (lstrlenW( path ) + 1) * sizeof(WCHAR);
1077 if (*ret_size + path_size > buf_size - sizeof(WCHAR))
1079 void *new_buf;
1080 if (!(new_buf = realloc( drop, buf_size * 2 + path_size )))
1082 free( path );
1083 continue;
1085 buf_size = buf_size * 2 + path_size;
1086 drop = new_buf;
1089 memcpy( (char *)drop + *ret_size, path, path_size );
1090 *ret_size += path_size;
1093 if (!drop) return NULL;
1094 *(WCHAR *)((char *)drop + *ret_size) = 0;
1095 *ret_size += sizeof(WCHAR);
1096 return drop;
1100 /**************************************************************************
1101 * uri_list_to_drop_files
1103 void *uri_list_to_drop_files( const void *data, size_t size, size_t *ret_size )
1105 const char *uriList = data;
1106 char *uri;
1107 WCHAR *path;
1108 WCHAR *out = NULL;
1109 int total = 0;
1110 int capacity = 4096;
1111 int start = 0;
1112 int end = 0;
1113 DROPFILES *dropFiles = NULL;
1115 if (!(out = malloc( capacity * sizeof(WCHAR) ))) return 0;
1117 while (end < size)
1119 while (end < size && uriList[end] != '\r')
1120 ++end;
1121 if (end < (size - 1) && uriList[end+1] != '\n')
1123 WARN("URI list line doesn't end in \\r\\n\n");
1124 break;
1127 uri = malloc( end - start + 1 );
1128 if (uri == NULL)
1129 break;
1130 lstrcpynA(uri, &uriList[start], end - start + 1);
1131 path = uri_to_dos(uri);
1132 TRACE("converted URI %s to DOS path %s\n", debugstr_a(uri), debugstr_w(path));
1133 free( uri );
1135 if (path)
1137 int pathSize = wcslen( path ) + 1;
1138 if (pathSize > capacity - total)
1140 WCHAR *new_out;
1141 capacity = 2*capacity + pathSize;
1142 new_out = realloc( out, (capacity + 1) * sizeof(WCHAR) );
1143 if (!new_out)
1144 goto done;
1145 out = new_out;
1147 memcpy(&out[total], path, pathSize * sizeof(WCHAR));
1148 total += pathSize;
1149 done:
1150 free( path );
1151 if (out == NULL)
1152 break;
1155 start = end + 2;
1156 end = start;
1158 if (out && end >= size)
1160 *ret_size = sizeof(DROPFILES) + (total + 1) * sizeof(WCHAR);
1161 if ((dropFiles = malloc( *ret_size )))
1163 dropFiles->pFiles = sizeof(DROPFILES);
1164 dropFiles->pt.x = 0;
1165 dropFiles->pt.y = 0;
1166 dropFiles->fNC = 0;
1167 dropFiles->fWide = TRUE;
1168 out[total] = '\0';
1169 memcpy( (char*)dropFiles + dropFiles->pFiles, out, (total + 1) * sizeof(WCHAR) );
1172 free( out );
1173 return dropFiles;
1177 /**************************************************************************
1178 * import_text_uri_list
1180 * Import text/uri-list.
1182 static void *import_text_uri_list( Atom type, const void *data, size_t size, size_t *ret_size )
1184 return uri_list_to_drop_files( data, size, ret_size );
1188 /**************************************************************************
1189 * import_targets
1191 * Import TARGETS and mark the corresponding clipboard formats as available.
1193 static void *import_targets( Atom type, const void *data, size_t size, size_t *ret_size )
1195 UINT i, pos, count = size / sizeof(Atom);
1196 const Atom *properties = data;
1197 struct clipboard_format *format, **formats;
1199 if (type != XA_ATOM && type != x11drv_atom(TARGETS)) return 0;
1201 register_x11_formats( properties, count );
1203 /* the builtin formats contain duplicates, so allocate some extra space */
1204 if (!(formats = malloc( (count + ARRAY_SIZE(builtin_formats)) * sizeof(*formats ))))
1205 return 0;
1207 pos = 0;
1208 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
1210 for (i = 0; i < count; i++) if (properties[i] == format->atom) break;
1211 if (i == count) continue;
1212 if (format->import && format->id)
1214 struct set_clipboard_params params = { .data = NULL };
1216 TRACE( "property %s -> format %s\n",
1217 debugstr_xatom( properties[i] ), debugstr_format( format->id ));
1219 NtUserSetClipboardData( format->id, 0, &params );
1220 formats[pos++] = format;
1222 else TRACE( "property %s (ignoring)\n", debugstr_xatom( properties[i] ));
1225 free( current_x11_formats );
1226 current_x11_formats = formats;
1227 nb_current_x11_formats = pos;
1228 *ret_size = 0;
1229 return (void *)1;
1233 /**************************************************************************
1234 * import_data
1236 * Generic import clipboard data routine.
1238 static void *import_data( Atom type, const void *data, size_t size, size_t *ret_size )
1240 void *ret = malloc( size );
1241 if (ret)
1243 memcpy( ret, data, size );
1244 *ret_size = size;
1246 return ret;
1250 /**************************************************************************
1251 * import_selection
1253 * Import the specified format from the selection and return a global handle to the data.
1255 static void *import_selection( Display *display, Window win, Atom selection,
1256 struct clipboard_format *format, size_t *ret_size )
1258 unsigned char *data;
1259 size_t size;
1260 Atom type;
1261 HANDLE ret;
1263 if (!format->import) return 0;
1265 if (!convert_selection( display, win, selection, format, &type, &data, &size ))
1267 TRACE( "failed to convert selection\n" );
1268 return 0;
1270 ret = format->import( type, data, size, ret_size );
1271 free( data );
1272 return ret;
1276 /**************************************************************************
1277 * import_xdnd_selection
1279 * Import the X selection into the clipboard format registered for the given X target.
1281 struct format_entry *import_xdnd_selection( Display *display, Window win, Atom selection,
1282 Atom *targets, UINT count, size_t *ret_size )
1284 size_t size, buf_size = 0, entry_size;
1285 UINT i;
1286 void *data;
1287 struct clipboard_format *format;
1288 struct format_entry *ret = NULL, *tmp, *entry;
1289 BOOL have_hdrop = FALSE;
1291 register_x11_formats( targets, count );
1292 *ret_size = 0;
1294 for (i = 0; i < count; i++)
1296 if (!(format = find_x11_format( targets[i] ))) continue;
1297 if (format->id != CF_HDROP) continue;
1298 have_hdrop = TRUE;
1299 break;
1302 for (i = 0; i < count; i++)
1304 if (!(format = find_x11_format( targets[i] ))) continue;
1305 if (!format->id) continue;
1306 if (have_hdrop && format->id != CF_HDROP && format->id < CF_MAX) continue;
1308 if (!(data = import_selection( display, win, selection, format, &size ))) continue;
1310 entry_size = (FIELD_OFFSET( struct format_entry, data[size] ) + 7) & ~7;
1311 if (buf_size < size + entry_size)
1313 if (!(tmp = realloc( ret, *ret_size + entry_size + 1024 ))) continue;
1314 ret = tmp;
1315 buf_size = *ret_size + entry_size + 1024; /* extra space for following entries */
1317 entry = (struct format_entry *)((char *)ret + *ret_size);
1318 entry->format = format->id;
1319 entry->size = size;
1320 if (size) memcpy( entry->data, data, size );
1321 *ret_size += entry_size;
1322 free( data );
1325 return ret;
1329 /**************************************************************************
1330 * render_format
1332 static BOOL render_format( UINT id )
1334 Display *display = thread_display();
1335 unsigned int i;
1337 if (!current_selection) return 0;
1339 for (i = 0; i < nb_current_x11_formats; i++)
1341 struct set_clipboard_params params = { 0 };
1342 if (current_x11_formats[i]->id != id) continue;
1343 if (!(params.data = import_selection( display, import_window, current_selection,
1344 current_x11_formats[i], &params.size ))) continue;
1345 NtUserSetClipboardData( id, 0, &params );
1346 if (params.size) free( params.data );
1347 return TRUE;
1349 return FALSE;
1353 /**************************************************************************
1354 * export_data
1356 * Generic export clipboard data routine.
1358 static BOOL export_data( Display *display, Window win, Atom prop, Atom target, void *data, size_t size )
1360 put_property( display, win, prop, target, 8, data, size );
1361 return TRUE;
1365 /**************************************************************************
1366 * string_from_unicode_text
1368 * Convert CF_UNICODETEXT data to a string in the specified codepage.
1370 static void string_from_unicode_text( char *str, size_t len, DWORD *size )
1372 DWORD i, j;
1374 /* remove carriage returns */
1375 for (i = j = 0; i < len; i++)
1377 if (str[i] == '\r' && (i == len - 1 || str[i + 1] == '\n')) continue;
1378 str[j++] = str[i];
1380 while (j && !str[j - 1]) j--; /* remove trailing nulls */
1381 TRACE( "returning %s\n", debugstr_an( str, j ));
1382 *size = j;
1386 /**************************************************************************
1387 * export_string
1389 * Export CF_UNICODETEXT converting the string to XA_STRING.
1391 static BOOL export_string( Display *display, Window win, Atom prop, Atom target, void *data, size_t size )
1393 DWORD len;
1394 char *text;
1396 if (!(text = malloc( size ))) return FALSE;
1397 RtlUnicodeToCustomCPN( get_xstring_cp(), text, size, &len, data, size );
1398 string_from_unicode_text( text, len, &len );
1400 put_property( display, win, prop, target, 8, text, len );
1401 free( text );
1402 return TRUE;
1406 /**************************************************************************
1407 * export_utf8_string
1409 * Export CF_UNICODE converting the string to UTF8.
1411 static BOOL export_utf8_string( Display *display, Window win, Atom prop, Atom target,
1412 void *data, size_t size )
1414 DWORD len;
1415 char *text;
1417 if (!(text = malloc( size / sizeof(WCHAR) * 3 ))) return FALSE;
1418 RtlUnicodeToUTF8N( text, size / sizeof(WCHAR) * 3, &len, data, size );
1419 string_from_unicode_text( text, len, &len );
1421 put_property( display, win, prop, target, 8, text, len );
1422 free( text );
1423 return TRUE;
1427 /**************************************************************************
1428 * export_text
1430 * Export CF_UNICODE to the polymorphic TEXT type, using UTF8.
1432 static BOOL export_text( Display *display, Window win, Atom prop, Atom target, void *data, size_t size )
1434 return export_utf8_string( display, win, prop, x11drv_atom(UTF8_STRING), data, size );
1438 /**************************************************************************
1439 * export_compound_text
1441 * Export CF_UNICODE to COMPOUND_TEXT
1443 static BOOL export_compound_text( Display *display, Window win, Atom prop, Atom target,
1444 void *data, size_t size )
1446 XTextProperty textprop;
1447 XICCEncodingStyle style;
1448 DWORD len;
1449 char *text;
1452 if (!(text = malloc( size / sizeof(WCHAR) * 3 ))) return FALSE;
1453 len = ntdll_wcstoumbs( data, size / sizeof(WCHAR), text, size / sizeof(WCHAR) * 3, FALSE );
1454 string_from_unicode_text( text, len, &len );
1456 if (target == x11drv_atom(COMPOUND_TEXT))
1457 style = XCompoundTextStyle;
1458 else
1459 style = XStdICCTextStyle;
1461 /* Update the X property */
1462 if (XmbTextListToTextProperty( display, &text, 1, style, &textprop ) == Success)
1464 XSetTextProperty( display, win, &textprop, prop );
1465 XFree( textprop.value );
1468 free( text );
1469 return TRUE;
1473 /**************************************************************************
1474 * export_pixmap
1476 * Export CF_DIB to XA_PIXMAP.
1478 static BOOL export_pixmap( Display *display, Window win, Atom prop, Atom target, void *data, size_t size )
1480 Pixmap pixmap;
1481 BITMAPINFO *pbmi = data;
1482 struct gdi_image_bits bits;
1484 bits.ptr = (LPBYTE)pbmi + bitmap_info_size( pbmi, DIB_RGB_COLORS );
1485 bits.free = NULL;
1486 bits.is_copy = FALSE;
1487 pixmap = create_pixmap_from_image( 0, &default_visual, pbmi, &bits, DIB_RGB_COLORS );
1489 put_property( display, win, prop, target, 32, &pixmap, 1 );
1490 /* FIXME: free the pixmap when the property is deleted */
1491 return TRUE;
1495 /**************************************************************************
1496 * export_image_bmp
1498 * Export CF_DIB to image/bmp.
1500 static BOOL export_image_bmp( Display *display, Window win, Atom prop, Atom target, void *data, size_t size )
1502 LPBYTE dibdata = data;
1503 UINT bmpsize;
1504 BITMAPFILEHEADER *bfh;
1506 bmpsize = sizeof(BITMAPFILEHEADER) + size;
1507 bfh = malloc( bmpsize );
1508 if (bfh)
1510 /* bitmap file header */
1511 bfh->bfType = 0x4d42; /* "BM" */
1512 bfh->bfSize = bmpsize;
1513 bfh->bfReserved1 = 0;
1514 bfh->bfReserved2 = 0;
1515 bfh->bfOffBits = sizeof(BITMAPFILEHEADER) + bitmap_info_size((BITMAPINFO*)dibdata, DIB_RGB_COLORS);
1517 /* rest of bitmap is the same as the packed dib */
1518 memcpy(bfh+1, dibdata, bmpsize-sizeof(BITMAPFILEHEADER));
1520 put_property( display, win, prop, target, 8, bfh, bmpsize );
1521 free( bfh );
1522 return TRUE;
1526 /**************************************************************************
1527 * export_text_html
1529 * Export HTML Format to text/html.
1531 * FIXME: We should attempt to add an <a base> tag and convert windows paths.
1533 static BOOL export_text_html( Display *display, Window win, Atom prop, Atom target, void *data, size_t size )
1535 const char *p;
1536 UINT start = 0, end = 0;
1537 BOOL ret = TRUE;
1539 p = data;
1540 while (*p && *p != '<')
1542 if (!strncmp( p, "StartFragment:", 14 )) start = atoi( p + 14 );
1543 else if (!strncmp( p, "EndFragment:", 12 )) end = atoi( p + 12 );
1544 if (!(p = strpbrk( p, "\r\n" ))) break;
1545 while (*p == '\r' || *p == '\n') p++;
1547 if (start && start < end && end <= size)
1548 put_property( display, win, prop, target, 8, (char *)data + start, end - start );
1549 else
1550 ret = FALSE;
1552 return ret;
1556 /**************************************************************************
1557 * export_hdrop
1559 * Export CF_HDROP format to text/uri-list.
1561 static BOOL export_hdrop( Display *display, Window win, Atom prop, Atom target, void *data, size_t size )
1563 char *textUriList = NULL;
1564 UINT textUriListSize = 32;
1565 UINT next = 0;
1566 const WCHAR *ptr;
1567 WCHAR *unicode_data = NULL;
1568 DROPFILES *drop_files = data;
1570 if (!drop_files->fWide)
1572 char *files = (char *)data + drop_files->pFiles;
1573 CPTABLEINFO *cp = get_ansi_cp();
1574 DWORD len = 0;
1576 while (files[len]) len += strlen( files + len ) + 1;
1577 len++;
1579 if (!(ptr = unicode_data = malloc( len * sizeof(WCHAR) ))) goto failed;
1581 if (cp->CodePage == CP_UTF8)
1582 RtlUTF8ToUnicodeN( unicode_data, len * sizeof(WCHAR), &len, files, len );
1583 else
1584 RtlCustomCPToUnicodeN( cp, unicode_data, len * sizeof(WCHAR), &len, files, len );
1586 else ptr = (const WCHAR *)((char *)data + drop_files->pFiles);
1588 if (!(textUriList = malloc( textUriListSize ))) goto failed;
1590 while (*ptr)
1592 char *unixFilename = NULL;
1593 UINT uriSize;
1594 UINT u;
1596 unixFilename = get_unix_file_name( ptr );
1597 if (unixFilename == NULL) goto failed;
1598 ptr += lstrlenW( ptr ) + 1;
1600 uriSize = 8 + /* file:/// */
1601 3 * (lstrlenA(unixFilename) - 1) + /* "%xy" per char except first '/' */
1602 2; /* \r\n */
1603 if ((next + uriSize) > textUriListSize)
1605 UINT biggerSize = max( 2 * textUriListSize, next + uriSize );
1606 void *bigger = realloc( textUriList, biggerSize );
1607 if (bigger)
1609 textUriList = bigger;
1610 textUriListSize = biggerSize;
1612 else
1614 free( unixFilename );
1615 goto failed;
1618 lstrcpyA(&textUriList[next], "file:///");
1619 next += 8;
1620 /* URL encode everything - unnecessary, but easier/lighter than linking in shlwapi, and can't hurt */
1621 for (u = 1; unixFilename[u]; u++)
1623 static const char hex_table[] = "0123456789abcdef";
1624 textUriList[next++] = '%';
1625 textUriList[next++] = hex_table[unixFilename[u] >> 4];
1626 textUriList[next++] = hex_table[unixFilename[u] & 0xf];
1628 textUriList[next++] = '\r';
1629 textUriList[next++] = '\n';
1630 free( unixFilename );
1632 put_property( display, win, prop, target, 8, textUriList, next );
1633 free( textUriList );
1634 return TRUE;
1636 failed:
1637 free( unicode_data );
1638 free( textUriList );
1639 return FALSE;
1643 /***********************************************************************
1644 * get_clipboard_formats
1646 * Return a list of all formats currently available on the Win32 clipboard.
1647 * Helper for export_targets.
1649 static UINT *get_clipboard_formats( UINT *size )
1651 UINT *ids;
1653 *size = 256;
1654 for (;;)
1656 if (!(ids = malloc( *size * sizeof(*ids) ))) return NULL;
1657 if (NtUserGetUpdatedClipboardFormats( ids, *size, size )) break;
1658 free( ids );
1659 if (RtlGetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER) return NULL;
1661 register_win32_formats( ids, *size );
1662 return ids;
1666 /***********************************************************************
1667 * is_format_available
1669 * Check if a clipboard format is included in the list.
1670 * Helper for export_targets.
1672 static BOOL is_format_available( UINT format, const UINT *ids, unsigned int count )
1674 while (count--) if (*ids++ == format) return TRUE;
1675 return FALSE;
1679 /***********************************************************************
1680 * export_targets
1682 * Service a TARGETS selection request event
1684 static BOOL export_targets( Display *display, Window win, Atom prop, Atom target, void *data, size_t size )
1686 struct clipboard_format *format;
1687 UINT pos, count, *formats;
1688 Atom *targets;
1690 if (!(formats = get_clipboard_formats( &count ))) return FALSE;
1692 /* the builtin formats contain duplicates, so allocate some extra space */
1693 if (!(targets = malloc( (count + ARRAY_SIZE(builtin_formats)) * sizeof(*targets) )))
1695 free( formats );
1696 return FALSE;
1699 pos = 0;
1700 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
1702 if (!format->export) continue;
1703 /* formats with id==0 are always exported */
1704 if (format->id && !is_format_available( format->id, formats, count )) continue;
1705 TRACE( "%d: %s -> %s\n", pos, debugstr_format( format->id ), debugstr_xatom( format->atom ));
1706 targets[pos++] = format->atom;
1709 put_property( display, win, prop, XA_ATOM, 32, targets, pos );
1710 free( targets );
1711 free( formats );
1712 return TRUE;
1716 /**************************************************************************
1717 * export_selection
1719 * Export selection data, depending on the target type.
1721 static BOOL export_selection( Display *display, Window win, Atom prop, Atom target )
1723 struct get_clipboard_params params = { .data_only = TRUE };
1724 struct clipboard_format *format;
1725 BOOL open = FALSE, ret = FALSE;
1726 size_t buffer_size = 0;
1728 LIST_FOR_EACH_ENTRY( format, &format_list, struct clipboard_format, entry )
1730 if (format->atom != target) continue;
1731 if (!format->export) continue;
1732 if (!format->id)
1734 TRACE( "win %lx prop %s target %s\n", win, debugstr_xatom( prop ), debugstr_xatom( target ));
1735 ret = format->export( display, win, prop, target, NULL, 0 );
1736 break;
1738 if (!open && !(open = NtUserOpenClipboard( clipboard_hwnd, 0 )))
1740 ERR( "failed to open clipboard for %s\n", debugstr_xatom( target ));
1741 return FALSE;
1744 if (!buffer_size)
1746 buffer_size = 1024;
1747 if (!(params.data = malloc( buffer_size ))) break;
1750 for (;;)
1752 params.size = buffer_size;
1753 if (NtUserGetClipboardData( format->id, &params ))
1755 TRACE( "win %lx prop %s target %s exporting %s\n",
1756 win, debugstr_xatom( prop ), debugstr_xatom( target ),
1757 debugstr_format( format->id ) );
1759 ret = format->export( display, win, prop, target, params.data, params.size );
1760 goto done;
1762 if (!params.data_size) break;
1763 free( params.data );
1764 if (!(params.data = malloc( params.data_size ))) goto done;
1765 buffer_size = params.data_size;
1766 params.data_size = 0;
1768 /* keep looking for another Win32 format mapping to the same target */
1770 done:
1771 free( params.data );
1772 if (open) NtUserCloseClipboard();
1773 return ret;
1777 /***********************************************************************
1778 * export_multiple
1780 * Service a MULTIPLE selection request event
1781 * prop contains a list of (target,property) atom pairs.
1782 * The first atom names a target and the second names a property.
1783 * The effect is as if we have received a sequence of SelectionRequest events
1784 * (one for each atom pair) except that:
1785 * 1. We reply with a SelectionNotify only when all the requested conversions
1786 * have been performed.
1787 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
1788 * we replace the atom in the property by None.
1790 static BOOL export_multiple( Display *display, Window win, Atom prop, Atom target, void *data, size_t size )
1792 Atom atype;
1793 int aformat;
1794 Atom *list;
1795 unsigned long i, count, failed, remain;
1797 /* Read the MULTIPLE property contents. This should contain a list of
1798 * (target,property) atom pairs.
1800 if (XGetWindowProperty( display, win, prop, 0, 0x3FFF, False, AnyPropertyType, &atype, &aformat,
1801 &count, &remain, (unsigned char**)&list ))
1802 return FALSE;
1804 TRACE( "type %s format %d count %ld remain %ld\n",
1805 debugstr_xatom( atype ), aformat, count, remain );
1808 * Make sure we got what we expect.
1809 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
1810 * in a MULTIPLE selection request should be of type ATOM_PAIR.
1811 * However some X apps(such as XPaint) are not compliant with this and return
1812 * a user defined atom in atype when XGetWindowProperty is called.
1813 * The data *is* an atom pair but is not denoted as such.
1815 if (aformat == 32 /* atype == xAtomPair */ )
1817 for (i = failed = 0; i < count; i += 2)
1819 if (list[i+1] == None) continue;
1820 if (export_selection( display, win, list[i + 1], list[i] )) continue;
1821 failed++;
1822 list[i + 1] = None;
1824 if (failed) put_property( display, win, prop, atype, 32, list, count );
1826 XFree( list );
1827 return TRUE;
1831 /***********************************************************************
1832 * export_timestamp
1834 * Export the timestamp that was used to acquire the selection
1836 static BOOL export_timestamp( Display *display, Window win, Atom prop, Atom target, void *data, size_t size )
1838 Time time = CurrentTime; /* FIXME */
1839 put_property( display, win, prop, XA_INTEGER, 32, &time, 1 );
1840 return TRUE;
1844 /**************************************************************************
1845 * X11DRV_CLIPBOARD_GetProperty
1846 * Gets type, data and size.
1848 static BOOL X11DRV_CLIPBOARD_GetProperty(Display *display, Window w, Atom prop,
1849 Atom *atype, unsigned char **data, size_t *datasize)
1851 int aformat;
1852 unsigned long pos = 0, nitems, remain, count;
1853 unsigned char *val = NULL, *buffer;
1855 for (;;)
1857 if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
1858 AnyPropertyType, atype, &aformat, &nitems, &remain, &buffer))
1860 WARN("Failed to read property\n");
1861 free( val );
1862 return FALSE;
1865 count = get_property_size( aformat, nitems );
1866 *data = realloc( val, pos * sizeof(int) + count + 1 );
1868 if (!*data)
1870 XFree( buffer );
1871 free( val );
1872 return FALSE;
1874 val = *data;
1875 memcpy( (int *)val + pos, buffer, count );
1876 XFree( buffer );
1877 if (!remain)
1879 *datasize = pos * sizeof(int) + count;
1880 val[*datasize] = 0;
1881 break;
1883 pos += count / sizeof(int);
1886 TRACE( "got property %s type %s format %u len %zu from window %lx\n",
1887 debugstr_xatom( prop ), debugstr_xatom( *atype ), aformat, *datasize, w );
1889 /* Delete the property on the window now that we are done
1890 * This will send a PropertyNotify event to the selection owner. */
1891 XDeleteProperty(display, w, prop);
1892 return TRUE;
1896 struct clipboard_data_packet {
1897 struct list entry;
1898 unsigned long size;
1899 unsigned char *data;
1902 /**************************************************************************
1903 * read_property
1905 * Reads the contents of the X selection property.
1907 static BOOL read_property( Display *display, Window w, Atom prop,
1908 Atom *type, unsigned char **data, size_t *datasize )
1910 XEvent xe;
1912 if (prop == None)
1913 return FALSE;
1915 while (XCheckTypedWindowEvent(display, w, PropertyNotify, &xe))
1918 if (!X11DRV_CLIPBOARD_GetProperty(display, w, prop, type, data, datasize))
1919 return FALSE;
1921 if (*type == x11drv_atom(INCR))
1923 unsigned char *buf;
1924 unsigned long bufsize = 0;
1925 struct list packets;
1926 struct clipboard_data_packet *packet, *packet2;
1927 BOOL res;
1929 free( *data );
1930 *data = NULL;
1932 list_init(&packets);
1934 for (;;)
1936 int i;
1937 unsigned char *prop_data;
1938 size_t prop_size;
1940 /* Wait until PropertyNotify is received */
1941 for (i = 0; i < SELECTION_RETRIES; i++)
1943 Bool res;
1945 res = XCheckTypedWindowEvent(display, w, PropertyNotify, &xe);
1946 if (res && xe.xproperty.atom == prop &&
1947 xe.xproperty.state == PropertyNewValue)
1948 break;
1949 selection_sleep();
1952 if (i >= SELECTION_RETRIES ||
1953 !X11DRV_CLIPBOARD_GetProperty(display, w, prop, type, &prop_data, &prop_size))
1955 res = FALSE;
1956 break;
1959 /* Retrieved entire data. */
1960 if (prop_size == 0)
1962 free( prop_data );
1963 res = TRUE;
1964 break;
1967 packet = malloc( sizeof(*packet) );
1968 if (!packet)
1970 free( prop_data );
1971 res = FALSE;
1972 break;
1975 packet->size = prop_size;
1976 packet->data = prop_data;
1977 list_add_tail(&packets, &packet->entry);
1978 bufsize += prop_size;
1981 if (res)
1983 buf = malloc( bufsize + 1 );
1984 if (buf)
1986 unsigned long bytes_copied = 0;
1987 *datasize = bufsize;
1988 LIST_FOR_EACH_ENTRY( packet, &packets, struct clipboard_data_packet, entry)
1990 memcpy(&buf[bytes_copied], packet->data, packet->size);
1991 bytes_copied += packet->size;
1993 buf[bufsize] = 0;
1994 *data = buf;
1996 else
1997 res = FALSE;
2000 LIST_FOR_EACH_ENTRY_SAFE( packet, packet2, &packets, struct clipboard_data_packet, entry)
2002 free( packet->data );
2003 free( packet );
2006 return res;
2009 return TRUE;
2013 /**************************************************************************
2014 * acquire_selection
2016 * Acquire the X11 selection when the Win32 clipboard has changed.
2018 static void acquire_selection( Display *display )
2020 if (selection_window) XDestroyWindow( display, selection_window );
2022 selection_window = XCreateWindow( display, root_window, 0, 0, 1, 1, 0, CopyFromParent,
2023 InputOutput, CopyFromParent, 0, NULL );
2024 if (!selection_window) return;
2026 XSetSelectionOwner( display, x11drv_atom(CLIPBOARD), selection_window, CurrentTime );
2027 if (use_primary_selection) XSetSelectionOwner( display, XA_PRIMARY, selection_window, CurrentTime );
2028 TRACE( "win %lx\n", selection_window );
2032 /**************************************************************************
2033 * release_selection
2035 * Release the X11 selection when some other X11 app has grabbed it.
2037 static void release_selection( Display *display, Time time )
2039 assert( selection_window );
2041 TRACE( "win %lx\n", selection_window );
2043 /* release PRIMARY if we still own it */
2044 if (use_primary_selection && XGetSelectionOwner( display, XA_PRIMARY ) == selection_window)
2045 XSetSelectionOwner( display, XA_PRIMARY, None, time );
2047 XDestroyWindow( display, selection_window );
2048 selection_window = 0;
2052 /**************************************************************************
2053 * request_selection_contents
2055 * Retrieve the contents of the X11 selection when it's owned by an X11 app.
2057 static BOOL request_selection_contents( Display *display, BOOL changed )
2059 struct clipboard_format *targets = find_x11_format( x11drv_atom(TARGETS) );
2060 struct clipboard_format *string = find_x11_format( XA_STRING );
2061 struct clipboard_format *format = NULL;
2062 Window owner = 0;
2063 unsigned char *data = NULL;
2064 size_t import_size, size = 0;
2065 Atom type = 0;
2067 static Atom last_selection;
2068 static Window last_owner;
2069 static struct clipboard_format *last_format;
2070 static Atom last_type;
2071 static unsigned char *last_data;
2072 static unsigned long last_size;
2074 assert( targets );
2075 assert( string );
2077 current_selection = 0;
2078 if (use_primary_selection)
2080 if ((owner = XGetSelectionOwner( display, XA_PRIMARY )))
2081 current_selection = XA_PRIMARY;
2083 if (!current_selection)
2085 if ((owner = XGetSelectionOwner( display, x11drv_atom(CLIPBOARD) )))
2086 current_selection = x11drv_atom(CLIPBOARD);
2089 if (current_selection)
2091 if (convert_selection( display, import_window, current_selection, targets, &type, &data, &size ))
2092 format = targets;
2093 else if (convert_selection( display, import_window, current_selection, string, &type, &data, &size ))
2094 format = string;
2097 changed = (changed ||
2098 rendered_formats ||
2099 last_selection != current_selection ||
2100 last_owner != owner ||
2101 last_format != format ||
2102 last_type != type ||
2103 last_size != size ||
2104 memcmp( last_data, data, size ));
2106 if (!changed || !NtUserOpenClipboard( clipboard_hwnd, 0 ))
2108 free( data );
2109 return FALSE;
2112 TRACE( "selection changed, importing\n" );
2113 NtUserEmptyClipboard();
2114 is_clipboard_owner = TRUE;
2115 rendered_formats = 0;
2117 if (format) format->import( type, data, size, &import_size );
2119 free( last_data );
2120 last_selection = current_selection;
2121 last_owner = owner;
2122 last_format = format;
2123 last_type = type;
2124 last_data = data;
2125 last_size = size;
2126 last_clipboard_update = NtGetTickCount();
2127 NtUserCloseClipboard();
2128 if (!use_xfixes)
2129 NtUserSetTimer( clipboard_hwnd, 1, SELECTION_UPDATE_DELAY, NULL, TIMERV_DEFAULT_COALESCING );
2130 return TRUE;
2134 /**************************************************************************
2135 * update_clipboard
2137 * Periodically update the clipboard while the selection is owned by an X11 app.
2139 BOOL update_clipboard( HWND hwnd )
2141 if (use_xfixes) return TRUE;
2142 if (hwnd != clipboard_hwnd) return TRUE;
2143 if (!is_clipboard_owner) return TRUE;
2144 if (NtGetTickCount() - last_clipboard_update <= SELECTION_UPDATE_DELAY) return TRUE;
2145 return request_selection_contents( thread_display(), FALSE );
2149 /**************************************************************************
2150 * selection_notify_event
2152 * Called when x11 clipboard content changes
2154 #ifdef SONAME_LIBXFIXES
2155 static BOOL selection_notify_event( HWND hwnd, XEvent *event )
2157 XFixesSelectionNotifyEvent *req = (XFixesSelectionNotifyEvent*)event;
2159 if (!is_clipboard_owner) return FALSE;
2160 if (req->owner == selection_window) return FALSE;
2161 request_selection_contents( req->display, TRUE );
2162 return FALSE;
2164 #endif
2166 /**************************************************************************
2167 * xfixes_init
2169 * Initialize xfixes to receive clipboard update notifications
2171 static void xfixes_init(void)
2173 #ifdef SONAME_LIBXFIXES
2174 typeof(XFixesSelectSelectionInput) *pXFixesSelectSelectionInput;
2175 typeof(XFixesQueryExtension) *pXFixesQueryExtension;
2176 typeof(XFixesQueryVersion) *pXFixesQueryVersion;
2178 int event_base, error_base;
2179 int major = 3, minor = 0;
2180 void *handle;
2182 handle = dlopen(SONAME_LIBXFIXES, RTLD_NOW);
2183 if (!handle) return;
2185 pXFixesQueryExtension = dlsym(handle, "XFixesQueryExtension");
2186 if (!pXFixesQueryExtension) return;
2187 pXFixesQueryVersion = dlsym(handle, "XFixesQueryVersion");
2188 if (!pXFixesQueryVersion) return;
2189 pXFixesSelectSelectionInput = dlsym(handle, "XFixesSelectSelectionInput");
2190 if (!pXFixesSelectSelectionInput) return;
2192 if (!pXFixesQueryExtension(clipboard_display, &event_base, &error_base))
2193 return;
2194 pXFixesQueryVersion(clipboard_display, &major, &minor);
2195 use_xfixes = (major >= 1);
2196 if (!use_xfixes) return;
2198 pXFixesSelectSelectionInput(clipboard_display, import_window, x11drv_atom(CLIPBOARD),
2199 XFixesSetSelectionOwnerNotifyMask |
2200 XFixesSelectionWindowDestroyNotifyMask |
2201 XFixesSelectionClientCloseNotifyMask);
2202 if (use_primary_selection)
2204 pXFixesSelectSelectionInput(clipboard_display, import_window, XA_PRIMARY,
2205 XFixesSetSelectionOwnerNotifyMask |
2206 XFixesSelectionWindowDestroyNotifyMask |
2207 XFixesSelectionClientCloseNotifyMask);
2209 X11DRV_register_event_handler(event_base + XFixesSelectionNotify,
2210 selection_notify_event, "XFixesSelectionNotify");
2211 TRACE("xfixes succesully initialized\n");
2212 #else
2213 WARN("xfixes not supported\n");
2214 #endif
2218 /**************************************************************************
2219 * clipboard_init
2221 * Thread running inside the desktop process to manage the clipboard
2223 static BOOL clipboard_init( HWND hwnd )
2225 XSetWindowAttributes attr;
2227 clipboard_hwnd = hwnd;
2228 clipboard_display = thread_init_display();
2229 attr.event_mask = PropertyChangeMask;
2230 import_window = XCreateWindow( clipboard_display, root_window, 0, 0, 1, 1, 0, CopyFromParent,
2231 InputOutput, CopyFromParent, CWEventMask, &attr );
2232 if (!import_window)
2234 ERR( "failed to create import window\n" );
2235 return FALSE;
2238 clipboard_thread_id = GetCurrentThreadId();
2239 NtUserAddClipboardFormatListener( hwnd );
2240 register_builtin_formats();
2241 xfixes_init();
2242 request_selection_contents( clipboard_display, TRUE );
2244 TRACE( "clipboard thread running\n" );
2245 return TRUE;
2251 /**************************************************************************
2252 * x11drv_clipboard_message
2254 LRESULT X11DRV_ClipboardWindowProc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam )
2256 switch (msg)
2258 case WM_NCCREATE:
2259 return clipboard_init( hwnd );
2260 case WM_CLIPBOARDUPDATE:
2261 if (is_clipboard_owner) break; /* ignore our own changes */
2262 acquire_selection( thread_init_display() );
2263 break;
2264 case WM_RENDERFORMAT:
2265 if (render_format( wparam )) rendered_formats++;
2266 break;
2267 case WM_TIMER:
2268 if (!is_clipboard_owner) break;
2269 request_selection_contents( thread_display(), FALSE );
2270 break;
2271 case WM_DESTROYCLIPBOARD:
2272 TRACE( "WM_DESTROYCLIPBOARD: lost ownership\n" );
2273 is_clipboard_owner = FALSE;
2274 NtUserKillTimer( hwnd, 1 );
2275 break;
2278 return NtUserMessageCall( hwnd, msg, wparam, lparam, NULL, NtUserDefWindowProc, FALSE );
2282 /**************************************************************************
2283 * X11DRV_UpdateClipboard
2285 void X11DRV_UpdateClipboard(void)
2287 static ULONG last_update;
2288 ULONG now;
2289 DWORD_PTR ret;
2291 if (use_xfixes) return;
2292 if (GetCurrentThreadId() == clipboard_thread_id) return;
2293 now = NtGetTickCount();
2294 if ((int)(now - last_update) <= SELECTION_UPDATE_DELAY) return;
2295 if (send_message_timeout( NtUserGetClipboardOwner(), WM_X11DRV_UPDATE_CLIPBOARD, 0, 0,
2296 SMTO_ABORTIFHUNG, 5000, &ret ) && ret)
2297 last_update = now;
2301 /***********************************************************************
2302 * X11DRV_HandleSelectionRequest
2304 BOOL X11DRV_SelectionRequest( HWND hwnd, XEvent *xev )
2306 XSelectionRequestEvent *event = &xev->xselectionrequest;
2307 Display *display = event->display;
2308 XEvent result;
2309 Atom rprop = None;
2311 TRACE( "got request on %lx for selection %s target %s win %lx prop %s\n",
2312 event->owner, debugstr_xatom( event->selection ), debugstr_xatom( event->target ),
2313 event->requestor, debugstr_xatom( event->property ));
2315 if (event->owner != selection_window) goto done;
2316 if ((event->selection != x11drv_atom(CLIPBOARD)) &&
2317 (!use_primary_selection || event->selection != XA_PRIMARY)) goto done;
2319 /* If the specified property is None the requestor is an obsolete client.
2320 * We support these by using the specified target atom as the reply property.
2322 rprop = event->property;
2323 if( rprop == None )
2324 rprop = event->target;
2326 if (!export_selection( display, event->requestor, rprop, event->target ))
2327 rprop = None; /* report failure to client */
2329 done:
2330 result.xselection.type = SelectionNotify;
2331 result.xselection.display = display;
2332 result.xselection.requestor = event->requestor;
2333 result.xselection.selection = event->selection;
2334 result.xselection.property = rprop;
2335 result.xselection.target = event->target;
2336 result.xselection.time = event->time;
2337 TRACE( "sending SelectionNotify for %s to %lx\n", debugstr_xatom( rprop ), event->requestor );
2338 XSendEvent( display, event->requestor, False, NoEventMask, &result );
2339 return FALSE;
2343 /***********************************************************************
2344 * X11DRV_SelectionClear
2346 BOOL X11DRV_SelectionClear( HWND hwnd, XEvent *xev )
2348 XSelectionClearEvent *event = &xev->xselectionclear;
2350 if (event->window != selection_window) return FALSE;
2351 if (event->selection != x11drv_atom(CLIPBOARD)) return FALSE;
2353 release_selection( event->display, event->time );
2354 request_selection_contents( event->display, TRUE );
2355 return FALSE;