cmd: DIR command outputs free space for the path.
[wine.git] / dlls / winex11.drv / clipboard.c
blob087e0aab79bedafbe4fa1d99d191c48a57b859c7
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 < *ret_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, *new_val, *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 if (!(new_val = realloc( val, pos * sizeof(int) + count + 1 )))
1868 XFree( buffer );
1869 free( val );
1870 return FALSE;
1872 val = new_val;
1873 memcpy( (int *)val + pos, buffer, count );
1874 XFree( buffer );
1875 if (!remain)
1877 *datasize = pos * sizeof(int) + count;
1878 val[*datasize] = 0;
1879 break;
1881 pos += count / sizeof(int);
1884 TRACE( "got property %s type %s format %u len %zu from window %lx\n",
1885 debugstr_xatom( prop ), debugstr_xatom( *atype ), aformat, *datasize, w );
1887 /* Delete the property on the window now that we are done
1888 * This will send a PropertyNotify event to the selection owner. */
1889 XDeleteProperty(display, w, prop);
1890 *data = val;
1891 return TRUE;
1895 struct clipboard_data_packet {
1896 struct list entry;
1897 unsigned long size;
1898 unsigned char *data;
1901 /**************************************************************************
1902 * read_property
1904 * Reads the contents of the X selection property.
1906 static BOOL read_property( Display *display, Window w, Atom prop,
1907 Atom *type, unsigned char **data, size_t *datasize )
1909 XEvent xe;
1911 if (prop == None)
1912 return FALSE;
1914 while (XCheckTypedWindowEvent(display, w, PropertyNotify, &xe))
1917 if (!X11DRV_CLIPBOARD_GetProperty(display, w, prop, type, data, datasize))
1918 return FALSE;
1920 if (*type == x11drv_atom(INCR))
1922 unsigned char *buf;
1923 unsigned long bufsize = 0;
1924 struct list packets;
1925 struct clipboard_data_packet *packet, *packet2;
1926 BOOL res;
1928 free( *data );
1929 *data = NULL;
1931 list_init(&packets);
1933 for (;;)
1935 int i;
1936 unsigned char *prop_data;
1937 size_t prop_size;
1939 /* Wait until PropertyNotify is received */
1940 for (i = 0; i < SELECTION_RETRIES; i++)
1942 Bool res;
1944 res = XCheckTypedWindowEvent(display, w, PropertyNotify, &xe);
1945 if (res && xe.xproperty.atom == prop &&
1946 xe.xproperty.state == PropertyNewValue)
1947 break;
1948 selection_sleep();
1951 if (i >= SELECTION_RETRIES ||
1952 !X11DRV_CLIPBOARD_GetProperty(display, w, prop, type, &prop_data, &prop_size))
1954 res = FALSE;
1955 break;
1958 /* Retrieved entire data. */
1959 if (prop_size == 0)
1961 free( prop_data );
1962 res = TRUE;
1963 break;
1966 packet = malloc( sizeof(*packet) );
1967 if (!packet)
1969 free( prop_data );
1970 res = FALSE;
1971 break;
1974 packet->size = prop_size;
1975 packet->data = prop_data;
1976 list_add_tail(&packets, &packet->entry);
1977 bufsize += prop_size;
1980 if (res)
1982 buf = malloc( bufsize + 1 );
1983 if (buf)
1985 unsigned long bytes_copied = 0;
1986 *datasize = bufsize;
1987 LIST_FOR_EACH_ENTRY( packet, &packets, struct clipboard_data_packet, entry)
1989 memcpy(&buf[bytes_copied], packet->data, packet->size);
1990 bytes_copied += packet->size;
1992 buf[bufsize] = 0;
1993 *data = buf;
1995 else
1996 res = FALSE;
1999 LIST_FOR_EACH_ENTRY_SAFE( packet, packet2, &packets, struct clipboard_data_packet, entry)
2001 free( packet->data );
2002 free( packet );
2005 return res;
2008 return TRUE;
2012 /**************************************************************************
2013 * acquire_selection
2015 * Acquire the X11 selection when the Win32 clipboard has changed.
2017 static void acquire_selection( Display *display )
2019 if (selection_window) XDestroyWindow( display, selection_window );
2021 selection_window = XCreateWindow( display, root_window, 0, 0, 1, 1, 0, CopyFromParent,
2022 InputOutput, CopyFromParent, 0, NULL );
2023 if (!selection_window) return;
2025 XSetSelectionOwner( display, x11drv_atom(CLIPBOARD), selection_window, CurrentTime );
2026 if (use_primary_selection) XSetSelectionOwner( display, XA_PRIMARY, selection_window, CurrentTime );
2027 TRACE( "win %lx\n", selection_window );
2031 /**************************************************************************
2032 * release_selection
2034 * Release the X11 selection when some other X11 app has grabbed it.
2036 static void release_selection( Display *display, Time time )
2038 assert( selection_window );
2040 TRACE( "win %lx\n", selection_window );
2042 /* release PRIMARY if we still own it */
2043 if (use_primary_selection && XGetSelectionOwner( display, XA_PRIMARY ) == selection_window)
2044 XSetSelectionOwner( display, XA_PRIMARY, None, time );
2046 XDestroyWindow( display, selection_window );
2047 selection_window = 0;
2051 /**************************************************************************
2052 * request_selection_contents
2054 * Retrieve the contents of the X11 selection when it's owned by an X11 app.
2056 static BOOL request_selection_contents( Display *display, BOOL changed )
2058 struct clipboard_format *targets = find_x11_format( x11drv_atom(TARGETS) );
2059 struct clipboard_format *string = find_x11_format( XA_STRING );
2060 struct clipboard_format *format = NULL;
2061 Window owner = 0;
2062 unsigned char *data = NULL;
2063 size_t import_size, size = 0;
2064 Atom type = 0;
2066 static Atom last_selection;
2067 static Window last_owner;
2068 static struct clipboard_format *last_format;
2069 static Atom last_type;
2070 static unsigned char *last_data;
2071 static unsigned long last_size;
2073 assert( targets );
2074 assert( string );
2076 current_selection = 0;
2077 if (use_primary_selection)
2079 if ((owner = XGetSelectionOwner( display, XA_PRIMARY )))
2080 current_selection = XA_PRIMARY;
2082 if (!current_selection)
2084 if ((owner = XGetSelectionOwner( display, x11drv_atom(CLIPBOARD) )))
2085 current_selection = x11drv_atom(CLIPBOARD);
2088 if (current_selection)
2090 if (convert_selection( display, import_window, current_selection, targets, &type, &data, &size ))
2091 format = targets;
2092 else if (convert_selection( display, import_window, current_selection, string, &type, &data, &size ))
2093 format = string;
2096 changed = (changed ||
2097 rendered_formats ||
2098 last_selection != current_selection ||
2099 last_owner != owner ||
2100 last_format != format ||
2101 last_type != type ||
2102 last_size != size ||
2103 memcmp( last_data, data, size ));
2105 if (!changed || !NtUserOpenClipboard( clipboard_hwnd, 0 ))
2107 free( data );
2108 return FALSE;
2111 TRACE( "selection changed, importing\n" );
2112 NtUserEmptyClipboard();
2113 is_clipboard_owner = TRUE;
2114 rendered_formats = 0;
2116 if (format) format->import( type, data, size, &import_size );
2118 free( last_data );
2119 last_selection = current_selection;
2120 last_owner = owner;
2121 last_format = format;
2122 last_type = type;
2123 last_data = data;
2124 last_size = size;
2125 last_clipboard_update = NtGetTickCount();
2126 NtUserCloseClipboard();
2127 if (!use_xfixes)
2128 NtUserSetTimer( clipboard_hwnd, 1, SELECTION_UPDATE_DELAY, NULL, TIMERV_DEFAULT_COALESCING );
2129 return TRUE;
2133 /**************************************************************************
2134 * update_clipboard
2136 * Periodically update the clipboard while the selection is owned by an X11 app.
2138 BOOL update_clipboard( HWND hwnd )
2140 if (use_xfixes) return TRUE;
2141 if (hwnd != clipboard_hwnd) return TRUE;
2142 if (!is_clipboard_owner) return TRUE;
2143 if (NtGetTickCount() - last_clipboard_update <= SELECTION_UPDATE_DELAY) return TRUE;
2144 return request_selection_contents( thread_display(), FALSE );
2148 /**************************************************************************
2149 * selection_notify_event
2151 * Called when x11 clipboard content changes
2153 #ifdef SONAME_LIBXFIXES
2154 static BOOL selection_notify_event( HWND hwnd, XEvent *event )
2156 XFixesSelectionNotifyEvent *req = (XFixesSelectionNotifyEvent*)event;
2158 if (!is_clipboard_owner) return FALSE;
2159 if (req->owner == selection_window) return FALSE;
2160 request_selection_contents( req->display, TRUE );
2161 return FALSE;
2163 #endif
2165 /**************************************************************************
2166 * xfixes_init
2168 * Initialize xfixes to receive clipboard update notifications
2170 static void xfixes_init(void)
2172 #ifdef SONAME_LIBXFIXES
2173 typeof(XFixesSelectSelectionInput) *pXFixesSelectSelectionInput;
2174 typeof(XFixesQueryExtension) *pXFixesQueryExtension;
2175 typeof(XFixesQueryVersion) *pXFixesQueryVersion;
2177 int event_base, error_base;
2178 int major = 3, minor = 0;
2179 void *handle;
2181 handle = dlopen(SONAME_LIBXFIXES, RTLD_NOW);
2182 if (!handle) return;
2184 pXFixesQueryExtension = dlsym(handle, "XFixesQueryExtension");
2185 if (!pXFixesQueryExtension) return;
2186 pXFixesQueryVersion = dlsym(handle, "XFixesQueryVersion");
2187 if (!pXFixesQueryVersion) return;
2188 pXFixesSelectSelectionInput = dlsym(handle, "XFixesSelectSelectionInput");
2189 if (!pXFixesSelectSelectionInput) return;
2191 if (!pXFixesQueryExtension(clipboard_display, &event_base, &error_base))
2192 return;
2193 pXFixesQueryVersion(clipboard_display, &major, &minor);
2194 use_xfixes = (major >= 1);
2195 if (!use_xfixes) return;
2197 pXFixesSelectSelectionInput(clipboard_display, import_window, x11drv_atom(CLIPBOARD),
2198 XFixesSetSelectionOwnerNotifyMask |
2199 XFixesSelectionWindowDestroyNotifyMask |
2200 XFixesSelectionClientCloseNotifyMask);
2201 if (use_primary_selection)
2203 pXFixesSelectSelectionInput(clipboard_display, import_window, XA_PRIMARY,
2204 XFixesSetSelectionOwnerNotifyMask |
2205 XFixesSelectionWindowDestroyNotifyMask |
2206 XFixesSelectionClientCloseNotifyMask);
2208 X11DRV_register_event_handler(event_base + XFixesSelectionNotify,
2209 selection_notify_event, "XFixesSelectionNotify");
2210 TRACE("xfixes succesully initialized\n");
2211 #else
2212 WARN("xfixes not supported\n");
2213 #endif
2217 /**************************************************************************
2218 * clipboard_init
2220 * Thread running inside the desktop process to manage the clipboard
2222 static BOOL clipboard_init( HWND hwnd )
2224 XSetWindowAttributes attr;
2226 clipboard_hwnd = hwnd;
2227 clipboard_display = thread_init_display();
2228 attr.event_mask = PropertyChangeMask;
2229 import_window = XCreateWindow( clipboard_display, root_window, 0, 0, 1, 1, 0, CopyFromParent,
2230 InputOutput, CopyFromParent, CWEventMask, &attr );
2231 if (!import_window)
2233 ERR( "failed to create import window\n" );
2234 return FALSE;
2237 clipboard_thread_id = GetCurrentThreadId();
2238 NtUserAddClipboardFormatListener( hwnd );
2239 register_builtin_formats();
2240 xfixes_init();
2241 request_selection_contents( clipboard_display, TRUE );
2243 TRACE( "clipboard thread running\n" );
2244 return TRUE;
2250 /**************************************************************************
2251 * x11drv_clipboard_message
2253 LRESULT X11DRV_ClipboardWindowProc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam )
2255 switch (msg)
2257 case WM_NCCREATE:
2258 return clipboard_init( hwnd );
2259 case WM_CLIPBOARDUPDATE:
2260 if (is_clipboard_owner) break; /* ignore our own changes */
2261 acquire_selection( thread_init_display() );
2262 break;
2263 case WM_RENDERFORMAT:
2264 if (render_format( wparam )) rendered_formats++;
2265 break;
2266 case WM_TIMER:
2267 if (!is_clipboard_owner) break;
2268 request_selection_contents( thread_display(), FALSE );
2269 break;
2270 case WM_DESTROYCLIPBOARD:
2271 TRACE( "WM_DESTROYCLIPBOARD: lost ownership\n" );
2272 is_clipboard_owner = FALSE;
2273 NtUserKillTimer( hwnd, 1 );
2274 break;
2277 return NtUserMessageCall( hwnd, msg, wparam, lparam, NULL, NtUserDefWindowProc, FALSE );
2281 /**************************************************************************
2282 * X11DRV_UpdateClipboard
2284 void X11DRV_UpdateClipboard(void)
2286 static ULONG last_update;
2287 ULONG now;
2288 DWORD_PTR ret;
2290 if (use_xfixes) return;
2291 if (GetCurrentThreadId() == clipboard_thread_id) return;
2292 now = NtGetTickCount();
2293 if ((int)(now - last_update) <= SELECTION_UPDATE_DELAY) return;
2294 if (send_message_timeout( NtUserGetClipboardOwner(), WM_X11DRV_UPDATE_CLIPBOARD, 0, 0,
2295 SMTO_ABORTIFHUNG, 5000, &ret ) && ret)
2296 last_update = now;
2300 /***********************************************************************
2301 * X11DRV_HandleSelectionRequest
2303 BOOL X11DRV_SelectionRequest( HWND hwnd, XEvent *xev )
2305 XSelectionRequestEvent *event = &xev->xselectionrequest;
2306 Display *display = event->display;
2307 XEvent result;
2308 Atom rprop = None;
2310 TRACE( "got request on %lx for selection %s target %s win %lx prop %s\n",
2311 event->owner, debugstr_xatom( event->selection ), debugstr_xatom( event->target ),
2312 event->requestor, debugstr_xatom( event->property ));
2314 if (event->owner != selection_window) goto done;
2315 if ((event->selection != x11drv_atom(CLIPBOARD)) &&
2316 (!use_primary_selection || event->selection != XA_PRIMARY)) goto done;
2318 /* If the specified property is None the requestor is an obsolete client.
2319 * We support these by using the specified target atom as the reply property.
2321 rprop = event->property;
2322 if( rprop == None )
2323 rprop = event->target;
2325 if (!export_selection( display, event->requestor, rprop, event->target ))
2326 rprop = None; /* report failure to client */
2328 done:
2329 result.xselection.type = SelectionNotify;
2330 result.xselection.display = display;
2331 result.xselection.requestor = event->requestor;
2332 result.xselection.selection = event->selection;
2333 result.xselection.property = rprop;
2334 result.xselection.target = event->target;
2335 result.xselection.time = event->time;
2336 TRACE( "sending SelectionNotify for %s to %lx\n", debugstr_xatom( rprop ), event->requestor );
2337 XSendEvent( display, event->requestor, False, NoEventMask, &result );
2338 return FALSE;
2342 /***********************************************************************
2343 * X11DRV_SelectionClear
2345 BOOL X11DRV_SelectionClear( HWND hwnd, XEvent *xev )
2347 XSelectionClearEvent *event = &xev->xselectionclear;
2349 if (event->window != selection_window) return FALSE;
2350 if (event->selection != x11drv_atom(CLIPBOARD)) return FALSE;
2352 release_selection( event->display, event->time );
2353 request_selection_contents( event->display, TRUE );
2354 return FALSE;