netprofm: Implement INetworkListManager::GetNetwork.
[wine/multimedia.git] / dlls / winex11.drv / clipboard.c
blob6c6b3b9fe9f40a2463dd38b72cc279625507bc3a
1 /*
2 * X11 clipboard windows driver
4 * Copyright 1994 Martin Ayotte
5 * 1996 Alex Korobka
6 * 1999 Noel Borthwick
7 * 2003 Ulrich Czekalla for CodeWeavers
8 * 2014 Damjan Jovanovic
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 * NOTES:
25 * This file contains the X specific implementation for the windows
26 * Clipboard API.
28 * Wine's internal clipboard is exposed to external apps via the X
29 * selection mechanism.
30 * Currently the driver asserts ownership via two selection atoms:
31 * 1. PRIMARY(XA_PRIMARY)
32 * 2. CLIPBOARD
34 * In our implementation, the CLIPBOARD selection takes precedence over PRIMARY,
35 * i.e. if a CLIPBOARD selection is available, it is used instead of PRIMARY.
36 * When Wine takes ownership of the clipboard, it takes ownership of BOTH selections.
37 * While giving up selection ownership, if the CLIPBOARD selection is lost,
38 * it will lose both PRIMARY and CLIPBOARD and empty the clipboard.
39 * However if only PRIMARY is lost, it will continue to hold the CLIPBOARD selection
40 * (leaving the clipboard cache content unaffected).
42 * Every format exposed via a windows clipboard format is also exposed through
43 * a corresponding X selection target. A selection target atom is synthesized
44 * whenever a new Windows clipboard format is registered via RegisterClipboardFormat,
45 * or when a built-in format is used for the first time.
46 * Windows native format are exposed by prefixing the format name with "<WCF>"
47 * This allows us to uniquely identify windows native formats exposed by other
48 * running WINE apps.
50 * In order to allow external applications to query WINE for supported formats,
51 * we respond to the "TARGETS" selection target. (See EVENT_SelectionRequest
52 * for implementation) We use the same mechanism to query external clients for
53 * availability of a particular format, by caching the list of available targets
54 * by using the clipboard cache's "delayed render" mechanism. If a selection client
55 * does not support the "TARGETS" selection target, we actually attempt to retrieve
56 * the format requested as a fallback mechanism.
58 * Certain Windows native formats are automatically converted to X native formats
59 * and vice versa. If a native format is available in the selection, it takes
60 * precedence, in order to avoid unnecessary conversions.
62 * FIXME: global format list needs a critical section
65 #include "config.h"
66 #include "wine/port.h"
68 #include <string.h>
69 #include <stdarg.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #ifdef HAVE_UNISTD_H
73 # include <unistd.h>
74 #endif
75 #include <fcntl.h>
76 #include <limits.h>
77 #include <time.h>
78 #include <assert.h>
80 #include "windef.h"
81 #include "winbase.h"
82 #include "shlobj.h"
83 #include "shellapi.h"
84 #include "shlwapi.h"
85 #include "x11drv.h"
86 #include "wine/list.h"
87 #include "wine/debug.h"
88 #include "wine/unicode.h"
89 #include "wine/server.h"
91 WINE_DEFAULT_DEBUG_CHANNEL(clipboard);
93 /* Maximum wait time for selection notify */
94 #define SELECTION_RETRIES 500 /* wait for .5 seconds */
95 #define SELECTION_WAIT 1000 /* us */
97 /* Selection masks */
98 #define S_NOSELECTION 0
99 #define S_PRIMARY 1
100 #define S_CLIPBOARD 2
102 struct tagWINE_CLIPDATA; /* Forward */
104 typedef HANDLE (*DRVEXPORTFUNC)(Display *display, Window requestor, Atom aTarget, Atom rprop,
105 struct tagWINE_CLIPDATA* lpData, LPDWORD lpBytes);
106 typedef HANDLE (*DRVIMPORTFUNC)(Display *d, Window w, Atom prop);
108 typedef struct tagWINE_CLIPFORMAT {
109 struct list entry;
110 UINT wFormatID;
111 UINT drvData;
112 DRVIMPORTFUNC lpDrvImportFunc;
113 DRVEXPORTFUNC lpDrvExportFunc;
114 } WINE_CLIPFORMAT, *LPWINE_CLIPFORMAT;
116 typedef struct tagWINE_CLIPDATA {
117 struct list entry;
118 UINT wFormatID;
119 HANDLE hData;
120 UINT wFlags;
121 UINT drvData;
122 LPWINE_CLIPFORMAT lpFormat;
123 } WINE_CLIPDATA, *LPWINE_CLIPDATA;
125 #define CF_FLAG_UNOWNED 0x0001 /* cached data is not owned */
126 #define CF_FLAG_SYNTHESIZED 0x0002 /* Implicitly converted data */
128 static int selectionAcquired = 0; /* Contains the current selection masks */
129 static Window selectionWindow = None; /* The top level X window which owns the selection */
130 static Atom selectionCacheSrc = XA_PRIMARY; /* The selection source from which the clipboard cache was filled */
132 void CDECL X11DRV_EndClipboardUpdate(void);
133 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *d, Window w, Atom prop);
134 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *d, Window w, Atom prop);
135 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *d, Window w, Atom prop);
136 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *d, Window w, Atom prop);
137 static HANDLE X11DRV_CLIPBOARD_ImportImageBmp(Display *d, Window w, Atom prop);
138 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *d, Window w, Atom prop);
139 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *d, Window w, Atom prop);
140 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *d, Window w, Atom prop);
141 static HANDLE X11DRV_CLIPBOARD_ImportTextUriList(Display *display, Window w, Atom prop);
142 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
143 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
144 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget,
145 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
146 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget,
147 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
148 static HANDLE X11DRV_CLIPBOARD_ExportImageBmp(Display *display, Window requestor, Atom aTarget,
149 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
150 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget,
151 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
152 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget,
153 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
154 static HANDLE X11DRV_CLIPBOARD_ExportTextHtml(Display *display, Window requestor, Atom aTarget,
155 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
156 static HANDLE X11DRV_CLIPBOARD_ExportHDROP(Display *display, Window requestor, Atom aTarget,
157 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
158 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(UINT id, Atom prop);
159 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID);
160 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData);
161 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display);
162 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData);
163 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
164 unsigned char** data, unsigned long* datasize);
165 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData);
166 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out);
167 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID);
168 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData);
169 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display);
170 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display);
171 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile(Display *display);
172 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple );
173 static void empty_clipboard( BOOL keepunowned );
175 /* Clipboard formats */
177 static const struct
179 UINT id;
180 UINT data;
181 DRVIMPORTFUNC import;
182 DRVEXPORTFUNC export;
183 } builtin_formats[] =
185 { CF_TEXT, XA_STRING, X11DRV_CLIPBOARD_ImportXAString, X11DRV_CLIPBOARD_ExportString},
186 { CF_TEXT, XATOM_text_plain, X11DRV_CLIPBOARD_ImportXAString, X11DRV_CLIPBOARD_ExportString},
187 { CF_BITMAP, XATOM_WCF_BITMAP, X11DRV_CLIPBOARD_ImportClipboardData, NULL},
188 { CF_METAFILEPICT, XATOM_WCF_METAFILEPICT, X11DRV_CLIPBOARD_ImportMetaFilePict, X11DRV_CLIPBOARD_ExportMetaFilePict },
189 { CF_SYLK, XATOM_WCF_SYLK, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
190 { CF_DIF, XATOM_WCF_DIF, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
191 { CF_TIFF, XATOM_WCF_TIFF, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
192 { CF_OEMTEXT, XATOM_WCF_OEMTEXT, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
193 { CF_DIB, XA_PIXMAP, X11DRV_CLIPBOARD_ImportXAPIXMAP, X11DRV_CLIPBOARD_ExportXAPIXMAP },
194 { CF_PALETTE, XATOM_WCF_PALETTE, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
195 { CF_PENDATA, XATOM_WCF_PENDATA, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
196 { CF_RIFF, XATOM_WCF_RIFF, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
197 { CF_WAVE, XATOM_WCF_WAVE, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
198 { CF_UNICODETEXT, XATOM_UTF8_STRING, X11DRV_CLIPBOARD_ImportUTF8, X11DRV_CLIPBOARD_ExportString },
199 /* If UTF8_STRING is not available, attempt COMPOUND_TEXT */
200 { CF_UNICODETEXT, XATOM_COMPOUND_TEXT, X11DRV_CLIPBOARD_ImportCompoundText, X11DRV_CLIPBOARD_ExportString },
201 { CF_ENHMETAFILE, XATOM_WCF_ENHMETAFILE, X11DRV_CLIPBOARD_ImportEnhMetaFile, X11DRV_CLIPBOARD_ExportEnhMetaFile },
202 { CF_HDROP, XATOM_text_uri_list, X11DRV_CLIPBOARD_ImportTextUriList, X11DRV_CLIPBOARD_ExportHDROP },
203 { CF_LOCALE, XATOM_WCF_LOCALE, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
204 { CF_DIBV5, XATOM_WCF_DIBV5, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
205 { CF_OWNERDISPLAY, XATOM_WCF_OWNERDISPLAY, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
206 { CF_DSPTEXT, XATOM_WCF_DSPTEXT, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
207 { CF_DSPBITMAP, XATOM_WCF_DSPBITMAP, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
208 { CF_DSPMETAFILEPICT, XATOM_WCF_DSPMETAFILEPICT, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
209 { CF_DSPENHMETAFILE, XATOM_WCF_DSPENHMETAFILE, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
210 { CF_DIB, XATOM_image_bmp, X11DRV_CLIPBOARD_ImportImageBmp, X11DRV_CLIPBOARD_ExportImageBmp },
213 static struct list format_list = LIST_INIT( format_list );
215 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
217 /* Maps X properties to Windows formats */
218 static const WCHAR wszRichTextFormat[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
219 static const WCHAR wszGIF[] = {'G','I','F',0};
220 static const WCHAR wszJFIF[] = {'J','F','I','F',0};
221 static const WCHAR wszPNG[] = {'P','N','G',0};
222 static const WCHAR wszHTMLFormat[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
223 static const struct
225 LPCWSTR lpszFormat;
226 UINT prop;
227 } PropertyFormatMap[] =
229 { wszRichTextFormat, XATOM_text_rtf },
230 { wszRichTextFormat, XATOM_text_richtext },
231 { wszGIF, XATOM_image_gif },
232 { wszJFIF, XATOM_image_jpeg },
233 { wszPNG, XATOM_image_png },
234 { wszHTMLFormat, XATOM_HTML_Format }, /* prefer this to text/html */
239 * Cached clipboard data.
241 static struct list data_list = LIST_INIT( data_list );
242 static UINT ClipDataCount = 0;
245 * Clipboard sequence number
247 static UINT wSeqNo = 0;
249 /**************************************************************************
250 * Internal Clipboard implementation methods
251 **************************************************************************/
253 static Window thread_selection_wnd(void)
255 struct x11drv_thread_data *thread_data = x11drv_init_thread_data();
256 Window w = thread_data->selection_wnd;
258 if (!w)
260 w = XCreateWindow(thread_data->display, root_window, 0, 0, 1, 1, 0, CopyFromParent,
261 InputOnly, CopyFromParent, 0, NULL);
262 if (w)
264 thread_data->selection_wnd = w;
266 XSelectInput(thread_data->display, w, PropertyChangeMask);
268 else
269 FIXME("Failed to create window. Fetching selection data will fail.\n");
272 return w;
275 static const char *debugstr_format( UINT id )
277 WCHAR buffer[256];
279 if (GetClipboardFormatNameW( id, buffer, 256 ))
280 return wine_dbg_sprintf( "%04x %s", id, debugstr_w(buffer) );
282 switch (id)
284 #define BUILTIN(id) case id: return #id;
285 BUILTIN(CF_TEXT)
286 BUILTIN(CF_BITMAP)
287 BUILTIN(CF_METAFILEPICT)
288 BUILTIN(CF_SYLK)
289 BUILTIN(CF_DIF)
290 BUILTIN(CF_TIFF)
291 BUILTIN(CF_OEMTEXT)
292 BUILTIN(CF_DIB)
293 BUILTIN(CF_PALETTE)
294 BUILTIN(CF_PENDATA)
295 BUILTIN(CF_RIFF)
296 BUILTIN(CF_WAVE)
297 BUILTIN(CF_UNICODETEXT)
298 BUILTIN(CF_ENHMETAFILE)
299 BUILTIN(CF_HDROP)
300 BUILTIN(CF_LOCALE)
301 BUILTIN(CF_DIBV5)
302 BUILTIN(CF_OWNERDISPLAY)
303 BUILTIN(CF_DSPTEXT)
304 BUILTIN(CF_DSPBITMAP)
305 BUILTIN(CF_DSPMETAFILEPICT)
306 BUILTIN(CF_DSPENHMETAFILE)
307 #undef BUILTIN
308 default: return wine_dbg_sprintf( "%04x", id );
312 /**************************************************************************
313 * X11DRV_InitClipboard
315 void X11DRV_InitClipboard(void)
317 UINT i;
318 WINE_CLIPFORMAT *format;
320 /* Register built-in formats */
321 for (i = 0; i < sizeof(builtin_formats)/sizeof(builtin_formats[0]); i++)
323 if (!(format = HeapAlloc( GetProcessHeap(), 0, sizeof(*format )))) break;
324 format->wFormatID = builtin_formats[i].id;
325 format->drvData = GET_ATOM(builtin_formats[i].data);
326 format->lpDrvImportFunc = builtin_formats[i].import;
327 format->lpDrvExportFunc = builtin_formats[i].export;
328 list_add_tail( &format_list, &format->entry );
331 /* Register known mapping between window formats and X properties */
332 for (i = 0; i < sizeof(PropertyFormatMap)/sizeof(PropertyFormatMap[0]); i++)
333 X11DRV_CLIPBOARD_InsertClipboardFormat( RegisterClipboardFormatW(PropertyFormatMap[i].lpszFormat),
334 GET_ATOM(PropertyFormatMap[i].prop));
336 /* Set up a conversion function from "HTML Format" to "text/html" */
337 format = X11DRV_CLIPBOARD_InsertClipboardFormat( RegisterClipboardFormatW(wszHTMLFormat),
338 GET_ATOM(XATOM_text_html));
339 format->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportTextHtml;
343 /**************************************************************************
344 * intern_atoms
346 * Intern atoms for formats that don't have one yet.
348 static void intern_atoms(void)
350 LPWINE_CLIPFORMAT format;
351 int i, count, len;
352 char **names;
353 Atom *atoms;
354 Display *display;
355 WCHAR buffer[256];
357 count = 0;
358 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
359 if (!format->drvData) count++;
360 if (!count) return;
362 display = thread_init_display();
364 names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
365 atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
367 i = 0;
368 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
369 if (!format->drvData) {
370 GetClipboardFormatNameW( format->wFormatID, buffer, 256 );
371 len = WideCharToMultiByte(CP_UNIXCP, 0, buffer, -1, NULL, 0, NULL, NULL);
372 names[i] = HeapAlloc(GetProcessHeap(), 0, len);
373 WideCharToMultiByte(CP_UNIXCP, 0, buffer, -1, names[i++], len, NULL, NULL);
376 XInternAtoms( display, names, count, False, atoms );
378 i = 0;
379 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
380 if (!format->drvData) {
381 HeapFree(GetProcessHeap(), 0, names[i]);
382 format->drvData = atoms[i++];
385 HeapFree( GetProcessHeap(), 0, names );
386 HeapFree( GetProcessHeap(), 0, atoms );
390 /**************************************************************************
391 * register_format
393 * Register a custom X clipboard format.
395 static WINE_CLIPFORMAT *register_format( UINT id, Atom prop )
397 LPWINE_CLIPFORMAT lpFormat;
399 /* walk format chain to see if it's already registered */
400 LIST_FOR_EACH_ENTRY( lpFormat, &format_list, WINE_CLIPFORMAT, entry )
401 if (lpFormat->wFormatID == id) return lpFormat;
403 return X11DRV_CLIPBOARD_InsertClipboardFormat(id, prop);
407 /**************************************************************************
408 * X11DRV_CLIPBOARD_LookupProperty
410 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupProperty(LPWINE_CLIPFORMAT current, UINT drvData)
412 for (;;)
414 struct list *ptr = current ? &current->entry : &format_list;
415 BOOL need_intern = FALSE;
417 while ((ptr = list_next( &format_list, ptr )))
419 LPWINE_CLIPFORMAT lpFormat = LIST_ENTRY( ptr, WINE_CLIPFORMAT, entry );
420 if (lpFormat->drvData == drvData) return lpFormat;
421 if (!lpFormat->drvData) need_intern = TRUE;
423 if (!need_intern) return NULL;
424 intern_atoms();
425 /* restart the search for the new atoms */
430 /**************************************************************************
431 * X11DRV_CLIPBOARD_LookupData
433 static LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
435 WINE_CLIPDATA *data;
437 LIST_FOR_EACH_ENTRY( data, &data_list, WINE_CLIPDATA, entry )
438 if (data->wFormatID == wID) return data;
440 return NULL;
444 /**************************************************************************
445 * InsertClipboardFormat
447 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat( UINT id, Atom prop )
449 LPWINE_CLIPFORMAT lpNewFormat;
451 /* allocate storage for new format entry */
452 lpNewFormat = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPFORMAT));
454 if(lpNewFormat == NULL)
456 WARN("No more memory for a new format!\n");
457 return NULL;
459 lpNewFormat->wFormatID = id;
460 lpNewFormat->drvData = prop;
461 lpNewFormat->lpDrvImportFunc = X11DRV_CLIPBOARD_ImportClipboardData;
462 lpNewFormat->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportClipboardData;
464 list_add_tail( &format_list, &lpNewFormat->entry );
466 TRACE("Registering format %s drvData %d\n",
467 debugstr_format(lpNewFormat->wFormatID), lpNewFormat->drvData);
469 return lpNewFormat;
475 /**************************************************************************
476 * X11DRV_CLIPBOARD_IsProcessOwner
478 static BOOL X11DRV_CLIPBOARD_IsProcessOwner( HWND *owner )
480 BOOL ret = FALSE;
482 SERVER_START_REQ( set_clipboard_info )
484 req->flags = 0;
485 if (!wine_server_call_err( req ))
487 *owner = wine_server_ptr_handle( reply->old_owner );
488 ret = (reply->flags & CB_PROCESS);
491 SERVER_END_REQ;
493 return ret;
497 /**************************************************************************
498 * X11DRV_CLIPBOARD_ReleaseOwnership
500 static BOOL X11DRV_CLIPBOARD_ReleaseOwnership(void)
502 BOOL ret;
504 SERVER_START_REQ( set_clipboard_info )
506 req->flags = SET_CB_RELOWNER | SET_CB_SEQNO;
507 ret = !wine_server_call_err( req );
509 SERVER_END_REQ;
511 return ret;
516 /**************************************************************************
517 * X11DRV_CLIPBOARD_InsertClipboardData
519 * Caller *must* have the clipboard open and be the owner.
521 static BOOL X11DRV_CLIPBOARD_InsertClipboardData(UINT wFormatID, HANDLE hData, DWORD flags,
522 LPWINE_CLIPFORMAT lpFormat, BOOL override)
524 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormatID);
526 TRACE("format=%04x lpData=%p hData=%p flags=0x%08x lpFormat=%p override=%d\n",
527 wFormatID, lpData, hData, flags, lpFormat, override);
529 /* make sure the format exists */
530 if (!lpFormat) register_format( wFormatID, 0 );
532 if (lpData && !override)
533 return TRUE;
535 if (lpData)
537 X11DRV_CLIPBOARD_FreeData(lpData);
539 lpData->hData = hData;
541 else
543 lpData = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPDATA));
545 lpData->wFormatID = wFormatID;
546 lpData->hData = hData;
547 lpData->lpFormat = lpFormat;
548 lpData->drvData = 0;
550 list_add_tail( &data_list, &lpData->entry );
551 ClipDataCount++;
554 lpData->wFlags = flags;
556 return TRUE;
560 /**************************************************************************
561 * X11DRV_CLIPBOARD_FreeData
563 * Free clipboard data handle.
565 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData)
567 TRACE("%04x\n", lpData->wFormatID);
569 if ((lpData->wFormatID >= CF_GDIOBJFIRST &&
570 lpData->wFormatID <= CF_GDIOBJLAST) ||
571 lpData->wFormatID == CF_BITMAP ||
572 lpData->wFormatID == CF_DIB ||
573 lpData->wFormatID == CF_PALETTE)
575 if (lpData->hData)
576 DeleteObject(lpData->hData);
578 if ((lpData->wFormatID == CF_DIB) && lpData->drvData)
579 XFreePixmap(gdi_display, lpData->drvData);
581 else if (lpData->wFormatID == CF_METAFILEPICT)
583 if (lpData->hData)
585 DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData ))->hMF );
586 GlobalFree(lpData->hData);
589 else if (lpData->wFormatID == CF_ENHMETAFILE)
591 if (lpData->hData)
592 DeleteEnhMetaFile(lpData->hData);
594 else if (lpData->wFormatID < CF_PRIVATEFIRST ||
595 lpData->wFormatID > CF_PRIVATELAST)
597 if (lpData->hData)
598 GlobalFree(lpData->hData);
601 lpData->hData = 0;
602 lpData->drvData = 0;
606 /**************************************************************************
607 * X11DRV_CLIPBOARD_UpdateCache
609 static BOOL X11DRV_CLIPBOARD_UpdateCache(void)
611 BOOL bret = TRUE;
613 if (!selectionAcquired)
615 DWORD seqno = GetClipboardSequenceNumber();
617 if (!seqno)
619 ERR("Failed to retrieve clipboard information.\n");
620 bret = FALSE;
622 else if (wSeqNo < seqno)
624 empty_clipboard( TRUE );
626 if (X11DRV_CLIPBOARD_QueryAvailableData(thread_init_display()) < 0)
628 ERR("Failed to cache clipboard data owned by another process.\n");
629 bret = FALSE;
631 else
633 X11DRV_EndClipboardUpdate();
636 wSeqNo = seqno;
640 return bret;
644 /**************************************************************************
645 * X11DRV_CLIPBOARD_RenderFormat
647 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData)
649 BOOL bret = TRUE;
651 TRACE(" 0x%04x hData(%p)\n", lpData->wFormatID, lpData->hData);
653 if (lpData->hData) return bret; /* Already rendered */
655 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
656 bret = X11DRV_CLIPBOARD_RenderSynthesizedFormat(display, lpData);
657 else if (!selectionAcquired)
659 if (!X11DRV_CLIPBOARD_ReadSelectionData(display, lpData))
661 ERR("Failed to cache clipboard data owned by another process. Format=%04x\n",
662 lpData->wFormatID);
663 bret = FALSE;
666 else
668 HWND owner = GetClipboardOwner();
670 if (owner)
672 /* Send a WM_RENDERFORMAT message to notify the owner to render the
673 * data requested into the clipboard.
675 TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", owner);
676 SendMessageW(owner, WM_RENDERFORMAT, lpData->wFormatID, 0);
678 if (!lpData->hData) bret = FALSE;
680 else
682 ERR("hWndClipOwner is lost!\n");
683 bret = FALSE;
687 return bret;
691 /**************************************************************************
692 * CLIPBOARD_ConvertText
693 * Returns number of required/converted characters - not bytes!
695 static INT CLIPBOARD_ConvertText(WORD src_fmt, void const *src, INT src_size,
696 WORD dst_fmt, void *dst, INT dst_size)
698 UINT cp;
700 if(src_fmt == CF_UNICODETEXT)
702 switch(dst_fmt)
704 case CF_TEXT:
705 cp = CP_ACP;
706 break;
707 case CF_OEMTEXT:
708 cp = CP_OEMCP;
709 break;
710 default:
711 return 0;
713 return WideCharToMultiByte(cp, 0, src, src_size, dst, dst_size, NULL, NULL);
716 if(dst_fmt == CF_UNICODETEXT)
718 switch(src_fmt)
720 case CF_TEXT:
721 cp = CP_ACP;
722 break;
723 case CF_OEMTEXT:
724 cp = CP_OEMCP;
725 break;
726 default:
727 return 0;
729 return MultiByteToWideChar(cp, 0, src, src_size, dst, dst_size);
732 if(!dst_size) return src_size;
734 if(dst_size > src_size) dst_size = src_size;
736 if(src_fmt == CF_TEXT )
737 CharToOemBuffA(src, dst, dst_size);
738 else
739 OemToCharBuffA(src, dst, dst_size);
741 return dst_size;
745 /**************************************************************************
746 * X11DRV_CLIPBOARD_RenderSynthesizedFormat
748 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData)
750 BOOL bret = FALSE;
752 TRACE("\n");
754 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
756 UINT wFormatID = lpData->wFormatID;
758 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
759 bret = X11DRV_CLIPBOARD_RenderSynthesizedText(display, wFormatID);
760 else
762 switch (wFormatID)
764 case CF_DIB:
765 bret = X11DRV_CLIPBOARD_RenderSynthesizedDIB( display );
766 break;
768 case CF_BITMAP:
769 bret = X11DRV_CLIPBOARD_RenderSynthesizedBitmap( display );
770 break;
772 case CF_ENHMETAFILE:
773 bret = X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile( display );
774 break;
776 case CF_METAFILEPICT:
777 FIXME("Synthesizing CF_METAFILEPICT not implemented\n");
778 break;
780 default:
781 FIXME("Called to synthesize unknown format 0x%08x\n", wFormatID);
782 break;
786 lpData->wFlags &= ~CF_FLAG_SYNTHESIZED;
789 return bret;
793 /**************************************************************************
794 * X11DRV_CLIPBOARD_RenderSynthesizedText
796 * Renders synthesized text
798 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID)
800 LPCSTR lpstrS;
801 LPSTR lpstrT;
802 HANDLE hData;
803 INT src_chars, dst_chars, alloc_size;
804 LPWINE_CLIPDATA lpSource = NULL;
806 TRACE("%04x\n", wFormatID);
808 if ((lpSource = X11DRV_CLIPBOARD_LookupData(wFormatID)) &&
809 lpSource->hData)
810 return TRUE;
812 /* Look for rendered source or non-synthesized source */
813 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
814 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
816 TRACE("UNICODETEXT -> %04x\n", wFormatID);
818 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
819 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
821 TRACE("TEXT -> %04x\n", wFormatID);
823 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
824 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
826 TRACE("OEMTEXT -> %04x\n", wFormatID);
829 if (!lpSource || (lpSource->wFlags & CF_FLAG_SYNTHESIZED &&
830 !lpSource->hData))
831 return FALSE;
833 /* Ask the clipboard owner to render the source text if necessary */
834 if (!lpSource->hData && !X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
835 return FALSE;
837 lpstrS = GlobalLock(lpSource->hData);
838 if (!lpstrS)
839 return FALSE;
841 /* Text always NULL terminated */
842 if(lpSource->wFormatID == CF_UNICODETEXT)
843 src_chars = strlenW((LPCWSTR)lpstrS) + 1;
844 else
845 src_chars = strlen(lpstrS) + 1;
847 /* Calculate number of characters in the destination buffer */
848 dst_chars = CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS,
849 src_chars, wFormatID, NULL, 0);
851 if (!dst_chars)
852 return FALSE;
854 TRACE("Converting from '%04x' to '%04x', %i chars\n",
855 lpSource->wFormatID, wFormatID, src_chars);
857 /* Convert characters to bytes */
858 if(wFormatID == CF_UNICODETEXT)
859 alloc_size = dst_chars * sizeof(WCHAR);
860 else
861 alloc_size = dst_chars;
863 hData = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
864 GMEM_DDESHARE, alloc_size);
866 lpstrT = GlobalLock(hData);
868 if (lpstrT)
870 CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS, src_chars,
871 wFormatID, lpstrT, dst_chars);
872 GlobalUnlock(hData);
875 GlobalUnlock(lpSource->hData);
877 return X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, hData, 0, NULL, TRUE);
881 /***********************************************************************
882 * bitmap_info_size
884 * Return the size of the bitmap info structure including color table.
886 static int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
888 unsigned int colors, size, masks = 0;
890 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
892 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
893 colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
894 return sizeof(BITMAPCOREHEADER) + colors *
895 ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
897 else /* assume BITMAPINFOHEADER */
899 colors = info->bmiHeader.biClrUsed;
900 if (!colors && (info->bmiHeader.biBitCount <= 8))
901 colors = 1 << info->bmiHeader.biBitCount;
902 if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
903 size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
904 return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
909 /***********************************************************************
910 * create_dib_from_bitmap
912 * Allocates a packed DIB and copies the bitmap data into it.
914 static HGLOBAL create_dib_from_bitmap(HBITMAP hBmp)
916 BITMAP bmp;
917 HDC hdc;
918 HGLOBAL hPackedDIB;
919 LPBYTE pPackedDIB;
920 LPBITMAPINFOHEADER pbmiHeader;
921 unsigned int cDataSize, cPackedSize, OffsetBits;
922 int nLinesCopied;
924 if (!GetObjectW( hBmp, sizeof(bmp), &bmp )) return 0;
927 * A packed DIB contains a BITMAPINFO structure followed immediately by
928 * an optional color palette and the pixel data.
931 /* Calculate the size of the packed DIB */
932 cDataSize = abs( bmp.bmHeight ) * (((bmp.bmWidth * bmp.bmBitsPixel + 31) / 8) & ~3);
933 cPackedSize = sizeof(BITMAPINFOHEADER)
934 + ( (bmp.bmBitsPixel <= 8) ? (sizeof(RGBQUAD) * (1 << bmp.bmBitsPixel)) : 0 )
935 + cDataSize;
936 /* Get the offset to the bits */
937 OffsetBits = cPackedSize - cDataSize;
939 /* Allocate the packed DIB */
940 TRACE("\tAllocating packed DIB of size %d\n", cPackedSize);
941 hPackedDIB = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE /*| GMEM_ZEROINIT*/,
942 cPackedSize );
943 if ( !hPackedDIB )
945 WARN("Could not allocate packed DIB!\n");
946 return 0;
949 /* A packed DIB starts with a BITMAPINFOHEADER */
950 pPackedDIB = GlobalLock(hPackedDIB);
951 pbmiHeader = (LPBITMAPINFOHEADER)pPackedDIB;
953 /* Init the BITMAPINFOHEADER */
954 pbmiHeader->biSize = sizeof(BITMAPINFOHEADER);
955 pbmiHeader->biWidth = bmp.bmWidth;
956 pbmiHeader->biHeight = bmp.bmHeight;
957 pbmiHeader->biPlanes = 1;
958 pbmiHeader->biBitCount = bmp.bmBitsPixel;
959 pbmiHeader->biCompression = BI_RGB;
960 pbmiHeader->biSizeImage = 0;
961 pbmiHeader->biXPelsPerMeter = pbmiHeader->biYPelsPerMeter = 0;
962 pbmiHeader->biClrUsed = 0;
963 pbmiHeader->biClrImportant = 0;
965 /* Retrieve the DIB bits from the bitmap and fill in the
966 * DIB color table if present */
967 hdc = GetDC( 0 );
968 nLinesCopied = GetDIBits(hdc, /* Handle to device context */
969 hBmp, /* Handle to bitmap */
970 0, /* First scan line to set in dest bitmap */
971 bmp.bmHeight, /* Number of scan lines to copy */
972 pPackedDIB + OffsetBits, /* [out] Address of array for bitmap bits */
973 (LPBITMAPINFO) pbmiHeader, /* [out] Address of BITMAPINFO structure */
974 0); /* RGB or palette index */
975 GlobalUnlock(hPackedDIB);
976 ReleaseDC( 0, hdc );
978 /* Cleanup if GetDIBits failed */
979 if (nLinesCopied != bmp.bmHeight)
981 TRACE("\tGetDIBits returned %d. Actual lines=%d\n", nLinesCopied, bmp.bmHeight);
982 GlobalFree(hPackedDIB);
983 hPackedDIB = 0;
985 return hPackedDIB;
989 /***********************************************************************
990 * uri_to_dos
992 * Converts a text/uri-list URI to DOS filename.
994 static WCHAR* uri_to_dos(char *encodedURI)
996 WCHAR *ret = NULL;
997 int i;
998 int j = 0;
999 char *uri = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, strlen(encodedURI) + 1);
1000 if (uri == NULL)
1001 return NULL;
1002 for (i = 0; encodedURI[i]; ++i)
1004 if (encodedURI[i] == '%')
1006 if (encodedURI[i+1] && encodedURI[i+2])
1008 char buffer[3];
1009 int number;
1010 buffer[0] = encodedURI[i+1];
1011 buffer[1] = encodedURI[i+2];
1012 buffer[2] = '\0';
1013 sscanf(buffer, "%x", &number);
1014 uri[j++] = number;
1015 i += 2;
1017 else
1019 WARN("invalid URI encoding in %s\n", debugstr_a(encodedURI));
1020 HeapFree(GetProcessHeap(), 0, uri);
1021 return NULL;
1024 else
1025 uri[j++] = encodedURI[i];
1028 /* Read http://www.freedesktop.org/wiki/Draganddropwarts and cry... */
1029 if (strncmp(uri, "file:/", 6) == 0)
1031 if (uri[6] == '/')
1033 if (uri[7] == '/')
1035 /* file:///path/to/file (nautilus, thunar) */
1036 ret = wine_get_dos_file_name(&uri[7]);
1038 else if (uri[7])
1040 /* file://hostname/path/to/file (X file drag spec) */
1041 char hostname[256];
1042 char *path = strchr(&uri[7], '/');
1043 if (path)
1045 *path = '\0';
1046 if (strcmp(&uri[7], "localhost") == 0)
1048 *path = '/';
1049 ret = wine_get_dos_file_name(path);
1051 else if (gethostname(hostname, sizeof(hostname)) == 0)
1053 if (strcmp(hostname, &uri[7]) == 0)
1055 *path = '/';
1056 ret = wine_get_dos_file_name(path);
1062 else if (uri[6])
1064 /* file:/path/to/file (konqueror) */
1065 ret = wine_get_dos_file_name(&uri[5]);
1068 HeapFree(GetProcessHeap(), 0, uri);
1069 return ret;
1073 /**************************************************************************
1074 * X11DRV_CLIPBOARD_RenderSynthesizedDIB
1076 * Renders synthesized DIB
1078 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display)
1080 BOOL bret = FALSE;
1081 LPWINE_CLIPDATA lpSource = NULL;
1083 TRACE("\n");
1085 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) && lpSource->hData)
1087 bret = TRUE;
1089 /* If we have a bitmap and it's not synthesized or it has been rendered */
1090 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
1091 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1093 /* Render source if required */
1094 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1096 HGLOBAL hData = create_dib_from_bitmap( lpSource->hData );
1097 if (hData)
1099 X11DRV_CLIPBOARD_InsertClipboardData(CF_DIB, hData, 0, NULL, TRUE);
1100 bret = TRUE;
1105 return bret;
1109 /**************************************************************************
1110 * X11DRV_CLIPBOARD_RenderSynthesizedBitmap
1112 * Renders synthesized bitmap
1114 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display)
1116 BOOL bret = FALSE;
1117 LPWINE_CLIPDATA lpSource = NULL;
1119 TRACE("\n");
1121 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) && lpSource->hData)
1123 bret = TRUE;
1125 /* If we have a dib and it's not synthesized or it has been rendered */
1126 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
1127 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1129 /* Render source if required */
1130 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1132 HDC hdc;
1133 HBITMAP hData = NULL;
1134 unsigned int offset;
1135 LPBITMAPINFOHEADER lpbmih;
1137 hdc = GetDC(NULL);
1138 lpbmih = GlobalLock(lpSource->hData);
1139 if (lpbmih)
1141 offset = sizeof(BITMAPINFOHEADER)
1142 + ((lpbmih->biBitCount <= 8) ? (sizeof(RGBQUAD) *
1143 (1 << lpbmih->biBitCount)) : 0);
1145 hData = CreateDIBitmap(hdc, lpbmih, CBM_INIT, (LPBYTE)lpbmih +
1146 offset, (LPBITMAPINFO) lpbmih, DIB_RGB_COLORS);
1148 GlobalUnlock(lpSource->hData);
1150 ReleaseDC(NULL, hdc);
1152 if (hData)
1154 X11DRV_CLIPBOARD_InsertClipboardData(CF_BITMAP, hData, 0, NULL, TRUE);
1155 bret = TRUE;
1160 return bret;
1164 /**************************************************************************
1165 * X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile
1167 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile(Display *display)
1169 LPWINE_CLIPDATA lpSource = NULL;
1171 TRACE("\n");
1173 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_ENHMETAFILE)) && lpSource->hData)
1174 return TRUE;
1175 /* If we have a MF pict and it's not synthesized or it has been rendered */
1176 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
1177 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1179 /* Render source if required */
1180 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1182 METAFILEPICT *pmfp;
1183 HENHMETAFILE hData = NULL;
1185 pmfp = GlobalLock(lpSource->hData);
1186 if (pmfp)
1188 UINT size_mf_bits = GetMetaFileBitsEx(pmfp->hMF, 0, NULL);
1189 void *mf_bits = HeapAlloc(GetProcessHeap(), 0, size_mf_bits);
1190 if (mf_bits)
1192 GetMetaFileBitsEx(pmfp->hMF, size_mf_bits, mf_bits);
1193 hData = SetWinMetaFileBits(size_mf_bits, mf_bits, NULL, pmfp);
1194 HeapFree(GetProcessHeap(), 0, mf_bits);
1196 GlobalUnlock(lpSource->hData);
1199 if (hData)
1201 X11DRV_CLIPBOARD_InsertClipboardData(CF_ENHMETAFILE, hData, 0, NULL, TRUE);
1202 return TRUE;
1207 return FALSE;
1211 /**************************************************************************
1212 * X11DRV_CLIPBOARD_ImportXAString
1214 * Import XA_STRING, converting the string to CF_TEXT.
1216 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *display, Window w, Atom prop)
1218 LPBYTE lpdata;
1219 unsigned long cbytes;
1220 LPSTR lpstr;
1221 unsigned long i, inlcount = 0;
1222 HANDLE hText = 0;
1224 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1225 return 0;
1227 for (i = 0; i <= cbytes; i++)
1229 if (lpdata[i] == '\n')
1230 inlcount++;
1233 if ((hText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes + inlcount + 1)))
1235 lpstr = GlobalLock(hText);
1237 for (i = 0, inlcount = 0; i <= cbytes; i++)
1239 if (lpdata[i] == '\n')
1240 lpstr[inlcount++] = '\r';
1242 lpstr[inlcount++] = lpdata[i];
1245 GlobalUnlock(hText);
1248 /* Free the retrieved property data */
1249 HeapFree(GetProcessHeap(), 0, lpdata);
1251 return hText;
1255 /**************************************************************************
1256 * X11DRV_CLIPBOARD_ImportUTF8
1258 * Import XA_STRING, converting the string to CF_UNICODE.
1260 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *display, Window w, Atom prop)
1262 LPBYTE lpdata;
1263 unsigned long cbytes;
1264 LPSTR lpstr;
1265 unsigned long i, inlcount = 0;
1266 HANDLE hUnicodeText = 0;
1268 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1269 return 0;
1271 for (i = 0; i <= cbytes; i++)
1273 if (lpdata[i] == '\n')
1274 inlcount++;
1277 if ((lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbytes + inlcount + 1)))
1279 UINT count;
1281 for (i = 0, inlcount = 0; i <= cbytes; i++)
1283 if (lpdata[i] == '\n')
1284 lpstr[inlcount++] = '\r';
1286 lpstr[inlcount++] = lpdata[i];
1289 count = MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, NULL, 0);
1290 hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
1292 if (hUnicodeText)
1294 WCHAR *textW = GlobalLock(hUnicodeText);
1295 MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, textW, count);
1296 GlobalUnlock(hUnicodeText);
1299 HeapFree(GetProcessHeap(), 0, lpstr);
1302 /* Free the retrieved property data */
1303 HeapFree(GetProcessHeap(), 0, lpdata);
1305 return hUnicodeText;
1309 /**************************************************************************
1310 * X11DRV_CLIPBOARD_ImportCompoundText
1312 * Import COMPOUND_TEXT to CF_UNICODE
1314 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *display, Window w, Atom prop)
1316 int i, j, ret;
1317 char** srcstr;
1318 int count, lcount;
1319 int srclen, destlen;
1320 HANDLE hUnicodeText;
1321 XTextProperty txtprop;
1323 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &txtprop.value, &txtprop.nitems))
1325 return 0;
1328 txtprop.encoding = x11drv_atom(COMPOUND_TEXT);
1329 txtprop.format = 8;
1330 ret = XmbTextPropertyToTextList(display, &txtprop, &srcstr, &count);
1331 HeapFree(GetProcessHeap(), 0, txtprop.value);
1332 if (ret != Success || !count) return 0;
1334 TRACE("Importing %d line(s)\n", count);
1336 /* Compute number of lines */
1337 srclen = strlen(srcstr[0]);
1338 for (i = 0, lcount = 0; i <= srclen; i++)
1340 if (srcstr[0][i] == '\n')
1341 lcount++;
1344 destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
1346 TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
1348 if ((hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (destlen + lcount + 1) * sizeof(WCHAR))))
1350 WCHAR *deststr = GlobalLock(hUnicodeText);
1351 MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1353 if (lcount)
1355 for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1357 deststr[j] = deststr[i];
1359 if (deststr[i] == '\n')
1360 deststr[--j] = '\r';
1364 GlobalUnlock(hUnicodeText);
1367 XFreeStringList(srcstr);
1369 return hUnicodeText;
1373 /**************************************************************************
1374 * X11DRV_CLIPBOARD_ImportXAPIXMAP
1376 * Import XA_PIXMAP, converting the image to CF_DIB.
1378 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *display, Window w, Atom prop)
1380 LPBYTE lpdata;
1381 unsigned long cbytes;
1382 Pixmap *pPixmap;
1383 HANDLE hClipData = 0;
1385 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1387 XVisualInfo vis = default_visual;
1388 char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
1389 BITMAPINFO *info = (BITMAPINFO *)buffer;
1390 struct gdi_image_bits bits;
1391 Window root;
1392 int x,y; /* Unused */
1393 unsigned border_width; /* Unused */
1394 unsigned int depth, width, height;
1396 pPixmap = (Pixmap *) lpdata;
1398 /* Get the Pixmap dimensions and bit depth */
1399 if (!XGetGeometry(gdi_display, *pPixmap, &root, &x, &y, &width, &height,
1400 &border_width, &depth)) depth = 0;
1401 if (!pixmap_formats[depth]) return 0;
1403 TRACE("\tPixmap properties: width=%d, height=%d, depth=%d\n",
1404 width, height, depth);
1406 if (depth != vis.depth) switch (pixmap_formats[depth]->bits_per_pixel)
1408 case 1:
1409 case 4:
1410 case 8:
1411 break;
1412 case 16: /* assume R5G5B5 */
1413 vis.red_mask = 0x7c00;
1414 vis.green_mask = 0x03e0;
1415 vis.blue_mask = 0x001f;
1416 break;
1417 case 24: /* assume R8G8B8 */
1418 case 32: /* assume A8R8G8B8 */
1419 vis.red_mask = 0xff0000;
1420 vis.green_mask = 0x00ff00;
1421 vis.blue_mask = 0x0000ff;
1422 break;
1423 default:
1424 return 0;
1427 if (!get_pixmap_image( *pPixmap, width, height, &vis, info, &bits ))
1429 DWORD info_size = bitmap_info_size( info, DIB_RGB_COLORS );
1430 BYTE *ptr;
1432 hClipData = GlobalAlloc( GMEM_MOVEABLE | GMEM_DDESHARE,
1433 info_size + info->bmiHeader.biSizeImage );
1434 if (hClipData)
1436 ptr = GlobalLock( hClipData );
1437 memcpy( ptr, info, info_size );
1438 memcpy( ptr + info_size, bits.ptr, info->bmiHeader.biSizeImage );
1439 GlobalUnlock( hClipData );
1441 if (bits.free) bits.free( &bits );
1444 HeapFree(GetProcessHeap(), 0, lpdata);
1447 return hClipData;
1451 /**************************************************************************
1452 * X11DRV_CLIPBOARD_ImportImageBmp
1454 * Import image/bmp, converting the image to CF_DIB.
1456 static HANDLE X11DRV_CLIPBOARD_ImportImageBmp(Display *display, Window w, Atom prop)
1458 LPBYTE lpdata;
1459 unsigned long cbytes;
1460 HANDLE hClipData = 0;
1462 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1464 BITMAPFILEHEADER *bfh = (BITMAPFILEHEADER*)lpdata;
1466 if (cbytes >= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPCOREHEADER) &&
1467 bfh->bfType == 0x4d42 /* "BM" */)
1469 BITMAPINFO *bmi = (BITMAPINFO*)(bfh+1);
1470 HBITMAP hbmp;
1471 HDC hdc;
1473 hdc = GetDC(0);
1474 hbmp = CreateDIBitmap(
1475 hdc,
1476 &(bmi->bmiHeader),
1477 CBM_INIT,
1478 lpdata+bfh->bfOffBits,
1479 bmi,
1480 DIB_RGB_COLORS
1483 hClipData = create_dib_from_bitmap( hbmp );
1485 DeleteObject(hbmp);
1486 ReleaseDC(0, hdc);
1489 /* Free the retrieved property data */
1490 HeapFree(GetProcessHeap(), 0, lpdata);
1493 return hClipData;
1497 /**************************************************************************
1498 * X11DRV_CLIPBOARD_ImportMetaFilePict
1500 * Import MetaFilePict.
1502 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *display, Window w, Atom prop)
1504 LPBYTE lpdata;
1505 unsigned long cbytes;
1506 HANDLE hClipData = 0;
1508 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1510 if (cbytes)
1511 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata, (LPDWORD)&cbytes, FALSE);
1513 /* Free the retrieved property data */
1514 HeapFree(GetProcessHeap(), 0, lpdata);
1517 return hClipData;
1521 /**************************************************************************
1522 * X11DRV_ImportEnhMetaFile
1524 * Import EnhMetaFile.
1526 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *display, Window w, Atom prop)
1528 LPBYTE lpdata;
1529 unsigned long cbytes;
1530 HANDLE hClipData = 0;
1532 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1534 if (cbytes)
1535 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata, (LPDWORD)&cbytes, FALSE);
1537 /* Free the retrieved property data */
1538 HeapFree(GetProcessHeap(), 0, lpdata);
1541 return hClipData;
1545 /**************************************************************************
1546 * X11DRV_CLIPBOARD_ImportTextUriList
1548 * Import text/uri-list.
1550 static HANDLE X11DRV_CLIPBOARD_ImportTextUriList(Display *display, Window w, Atom prop)
1552 char *uriList;
1553 unsigned long len;
1554 char *uri;
1555 WCHAR *path;
1556 WCHAR *out = NULL;
1557 int size = 0;
1558 int capacity = 4096;
1559 int start = 0;
1560 int end = 0;
1561 HANDLE handle = NULL;
1563 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, (LPBYTE*)&uriList, &len))
1564 return 0;
1566 out = HeapAlloc(GetProcessHeap(), 0, capacity * sizeof(WCHAR));
1567 if (out == NULL) {
1568 HeapFree(GetProcessHeap(), 0, uriList);
1569 return 0;
1572 while (end < len)
1574 while (end < len && uriList[end] != '\r')
1575 ++end;
1576 if (end < (len - 1) && uriList[end+1] != '\n')
1578 WARN("URI list line doesn't end in \\r\\n\n");
1579 break;
1582 uri = HeapAlloc(GetProcessHeap(), 0, end - start + 1);
1583 if (uri == NULL)
1584 break;
1585 lstrcpynA(uri, &uriList[start], end - start + 1);
1586 path = uri_to_dos(uri);
1587 TRACE("converted URI %s to DOS path %s\n", debugstr_a(uri), debugstr_w(path));
1588 HeapFree(GetProcessHeap(), 0, uri);
1590 if (path)
1592 int pathSize = strlenW(path) + 1;
1593 if (pathSize > capacity-size)
1595 capacity = 2*capacity + pathSize;
1596 out = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, out, (capacity + 1)*sizeof(WCHAR));
1597 if (out == NULL)
1598 goto done;
1600 memcpy(&out[size], path, pathSize * sizeof(WCHAR));
1601 size += pathSize;
1602 done:
1603 HeapFree(GetProcessHeap(), 0, path);
1604 if (out == NULL)
1605 break;
1608 start = end + 2;
1609 end = start;
1611 if (out && end >= len)
1613 DROPFILES *dropFiles;
1614 handle = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, sizeof(DROPFILES) + (size + 1)*sizeof(WCHAR));
1615 if (handle)
1617 dropFiles = (DROPFILES*) GlobalLock(handle);
1618 dropFiles->pFiles = sizeof(DROPFILES);
1619 dropFiles->pt.x = 0;
1620 dropFiles->pt.y = 0;
1621 dropFiles->fNC = 0;
1622 dropFiles->fWide = TRUE;
1623 out[size] = '\0';
1624 memcpy(((char*)dropFiles) + dropFiles->pFiles, out, (size + 1)*sizeof(WCHAR));
1625 GlobalUnlock(handle);
1628 HeapFree(GetProcessHeap(), 0, out);
1629 HeapFree(GetProcessHeap(), 0, uriList);
1630 return handle;
1634 /**************************************************************************
1635 * X11DRV_ImportClipbordaData
1637 * Generic import clipboard data routine.
1639 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *display, Window w, Atom prop)
1641 LPVOID lpClipData;
1642 LPBYTE lpdata;
1643 unsigned long cbytes;
1644 HANDLE hClipData = 0;
1646 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1648 if (cbytes)
1650 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
1651 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes);
1652 if (hClipData == 0)
1654 HeapFree(GetProcessHeap(), 0, lpdata);
1655 return NULL;
1658 if ((lpClipData = GlobalLock(hClipData)))
1660 memcpy(lpClipData, lpdata, cbytes);
1661 GlobalUnlock(hClipData);
1663 else
1665 GlobalFree(hClipData);
1666 hClipData = 0;
1670 /* Free the retrieved property data */
1671 HeapFree(GetProcessHeap(), 0, lpdata);
1674 return hClipData;
1677 /**************************************************************************
1678 * X11DRV_CLIPBOARD_ImportSelection
1680 * Import the X selection into the clipboard format registered for the given X target.
1682 HANDLE X11DRV_CLIPBOARD_ImportSelection(Display *d, Atom target, Window w, Atom prop, UINT *windowsFormat)
1684 WINE_CLIPFORMAT *clipFormat;
1686 clipFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, target);
1687 if (clipFormat)
1689 *windowsFormat = clipFormat->wFormatID;
1690 return clipFormat->lpDrvImportFunc(d, w, prop);
1692 return NULL;
1696 /**************************************************************************
1697 X11DRV_CLIPBOARD_ExportClipboardData
1699 * Generic export clipboard data routine.
1701 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
1702 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1704 LPVOID lpClipData;
1705 UINT datasize = 0;
1706 HANDLE hClipData = 0;
1708 *lpBytes = 0; /* Assume failure */
1710 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1711 ERR("Failed to export %04x format\n", lpData->wFormatID);
1712 else
1714 datasize = GlobalSize(lpData->hData);
1716 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, datasize);
1717 if (hClipData == 0) return NULL;
1719 if ((lpClipData = GlobalLock(hClipData)))
1721 LPVOID lpdata = GlobalLock(lpData->hData);
1723 memcpy(lpClipData, lpdata, datasize);
1724 *lpBytes = datasize;
1726 GlobalUnlock(lpData->hData);
1727 GlobalUnlock(hClipData);
1728 } else {
1729 GlobalFree(hClipData);
1730 hClipData = 0;
1734 return hClipData;
1738 /**************************************************************************
1739 * X11DRV_CLIPBOARD_ExportXAString
1741 * Export CF_TEXT converting the string to XA_STRING.
1742 * Helper function for X11DRV_CLIPBOARD_ExportString.
1744 static HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1746 UINT i, j;
1747 UINT size;
1748 LPSTR text, lpstr = NULL;
1750 *lpBytes = 0; /* Assume return has zero bytes */
1752 text = GlobalLock(lpData->hData);
1753 size = strlen(text);
1755 /* remove carriage returns */
1756 lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1757 if (lpstr == NULL)
1758 goto done;
1760 for (i = 0,j = 0; i < size && text[i]; i++)
1762 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1763 continue;
1764 lpstr[j++] = text[i];
1767 lpstr[j]='\0';
1768 *lpBytes = j; /* Number of bytes in string */
1770 done:
1771 GlobalUnlock(lpData->hData);
1773 return lpstr;
1777 /**************************************************************************
1778 * X11DRV_CLIPBOARD_ExportUTF8String
1780 * Export CF_UNICODE converting the string to UTF8.
1781 * Helper function for X11DRV_CLIPBOARD_ExportString.
1783 static HANDLE X11DRV_CLIPBOARD_ExportUTF8String(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1785 UINT i, j;
1786 UINT size;
1787 LPWSTR uni_text;
1788 LPSTR text, lpstr = NULL;
1790 *lpBytes = 0; /* Assume return has zero bytes */
1792 uni_text = GlobalLock(lpData->hData);
1794 size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1796 text = HeapAlloc(GetProcessHeap(), 0, size);
1797 if (!text)
1798 goto done;
1799 WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1801 /* remove carriage returns */
1802 lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1803 if (lpstr == NULL)
1804 goto done;
1806 for (i = 0,j = 0; i < size && text[i]; i++)
1808 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1809 continue;
1810 lpstr[j++] = text[i];
1812 lpstr[j]='\0';
1814 *lpBytes = j; /* Number of bytes in string */
1816 done:
1817 HeapFree(GetProcessHeap(), 0, text);
1818 GlobalUnlock(lpData->hData);
1820 return lpstr;
1825 /**************************************************************************
1826 * X11DRV_CLIPBOARD_ExportCompoundText
1828 * Export CF_UNICODE to COMPOUND_TEXT
1829 * Helper function for X11DRV_CLIPBOARD_ExportString.
1831 static HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Display *display, Window requestor, Atom aTarget, Atom rprop,
1832 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1834 char* lpstr = 0;
1835 XTextProperty prop;
1836 XICCEncodingStyle style;
1837 UINT i, j;
1838 UINT size;
1839 LPWSTR uni_text;
1841 uni_text = GlobalLock(lpData->hData);
1843 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1844 lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1845 if (!lpstr)
1846 return 0;
1848 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1850 /* remove carriage returns */
1851 for (i = 0, j = 0; i < size && lpstr[i]; i++)
1853 if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1854 continue;
1855 lpstr[j++] = lpstr[i];
1857 lpstr[j]='\0';
1859 GlobalUnlock(lpData->hData);
1861 if (aTarget == x11drv_atom(COMPOUND_TEXT))
1862 style = XCompoundTextStyle;
1863 else
1864 style = XStdICCTextStyle;
1866 /* Update the X property */
1867 if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1869 XSetTextProperty(display, requestor, &prop, rprop);
1870 XFree(prop.value);
1873 HeapFree(GetProcessHeap(), 0, lpstr);
1875 return 0;
1878 /**************************************************************************
1879 * X11DRV_CLIPBOARD_ExportString
1881 * Export string
1883 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget, Atom rprop,
1884 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1886 if (X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1888 if (aTarget == XA_STRING)
1889 return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1890 else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1891 return X11DRV_CLIPBOARD_ExportCompoundText(display, requestor, aTarget,
1892 rprop, lpData, lpBytes);
1893 else
1895 TRACE("Exporting target %ld to default UTF8_STRING\n", aTarget);
1896 return X11DRV_CLIPBOARD_ExportUTF8String(lpData, lpBytes);
1899 else
1900 ERR("Failed to render %04x format\n", lpData->wFormatID);
1902 return 0;
1906 /**************************************************************************
1907 * X11DRV_CLIPBOARD_ExportXAPIXMAP
1909 * Export CF_DIB to XA_PIXMAP.
1911 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget, Atom rprop,
1912 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1914 HANDLE hData;
1915 unsigned char* lpData;
1917 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1919 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1920 return 0;
1923 if (!lpdata->drvData) /* If not already rendered */
1925 Pixmap pixmap;
1926 LPBITMAPINFO pbmi;
1927 struct gdi_image_bits bits;
1929 pbmi = GlobalLock( lpdata->hData );
1930 bits.ptr = (LPBYTE)pbmi + bitmap_info_size( pbmi, DIB_RGB_COLORS );
1931 bits.free = NULL;
1932 bits.is_copy = FALSE;
1933 pixmap = create_pixmap_from_image( 0, &default_visual, pbmi, &bits, DIB_RGB_COLORS );
1934 GlobalUnlock( lpdata->hData );
1935 lpdata->drvData = pixmap;
1938 *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1940 /* Wrap pixmap so we can return a handle */
1941 hData = GlobalAlloc(0, *lpBytes);
1942 lpData = GlobalLock(hData);
1943 memcpy(lpData, &lpdata->drvData, *lpBytes);
1944 GlobalUnlock(hData);
1946 return hData;
1950 /**************************************************************************
1951 * X11DRV_CLIPBOARD_ExportImageBmp
1953 * Export CF_DIB to image/bmp.
1955 static HANDLE X11DRV_CLIPBOARD_ExportImageBmp(Display *display, Window requestor, Atom aTarget, Atom rprop,
1956 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1958 HANDLE hpackeddib;
1959 LPBYTE dibdata;
1960 UINT bmpsize;
1961 HANDLE hbmpdata;
1962 LPBYTE bmpdata;
1963 BITMAPFILEHEADER *bfh;
1965 *lpBytes = 0;
1967 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1969 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1970 return 0;
1973 hpackeddib = lpdata->hData;
1975 dibdata = GlobalLock(hpackeddib);
1976 if (!dibdata)
1978 ERR("Failed to lock packed DIB\n");
1979 return 0;
1982 bmpsize = sizeof(BITMAPFILEHEADER) + GlobalSize(hpackeddib);
1984 hbmpdata = GlobalAlloc(0, bmpsize);
1986 if (hbmpdata)
1988 bmpdata = GlobalLock(hbmpdata);
1990 if (!bmpdata)
1992 GlobalFree(hbmpdata);
1993 GlobalUnlock(hpackeddib);
1994 return 0;
1997 /* bitmap file header */
1998 bfh = (BITMAPFILEHEADER*)bmpdata;
1999 bfh->bfType = 0x4d42; /* "BM" */
2000 bfh->bfSize = bmpsize;
2001 bfh->bfReserved1 = 0;
2002 bfh->bfReserved2 = 0;
2003 bfh->bfOffBits = sizeof(BITMAPFILEHEADER) + bitmap_info_size((BITMAPINFO*)dibdata, DIB_RGB_COLORS);
2005 /* rest of bitmap is the same as the packed dib */
2006 memcpy(bfh+1, dibdata, bmpsize-sizeof(BITMAPFILEHEADER));
2008 *lpBytes = bmpsize;
2010 GlobalUnlock(hbmpdata);
2013 GlobalUnlock(hpackeddib);
2015 return hbmpdata;
2019 /**************************************************************************
2020 * X11DRV_CLIPBOARD_ExportMetaFilePict
2022 * Export MetaFilePict.
2024 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget, Atom rprop,
2025 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
2027 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
2029 ERR("Failed to export %04x format\n", lpdata->wFormatID);
2030 return 0;
2033 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata->hData, lpBytes, TRUE);
2037 /**************************************************************************
2038 * X11DRV_CLIPBOARD_ExportEnhMetaFile
2040 * Export EnhMetaFile.
2042 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget, Atom rprop,
2043 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
2045 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
2047 ERR("Failed to export %04x format\n", lpdata->wFormatID);
2048 return 0;
2051 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata->hData, lpBytes, TRUE);
2055 /**************************************************************************
2056 * get_html_description_field
2058 * Find the value of a field in an HTML Format description.
2060 static LPCSTR get_html_description_field(LPCSTR data, LPCSTR keyword)
2062 LPCSTR pos=data;
2064 while (pos && *pos && *pos != '<')
2066 if (memcmp(pos, keyword, strlen(keyword)) == 0)
2067 return pos+strlen(keyword);
2069 pos = strchr(pos, '\n');
2070 if (pos) pos++;
2073 return NULL;
2077 /**************************************************************************
2078 * X11DRV_CLIPBOARD_ExportTextHtml
2080 * Export HTML Format to text/html.
2082 * FIXME: We should attempt to add an <a base> tag and convert windows paths.
2084 static HANDLE X11DRV_CLIPBOARD_ExportTextHtml(Display *display, Window requestor, Atom aTarget,
2085 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
2087 HANDLE hdata;
2088 LPCSTR data, field_value;
2089 UINT fragmentstart, fragmentend, htmlsize;
2090 HANDLE hhtmldata=NULL;
2091 LPSTR htmldata;
2093 *lpBytes = 0;
2095 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
2097 ERR("Failed to export %04x format\n", lpdata->wFormatID);
2098 return 0;
2101 hdata = lpdata->hData;
2103 data = GlobalLock(hdata);
2104 if (!data)
2106 ERR("Failed to lock HTML Format data\n");
2107 return 0;
2110 /* read the important fields */
2111 field_value = get_html_description_field(data, "StartFragment:");
2112 if (!field_value)
2114 ERR("Couldn't find StartFragment value\n");
2115 goto end;
2117 fragmentstart = atoi(field_value);
2119 field_value = get_html_description_field(data, "EndFragment:");
2120 if (!field_value)
2122 ERR("Couldn't find EndFragment value\n");
2123 goto end;
2125 fragmentend = atoi(field_value);
2127 /* export only the fragment */
2128 htmlsize = fragmentend - fragmentstart + 1;
2130 hhtmldata = GlobalAlloc(0, htmlsize);
2132 if (hhtmldata)
2134 htmldata = GlobalLock(hhtmldata);
2136 if (!htmldata)
2138 GlobalFree(hhtmldata);
2139 htmldata = NULL;
2140 goto end;
2143 memcpy(htmldata, &data[fragmentstart], fragmentend-fragmentstart);
2144 htmldata[htmlsize-1] = '\0';
2146 *lpBytes = htmlsize;
2148 GlobalUnlock(htmldata);
2151 end:
2153 GlobalUnlock(hdata);
2155 return hhtmldata;
2159 /**************************************************************************
2160 * X11DRV_CLIPBOARD_ExportHDROP
2162 * Export CF_HDROP format to text/uri-list.
2164 static HANDLE X11DRV_CLIPBOARD_ExportHDROP(Display *display, Window requestor, Atom aTarget,
2165 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
2167 HDROP hDrop;
2168 UINT i;
2169 UINT numFiles;
2170 HGLOBAL hClipData = NULL;
2171 char *textUriList = NULL;
2172 UINT textUriListSize = 32;
2173 UINT next = 0;
2175 *lpBytes = 0;
2177 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
2179 ERR("Failed to export %04x format\n", lpdata->wFormatID);
2180 return 0;
2182 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, textUriListSize);
2183 if (hClipData == NULL)
2184 return 0;
2185 hDrop = (HDROP) lpdata->hData;
2186 numFiles = DragQueryFileW(hDrop, 0xFFFFFFFF, NULL, 0);
2187 for (i = 0; i < numFiles; i++)
2189 UINT dosFilenameSize;
2190 WCHAR *dosFilename = NULL;
2191 char *unixFilename = NULL;
2192 UINT uriSize;
2193 UINT u;
2195 dosFilenameSize = 1 + DragQueryFileW(hDrop, i, NULL, 0);
2196 dosFilename = HeapAlloc(GetProcessHeap(), 0, dosFilenameSize*sizeof(WCHAR));
2197 if (dosFilename == NULL) goto failed;
2198 DragQueryFileW(hDrop, i, dosFilename, dosFilenameSize);
2199 unixFilename = wine_get_unix_file_name(dosFilename);
2200 HeapFree(GetProcessHeap(), 0, dosFilename);
2201 if (unixFilename == NULL) goto failed;
2202 uriSize = 8 + /* file:/// */
2203 3 * (lstrlenA(unixFilename) - 1) + /* "%xy" per char except first '/' */
2204 2; /* \r\n */
2205 if ((next + uriSize) > textUriListSize)
2207 UINT biggerSize = max( 2 * textUriListSize, next + uriSize );
2208 HGLOBAL bigger = GlobalReAlloc(hClipData, biggerSize, 0);
2209 if (bigger)
2211 hClipData = bigger;
2212 textUriListSize = biggerSize;
2214 else
2216 HeapFree(GetProcessHeap(), 0, unixFilename);
2217 goto failed;
2220 textUriList = GlobalLock(hClipData);
2221 lstrcpyA(&textUriList[next], "file:///");
2222 next += 8;
2223 /* URL encode everything - unnecessary, but easier/lighter than linking in shlwapi, and can't hurt */
2224 for (u = 1; unixFilename[u]; u++)
2226 static const char hex_table[] = "0123456789abcdef";
2227 textUriList[next++] = '%';
2228 textUriList[next++] = hex_table[unixFilename[u] >> 4];
2229 textUriList[next++] = hex_table[unixFilename[u] & 0xf];
2231 textUriList[next++] = '\r';
2232 textUriList[next++] = '\n';
2233 GlobalUnlock(hClipData);
2234 HeapFree(GetProcessHeap(), 0, unixFilename);
2237 *lpBytes = next;
2238 return hClipData;
2240 failed:
2241 GlobalFree(hClipData);
2242 *lpBytes = 0;
2243 return 0;
2247 /**************************************************************************
2248 * X11DRV_CLIPBOARD_QueryTargets
2250 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection,
2251 Atom target, XEvent *xe)
2253 INT i;
2255 XConvertSelection(display, selection, target, x11drv_atom(SELECTION_DATA), w, CurrentTime);
2258 * Wait until SelectionNotify is received
2260 for (i = 0; i < SELECTION_RETRIES; i++)
2262 Bool res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
2263 if (res && xe->xselection.selection == selection) break;
2265 usleep(SELECTION_WAIT);
2268 if (i == SELECTION_RETRIES)
2270 ERR("Timed out waiting for SelectionNotify event\n");
2271 return FALSE;
2273 /* Verify that the selection returned a valid TARGETS property */
2274 if ((xe->xselection.target != target) || (xe->xselection.property == None))
2276 /* Selection owner failed to respond or we missed the SelectionNotify */
2277 WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
2278 return FALSE;
2281 return TRUE;
2285 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
2287 return (event->error_code == BadAtom);
2290 /**************************************************************************
2291 * X11DRV_CLIPBOARD_InsertSelectionProperties
2293 * Mark properties available for future retrieval.
2295 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
2297 UINT i, nb_atoms = 0;
2298 Atom *atoms = NULL;
2300 /* Cache these formats in the clipboard cache */
2301 for (i = 0; i < count; i++)
2303 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
2305 if (lpFormat)
2307 /* We found at least one Window's format that mapps to the property.
2308 * Continue looking for more.
2310 * If more than one property map to a Window's format then we use the first
2311 * one and ignore the rest.
2313 while (lpFormat)
2315 TRACE("Atom#%d Property(%d): --> Format %s\n",
2316 i, lpFormat->drvData, debugstr_format(lpFormat->wFormatID));
2317 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, lpFormat, FALSE);
2318 lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
2321 else if (properties[i])
2323 /* add it to the list of atoms that we don't know about yet */
2324 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
2325 (count - i) * sizeof(*atoms) );
2326 if (atoms) atoms[nb_atoms++] = properties[i];
2330 /* query all unknown atoms in one go */
2331 if (atoms)
2333 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
2334 if (names)
2336 X11DRV_expect_error( display, is_atom_error, NULL );
2337 if (!XGetAtomNames( display, atoms, nb_atoms, names )) nb_atoms = 0;
2338 if (X11DRV_check_error())
2340 WARN( "got some bad atoms, ignoring\n" );
2341 nb_atoms = 0;
2343 for (i = 0; i < nb_atoms; i++)
2345 WINE_CLIPFORMAT *lpFormat;
2346 LPWSTR wname;
2347 int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
2348 wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2349 MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
2351 lpFormat = register_format( RegisterClipboardFormatW(wname), atoms[i] );
2352 HeapFree(GetProcessHeap(), 0, wname);
2353 if (!lpFormat)
2355 ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
2356 continue;
2358 TRACE("Atom#%d Property(%d): --> Format %s\n",
2359 i, lpFormat->drvData, debugstr_format(lpFormat->wFormatID));
2360 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, lpFormat, FALSE);
2362 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
2363 HeapFree( GetProcessHeap(), 0, names );
2365 HeapFree( GetProcessHeap(), 0, atoms );
2370 /**************************************************************************
2371 * X11DRV_CLIPBOARD_QueryAvailableData
2373 * Caches the list of data formats available from the current selection.
2374 * This queries the selection owner for the TARGETS property and saves all
2375 * reported property types.
2377 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display)
2379 XEvent xe;
2380 Atom atype=AnyPropertyType;
2381 int aformat;
2382 unsigned long remain;
2383 Atom* targetList=NULL;
2384 Window w;
2385 unsigned long cSelectionTargets = 0;
2387 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
2389 ERR("Received request to cache selection but process is owner=(%08x)\n",
2390 (unsigned) selectionWindow);
2391 return -1; /* Prevent self request */
2394 w = thread_selection_wnd();
2395 if (!w)
2397 ERR("No window available to retrieve selection!\n");
2398 return -1;
2402 * Query the selection owner for the TARGETS property
2404 if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
2405 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2407 if (use_primary_selection && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
2408 selectionCacheSrc = XA_PRIMARY;
2409 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
2410 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2411 else
2413 Atom xstr = XA_STRING;
2415 /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
2416 if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
2418 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2419 selectionCacheSrc = XA_PRIMARY;
2420 return 1;
2422 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
2424 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2425 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2426 return 1;
2428 else
2430 WARN("Failed to query selection owner for available data.\n");
2431 return -1;
2435 else return 0; /* No selection owner so report 0 targets available */
2437 /* Read the TARGETS property contents */
2438 if (!XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
2439 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
2440 &remain, (unsigned char**)&targetList) != Success)
2442 TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
2443 atype, aformat, cSelectionTargets, remain);
2445 * The TARGETS property should have returned us a list of atoms
2446 * corresponding to each selection target format supported.
2448 if (atype == XA_ATOM || atype == x11drv_atom(TARGETS))
2450 if (aformat == 32)
2452 X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, cSelectionTargets);
2454 else if (aformat == 8) /* work around quartz-wm brain damage */
2456 unsigned long i, count = cSelectionTargets / sizeof(CARD32);
2457 Atom *atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(Atom) );
2458 for (i = 0; i < count; i++)
2459 atoms[i] = ((CARD32 *)targetList)[i]; /* FIXME: byte swapping */
2460 X11DRV_CLIPBOARD_InsertSelectionProperties( display, atoms, count );
2461 HeapFree( GetProcessHeap(), 0, atoms );
2465 /* Free the list of targets */
2466 XFree(targetList);
2468 else WARN("Failed to read TARGETS property\n");
2470 return cSelectionTargets;
2474 /**************************************************************************
2475 * X11DRV_CLIPBOARD_ReadSelectionData
2477 * This method is invoked only when we DO NOT own the X selection
2479 * We always get the data from the selection client each time,
2480 * since we have no way of determining if the data in our cache is stale.
2482 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData)
2484 Bool res;
2485 DWORD i;
2486 XEvent xe;
2487 BOOL bRet = FALSE;
2489 TRACE("%04x\n", lpData->wFormatID);
2491 if (!lpData->lpFormat)
2493 ERR("Requesting format %04x but no source format linked to data.\n",
2494 lpData->wFormatID);
2495 return FALSE;
2498 if (!selectionAcquired)
2500 Window w = thread_selection_wnd();
2501 if(!w)
2503 ERR("No window available to read selection data!\n");
2504 return FALSE;
2507 TRACE("Requesting conversion of %s property (%d) from selection type %08x\n",
2508 debugstr_format(lpData->lpFormat->wFormatID), lpData->lpFormat->drvData,
2509 (UINT)selectionCacheSrc);
2511 XConvertSelection(display, selectionCacheSrc, lpData->lpFormat->drvData,
2512 x11drv_atom(SELECTION_DATA), w, CurrentTime);
2514 /* wait until SelectionNotify is received */
2515 for (i = 0; i < SELECTION_RETRIES; i++)
2517 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
2518 if (res && xe.xselection.selection == selectionCacheSrc) break;
2520 usleep(SELECTION_WAIT);
2523 if (i == SELECTION_RETRIES)
2525 ERR("Timed out waiting for SelectionNotify event\n");
2527 /* Verify that the selection returned a valid TARGETS property */
2528 else if (xe.xselection.property != None)
2531 * Read the contents of the X selection property
2532 * into WINE's clipboard cache and converting the
2533 * data format if necessary.
2535 HANDLE hData = lpData->lpFormat->lpDrvImportFunc(display, xe.xselection.requestor,
2536 xe.xselection.property);
2538 if (hData)
2539 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, hData, 0, lpData->lpFormat, TRUE);
2540 else
2541 TRACE("Import function failed\n");
2543 else
2545 TRACE("Failed to convert selection\n");
2548 else
2550 ERR("Received request to cache selection data but process is owner\n");
2553 TRACE("Returning %d\n", bRet);
2555 return bRet;
2559 /**************************************************************************
2560 * X11DRV_CLIPBOARD_GetProperty
2561 * Gets type, data and size.
2563 static BOOL X11DRV_CLIPBOARD_GetProperty(Display *display, Window w, Atom prop,
2564 Atom *atype, unsigned char** data, unsigned long* datasize)
2566 int aformat;
2567 unsigned long pos = 0, nitems, remain, count;
2568 unsigned char *val = NULL, *buffer;
2570 TRACE("Reading property %lu from X window %lx\n", prop, w);
2572 for (;;)
2574 if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
2575 AnyPropertyType, atype, &aformat, &nitems, &remain, &buffer) != Success)
2577 WARN("Failed to read property\n");
2578 HeapFree( GetProcessHeap(), 0, val );
2579 return FALSE;
2582 count = get_property_size( aformat, nitems );
2583 if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
2584 else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
2586 if (!*data)
2588 XFree( buffer );
2589 HeapFree( GetProcessHeap(), 0, val );
2590 return FALSE;
2592 val = *data;
2593 memcpy( (int *)val + pos, buffer, count );
2594 XFree( buffer );
2595 if (!remain)
2597 *datasize = pos * sizeof(int) + count;
2598 val[*datasize] = 0;
2599 break;
2601 pos += count / sizeof(int);
2604 /* Delete the property on the window now that we are done
2605 * This will send a PropertyNotify event to the selection owner. */
2606 XDeleteProperty(display, w, prop);
2607 return TRUE;
2611 struct clipboard_data_packet {
2612 struct list entry;
2613 unsigned long size;
2614 unsigned char *data;
2617 /**************************************************************************
2618 * X11DRV_CLIPBOARD_ReadProperty
2619 * Reads the contents of the X selection property.
2621 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
2622 unsigned char** data, unsigned long* datasize)
2624 Atom atype;
2625 XEvent xe;
2627 if (prop == None)
2628 return FALSE;
2630 while (XCheckTypedWindowEvent(display, w, PropertyNotify, &xe))
2633 if (!X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, data, datasize))
2634 return FALSE;
2636 if (atype == x11drv_atom(INCR))
2638 unsigned char *buf;
2639 unsigned long bufsize = 0;
2640 struct list packets;
2641 struct clipboard_data_packet *packet, *packet2;
2642 BOOL res;
2644 HeapFree(GetProcessHeap(), 0, *data);
2645 *data = NULL;
2647 list_init(&packets);
2649 for (;;)
2651 int i;
2652 unsigned char *prop_data;
2653 unsigned long prop_size;
2655 /* Wait until PropertyNotify is received */
2656 for (i = 0; i < SELECTION_RETRIES; i++)
2658 Bool res;
2660 res = XCheckTypedWindowEvent(display, w, PropertyNotify, &xe);
2661 if (res && xe.xproperty.atom == prop &&
2662 xe.xproperty.state == PropertyNewValue)
2663 break;
2664 usleep(SELECTION_WAIT);
2667 if (i >= SELECTION_RETRIES ||
2668 !X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, &prop_data, &prop_size))
2670 res = FALSE;
2671 break;
2674 /* Retrieved entire data. */
2675 if (prop_size == 0)
2677 HeapFree(GetProcessHeap(), 0, prop_data);
2678 res = TRUE;
2679 break;
2682 packet = HeapAlloc(GetProcessHeap(), 0, sizeof(*packet));
2683 if (!packet)
2685 HeapFree(GetProcessHeap(), 0, prop_data);
2686 res = FALSE;
2687 break;
2690 packet->size = prop_size;
2691 packet->data = prop_data;
2692 list_add_tail(&packets, &packet->entry);
2693 bufsize += prop_size;
2696 if (res)
2698 buf = HeapAlloc(GetProcessHeap(), 0, bufsize + 1);
2699 if (buf)
2701 unsigned long bytes_copied = 0;
2702 *datasize = bufsize;
2703 LIST_FOR_EACH_ENTRY( packet, &packets, struct clipboard_data_packet, entry)
2705 memcpy(&buf[bytes_copied], packet->data, packet->size);
2706 bytes_copied += packet->size;
2708 buf[bufsize] = 0;
2709 *data = buf;
2711 else
2712 res = FALSE;
2715 LIST_FOR_EACH_ENTRY_SAFE( packet, packet2, &packets, struct clipboard_data_packet, entry)
2717 HeapFree(GetProcessHeap(), 0, packet->data);
2718 HeapFree(GetProcessHeap(), 0, packet);
2721 return res;
2724 return TRUE;
2728 /**************************************************************************
2729 * CLIPBOARD_SerializeMetafile
2731 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
2733 HANDLE h = 0;
2735 TRACE(" wFormat=%d hdata=%p out=%d\n", wformat, hdata, out);
2737 if (out) /* Serialize out, caller should free memory */
2739 *lpcbytes = 0; /* Assume failure */
2741 if (wformat == CF_METAFILEPICT)
2743 LPMETAFILEPICT lpmfp = GlobalLock(hdata);
2744 unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2746 h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
2747 if (h)
2749 char *pdata = GlobalLock(h);
2751 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
2752 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
2754 *lpcbytes = size + sizeof(METAFILEPICT);
2756 GlobalUnlock(h);
2759 GlobalUnlock(hdata);
2761 else if (wformat == CF_ENHMETAFILE)
2763 int size = GetEnhMetaFileBits(hdata, 0, NULL);
2765 h = GlobalAlloc(0, size);
2766 if (h)
2768 LPVOID pdata = GlobalLock(h);
2770 GetEnhMetaFileBits(hdata, size, pdata);
2771 *lpcbytes = size;
2773 GlobalUnlock(h);
2777 else
2779 if (wformat == CF_METAFILEPICT)
2781 h = GlobalAlloc(0, sizeof(METAFILEPICT));
2782 if (h)
2784 unsigned int wiresize;
2785 LPMETAFILEPICT lpmfp = GlobalLock(h);
2787 memcpy(lpmfp, hdata, sizeof(METAFILEPICT));
2788 wiresize = *lpcbytes - sizeof(METAFILEPICT);
2789 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
2790 ((const BYTE *)hdata) + sizeof(METAFILEPICT));
2791 GlobalUnlock(h);
2794 else if (wformat == CF_ENHMETAFILE)
2796 h = SetEnhMetaFileBits(*lpcbytes, hdata);
2800 return h;
2804 /**************************************************************************
2805 * X11DRV_CLIPBOARD_ReleaseSelection
2807 * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
2809 static void X11DRV_CLIPBOARD_ReleaseSelection(Display *display, Atom selType, Window w, HWND hwnd, Time time)
2811 /* w is the window that lost the selection
2813 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
2814 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
2816 if (selectionAcquired && (w == selectionWindow))
2818 HWND owner;
2820 /* completely give up the selection */
2821 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
2823 if (X11DRV_CLIPBOARD_IsProcessOwner( &owner ))
2825 /* Since we're still the owner, this wasn't initiated by
2826 another Wine process */
2827 if (OpenClipboard(hwnd))
2829 /* Destroy private objects */
2830 SendMessageW(owner, WM_DESTROYCLIPBOARD, 0, 0);
2832 /* Give up ownership of the windows clipboard */
2833 X11DRV_CLIPBOARD_ReleaseOwnership();
2834 CloseClipboard();
2838 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2840 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2842 if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2844 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2845 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2847 else
2848 TRACE("We no longer own PRIMARY\n");
2850 else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2852 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2854 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2856 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2857 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2859 else
2860 TRACE("We no longer own CLIPBOARD\n");
2863 selectionWindow = None;
2865 empty_clipboard( FALSE );
2867 /* Reset the selection flags now that we are done */
2868 selectionAcquired = S_NOSELECTION;
2873 /**************************************************************************
2874 * X11DRV Clipboard Exports
2875 **************************************************************************/
2878 static void selection_acquire(void)
2880 Window owner;
2881 Display *display;
2883 owner = thread_selection_wnd();
2884 display = thread_display();
2886 selectionAcquired = 0;
2887 selectionWindow = 0;
2889 /* Grab PRIMARY selection if not owned */
2890 if (use_primary_selection)
2891 XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2893 /* Grab CLIPBOARD selection if not owned */
2894 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2896 if (use_primary_selection && XGetSelectionOwner(display, XA_PRIMARY) == owner)
2897 selectionAcquired |= S_PRIMARY;
2899 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2900 selectionAcquired |= S_CLIPBOARD;
2902 if (selectionAcquired)
2904 selectionWindow = owner;
2905 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2909 static DWORD WINAPI selection_thread_proc(LPVOID p)
2911 HANDLE event = p;
2913 TRACE("\n");
2915 selection_acquire();
2916 SetEvent(event);
2918 while (selectionAcquired)
2920 MsgWaitForMultipleObjectsEx(0, NULL, INFINITE, QS_SENDMESSAGE, 0);
2923 return 0;
2926 /**************************************************************************
2927 * X11DRV_AcquireClipboard
2929 void X11DRV_AcquireClipboard(HWND hWndClipWindow)
2931 DWORD procid;
2932 HANDLE selectionThread;
2934 TRACE(" %p\n", hWndClipWindow);
2937 * It's important that the selection get acquired from the thread
2938 * that owns the clipboard window. The primary reason is that we know
2939 * it is running a message loop and therefore can process the
2940 * X selection events.
2942 if (hWndClipWindow &&
2943 GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, &procid))
2945 if (procid != GetCurrentProcessId())
2947 WARN("Setting clipboard owner to other process is not supported\n");
2948 hWndClipWindow = NULL;
2950 else
2952 TRACE("Thread %x is acquiring selection with thread %x's window %p\n",
2953 GetCurrentThreadId(),
2954 GetWindowThreadProcessId(hWndClipWindow, NULL), hWndClipWindow);
2956 SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0);
2957 return;
2961 if (hWndClipWindow)
2963 selection_acquire();
2965 else
2967 HANDLE event = CreateEventW(NULL, FALSE, FALSE, NULL);
2968 selectionThread = CreateThread(NULL, 0, selection_thread_proc, event, 0, NULL);
2970 if (selectionThread)
2972 WaitForSingleObject(event, INFINITE);
2973 CloseHandle(selectionThread);
2975 CloseHandle(event);
2980 static void empty_clipboard(BOOL keepunowned)
2982 WINE_CLIPDATA *data, *next;
2984 LIST_FOR_EACH_ENTRY_SAFE( data, next, &data_list, WINE_CLIPDATA, entry )
2986 if (keepunowned && (data->wFlags & CF_FLAG_UNOWNED)) continue;
2987 list_remove( &data->entry );
2988 X11DRV_CLIPBOARD_FreeData( data );
2989 HeapFree( GetProcessHeap(), 0, data );
2990 ClipDataCount--;
2993 TRACE(" %d entries remaining in cache.\n", ClipDataCount);
2996 /**************************************************************************
2997 * X11DRV_EmptyClipboard
2999 * Empty cached clipboard data.
3001 void CDECL X11DRV_EmptyClipboard(void)
3003 X11DRV_AcquireClipboard( GetOpenClipboardWindow() );
3004 empty_clipboard( FALSE );
3007 /**************************************************************************
3008 * X11DRV_SetClipboardData
3010 BOOL CDECL X11DRV_SetClipboardData(UINT wFormat, HANDLE hData, BOOL owner)
3012 DWORD flags = 0;
3013 BOOL bResult = TRUE;
3015 /* If it's not owned, data can only be set if the format data is not already owned
3016 and its rendering is not delayed */
3017 if (!owner)
3019 LPWINE_CLIPDATA lpRender;
3021 X11DRV_CLIPBOARD_UpdateCache();
3023 if (!hData ||
3024 ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)) &&
3025 !(lpRender->wFlags & CF_FLAG_UNOWNED)))
3026 bResult = FALSE;
3027 else
3028 flags = CF_FLAG_UNOWNED;
3031 bResult &= X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData, flags, NULL, TRUE);
3033 return bResult;
3037 /**************************************************************************
3038 * CountClipboardFormats
3040 INT CDECL X11DRV_CountClipboardFormats(void)
3042 X11DRV_CLIPBOARD_UpdateCache();
3044 TRACE(" count=%d\n", ClipDataCount);
3046 return ClipDataCount;
3050 /**************************************************************************
3051 * X11DRV_EnumClipboardFormats
3053 UINT CDECL X11DRV_EnumClipboardFormats(UINT wFormat)
3055 struct list *ptr = NULL;
3057 TRACE("(%04X)\n", wFormat);
3059 X11DRV_CLIPBOARD_UpdateCache();
3061 if (!wFormat)
3063 ptr = list_head( &data_list );
3065 else
3067 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
3068 if (lpData) ptr = list_next( &data_list, &lpData->entry );
3071 if (!ptr) return 0;
3072 return LIST_ENTRY( ptr, WINE_CLIPDATA, entry )->wFormatID;
3076 /**************************************************************************
3077 * X11DRV_IsClipboardFormatAvailable
3079 BOOL CDECL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
3081 BOOL bRet = FALSE;
3083 TRACE("(%04X)\n", wFormat);
3085 X11DRV_CLIPBOARD_UpdateCache();
3087 if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
3088 bRet = TRUE;
3090 TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
3092 return bRet;
3096 /**************************************************************************
3097 * GetClipboardData (USER.142)
3099 HANDLE CDECL X11DRV_GetClipboardData(UINT wFormat)
3101 LPWINE_CLIPDATA lpRender;
3103 TRACE("(%04X)\n", wFormat);
3105 X11DRV_CLIPBOARD_UpdateCache();
3107 if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
3109 if ( !lpRender->hData )
3110 X11DRV_CLIPBOARD_RenderFormat(thread_init_display(), lpRender);
3112 TRACE(" returning %p (type %04x)\n", lpRender->hData, lpRender->wFormatID);
3113 return lpRender->hData;
3116 return 0;
3120 /**************************************************************************
3121 * ResetSelectionOwner
3123 * Called when the thread owning the selection is destroyed and we need to
3124 * preserve the selection ownership. We look for another top level window
3125 * in this process and send it a message to acquire the selection.
3127 void X11DRV_ResetSelectionOwner(void)
3129 HWND hwnd;
3130 DWORD procid;
3132 TRACE("\n");
3134 if (!selectionAcquired || thread_selection_wnd() != selectionWindow)
3135 return;
3137 selectionAcquired = S_NOSELECTION;
3138 selectionWindow = 0;
3140 hwnd = GetWindow(GetDesktopWindow(), GW_CHILD);
3143 if (GetCurrentThreadId() != GetWindowThreadProcessId(hwnd, &procid))
3145 if (GetCurrentProcessId() == procid)
3147 if (SendMessageW(hwnd, WM_X11DRV_ACQUIRE_SELECTION, 0, 0))
3148 return;
3151 } while ((hwnd = GetWindow(hwnd, GW_HWNDNEXT)) != NULL);
3153 WARN("Failed to find another thread to take selection ownership. Clipboard data will be lost.\n");
3155 X11DRV_CLIPBOARD_ReleaseOwnership();
3156 empty_clipboard( FALSE );
3160 /**************************************************************************
3161 * X11DRV_CLIPBOARD_SynthesizeData
3163 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID)
3165 BOOL bsyn = TRUE;
3166 LPWINE_CLIPDATA lpSource = NULL;
3168 TRACE(" %04x\n", wFormatID);
3170 /* Don't need to synthesize if it already exists */
3171 if (X11DRV_CLIPBOARD_LookupData(wFormatID))
3172 return TRUE;
3174 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
3176 bsyn = ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
3177 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
3178 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
3179 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
3180 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
3181 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED);
3183 else if (wFormatID == CF_ENHMETAFILE)
3185 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
3186 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
3188 else if (wFormatID == CF_METAFILEPICT)
3190 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_ENHMETAFILE)) &&
3191 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
3193 else if (wFormatID == CF_DIB)
3195 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
3196 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
3198 else if (wFormatID == CF_BITMAP)
3200 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
3201 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
3204 if (bsyn)
3205 X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, CF_FLAG_SYNTHESIZED, NULL, TRUE);
3207 return bsyn;
3212 /**************************************************************************
3213 * X11DRV_EndClipboardUpdate
3214 * TODO:
3215 * Add locale if it hasn't already been added
3217 void CDECL X11DRV_EndClipboardUpdate(void)
3219 INT count = ClipDataCount;
3221 /* Do Unicode <-> Text <-> OEM mapping */
3222 X11DRV_CLIPBOARD_SynthesizeData(CF_TEXT);
3223 X11DRV_CLIPBOARD_SynthesizeData(CF_OEMTEXT);
3224 X11DRV_CLIPBOARD_SynthesizeData(CF_UNICODETEXT);
3226 /* Enhmetafile <-> MetafilePict mapping */
3227 X11DRV_CLIPBOARD_SynthesizeData(CF_ENHMETAFILE);
3228 X11DRV_CLIPBOARD_SynthesizeData(CF_METAFILEPICT);
3230 /* DIB <-> Bitmap mapping */
3231 X11DRV_CLIPBOARD_SynthesizeData(CF_DIB);
3232 X11DRV_CLIPBOARD_SynthesizeData(CF_BITMAP);
3234 TRACE("%d formats added to cached data\n", ClipDataCount - count);
3238 /***********************************************************************
3239 * X11DRV_SelectionRequest_TARGETS
3240 * Service a TARGETS selection request event
3242 static Atom X11DRV_SelectionRequest_TARGETS( Display *display, Window requestor,
3243 Atom target, Atom rprop )
3245 UINT i;
3246 Atom* targets;
3247 ULONG cTargets;
3248 LPWINE_CLIPFORMAT format;
3249 LPWINE_CLIPDATA lpData;
3251 /* Create X atoms for any clipboard types which don't have atoms yet.
3252 * This avoids sending bogus zero atoms.
3253 * Without this, copying might not have access to all clipboard types.
3254 * FIXME: is it safe to call this here?
3256 intern_atoms();
3259 * Count the number of items we wish to expose as selection targets.
3261 cTargets = 1; /* Include TARGETS */
3263 if (!list_head( &data_list )) return None;
3265 LIST_FOR_EACH_ENTRY( lpData, &data_list, WINE_CLIPDATA, entry )
3266 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
3267 if ((format->wFormatID == lpData->wFormatID) &&
3268 format->lpDrvExportFunc && format->drvData)
3269 cTargets++;
3271 TRACE(" found %d formats\n", cTargets);
3273 /* Allocate temp buffer */
3274 targets = HeapAlloc( GetProcessHeap(), 0, cTargets * sizeof(Atom));
3275 if(targets == NULL)
3276 return None;
3278 i = 0;
3279 targets[i++] = x11drv_atom(TARGETS);
3281 LIST_FOR_EACH_ENTRY( lpData, &data_list, WINE_CLIPDATA, entry )
3282 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
3283 if ((format->wFormatID == lpData->wFormatID) &&
3284 format->lpDrvExportFunc && format->drvData)
3285 targets[i++] = format->drvData;
3287 if (TRACE_ON(clipboard))
3289 unsigned int i;
3290 for ( i = 0; i < cTargets; i++)
3292 char *itemFmtName = XGetAtomName(display, targets[i]);
3293 TRACE("\tAtom# %d: Property %ld Type %s\n", i, targets[i], itemFmtName);
3294 XFree(itemFmtName);
3298 /* We may want to consider setting the type to xaTargets instead,
3299 * in case some apps expect this instead of XA_ATOM */
3300 XChangeProperty(display, requestor, rprop, XA_ATOM, 32,
3301 PropModeReplace, (unsigned char *)targets, cTargets);
3303 HeapFree(GetProcessHeap(), 0, targets);
3305 return rprop;
3309 /***********************************************************************
3310 * X11DRV_SelectionRequest_MULTIPLE
3311 * Service a MULTIPLE selection request event
3312 * rprop contains a list of (target,property) atom pairs.
3313 * The first atom names a target and the second names a property.
3314 * The effect is as if we have received a sequence of SelectionRequest events
3315 * (one for each atom pair) except that:
3316 * 1. We reply with a SelectionNotify only when all the requested conversions
3317 * have been performed.
3318 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
3319 * we replace the atom in the property by None.
3321 static Atom X11DRV_SelectionRequest_MULTIPLE( HWND hWnd, XSelectionRequestEvent *pevent )
3323 Display *display = pevent->display;
3324 Atom rprop;
3325 Atom atype=AnyPropertyType;
3326 int aformat;
3327 unsigned long remain;
3328 Atom* targetPropList=NULL;
3329 unsigned long cTargetPropList = 0;
3331 /* If the specified property is None the requestor is an obsolete client.
3332 * We support these by using the specified target atom as the reply property.
3334 rprop = pevent->property;
3335 if( rprop == None )
3336 rprop = pevent->target;
3337 if (!rprop)
3338 return 0;
3340 /* Read the MULTIPLE property contents. This should contain a list of
3341 * (target,property) atom pairs.
3343 if (!XGetWindowProperty(display, pevent->requestor, rprop,
3344 0, 0x3FFF, False, AnyPropertyType, &atype,&aformat,
3345 &cTargetPropList, &remain,
3346 (unsigned char**)&targetPropList) != Success)
3348 if (TRACE_ON(clipboard))
3350 char * const typeName = XGetAtomName(display, atype);
3351 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
3352 typeName, aformat, cTargetPropList, remain);
3353 XFree(typeName);
3357 * Make sure we got what we expect.
3358 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
3359 * in a MULTIPLE selection request should be of type ATOM_PAIR.
3360 * However some X apps(such as XPaint) are not compliant with this and return
3361 * a user defined atom in atype when XGetWindowProperty is called.
3362 * The data *is* an atom pair but is not denoted as such.
3364 if(aformat == 32 /* atype == xAtomPair */ )
3366 unsigned int i;
3368 /* Iterate through the ATOM_PAIR list and execute a SelectionRequest
3369 * for each (target,property) pair */
3371 for (i = 0; i < cTargetPropList; i+=2)
3373 XSelectionRequestEvent event;
3375 if (TRACE_ON(clipboard))
3377 char *targetName, *propName;
3378 targetName = XGetAtomName(display, targetPropList[i]);
3379 propName = XGetAtomName(display, targetPropList[i+1]);
3380 TRACE("MULTIPLE(%d): Target='%s' Prop='%s'\n",
3381 i/2, targetName, propName);
3382 XFree(targetName);
3383 XFree(propName);
3386 /* We must have a non "None" property to service a MULTIPLE target atom */
3387 if ( !targetPropList[i+1] )
3389 TRACE("\tMULTIPLE(%d): Skipping target with empty property!\n", i);
3390 continue;
3393 /* Set up an XSelectionRequestEvent for this (target,property) pair */
3394 event = *pevent;
3395 event.target = targetPropList[i];
3396 event.property = targetPropList[i+1];
3398 /* Fire a SelectionRequest, informing the handler that we are processing
3399 * a MULTIPLE selection request event.
3401 X11DRV_HandleSelectionRequest( hWnd, &event, TRUE );
3405 /* Free the list of targets/properties */
3406 XFree(targetPropList);
3408 else TRACE("Couldn't read MULTIPLE property\n");
3410 return rprop;
3414 /***********************************************************************
3415 * X11DRV_HandleSelectionRequest
3416 * Process an event selection request event.
3417 * The bIsMultiple flag is used to signal when EVENT_SelectionRequest is called
3418 * recursively while servicing a "MULTIPLE" selection target.
3420 * Note: We only receive this event when WINE owns the X selection
3422 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple )
3424 Display *display = event->display;
3425 XSelectionEvent result;
3426 Atom rprop = None;
3427 Window request = event->requestor;
3429 TRACE("\n");
3432 * We can only handle the selection request if :
3433 * The selection is PRIMARY or CLIPBOARD, AND we can successfully open the clipboard.
3434 * Don't do these checks or open the clipboard while recursively processing MULTIPLE,
3435 * since this has been already done.
3437 if ( !bIsMultiple )
3439 if (((event->selection != XA_PRIMARY) && (event->selection != x11drv_atom(CLIPBOARD))))
3440 goto END;
3443 /* If the specified property is None the requestor is an obsolete client.
3444 * We support these by using the specified target atom as the reply property.
3446 rprop = event->property;
3447 if( rprop == None )
3448 rprop = event->target;
3450 if(event->target == x11drv_atom(TARGETS)) /* Return a list of all supported targets */
3452 /* TARGETS selection request */
3453 rprop = X11DRV_SelectionRequest_TARGETS( display, request, event->target, rprop );
3455 else if(event->target == x11drv_atom(MULTIPLE)) /* rprop contains a list of (target, property) atom pairs */
3457 /* MULTIPLE selection request */
3458 rprop = X11DRV_SelectionRequest_MULTIPLE( hWnd, event );
3460 else
3462 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, event->target);
3463 BOOL success = FALSE;
3465 if (lpFormat && lpFormat->lpDrvExportFunc)
3467 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(lpFormat->wFormatID);
3469 if (lpData)
3471 unsigned char* lpClipData;
3472 DWORD cBytes;
3473 HANDLE hClipData = lpFormat->lpDrvExportFunc(display, request, event->target,
3474 rprop, lpData, &cBytes);
3476 if (hClipData && (lpClipData = GlobalLock(hClipData)))
3478 int mode = PropModeReplace;
3480 TRACE("\tUpdating property %s, %d bytes\n",
3481 debugstr_format(lpFormat->wFormatID), cBytes);
3484 int nelements = min(cBytes, 65536);
3485 XChangeProperty(display, request, rprop, event->target,
3486 8, mode, lpClipData, nelements);
3487 mode = PropModeAppend;
3488 cBytes -= nelements;
3489 lpClipData += nelements;
3490 } while (cBytes > 0);
3492 GlobalUnlock(hClipData);
3493 GlobalFree(hClipData);
3494 success = TRUE;
3499 if (!success)
3500 rprop = None; /* report failure to client */
3503 END:
3504 /* reply to sender
3505 * SelectionNotify should be sent only at the end of a MULTIPLE request
3507 if ( !bIsMultiple )
3509 result.type = SelectionNotify;
3510 result.display = display;
3511 result.requestor = request;
3512 result.selection = event->selection;
3513 result.property = rprop;
3514 result.target = event->target;
3515 result.time = event->time;
3516 TRACE("Sending SelectionNotify event...\n");
3517 XSendEvent(display,event->requestor,False,NoEventMask,(XEvent*)&result);
3522 /***********************************************************************
3523 * X11DRV_SelectionRequest
3525 void X11DRV_SelectionRequest( HWND hWnd, XEvent *event )
3527 X11DRV_HandleSelectionRequest( hWnd, &event->xselectionrequest, FALSE );
3531 /***********************************************************************
3532 * X11DRV_SelectionClear
3534 void X11DRV_SelectionClear( HWND hWnd, XEvent *xev )
3536 XSelectionClearEvent *event = &xev->xselectionclear;
3537 if (event->selection == XA_PRIMARY || event->selection == x11drv_atom(CLIPBOARD))
3538 X11DRV_CLIPBOARD_ReleaseSelection( event->display, event->selection,
3539 event->window, hWnd, event->time );