winex11: Avoid memory leaks (coverity).
[wine.git] / dlls / winex11.drv / clipboard.c
blobbd3ef7b3a106c3d018386a1979a362d047861872
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
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 * NOTES:
24 * This file contains the X specific implementation for the windows
25 * Clipboard API.
27 * Wine's internal clipboard is exposed to external apps via the X
28 * selection mechanism.
29 * Currently the driver asserts ownership via two selection atoms:
30 * 1. PRIMARY(XA_PRIMARY)
31 * 2. CLIPBOARD
33 * In our implementation, the CLIPBOARD selection takes precedence over PRIMARY,
34 * i.e. if a CLIPBOARD selection is available, it is used instead of PRIMARY.
35 * When Wine takes ownership of the clipboard, it takes ownership of BOTH selections.
36 * While giving up selection ownership, if the CLIPBOARD selection is lost,
37 * it will lose both PRIMARY and CLIPBOARD and empty the clipboard.
38 * However if only PRIMARY is lost, it will continue to hold the CLIPBOARD selection
39 * (leaving the clipboard cache content unaffected).
41 * Every format exposed via a windows clipboard format is also exposed through
42 * a corresponding X selection target. A selection target atom is synthesized
43 * whenever a new Windows clipboard format is registered via RegisterClipboardFormat,
44 * or when a built-in format is used for the first time.
45 * Windows native format are exposed by prefixing the format name with "<WCF>"
46 * This allows us to uniquely identify windows native formats exposed by other
47 * running WINE apps.
49 * In order to allow external applications to query WINE for supported formats,
50 * we respond to the "TARGETS" selection target. (See EVENT_SelectionRequest
51 * for implementation) We use the same mechanism to query external clients for
52 * availability of a particular format, by caching the list of available targets
53 * by using the clipboard cache's "delayed render" mechanism. If a selection client
54 * does not support the "TARGETS" selection target, we actually attempt to retrieve
55 * the format requested as a fallback mechanism.
57 * Certain Windows native formats are automatically converted to X native formats
58 * and vice versa. If a native format is available in the selection, it takes
59 * precedence, in order to avoid unnecessary conversions.
61 * FIXME: global format list needs a critical section
64 #include "config.h"
65 #include "wine/port.h"
67 #include <string.h>
68 #include <stdarg.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #ifdef HAVE_UNISTD_H
72 # include <unistd.h>
73 #endif
74 #include <fcntl.h>
75 #include <limits.h>
76 #include <time.h>
77 #include <assert.h>
79 #include "windef.h"
80 #include "winbase.h"
81 #include "x11drv.h"
82 #include "wine/list.h"
83 #include "wine/debug.h"
84 #include "wine/unicode.h"
85 #include "wine/server.h"
87 WINE_DEFAULT_DEBUG_CHANNEL(clipboard);
89 /* Maximum wait time for selection notify */
90 #define SELECTION_RETRIES 500 /* wait for .5 seconds */
91 #define SELECTION_WAIT 1000 /* us */
93 /* Selection masks */
94 #define S_NOSELECTION 0
95 #define S_PRIMARY 1
96 #define S_CLIPBOARD 2
98 typedef struct
100 HWND hWndOpen;
101 HWND hWndOwner;
102 HWND hWndViewer;
103 UINT seqno;
104 UINT flags;
105 } CLIPBOARDINFO, *LPCLIPBOARDINFO;
107 struct tagWINE_CLIPDATA; /* Forward */
109 typedef HANDLE (*DRVEXPORTFUNC)(Display *display, Window requestor, Atom aTarget, Atom rprop,
110 struct tagWINE_CLIPDATA* lpData, LPDWORD lpBytes);
111 typedef HANDLE (*DRVIMPORTFUNC)(Display *d, Window w, Atom prop);
113 typedef struct tagWINE_CLIPFORMAT {
114 struct list entry;
115 UINT wFormatID;
116 UINT drvData;
117 DRVIMPORTFUNC lpDrvImportFunc;
118 DRVEXPORTFUNC lpDrvExportFunc;
119 } WINE_CLIPFORMAT, *LPWINE_CLIPFORMAT;
121 typedef struct tagWINE_CLIPDATA {
122 struct list entry;
123 UINT wFormatID;
124 HANDLE hData;
125 UINT wFlags;
126 UINT drvData;
127 LPWINE_CLIPFORMAT lpFormat;
128 } WINE_CLIPDATA, *LPWINE_CLIPDATA;
130 #define CF_FLAG_UNOWNED 0x0001 /* cached data is not owned */
131 #define CF_FLAG_SYNTHESIZED 0x0002 /* Implicitly converted data */
133 static int selectionAcquired = 0; /* Contains the current selection masks */
134 static Window selectionWindow = None; /* The top level X window which owns the selection */
135 static Atom selectionCacheSrc = XA_PRIMARY; /* The selection source from which the clipboard cache was filled */
137 void CDECL X11DRV_EmptyClipboard(BOOL keepunowned);
138 void CDECL X11DRV_EndClipboardUpdate(void);
139 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *d, Window w, Atom prop);
140 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *d, Window w, Atom prop);
141 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *d, Window w, Atom prop);
142 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *d, Window w, Atom prop);
143 static HANDLE X11DRV_CLIPBOARD_ImportImageBmp(Display *d, Window w, Atom prop);
144 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *d, Window w, Atom prop);
145 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *d, Window w, Atom prop);
146 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *d, Window w, Atom prop);
147 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
148 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
149 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget,
150 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes);
151 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget,
152 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
153 static HANDLE X11DRV_CLIPBOARD_ExportImageBmp(Display *display, Window requestor, Atom aTarget,
154 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
155 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget,
156 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
157 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget,
158 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
159 static HANDLE X11DRV_CLIPBOARD_ExportTextHtml(Display *display, Window requestor, Atom aTarget,
160 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes);
161 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat(UINT id, Atom prop);
162 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID);
163 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData);
164 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void);
165 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo);
166 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData);
167 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
168 unsigned char** data, unsigned long* datasize);
169 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData);
170 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out);
171 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID);
172 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData);
173 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display);
174 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display);
175 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile(Display *display);
176 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple );
178 /* Clipboard formats */
180 static const struct
182 UINT id;
183 UINT data;
184 DRVIMPORTFUNC import;
185 DRVEXPORTFUNC export;
186 } builtin_formats[] =
188 { CF_TEXT, XA_STRING, X11DRV_CLIPBOARD_ImportXAString, X11DRV_CLIPBOARD_ExportString},
189 { CF_BITMAP, XATOM_WCF_BITMAP, X11DRV_CLIPBOARD_ImportClipboardData, NULL},
190 { CF_METAFILEPICT, XATOM_WCF_METAFILEPICT, X11DRV_CLIPBOARD_ImportMetaFilePict, X11DRV_CLIPBOARD_ExportMetaFilePict },
191 { CF_SYLK, XATOM_WCF_SYLK, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
192 { CF_DIF, XATOM_WCF_DIF, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
193 { CF_TIFF, XATOM_WCF_TIFF, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
194 { CF_OEMTEXT, XATOM_WCF_OEMTEXT, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
195 { CF_DIB, XA_PIXMAP, X11DRV_CLIPBOARD_ImportXAPIXMAP, X11DRV_CLIPBOARD_ExportXAPIXMAP },
196 { CF_PALETTE, XATOM_WCF_PALETTE, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
197 { CF_PENDATA, XATOM_WCF_PENDATA, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
198 { CF_RIFF, XATOM_WCF_RIFF, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
199 { CF_WAVE, XATOM_WCF_WAVE, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
200 { CF_UNICODETEXT, XATOM_UTF8_STRING, X11DRV_CLIPBOARD_ImportUTF8, X11DRV_CLIPBOARD_ExportString },
201 /* If UTF8_STRING is not available, attempt COMPOUND_TEXT */
202 { CF_UNICODETEXT, XATOM_COMPOUND_TEXT, X11DRV_CLIPBOARD_ImportCompoundText, X11DRV_CLIPBOARD_ExportString },
203 { CF_ENHMETAFILE, XATOM_WCF_ENHMETAFILE, X11DRV_CLIPBOARD_ImportEnhMetaFile, X11DRV_CLIPBOARD_ExportEnhMetaFile },
204 { CF_HDROP, XATOM_WCF_HDROP, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
205 { CF_LOCALE, XATOM_WCF_LOCALE, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
206 { CF_DIBV5, XATOM_WCF_DIBV5, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
207 { CF_OWNERDISPLAY, XATOM_WCF_OWNERDISPLAY, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
208 { CF_DSPTEXT, XATOM_WCF_DSPTEXT, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
209 { CF_DSPBITMAP, XATOM_WCF_DSPBITMAP, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
210 { CF_DSPMETAFILEPICT, XATOM_WCF_DSPMETAFILEPICT, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
211 { CF_DSPENHMETAFILE, XATOM_WCF_DSPENHMETAFILE, X11DRV_CLIPBOARD_ImportClipboardData, X11DRV_CLIPBOARD_ExportClipboardData },
212 { CF_DIB, XATOM_image_bmp, X11DRV_CLIPBOARD_ImportImageBmp, X11DRV_CLIPBOARD_ExportImageBmp },
215 static struct list format_list = LIST_INIT( format_list );
217 #define GET_ATOM(prop) (((prop) < FIRST_XATOM) ? (Atom)(prop) : X11DRV_Atoms[(prop) - FIRST_XATOM])
219 /* Maps X properties to Windows formats */
220 static const WCHAR wszRichTextFormat[] = {'R','i','c','h',' ','T','e','x','t',' ','F','o','r','m','a','t',0};
221 static const WCHAR wszGIF[] = {'G','I','F',0};
222 static const WCHAR wszJFIF[] = {'J','F','I','F',0};
223 static const WCHAR wszPNG[] = {'P','N','G',0};
224 static const WCHAR wszHTMLFormat[] = {'H','T','M','L',' ','F','o','r','m','a','t',0};
225 static const struct
227 LPCWSTR lpszFormat;
228 UINT prop;
229 } PropertyFormatMap[] =
231 { wszRichTextFormat, XATOM_text_rtf },
232 { wszRichTextFormat, XATOM_text_richtext },
233 { wszGIF, XATOM_image_gif },
234 { wszJFIF, XATOM_image_jpeg },
235 { wszPNG, XATOM_image_png },
236 { wszHTMLFormat, XATOM_HTML_Format }, /* prefer this to text/html */
241 * Cached clipboard data.
243 static struct list data_list = LIST_INIT( data_list );
244 static UINT ClipDataCount = 0;
247 * Clipboard sequence number
249 static UINT wSeqNo = 0;
251 /**************************************************************************
252 * Internal Clipboard implementation methods
253 **************************************************************************/
255 static Window thread_selection_wnd(void)
257 struct x11drv_thread_data *thread_data = x11drv_init_thread_data();
258 Window w = thread_data->selection_wnd;
260 if (!w)
262 w = XCreateWindow(thread_data->display, root_window, 0, 0, 1, 1, 0, CopyFromParent,
263 InputOnly, CopyFromParent, 0, NULL);
264 if (w)
265 thread_data->selection_wnd = w;
266 else
267 FIXME("Failed to create window. Fetching selection data will fail.\n");
270 return w;
273 static const char *debugstr_format( UINT id )
275 WCHAR buffer[256];
277 if (GetClipboardFormatNameW( id, buffer, 256 ))
278 return wine_dbg_sprintf( "%04x %s", id, debugstr_w(buffer) );
280 switch (id)
282 #define BUILTIN(id) case id: return #id;
283 BUILTIN(CF_TEXT)
284 BUILTIN(CF_BITMAP)
285 BUILTIN(CF_METAFILEPICT)
286 BUILTIN(CF_SYLK)
287 BUILTIN(CF_DIF)
288 BUILTIN(CF_TIFF)
289 BUILTIN(CF_OEMTEXT)
290 BUILTIN(CF_DIB)
291 BUILTIN(CF_PALETTE)
292 BUILTIN(CF_PENDATA)
293 BUILTIN(CF_RIFF)
294 BUILTIN(CF_WAVE)
295 BUILTIN(CF_UNICODETEXT)
296 BUILTIN(CF_ENHMETAFILE)
297 BUILTIN(CF_HDROP)
298 BUILTIN(CF_LOCALE)
299 BUILTIN(CF_DIBV5)
300 BUILTIN(CF_OWNERDISPLAY)
301 BUILTIN(CF_DSPTEXT)
302 BUILTIN(CF_DSPBITMAP)
303 BUILTIN(CF_DSPMETAFILEPICT)
304 BUILTIN(CF_DSPENHMETAFILE)
305 #undef BUILTIN
306 default: return wine_dbg_sprintf( "%04x", id );
310 /**************************************************************************
311 * X11DRV_InitClipboard
313 void X11DRV_InitClipboard(void)
315 UINT i;
316 WINE_CLIPFORMAT *format;
318 /* Register built-in formats */
319 for (i = 0; i < sizeof(builtin_formats)/sizeof(builtin_formats[0]); i++)
321 if (!(format = HeapAlloc( GetProcessHeap(), 0, sizeof(*format )))) break;
322 format->wFormatID = builtin_formats[i].id;
323 format->drvData = GET_ATOM(builtin_formats[i].data);
324 format->lpDrvImportFunc = builtin_formats[i].import;
325 format->lpDrvExportFunc = builtin_formats[i].export;
326 list_add_tail( &format_list, &format->entry );
329 /* Register known mapping between window formats and X properties */
330 for (i = 0; i < sizeof(PropertyFormatMap)/sizeof(PropertyFormatMap[0]); i++)
331 X11DRV_CLIPBOARD_InsertClipboardFormat( RegisterClipboardFormatW(PropertyFormatMap[i].lpszFormat),
332 GET_ATOM(PropertyFormatMap[i].prop));
334 /* Set up a conversion function from "HTML Format" to "text/html" */
335 format = X11DRV_CLIPBOARD_InsertClipboardFormat( RegisterClipboardFormatW(wszHTMLFormat),
336 GET_ATOM(XATOM_text_html));
337 format->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportTextHtml;
341 /**************************************************************************
342 * intern_atoms
344 * Intern atoms for formats that don't have one yet.
346 static void intern_atoms(void)
348 LPWINE_CLIPFORMAT format;
349 int i, count, len;
350 char **names;
351 Atom *atoms;
352 Display *display;
353 WCHAR buffer[256];
355 count = 0;
356 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
357 if (!format->drvData) count++;
358 if (!count) return;
360 display = thread_init_display();
362 names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
363 atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
365 i = 0;
366 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
367 if (!format->drvData) {
368 GetClipboardFormatNameW( format->wFormatID, buffer, 256 );
369 len = WideCharToMultiByte(CP_UNIXCP, 0, buffer, -1, NULL, 0, NULL, NULL);
370 names[i] = HeapAlloc(GetProcessHeap(), 0, len);
371 WideCharToMultiByte(CP_UNIXCP, 0, buffer, -1, names[i++], len, NULL, NULL);
374 XInternAtoms( display, names, count, False, atoms );
376 i = 0;
377 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
378 if (!format->drvData) {
379 HeapFree(GetProcessHeap(), 0, names[i]);
380 format->drvData = atoms[i++];
383 HeapFree( GetProcessHeap(), 0, names );
384 HeapFree( GetProcessHeap(), 0, atoms );
388 /**************************************************************************
389 * register_format
391 * Register a custom X clipboard format.
393 static WINE_CLIPFORMAT *register_format( UINT id, Atom prop )
395 LPWINE_CLIPFORMAT lpFormat;
397 /* walk format chain to see if it's already registered */
398 LIST_FOR_EACH_ENTRY( lpFormat, &format_list, WINE_CLIPFORMAT, entry )
399 if (lpFormat->wFormatID == id) return lpFormat;
401 return X11DRV_CLIPBOARD_InsertClipboardFormat(id, prop);
405 /**************************************************************************
406 * X11DRV_CLIPBOARD_LookupProperty
408 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupProperty(LPWINE_CLIPFORMAT current, UINT drvData)
410 for (;;)
412 struct list *ptr = current ? &current->entry : &format_list;
413 BOOL need_intern = FALSE;
415 while ((ptr = list_next( &format_list, ptr )))
417 LPWINE_CLIPFORMAT lpFormat = LIST_ENTRY( ptr, WINE_CLIPFORMAT, entry );
418 if (lpFormat->drvData == drvData) return lpFormat;
419 if (!lpFormat->drvData) need_intern = TRUE;
421 if (!need_intern) return NULL;
422 intern_atoms();
423 /* restart the search for the new atoms */
428 /**************************************************************************
429 * X11DRV_CLIPBOARD_LookupData
431 static LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
433 WINE_CLIPDATA *data;
435 LIST_FOR_EACH_ENTRY( data, &data_list, WINE_CLIPDATA, entry )
436 if (data->wFormatID == wID) return data;
438 return NULL;
442 /**************************************************************************
443 * InsertClipboardFormat
445 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat( UINT id, Atom prop )
447 LPWINE_CLIPFORMAT lpNewFormat;
449 /* allocate storage for new format entry */
450 lpNewFormat = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPFORMAT));
452 if(lpNewFormat == NULL)
454 WARN("No more memory for a new format!\n");
455 return NULL;
457 lpNewFormat->wFormatID = id;
458 lpNewFormat->drvData = prop;
459 lpNewFormat->lpDrvImportFunc = X11DRV_CLIPBOARD_ImportClipboardData;
460 lpNewFormat->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportClipboardData;
462 list_add_tail( &format_list, &lpNewFormat->entry );
464 TRACE("Registering format %s drvData %d\n",
465 debugstr_format(lpNewFormat->wFormatID), lpNewFormat->drvData);
467 return lpNewFormat;
473 /**************************************************************************
474 * X11DRV_CLIPBOARD_GetClipboardInfo
476 static BOOL X11DRV_CLIPBOARD_GetClipboardInfo(LPCLIPBOARDINFO cbInfo)
478 BOOL bRet = FALSE;
480 SERVER_START_REQ( set_clipboard_info )
482 req->flags = 0;
484 if (wine_server_call_err( req ))
486 ERR("Failed to get clipboard owner.\n");
488 else
490 cbInfo->hWndOpen = wine_server_ptr_handle( reply->old_clipboard );
491 cbInfo->hWndOwner = wine_server_ptr_handle( reply->old_owner );
492 cbInfo->hWndViewer = wine_server_ptr_handle( reply->old_viewer );
493 cbInfo->seqno = reply->seqno;
494 cbInfo->flags = reply->flags;
496 bRet = TRUE;
499 SERVER_END_REQ;
501 return bRet;
505 /**************************************************************************
506 * X11DRV_CLIPBOARD_ReleaseOwnership
508 static BOOL X11DRV_CLIPBOARD_ReleaseOwnership(void)
510 BOOL bRet = FALSE;
512 SERVER_START_REQ( set_clipboard_info )
514 req->flags = SET_CB_RELOWNER | SET_CB_SEQNO;
516 if (wine_server_call_err( req ))
518 ERR("Failed to set clipboard.\n");
520 else
522 bRet = TRUE;
525 SERVER_END_REQ;
527 return bRet;
532 /**************************************************************************
533 * X11DRV_CLIPBOARD_InsertClipboardData
535 * Caller *must* have the clipboard open and be the owner.
537 static BOOL X11DRV_CLIPBOARD_InsertClipboardData(UINT wFormatID, HANDLE hData, DWORD flags,
538 LPWINE_CLIPFORMAT lpFormat, BOOL override)
540 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormatID);
542 TRACE("format=%04x lpData=%p hData=%p flags=0x%08x lpFormat=%p override=%d\n",
543 wFormatID, lpData, hData, flags, lpFormat, override);
545 /* make sure the format exists */
546 if (!lpFormat) register_format( wFormatID, 0 );
548 if (lpData && !override)
549 return TRUE;
551 if (lpData)
553 X11DRV_CLIPBOARD_FreeData(lpData);
555 lpData->hData = hData;
557 else
559 lpData = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPDATA));
561 lpData->wFormatID = wFormatID;
562 lpData->hData = hData;
563 lpData->lpFormat = lpFormat;
564 lpData->drvData = 0;
566 list_add_tail( &data_list, &lpData->entry );
567 ClipDataCount++;
570 lpData->wFlags = flags;
572 return TRUE;
576 /**************************************************************************
577 * X11DRV_CLIPBOARD_FreeData
579 * Free clipboard data handle.
581 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData)
583 TRACE("%04x\n", lpData->wFormatID);
585 if ((lpData->wFormatID >= CF_GDIOBJFIRST &&
586 lpData->wFormatID <= CF_GDIOBJLAST) ||
587 lpData->wFormatID == CF_BITMAP ||
588 lpData->wFormatID == CF_DIB ||
589 lpData->wFormatID == CF_PALETTE)
591 if (lpData->hData)
592 DeleteObject(lpData->hData);
594 if ((lpData->wFormatID == CF_DIB) && lpData->drvData)
595 XFreePixmap(gdi_display, lpData->drvData);
597 else if (lpData->wFormatID == CF_METAFILEPICT)
599 if (lpData->hData)
601 DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData ))->hMF );
602 GlobalFree(lpData->hData);
605 else if (lpData->wFormatID == CF_ENHMETAFILE)
607 if (lpData->hData)
608 DeleteEnhMetaFile(lpData->hData);
610 else if (lpData->wFormatID < CF_PRIVATEFIRST ||
611 lpData->wFormatID > CF_PRIVATELAST)
613 if (lpData->hData)
614 GlobalFree(lpData->hData);
617 lpData->hData = 0;
618 lpData->drvData = 0;
622 /**************************************************************************
623 * X11DRV_CLIPBOARD_UpdateCache
625 static BOOL X11DRV_CLIPBOARD_UpdateCache(LPCLIPBOARDINFO lpcbinfo)
627 BOOL bret = TRUE;
629 if (!X11DRV_CLIPBOARD_IsSelectionOwner())
631 if (!X11DRV_CLIPBOARD_GetClipboardInfo(lpcbinfo))
633 ERR("Failed to retrieve clipboard information.\n");
634 bret = FALSE;
636 else if (wSeqNo < lpcbinfo->seqno)
638 X11DRV_EmptyClipboard(TRUE);
640 if (X11DRV_CLIPBOARD_QueryAvailableData(thread_init_display(), lpcbinfo) < 0)
642 ERR("Failed to cache clipboard data owned by another process.\n");
643 bret = FALSE;
645 else
647 X11DRV_EndClipboardUpdate();
650 wSeqNo = lpcbinfo->seqno;
654 return bret;
658 /**************************************************************************
659 * X11DRV_CLIPBOARD_RenderFormat
661 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData)
663 BOOL bret = TRUE;
665 TRACE(" 0x%04x hData(%p)\n", lpData->wFormatID, lpData->hData);
667 if (lpData->hData) return bret; /* Already rendered */
669 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
670 bret = X11DRV_CLIPBOARD_RenderSynthesizedFormat(display, lpData);
671 else if (!X11DRV_CLIPBOARD_IsSelectionOwner())
673 if (!X11DRV_CLIPBOARD_ReadSelectionData(display, lpData))
675 ERR("Failed to cache clipboard data owned by another process. Format=%04x\n",
676 lpData->wFormatID);
677 bret = FALSE;
680 else
682 CLIPBOARDINFO cbInfo;
684 if (X11DRV_CLIPBOARD_GetClipboardInfo(&cbInfo) && cbInfo.hWndOwner)
686 /* Send a WM_RENDERFORMAT message to notify the owner to render the
687 * data requested into the clipboard.
689 TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", cbInfo.hWndOwner);
690 SendMessageW(cbInfo.hWndOwner, WM_RENDERFORMAT, lpData->wFormatID, 0);
692 if (!lpData->hData) bret = FALSE;
694 else
696 ERR("hWndClipOwner is lost!\n");
697 bret = FALSE;
701 return bret;
705 /**************************************************************************
706 * CLIPBOARD_ConvertText
707 * Returns number of required/converted characters - not bytes!
709 static INT CLIPBOARD_ConvertText(WORD src_fmt, void const *src, INT src_size,
710 WORD dst_fmt, void *dst, INT dst_size)
712 UINT cp;
714 if(src_fmt == CF_UNICODETEXT)
716 switch(dst_fmt)
718 case CF_TEXT:
719 cp = CP_ACP;
720 break;
721 case CF_OEMTEXT:
722 cp = CP_OEMCP;
723 break;
724 default:
725 return 0;
727 return WideCharToMultiByte(cp, 0, src, src_size, dst, dst_size, NULL, NULL);
730 if(dst_fmt == CF_UNICODETEXT)
732 switch(src_fmt)
734 case CF_TEXT:
735 cp = CP_ACP;
736 break;
737 case CF_OEMTEXT:
738 cp = CP_OEMCP;
739 break;
740 default:
741 return 0;
743 return MultiByteToWideChar(cp, 0, src, src_size, dst, dst_size);
746 if(!dst_size) return src_size;
748 if(dst_size > src_size) dst_size = src_size;
750 if(src_fmt == CF_TEXT )
751 CharToOemBuffA(src, dst, dst_size);
752 else
753 OemToCharBuffA(src, dst, dst_size);
755 return dst_size;
759 /**************************************************************************
760 * X11DRV_CLIPBOARD_RenderSynthesizedFormat
762 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData)
764 BOOL bret = FALSE;
766 TRACE("\n");
768 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
770 UINT wFormatID = lpData->wFormatID;
772 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
773 bret = X11DRV_CLIPBOARD_RenderSynthesizedText(display, wFormatID);
774 else
776 switch (wFormatID)
778 case CF_DIB:
779 bret = X11DRV_CLIPBOARD_RenderSynthesizedDIB( display );
780 break;
782 case CF_BITMAP:
783 bret = X11DRV_CLIPBOARD_RenderSynthesizedBitmap( display );
784 break;
786 case CF_ENHMETAFILE:
787 bret = X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile( display );
788 break;
790 case CF_METAFILEPICT:
791 FIXME("Synthesizing CF_METAFILEPICT not implemented\n");
792 break;
794 default:
795 FIXME("Called to synthesize unknown format 0x%08x\n", wFormatID);
796 break;
800 lpData->wFlags &= ~CF_FLAG_SYNTHESIZED;
803 return bret;
807 /**************************************************************************
808 * X11DRV_CLIPBOARD_RenderSynthesizedText
810 * Renders synthesized text
812 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID)
814 LPCSTR lpstrS;
815 LPSTR lpstrT;
816 HANDLE hData;
817 INT src_chars, dst_chars, alloc_size;
818 LPWINE_CLIPDATA lpSource = NULL;
820 TRACE("%04x\n", wFormatID);
822 if ((lpSource = X11DRV_CLIPBOARD_LookupData(wFormatID)) &&
823 lpSource->hData)
824 return TRUE;
826 /* Look for rendered source or non-synthesized source */
827 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
828 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
830 TRACE("UNICODETEXT -> %04x\n", wFormatID);
832 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
833 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
835 TRACE("TEXT -> %04x\n", wFormatID);
837 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
838 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
840 TRACE("OEMTEXT -> %04x\n", wFormatID);
843 if (!lpSource || (lpSource->wFlags & CF_FLAG_SYNTHESIZED &&
844 !lpSource->hData))
845 return FALSE;
847 /* Ask the clipboard owner to render the source text if necessary */
848 if (!lpSource->hData && !X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
849 return FALSE;
851 lpstrS = GlobalLock(lpSource->hData);
852 if (!lpstrS)
853 return FALSE;
855 /* Text always NULL terminated */
856 if(lpSource->wFormatID == CF_UNICODETEXT)
857 src_chars = strlenW((LPCWSTR)lpstrS) + 1;
858 else
859 src_chars = strlen(lpstrS) + 1;
861 /* Calculate number of characters in the destination buffer */
862 dst_chars = CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS,
863 src_chars, wFormatID, NULL, 0);
865 if (!dst_chars)
866 return FALSE;
868 TRACE("Converting from '%04x' to '%04x', %i chars\n",
869 lpSource->wFormatID, wFormatID, src_chars);
871 /* Convert characters to bytes */
872 if(wFormatID == CF_UNICODETEXT)
873 alloc_size = dst_chars * sizeof(WCHAR);
874 else
875 alloc_size = dst_chars;
877 hData = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
878 GMEM_DDESHARE, alloc_size);
880 lpstrT = GlobalLock(hData);
882 if (lpstrT)
884 CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS, src_chars,
885 wFormatID, lpstrT, dst_chars);
886 GlobalUnlock(hData);
889 GlobalUnlock(lpSource->hData);
891 return X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, hData, 0, NULL, TRUE);
895 /***********************************************************************
896 * bitmap_info_size
898 * Return the size of the bitmap info structure including color table.
900 static int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
902 unsigned int colors, size, masks = 0;
904 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
906 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
907 colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
908 return sizeof(BITMAPCOREHEADER) + colors *
909 ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
911 else /* assume BITMAPINFOHEADER */
913 colors = info->bmiHeader.biClrUsed;
914 if (!colors && (info->bmiHeader.biBitCount <= 8))
915 colors = 1 << info->bmiHeader.biBitCount;
916 if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
917 size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
918 return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
923 /***********************************************************************
924 * create_dib_from_bitmap
926 * Allocates a packed DIB and copies the bitmap data into it.
928 static HGLOBAL create_dib_from_bitmap(HBITMAP hBmp)
930 BITMAP bmp;
931 HDC hdc;
932 HGLOBAL hPackedDIB;
933 LPBYTE pPackedDIB;
934 LPBITMAPINFOHEADER pbmiHeader;
935 unsigned int cDataSize, cPackedSize, OffsetBits;
936 int nLinesCopied;
938 if (!GetObjectW( hBmp, sizeof(bmp), &bmp )) return 0;
941 * A packed DIB contains a BITMAPINFO structure followed immediately by
942 * an optional color palette and the pixel data.
945 /* Calculate the size of the packed DIB */
946 cDataSize = abs( bmp.bmHeight ) * (((bmp.bmWidth * bmp.bmBitsPixel + 31) / 8) & ~3);
947 cPackedSize = sizeof(BITMAPINFOHEADER)
948 + ( (bmp.bmBitsPixel <= 8) ? (sizeof(RGBQUAD) * (1 << bmp.bmBitsPixel)) : 0 )
949 + cDataSize;
950 /* Get the offset to the bits */
951 OffsetBits = cPackedSize - cDataSize;
953 /* Allocate the packed DIB */
954 TRACE("\tAllocating packed DIB of size %d\n", cPackedSize);
955 hPackedDIB = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE /*| GMEM_ZEROINIT*/,
956 cPackedSize );
957 if ( !hPackedDIB )
959 WARN("Could not allocate packed DIB!\n");
960 return 0;
963 /* A packed DIB starts with a BITMAPINFOHEADER */
964 pPackedDIB = GlobalLock(hPackedDIB);
965 pbmiHeader = (LPBITMAPINFOHEADER)pPackedDIB;
967 /* Init the BITMAPINFOHEADER */
968 pbmiHeader->biSize = sizeof(BITMAPINFOHEADER);
969 pbmiHeader->biWidth = bmp.bmWidth;
970 pbmiHeader->biHeight = bmp.bmHeight;
971 pbmiHeader->biPlanes = 1;
972 pbmiHeader->biBitCount = bmp.bmBitsPixel;
973 pbmiHeader->biCompression = BI_RGB;
974 pbmiHeader->biSizeImage = 0;
975 pbmiHeader->biXPelsPerMeter = pbmiHeader->biYPelsPerMeter = 0;
976 pbmiHeader->biClrUsed = 0;
977 pbmiHeader->biClrImportant = 0;
979 /* Retrieve the DIB bits from the bitmap and fill in the
980 * DIB color table if present */
981 hdc = GetDC( 0 );
982 nLinesCopied = GetDIBits(hdc, /* Handle to device context */
983 hBmp, /* Handle to bitmap */
984 0, /* First scan line to set in dest bitmap */
985 bmp.bmHeight, /* Number of scan lines to copy */
986 pPackedDIB + OffsetBits, /* [out] Address of array for bitmap bits */
987 (LPBITMAPINFO) pbmiHeader, /* [out] Address of BITMAPINFO structure */
988 0); /* RGB or palette index */
989 GlobalUnlock(hPackedDIB);
990 ReleaseDC( 0, hdc );
992 /* Cleanup if GetDIBits failed */
993 if (nLinesCopied != bmp.bmHeight)
995 TRACE("\tGetDIBits returned %d. Actual lines=%d\n", nLinesCopied, bmp.bmHeight);
996 GlobalFree(hPackedDIB);
997 hPackedDIB = 0;
999 return hPackedDIB;
1003 /**************************************************************************
1004 * X11DRV_CLIPBOARD_RenderSynthesizedDIB
1006 * Renders synthesized DIB
1008 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display)
1010 BOOL bret = FALSE;
1011 LPWINE_CLIPDATA lpSource = NULL;
1013 TRACE("\n");
1015 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) && lpSource->hData)
1017 bret = TRUE;
1019 /* If we have a bitmap and it's not synthesized or it has been rendered */
1020 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
1021 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1023 /* Render source if required */
1024 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1026 HGLOBAL hData = create_dib_from_bitmap( lpSource->hData );
1027 if (hData)
1029 X11DRV_CLIPBOARD_InsertClipboardData(CF_DIB, hData, 0, NULL, TRUE);
1030 bret = TRUE;
1035 return bret;
1039 /**************************************************************************
1040 * X11DRV_CLIPBOARD_RenderSynthesizedBitmap
1042 * Renders synthesized bitmap
1044 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display)
1046 BOOL bret = FALSE;
1047 LPWINE_CLIPDATA lpSource = NULL;
1049 TRACE("\n");
1051 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) && lpSource->hData)
1053 bret = TRUE;
1055 /* If we have a dib and it's not synthesized or it has been rendered */
1056 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
1057 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1059 /* Render source if required */
1060 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1062 HDC hdc;
1063 HBITMAP hData = NULL;
1064 unsigned int offset;
1065 LPBITMAPINFOHEADER lpbmih;
1067 hdc = GetDC(NULL);
1068 lpbmih = GlobalLock(lpSource->hData);
1069 if (lpbmih)
1071 offset = sizeof(BITMAPINFOHEADER)
1072 + ((lpbmih->biBitCount <= 8) ? (sizeof(RGBQUAD) *
1073 (1 << lpbmih->biBitCount)) : 0);
1075 hData = CreateDIBitmap(hdc, lpbmih, CBM_INIT, (LPBYTE)lpbmih +
1076 offset, (LPBITMAPINFO) lpbmih, DIB_RGB_COLORS);
1078 GlobalUnlock(lpSource->hData);
1080 ReleaseDC(NULL, hdc);
1082 if (hData)
1084 X11DRV_CLIPBOARD_InsertClipboardData(CF_BITMAP, hData, 0, NULL, TRUE);
1085 bret = TRUE;
1090 return bret;
1094 /**************************************************************************
1095 * X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile
1097 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile(Display *display)
1099 LPWINE_CLIPDATA lpSource = NULL;
1101 TRACE("\n");
1103 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_ENHMETAFILE)) && lpSource->hData)
1104 return TRUE;
1105 /* If we have a MF pict and it's not synthesized or it has been rendered */
1106 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
1107 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1109 /* Render source if required */
1110 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1112 METAFILEPICT *pmfp;
1113 HENHMETAFILE hData = NULL;
1115 pmfp = GlobalLock(lpSource->hData);
1116 if (pmfp)
1118 UINT size_mf_bits = GetMetaFileBitsEx(pmfp->hMF, 0, NULL);
1119 void *mf_bits = HeapAlloc(GetProcessHeap(), 0, size_mf_bits);
1120 if (mf_bits)
1122 GetMetaFileBitsEx(pmfp->hMF, size_mf_bits, mf_bits);
1123 hData = SetWinMetaFileBits(size_mf_bits, mf_bits, NULL, pmfp);
1124 HeapFree(GetProcessHeap(), 0, mf_bits);
1126 GlobalUnlock(lpSource->hData);
1129 if (hData)
1131 X11DRV_CLIPBOARD_InsertClipboardData(CF_ENHMETAFILE, hData, 0, NULL, TRUE);
1132 return TRUE;
1137 return FALSE;
1141 /**************************************************************************
1142 * X11DRV_CLIPBOARD_ImportXAString
1144 * Import XA_STRING, converting the string to CF_TEXT.
1146 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *display, Window w, Atom prop)
1148 LPBYTE lpdata;
1149 unsigned long cbytes;
1150 LPSTR lpstr;
1151 unsigned long i, inlcount = 0;
1152 HANDLE hText = 0;
1154 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1155 return 0;
1157 for (i = 0; i <= cbytes; i++)
1159 if (lpdata[i] == '\n')
1160 inlcount++;
1163 if ((hText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes + inlcount + 1)))
1165 lpstr = GlobalLock(hText);
1167 for (i = 0, inlcount = 0; i <= cbytes; i++)
1169 if (lpdata[i] == '\n')
1170 lpstr[inlcount++] = '\r';
1172 lpstr[inlcount++] = lpdata[i];
1175 GlobalUnlock(hText);
1178 /* Free the retrieved property data */
1179 HeapFree(GetProcessHeap(), 0, lpdata);
1181 return hText;
1185 /**************************************************************************
1186 * X11DRV_CLIPBOARD_ImportUTF8
1188 * Import XA_STRING, converting the string to CF_UNICODE.
1190 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *display, Window w, Atom prop)
1192 LPBYTE lpdata;
1193 unsigned long cbytes;
1194 LPSTR lpstr;
1195 unsigned long i, inlcount = 0;
1196 HANDLE hUnicodeText = 0;
1198 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1199 return 0;
1201 for (i = 0; i <= cbytes; i++)
1203 if (lpdata[i] == '\n')
1204 inlcount++;
1207 if ((lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbytes + inlcount + 1)))
1209 UINT count;
1211 for (i = 0, inlcount = 0; i <= cbytes; i++)
1213 if (lpdata[i] == '\n')
1214 lpstr[inlcount++] = '\r';
1216 lpstr[inlcount++] = lpdata[i];
1219 count = MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, NULL, 0);
1220 hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
1222 if (hUnicodeText)
1224 WCHAR *textW = GlobalLock(hUnicodeText);
1225 MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, textW, count);
1226 GlobalUnlock(hUnicodeText);
1229 HeapFree(GetProcessHeap(), 0, lpstr);
1232 /* Free the retrieved property data */
1233 HeapFree(GetProcessHeap(), 0, lpdata);
1235 return hUnicodeText;
1239 /**************************************************************************
1240 * X11DRV_CLIPBOARD_ImportCompoundText
1242 * Import COMPOUND_TEXT to CF_UNICODE
1244 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *display, Window w, Atom prop)
1246 int i, j, ret;
1247 char** srcstr;
1248 int count, lcount;
1249 int srclen, destlen;
1250 HANDLE hUnicodeText;
1251 XTextProperty txtprop;
1253 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &txtprop.value, &txtprop.nitems))
1255 return 0;
1258 txtprop.encoding = x11drv_atom(COMPOUND_TEXT);
1259 txtprop.format = 8;
1260 ret = XmbTextPropertyToTextList(display, &txtprop, &srcstr, &count);
1261 HeapFree(GetProcessHeap(), 0, txtprop.value);
1262 if (ret != Success || !count) return 0;
1264 TRACE("Importing %d line(s)\n", count);
1266 /* Compute number of lines */
1267 srclen = strlen(srcstr[0]);
1268 for (i = 0, lcount = 0; i <= srclen; i++)
1270 if (srcstr[0][i] == '\n')
1271 lcount++;
1274 destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
1276 TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
1278 if ((hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (destlen + lcount + 1) * sizeof(WCHAR))))
1280 WCHAR *deststr = GlobalLock(hUnicodeText);
1281 MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1283 if (lcount)
1285 for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1287 deststr[j] = deststr[i];
1289 if (deststr[i] == '\n')
1290 deststr[--j] = '\r';
1294 GlobalUnlock(hUnicodeText);
1297 XFreeStringList(srcstr);
1299 return hUnicodeText;
1303 /**************************************************************************
1304 * X11DRV_CLIPBOARD_ImportXAPIXMAP
1306 * Import XA_PIXMAP, converting the image to CF_DIB.
1308 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *display, Window w, Atom prop)
1310 LPBYTE lpdata;
1311 unsigned long cbytes;
1312 Pixmap *pPixmap;
1313 HANDLE hClipData = 0;
1315 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1317 XVisualInfo vis = default_visual;
1318 char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
1319 BITMAPINFO *info = (BITMAPINFO *)buffer;
1320 struct gdi_image_bits bits;
1321 Window root;
1322 int x,y; /* Unused */
1323 unsigned border_width; /* Unused */
1324 unsigned int depth, width, height;
1326 pPixmap = (Pixmap *) lpdata;
1328 /* Get the Pixmap dimensions and bit depth */
1329 if (!XGetGeometry(gdi_display, *pPixmap, &root, &x, &y, &width, &height,
1330 &border_width, &depth)) depth = 0;
1331 if (!pixmap_formats[depth]) return 0;
1333 TRACE("\tPixmap properties: width=%d, height=%d, depth=%d\n",
1334 width, height, depth);
1336 if (depth != vis.depth) switch (pixmap_formats[depth]->bits_per_pixel)
1338 case 1:
1339 case 4:
1340 case 8:
1341 break;
1342 case 16: /* assume R5G5B5 */
1343 vis.red_mask = 0x7c00;
1344 vis.green_mask = 0x03e0;
1345 vis.blue_mask = 0x001f;
1346 break;
1347 case 24: /* assume R8G8B8 */
1348 case 32: /* assume A8R8G8B8 */
1349 vis.red_mask = 0xff0000;
1350 vis.green_mask = 0x00ff00;
1351 vis.blue_mask = 0x0000ff;
1352 break;
1353 default:
1354 return 0;
1357 if (!get_pixmap_image( *pPixmap, width, height, &vis, info, &bits ))
1359 DWORD info_size = bitmap_info_size( info, DIB_RGB_COLORS );
1360 BYTE *ptr;
1362 hClipData = GlobalAlloc( GMEM_MOVEABLE | GMEM_DDESHARE,
1363 info_size + info->bmiHeader.biSizeImage );
1364 if (hClipData)
1366 ptr = GlobalLock( hClipData );
1367 memcpy( ptr, info, info_size );
1368 memcpy( ptr + info_size, bits.ptr, info->bmiHeader.biSizeImage );
1369 GlobalUnlock( hClipData );
1371 if (bits.free) bits.free( &bits );
1375 return hClipData;
1379 /**************************************************************************
1380 * X11DRV_CLIPBOARD_ImportImageBmp
1382 * Import image/bmp, converting the image to CF_DIB.
1384 static HANDLE X11DRV_CLIPBOARD_ImportImageBmp(Display *display, Window w, Atom prop)
1386 LPBYTE lpdata;
1387 unsigned long cbytes;
1388 HANDLE hClipData = 0;
1390 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1392 BITMAPFILEHEADER *bfh = (BITMAPFILEHEADER*)lpdata;
1394 if (cbytes >= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPCOREHEADER) &&
1395 bfh->bfType == 0x4d42 /* "BM" */)
1397 BITMAPINFO *bmi = (BITMAPINFO*)(bfh+1);
1398 HBITMAP hbmp;
1399 HDC hdc;
1401 hdc = GetDC(0);
1402 hbmp = CreateDIBitmap(
1403 hdc,
1404 &(bmi->bmiHeader),
1405 CBM_INIT,
1406 lpdata+bfh->bfOffBits,
1407 bmi,
1408 DIB_RGB_COLORS
1411 hClipData = create_dib_from_bitmap( hbmp );
1413 DeleteObject(hbmp);
1414 ReleaseDC(0, hdc);
1417 /* Free the retrieved property data */
1418 HeapFree(GetProcessHeap(), 0, lpdata);
1421 return hClipData;
1425 /**************************************************************************
1426 * X11DRV_CLIPBOARD_ImportMetaFilePict
1428 * Import MetaFilePict.
1430 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *display, Window w, Atom prop)
1432 LPBYTE lpdata;
1433 unsigned long cbytes;
1434 HANDLE hClipData = 0;
1436 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1438 if (cbytes)
1439 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata, (LPDWORD)&cbytes, FALSE);
1441 /* Free the retrieved property data */
1442 HeapFree(GetProcessHeap(), 0, lpdata);
1445 return hClipData;
1449 /**************************************************************************
1450 * X11DRV_ImportEnhMetaFile
1452 * Import EnhMetaFile.
1454 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *display, Window w, Atom prop)
1456 LPBYTE lpdata;
1457 unsigned long cbytes;
1458 HANDLE hClipData = 0;
1460 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1462 if (cbytes)
1463 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata, (LPDWORD)&cbytes, FALSE);
1465 /* Free the retrieved property data */
1466 HeapFree(GetProcessHeap(), 0, lpdata);
1469 return hClipData;
1473 /**************************************************************************
1474 * X11DRV_ImportClipbordaData
1476 * Generic import clipboard data routine.
1478 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *display, Window w, Atom prop)
1480 LPVOID lpClipData;
1481 LPBYTE lpdata;
1482 unsigned long cbytes;
1483 HANDLE hClipData = 0;
1485 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1487 if (cbytes)
1489 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
1490 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes);
1491 if (hClipData == 0)
1492 return NULL;
1494 if ((lpClipData = GlobalLock(hClipData)))
1496 memcpy(lpClipData, lpdata, cbytes);
1497 GlobalUnlock(hClipData);
1499 else
1501 GlobalFree(hClipData);
1502 hClipData = 0;
1506 /* Free the retrieved property data */
1507 HeapFree(GetProcessHeap(), 0, lpdata);
1510 return hClipData;
1514 /**************************************************************************
1515 X11DRV_CLIPBOARD_ExportClipboardData
1517 * Generic export clipboard data routine.
1519 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
1520 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1522 LPVOID lpClipData;
1523 UINT datasize = 0;
1524 HANDLE hClipData = 0;
1526 *lpBytes = 0; /* Assume failure */
1528 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1529 ERR("Failed to export %04x format\n", lpData->wFormatID);
1530 else
1532 datasize = GlobalSize(lpData->hData);
1534 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, datasize);
1535 if (hClipData == 0) return NULL;
1537 if ((lpClipData = GlobalLock(hClipData)))
1539 LPVOID lpdata = GlobalLock(lpData->hData);
1541 memcpy(lpClipData, lpdata, datasize);
1542 *lpBytes = datasize;
1544 GlobalUnlock(lpData->hData);
1545 GlobalUnlock(hClipData);
1546 } else {
1547 GlobalFree(hClipData);
1548 hClipData = 0;
1552 return hClipData;
1556 /**************************************************************************
1557 * X11DRV_CLIPBOARD_ExportXAString
1559 * Export CF_TEXT converting the string to XA_STRING.
1560 * Helper function for X11DRV_CLIPBOARD_ExportString.
1562 static HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1564 UINT i, j;
1565 UINT size;
1566 LPSTR text, lpstr = NULL;
1568 *lpBytes = 0; /* Assume return has zero bytes */
1570 text = GlobalLock(lpData->hData);
1571 size = strlen(text);
1573 /* remove carriage returns */
1574 lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1575 if (lpstr == NULL)
1576 goto done;
1578 for (i = 0,j = 0; i < size && text[i]; i++)
1580 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1581 continue;
1582 lpstr[j++] = text[i];
1585 lpstr[j]='\0';
1586 *lpBytes = j; /* Number of bytes in string */
1588 done:
1589 GlobalUnlock(lpData->hData);
1591 return lpstr;
1595 /**************************************************************************
1596 * X11DRV_CLIPBOARD_ExportUTF8String
1598 * Export CF_UNICODE converting the string to UTF8.
1599 * Helper function for X11DRV_CLIPBOARD_ExportString.
1601 static HANDLE X11DRV_CLIPBOARD_ExportUTF8String(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1603 UINT i, j;
1604 UINT size;
1605 LPWSTR uni_text;
1606 LPSTR text, lpstr = NULL;
1608 *lpBytes = 0; /* Assume return has zero bytes */
1610 uni_text = GlobalLock(lpData->hData);
1612 size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1614 text = HeapAlloc(GetProcessHeap(), 0, size);
1615 if (!text)
1616 goto done;
1617 WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1619 /* remove carriage returns */
1620 lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1621 if (lpstr == NULL)
1622 goto done;
1624 for (i = 0,j = 0; i < size && text[i]; i++)
1626 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1627 continue;
1628 lpstr[j++] = text[i];
1630 lpstr[j]='\0';
1632 *lpBytes = j; /* Number of bytes in string */
1634 done:
1635 HeapFree(GetProcessHeap(), 0, text);
1636 GlobalUnlock(lpData->hData);
1638 return lpstr;
1643 /**************************************************************************
1644 * X11DRV_CLIPBOARD_ExportCompoundText
1646 * Export CF_UNICODE to COMPOUND_TEXT
1647 * Helper function for X11DRV_CLIPBOARD_ExportString.
1649 static HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Display *display, Window requestor, Atom aTarget, Atom rprop,
1650 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1652 char* lpstr = 0;
1653 XTextProperty prop;
1654 XICCEncodingStyle style;
1655 UINT i, j;
1656 UINT size;
1657 LPWSTR uni_text;
1659 uni_text = GlobalLock(lpData->hData);
1661 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1662 lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1663 if (!lpstr)
1664 return 0;
1666 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1668 /* remove carriage returns */
1669 for (i = 0, j = 0; i < size && lpstr[i]; i++)
1671 if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1672 continue;
1673 lpstr[j++] = lpstr[i];
1675 lpstr[j]='\0';
1677 GlobalUnlock(lpData->hData);
1679 if (aTarget == x11drv_atom(COMPOUND_TEXT))
1680 style = XCompoundTextStyle;
1681 else
1682 style = XStdICCTextStyle;
1684 /* Update the X property */
1685 if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1687 XSetTextProperty(display, requestor, &prop, rprop);
1688 XFree(prop.value);
1691 HeapFree(GetProcessHeap(), 0, lpstr);
1693 return 0;
1696 /**************************************************************************
1697 * X11DRV_CLIPBOARD_ExportString
1699 * Export string
1701 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget, Atom rprop,
1702 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1704 if (X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1706 if (aTarget == XA_STRING)
1707 return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1708 else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1709 return X11DRV_CLIPBOARD_ExportCompoundText(display, requestor, aTarget,
1710 rprop, lpData, lpBytes);
1711 else
1713 TRACE("Exporting target %ld to default UTF8_STRING\n", aTarget);
1714 return X11DRV_CLIPBOARD_ExportUTF8String(lpData, lpBytes);
1717 else
1718 ERR("Failed to render %04x format\n", lpData->wFormatID);
1720 return 0;
1724 /**************************************************************************
1725 * X11DRV_CLIPBOARD_ExportXAPIXMAP
1727 * Export CF_DIB to XA_PIXMAP.
1729 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget, Atom rprop,
1730 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1732 HANDLE hData;
1733 unsigned char* lpData;
1735 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1737 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1738 return 0;
1741 if (!lpdata->drvData) /* If not already rendered */
1743 Pixmap pixmap;
1744 LPBITMAPINFO pbmi;
1745 struct gdi_image_bits bits;
1747 pbmi = GlobalLock( lpdata->hData );
1748 bits.ptr = (LPBYTE)pbmi + bitmap_info_size( pbmi, DIB_RGB_COLORS );
1749 bits.free = NULL;
1750 bits.is_copy = FALSE;
1751 pixmap = create_pixmap_from_image( 0, &default_visual, pbmi, &bits, DIB_RGB_COLORS );
1752 GlobalUnlock( lpdata->hData );
1753 lpdata->drvData = pixmap;
1756 *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1758 /* Wrap pixmap so we can return a handle */
1759 hData = GlobalAlloc(0, *lpBytes);
1760 lpData = GlobalLock(hData);
1761 memcpy(lpData, &lpdata->drvData, *lpBytes);
1762 GlobalUnlock(hData);
1764 return hData;
1768 /**************************************************************************
1769 * X11DRV_CLIPBOARD_ExportImageBmp
1771 * Export CF_DIB to image/bmp.
1773 static HANDLE X11DRV_CLIPBOARD_ExportImageBmp(Display *display, Window requestor, Atom aTarget, Atom rprop,
1774 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1776 HANDLE hpackeddib;
1777 LPBYTE dibdata;
1778 UINT bmpsize;
1779 HANDLE hbmpdata;
1780 LPBYTE bmpdata;
1781 BITMAPFILEHEADER *bfh;
1783 *lpBytes = 0;
1785 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1787 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1788 return 0;
1791 hpackeddib = lpdata->hData;
1793 dibdata = GlobalLock(hpackeddib);
1794 if (!dibdata)
1796 ERR("Failed to lock packed DIB\n");
1797 return 0;
1800 bmpsize = sizeof(BITMAPFILEHEADER) + GlobalSize(hpackeddib);
1802 hbmpdata = GlobalAlloc(0, bmpsize);
1804 if (hbmpdata)
1806 bmpdata = GlobalLock(hbmpdata);
1808 if (!bmpdata)
1810 GlobalFree(hbmpdata);
1811 GlobalUnlock(hpackeddib);
1812 return 0;
1815 /* bitmap file header */
1816 bfh = (BITMAPFILEHEADER*)bmpdata;
1817 bfh->bfType = 0x4d42; /* "BM" */
1818 bfh->bfSize = bmpsize;
1819 bfh->bfReserved1 = 0;
1820 bfh->bfReserved2 = 0;
1821 bfh->bfOffBits = sizeof(BITMAPFILEHEADER) + bitmap_info_size((BITMAPINFO*)dibdata, DIB_RGB_COLORS);
1823 /* rest of bitmap is the same as the packed dib */
1824 memcpy(bfh+1, dibdata, bmpsize-sizeof(BITMAPFILEHEADER));
1826 *lpBytes = bmpsize;
1828 GlobalUnlock(hbmpdata);
1831 GlobalUnlock(hpackeddib);
1833 return hbmpdata;
1837 /**************************************************************************
1838 * X11DRV_CLIPBOARD_ExportMetaFilePict
1840 * Export MetaFilePict.
1842 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget, Atom rprop,
1843 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1845 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1847 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1848 return 0;
1851 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata->hData, lpBytes, TRUE);
1855 /**************************************************************************
1856 * X11DRV_CLIPBOARD_ExportEnhMetaFile
1858 * Export EnhMetaFile.
1860 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget, Atom rprop,
1861 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1863 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1865 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1866 return 0;
1869 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata->hData, lpBytes, TRUE);
1873 /**************************************************************************
1874 * get_html_description_field
1876 * Find the value of a field in an HTML Format description.
1878 static LPCSTR get_html_description_field(LPCSTR data, LPCSTR keyword)
1880 LPCSTR pos=data;
1882 while (pos && *pos && *pos != '<')
1884 if (memcmp(pos, keyword, strlen(keyword)) == 0)
1885 return pos+strlen(keyword);
1887 pos = strchr(pos, '\n');
1888 if (pos) pos++;
1891 return NULL;
1895 /**************************************************************************
1896 * X11DRV_CLIPBOARD_ExportTextHtml
1898 * Export HTML Format to text/html.
1900 * FIXME: We should attempt to add an <a base> tag and convert windows paths.
1902 static HANDLE X11DRV_CLIPBOARD_ExportTextHtml(Display *display, Window requestor, Atom aTarget,
1903 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1905 HANDLE hdata;
1906 LPCSTR data, field_value;
1907 UINT fragmentstart, fragmentend, htmlsize;
1908 HANDLE hhtmldata=NULL;
1909 LPSTR htmldata;
1911 *lpBytes = 0;
1913 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1915 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1916 return 0;
1919 hdata = lpdata->hData;
1921 data = GlobalLock(hdata);
1922 if (!data)
1924 ERR("Failed to lock HTML Format data\n");
1925 return 0;
1928 /* read the important fields */
1929 field_value = get_html_description_field(data, "StartFragment:");
1930 if (!field_value)
1932 ERR("Couldn't find StartFragment value\n");
1933 goto end;
1935 fragmentstart = atoi(field_value);
1937 field_value = get_html_description_field(data, "EndFragment:");
1938 if (!field_value)
1940 ERR("Couldn't find EndFragment value\n");
1941 goto end;
1943 fragmentend = atoi(field_value);
1945 /* export only the fragment */
1946 htmlsize = fragmentend - fragmentstart + 1;
1948 hhtmldata = GlobalAlloc(0, htmlsize);
1950 if (hhtmldata)
1952 htmldata = GlobalLock(hhtmldata);
1954 if (!htmldata)
1956 GlobalFree(hhtmldata);
1957 htmldata = NULL;
1958 goto end;
1961 memcpy(htmldata, &data[fragmentstart], fragmentend-fragmentstart);
1962 htmldata[htmlsize-1] = '\0';
1964 *lpBytes = htmlsize;
1966 GlobalUnlock(htmldata);
1969 end:
1971 GlobalUnlock(hdata);
1973 return hhtmldata;
1977 /**************************************************************************
1978 * X11DRV_CLIPBOARD_QueryTargets
1980 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection,
1981 Atom target, XEvent *xe)
1983 INT i;
1985 XConvertSelection(display, selection, target, x11drv_atom(SELECTION_DATA), w, CurrentTime);
1988 * Wait until SelectionNotify is received
1990 for (i = 0; i < SELECTION_RETRIES; i++)
1992 Bool res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
1993 if (res && xe->xselection.selection == selection) break;
1995 usleep(SELECTION_WAIT);
1998 if (i == SELECTION_RETRIES)
2000 ERR("Timed out waiting for SelectionNotify event\n");
2001 return FALSE;
2003 /* Verify that the selection returned a valid TARGETS property */
2004 if ((xe->xselection.target != target) || (xe->xselection.property == None))
2006 /* Selection owner failed to respond or we missed the SelectionNotify */
2007 WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
2008 return FALSE;
2011 return TRUE;
2015 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
2017 return (event->error_code == BadAtom);
2020 /**************************************************************************
2021 * X11DRV_CLIPBOARD_InsertSelectionProperties
2023 * Mark properties available for future retrieval.
2025 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
2027 UINT i, nb_atoms = 0;
2028 Atom *atoms = NULL;
2030 /* Cache these formats in the clipboard cache */
2031 for (i = 0; i < count; i++)
2033 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
2035 if (lpFormat)
2037 /* We found at least one Window's format that mapps to the property.
2038 * Continue looking for more.
2040 * If more than one property map to a Window's format then we use the first
2041 * one and ignore the rest.
2043 while (lpFormat)
2045 TRACE("Atom#%d Property(%d): --> Format %s\n",
2046 i, lpFormat->drvData, debugstr_format(lpFormat->wFormatID));
2047 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, lpFormat, FALSE);
2048 lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
2051 else if (properties[i])
2053 /* add it to the list of atoms that we don't know about yet */
2054 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
2055 (count - i) * sizeof(*atoms) );
2056 if (atoms) atoms[nb_atoms++] = properties[i];
2060 /* query all unknown atoms in one go */
2061 if (atoms)
2063 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
2064 if (names)
2066 X11DRV_expect_error( display, is_atom_error, NULL );
2067 if (!XGetAtomNames( display, atoms, nb_atoms, names )) nb_atoms = 0;
2068 if (X11DRV_check_error())
2070 WARN( "got some bad atoms, ignoring\n" );
2071 nb_atoms = 0;
2073 for (i = 0; i < nb_atoms; i++)
2075 WINE_CLIPFORMAT *lpFormat;
2076 LPWSTR wname;
2077 int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
2078 wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2079 MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
2081 lpFormat = register_format( RegisterClipboardFormatW(wname), atoms[i] );
2082 HeapFree(GetProcessHeap(), 0, wname);
2083 if (!lpFormat)
2085 ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
2086 continue;
2088 TRACE("Atom#%d Property(%d): --> Format %s\n",
2089 i, lpFormat->drvData, debugstr_format(lpFormat->wFormatID));
2090 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, lpFormat, FALSE);
2092 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
2093 HeapFree( GetProcessHeap(), 0, names );
2095 HeapFree( GetProcessHeap(), 0, atoms );
2100 /**************************************************************************
2101 * X11DRV_CLIPBOARD_QueryAvailableData
2103 * Caches the list of data formats available from the current selection.
2104 * This queries the selection owner for the TARGETS property and saves all
2105 * reported property types.
2107 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo)
2109 XEvent xe;
2110 Atom atype=AnyPropertyType;
2111 int aformat;
2112 unsigned long remain;
2113 Atom* targetList=NULL;
2114 Window w;
2115 unsigned long cSelectionTargets = 0;
2117 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
2119 ERR("Received request to cache selection but process is owner=(%08x)\n",
2120 (unsigned) selectionWindow);
2121 return -1; /* Prevent self request */
2124 w = thread_selection_wnd();
2125 if (!w)
2127 ERR("No window available to retrieve selection!\n");
2128 return -1;
2132 * Query the selection owner for the TARGETS property
2134 if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
2135 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2137 if (use_primary_selection && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
2138 selectionCacheSrc = XA_PRIMARY;
2139 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
2140 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2141 else
2143 Atom xstr = XA_STRING;
2145 /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
2146 if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
2148 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2149 selectionCacheSrc = XA_PRIMARY;
2150 return 1;
2152 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
2154 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2155 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2156 return 1;
2158 else
2160 WARN("Failed to query selection owner for available data.\n");
2161 return -1;
2165 else return 0; /* No selection owner so report 0 targets available */
2167 /* Read the TARGETS property contents */
2168 if (!XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
2169 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
2170 &remain, (unsigned char**)&targetList) != Success)
2172 TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
2173 atype, aformat, cSelectionTargets, remain);
2175 * The TARGETS property should have returned us a list of atoms
2176 * corresponding to each selection target format supported.
2178 if (atype == XA_ATOM || atype == x11drv_atom(TARGETS))
2180 if (aformat == 32)
2182 X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, cSelectionTargets);
2184 else if (aformat == 8) /* work around quartz-wm brain damage */
2186 unsigned long i, count = cSelectionTargets / sizeof(CARD32);
2187 Atom *atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(Atom) );
2188 for (i = 0; i < count; i++)
2189 atoms[i] = ((CARD32 *)targetList)[i]; /* FIXME: byte swapping */
2190 X11DRV_CLIPBOARD_InsertSelectionProperties( display, atoms, count );
2191 HeapFree( GetProcessHeap(), 0, atoms );
2195 /* Free the list of targets */
2196 XFree(targetList);
2198 else WARN("Failed to read TARGETS property\n");
2200 return cSelectionTargets;
2204 /**************************************************************************
2205 * X11DRV_CLIPBOARD_ReadSelectionData
2207 * This method is invoked only when we DO NOT own the X selection
2209 * We always get the data from the selection client each time,
2210 * since we have no way of determining if the data in our cache is stale.
2212 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData)
2214 Bool res;
2215 DWORD i;
2216 XEvent xe;
2217 BOOL bRet = FALSE;
2219 TRACE("%04x\n", lpData->wFormatID);
2221 if (!lpData->lpFormat)
2223 ERR("Requesting format %04x but no source format linked to data.\n",
2224 lpData->wFormatID);
2225 return FALSE;
2228 if (!selectionAcquired)
2230 Window w = thread_selection_wnd();
2231 if(!w)
2233 ERR("No window available to read selection data!\n");
2234 return FALSE;
2237 TRACE("Requesting conversion of %s property (%d) from selection type %08x\n",
2238 debugstr_format(lpData->lpFormat->wFormatID), lpData->lpFormat->drvData,
2239 (UINT)selectionCacheSrc);
2241 XConvertSelection(display, selectionCacheSrc, lpData->lpFormat->drvData,
2242 x11drv_atom(SELECTION_DATA), w, CurrentTime);
2244 /* wait until SelectionNotify is received */
2245 for (i = 0; i < SELECTION_RETRIES; i++)
2247 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
2248 if (res && xe.xselection.selection == selectionCacheSrc) break;
2250 usleep(SELECTION_WAIT);
2253 if (i == SELECTION_RETRIES)
2255 ERR("Timed out waiting for SelectionNotify event\n");
2257 /* Verify that the selection returned a valid TARGETS property */
2258 else if (xe.xselection.property != None)
2261 * Read the contents of the X selection property
2262 * into WINE's clipboard cache and converting the
2263 * data format if necessary.
2265 HANDLE hData = lpData->lpFormat->lpDrvImportFunc(display, xe.xselection.requestor,
2266 xe.xselection.property);
2268 if (hData)
2269 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, hData, 0, lpData->lpFormat, TRUE);
2270 else
2271 TRACE("Import function failed\n");
2273 else
2275 TRACE("Failed to convert selection\n");
2278 else
2280 ERR("Received request to cache selection data but process is owner\n");
2283 TRACE("Returning %d\n", bRet);
2285 return bRet;
2289 /**************************************************************************
2290 * X11DRV_CLIPBOARD_GetProperty
2291 * Gets type, data and size.
2293 static BOOL X11DRV_CLIPBOARD_GetProperty(Display *display, Window w, Atom prop,
2294 Atom *atype, unsigned char** data, unsigned long* datasize)
2296 int aformat;
2297 unsigned long pos = 0, nitems, remain, count;
2298 unsigned char *val = NULL, *buffer;
2300 TRACE("Reading property %lu from X window %lx\n", prop, w);
2302 for (;;)
2304 if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
2305 AnyPropertyType, atype, &aformat, &nitems, &remain, &buffer) != Success)
2307 WARN("Failed to read property\n");
2308 HeapFree( GetProcessHeap(), 0, val );
2309 return FALSE;
2312 count = get_property_size( aformat, nitems );
2313 if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
2314 else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
2316 if (!*data)
2318 XFree( buffer );
2319 HeapFree( GetProcessHeap(), 0, val );
2320 return FALSE;
2322 val = *data;
2323 memcpy( (int *)val + pos, buffer, count );
2324 XFree( buffer );
2325 if (!remain)
2327 *datasize = pos * sizeof(int) + count;
2328 val[*datasize] = 0;
2329 break;
2331 pos += count / sizeof(int);
2334 /* Delete the property on the window now that we are done
2335 * This will send a PropertyNotify event to the selection owner. */
2336 XDeleteProperty(display, w, prop);
2337 return TRUE;
2341 /**************************************************************************
2342 * X11DRV_CLIPBOARD_ReadProperty
2343 * Reads the contents of the X selection property.
2345 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
2346 unsigned char** data, unsigned long* datasize)
2348 Atom atype;
2349 XEvent xe;
2351 if (prop == None)
2352 return FALSE;
2354 if (!X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, data, datasize))
2355 return FALSE;
2357 while (XCheckTypedWindowEvent(display, w, PropertyNotify, &xe))
2360 if (atype == x11drv_atom(INCR))
2362 unsigned char *buf = *data;
2363 unsigned long bufsize = 0;
2365 for (;;)
2367 int i;
2368 unsigned char *prop_data, *tmp;
2369 unsigned long prop_size;
2371 /* Wait until PropertyNotify is received */
2372 for (i = 0; i < SELECTION_RETRIES; i++)
2374 Bool res;
2376 res = XCheckTypedWindowEvent(display, w, PropertyNotify, &xe);
2377 if (res && xe.xproperty.atom == prop &&
2378 xe.xproperty.state == PropertyNewValue)
2379 break;
2380 usleep(SELECTION_WAIT);
2383 if (i >= SELECTION_RETRIES ||
2384 !X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, &prop_data, &prop_size))
2386 HeapFree(GetProcessHeap(), 0, buf);
2387 return FALSE;
2390 /* Retrieved entire data. */
2391 if (prop_size == 0)
2393 HeapFree(GetProcessHeap(), 0, prop_data);
2394 *data = buf;
2395 *datasize = bufsize;
2396 return TRUE;
2399 tmp = HeapReAlloc(GetProcessHeap(), 0, buf, bufsize + prop_size + 1);
2400 if (!tmp)
2402 HeapFree(GetProcessHeap(), 0, buf);
2403 HeapFree(GetProcessHeap(), 0, prop_data);
2404 return FALSE;
2407 buf = tmp;
2408 memcpy(buf + bufsize, prop_data, prop_size + 1);
2409 bufsize += prop_size;
2410 HeapFree(GetProcessHeap(), 0, prop_data);
2414 return TRUE;
2418 /**************************************************************************
2419 * CLIPBOARD_SerializeMetafile
2421 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
2423 HANDLE h = 0;
2425 TRACE(" wFormat=%d hdata=%p out=%d\n", wformat, hdata, out);
2427 if (out) /* Serialize out, caller should free memory */
2429 *lpcbytes = 0; /* Assume failure */
2431 if (wformat == CF_METAFILEPICT)
2433 LPMETAFILEPICT lpmfp = GlobalLock(hdata);
2434 unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2436 h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
2437 if (h)
2439 char *pdata = GlobalLock(h);
2441 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
2442 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
2444 *lpcbytes = size + sizeof(METAFILEPICT);
2446 GlobalUnlock(h);
2449 GlobalUnlock(hdata);
2451 else if (wformat == CF_ENHMETAFILE)
2453 int size = GetEnhMetaFileBits(hdata, 0, NULL);
2455 h = GlobalAlloc(0, size);
2456 if (h)
2458 LPVOID pdata = GlobalLock(h);
2460 GetEnhMetaFileBits(hdata, size, pdata);
2461 *lpcbytes = size;
2463 GlobalUnlock(h);
2467 else
2469 if (wformat == CF_METAFILEPICT)
2471 h = GlobalAlloc(0, sizeof(METAFILEPICT));
2472 if (h)
2474 unsigned int wiresize;
2475 LPMETAFILEPICT lpmfp = GlobalLock(h);
2477 memcpy(lpmfp, hdata, sizeof(METAFILEPICT));
2478 wiresize = *lpcbytes - sizeof(METAFILEPICT);
2479 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
2480 ((const BYTE *)hdata) + sizeof(METAFILEPICT));
2481 GlobalUnlock(h);
2484 else if (wformat == CF_ENHMETAFILE)
2486 h = SetEnhMetaFileBits(*lpcbytes, hdata);
2490 return h;
2494 /**************************************************************************
2495 * X11DRV_CLIPBOARD_ReleaseSelection
2497 * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
2499 static void X11DRV_CLIPBOARD_ReleaseSelection(Display *display, Atom selType, Window w, HWND hwnd, Time time)
2501 /* w is the window that lost the selection
2503 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
2504 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
2506 if (selectionAcquired && (w == selectionWindow))
2508 CLIPBOARDINFO cbinfo;
2510 /* completely give up the selection */
2511 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
2513 X11DRV_CLIPBOARD_GetClipboardInfo(&cbinfo);
2515 if (cbinfo.flags & CB_PROCESS)
2517 /* Since we're still the owner, this wasn't initiated by
2518 another Wine process */
2519 if (OpenClipboard(hwnd))
2521 /* Destroy private objects */
2522 SendMessageW(cbinfo.hWndOwner, WM_DESTROYCLIPBOARD, 0, 0);
2524 /* Give up ownership of the windows clipboard */
2525 X11DRV_CLIPBOARD_ReleaseOwnership();
2526 CloseClipboard();
2530 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2532 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2534 if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2536 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2537 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2539 else
2540 TRACE("We no longer own PRIMARY\n");
2542 else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2544 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2546 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2548 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2549 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2551 else
2552 TRACE("We no longer own CLIPBOARD\n");
2555 selectionWindow = None;
2557 X11DRV_EmptyClipboard(FALSE);
2559 /* Reset the selection flags now that we are done */
2560 selectionAcquired = S_NOSELECTION;
2565 /**************************************************************************
2566 * IsSelectionOwner (X11DRV.@)
2568 * Returns: TRUE if the selection is owned by this process, FALSE otherwise
2570 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void)
2572 return selectionAcquired;
2576 /**************************************************************************
2577 * X11DRV Clipboard Exports
2578 **************************************************************************/
2581 static void selection_acquire(void)
2583 Window owner;
2584 Display *display;
2586 owner = thread_selection_wnd();
2587 display = thread_display();
2589 selectionAcquired = 0;
2590 selectionWindow = 0;
2592 /* Grab PRIMARY selection if not owned */
2593 if (use_primary_selection)
2594 XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2596 /* Grab CLIPBOARD selection if not owned */
2597 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2599 if (use_primary_selection && XGetSelectionOwner(display, XA_PRIMARY) == owner)
2600 selectionAcquired |= S_PRIMARY;
2602 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2603 selectionAcquired |= S_CLIPBOARD;
2605 if (selectionAcquired)
2607 selectionWindow = owner;
2608 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2612 static DWORD WINAPI selection_thread_proc(LPVOID p)
2614 HANDLE event = p;
2616 TRACE("\n");
2618 selection_acquire();
2619 SetEvent(event);
2621 while (selectionAcquired)
2623 MsgWaitForMultipleObjectsEx(0, NULL, INFINITE, QS_SENDMESSAGE, 0);
2626 return 0;
2629 /**************************************************************************
2630 * AcquireClipboard (X11DRV.@)
2632 int CDECL X11DRV_AcquireClipboard(HWND hWndClipWindow)
2634 DWORD procid;
2635 HANDLE selectionThread;
2637 TRACE(" %p\n", hWndClipWindow);
2640 * It's important that the selection get acquired from the thread
2641 * that owns the clipboard window. The primary reason is that we know
2642 * it is running a message loop and therefore can process the
2643 * X selection events.
2645 if (hWndClipWindow &&
2646 GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, &procid))
2648 if (procid != GetCurrentProcessId())
2650 WARN("Setting clipboard owner to other process is not supported\n");
2651 hWndClipWindow = NULL;
2653 else
2655 TRACE("Thread %x is acquiring selection with thread %x's window %p\n",
2656 GetCurrentThreadId(),
2657 GetWindowThreadProcessId(hWndClipWindow, NULL), hWndClipWindow);
2659 return SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0);
2663 if (hWndClipWindow)
2665 selection_acquire();
2667 else
2669 HANDLE event = CreateEventW(NULL, FALSE, FALSE, NULL);
2670 selectionThread = CreateThread(NULL, 0, selection_thread_proc, event, 0, NULL);
2672 if (!selectionThread)
2674 WARN("Could not start clipboard thread\n");
2675 CloseHandle(event);
2676 return 0;
2679 WaitForSingleObject(event, INFINITE);
2680 CloseHandle(event);
2681 CloseHandle(selectionThread);
2684 return 1;
2688 /**************************************************************************
2689 * X11DRV_EmptyClipboard
2691 * Empty cached clipboard data.
2693 void CDECL X11DRV_EmptyClipboard(BOOL keepunowned)
2695 WINE_CLIPDATA *data, *next;
2697 LIST_FOR_EACH_ENTRY_SAFE( data, next, &data_list, WINE_CLIPDATA, entry )
2699 if (keepunowned && (data->wFlags & CF_FLAG_UNOWNED)) continue;
2700 list_remove( &data->entry );
2701 X11DRV_CLIPBOARD_FreeData( data );
2702 HeapFree( GetProcessHeap(), 0, data );
2703 ClipDataCount--;
2706 TRACE(" %d entries remaining in cache.\n", ClipDataCount);
2711 /**************************************************************************
2712 * X11DRV_SetClipboardData
2714 BOOL CDECL X11DRV_SetClipboardData(UINT wFormat, HANDLE hData, BOOL owner)
2716 DWORD flags = 0;
2717 BOOL bResult = TRUE;
2719 /* If it's not owned, data can only be set if the format data is not already owned
2720 and its rendering is not delayed */
2721 if (!owner)
2723 CLIPBOARDINFO cbinfo;
2724 LPWINE_CLIPDATA lpRender;
2726 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2728 if (!hData ||
2729 ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)) &&
2730 !(lpRender->wFlags & CF_FLAG_UNOWNED)))
2731 bResult = FALSE;
2732 else
2733 flags = CF_FLAG_UNOWNED;
2736 bResult &= X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData, flags, NULL, TRUE);
2738 return bResult;
2742 /**************************************************************************
2743 * CountClipboardFormats
2745 INT CDECL X11DRV_CountClipboardFormats(void)
2747 CLIPBOARDINFO cbinfo;
2749 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2751 TRACE(" count=%d\n", ClipDataCount);
2753 return ClipDataCount;
2757 /**************************************************************************
2758 * X11DRV_EnumClipboardFormats
2760 UINT CDECL X11DRV_EnumClipboardFormats(UINT wFormat)
2762 CLIPBOARDINFO cbinfo;
2763 struct list *ptr = NULL;
2765 TRACE("(%04X)\n", wFormat);
2767 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2769 if (!wFormat)
2771 ptr = list_head( &data_list );
2773 else
2775 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
2776 if (lpData) ptr = list_next( &data_list, &lpData->entry );
2779 if (!ptr) return 0;
2780 return LIST_ENTRY( ptr, WINE_CLIPDATA, entry )->wFormatID;
2784 /**************************************************************************
2785 * X11DRV_IsClipboardFormatAvailable
2787 BOOL CDECL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
2789 BOOL bRet = FALSE;
2790 CLIPBOARDINFO cbinfo;
2792 TRACE("(%04X)\n", wFormat);
2794 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2796 if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
2797 bRet = TRUE;
2799 TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
2801 return bRet;
2805 /**************************************************************************
2806 * GetClipboardData (USER.142)
2808 HANDLE CDECL X11DRV_GetClipboardData(UINT wFormat)
2810 CLIPBOARDINFO cbinfo;
2811 LPWINE_CLIPDATA lpRender;
2813 TRACE("(%04X)\n", wFormat);
2815 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2817 if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
2819 if ( !lpRender->hData )
2820 X11DRV_CLIPBOARD_RenderFormat(thread_init_display(), lpRender);
2822 TRACE(" returning %p (type %04x)\n", lpRender->hData, lpRender->wFormatID);
2823 return lpRender->hData;
2826 return 0;
2830 /**************************************************************************
2831 * ResetSelectionOwner
2833 * Called when the thread owning the selection is destroyed and we need to
2834 * preserve the selection ownership. We look for another top level window
2835 * in this process and send it a message to acquire the selection.
2837 void X11DRV_ResetSelectionOwner(void)
2839 HWND hwnd;
2840 DWORD procid;
2842 TRACE("\n");
2844 if (!selectionAcquired || thread_selection_wnd() != selectionWindow)
2845 return;
2847 selectionAcquired = S_NOSELECTION;
2848 selectionWindow = 0;
2850 hwnd = GetWindow(GetDesktopWindow(), GW_CHILD);
2853 if (GetCurrentThreadId() != GetWindowThreadProcessId(hwnd, &procid))
2855 if (GetCurrentProcessId() == procid)
2857 if (SendMessageW(hwnd, WM_X11DRV_ACQUIRE_SELECTION, 0, 0))
2858 return;
2861 } while ((hwnd = GetWindow(hwnd, GW_HWNDNEXT)) != NULL);
2863 WARN("Failed to find another thread to take selection ownership. Clipboard data will be lost.\n");
2865 X11DRV_CLIPBOARD_ReleaseOwnership();
2866 X11DRV_EmptyClipboard(FALSE);
2870 /**************************************************************************
2871 * X11DRV_CLIPBOARD_SynthesizeData
2873 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID)
2875 BOOL bsyn = TRUE;
2876 LPWINE_CLIPDATA lpSource = NULL;
2878 TRACE(" %04x\n", wFormatID);
2880 /* Don't need to synthesize if it already exists */
2881 if (X11DRV_CLIPBOARD_LookupData(wFormatID))
2882 return TRUE;
2884 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
2886 bsyn = ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
2887 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2888 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
2889 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2890 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
2891 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED);
2893 else if (wFormatID == CF_ENHMETAFILE)
2895 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2896 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2898 else if (wFormatID == CF_METAFILEPICT)
2900 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_ENHMETAFILE)) &&
2901 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2903 else if (wFormatID == CF_DIB)
2905 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
2906 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2908 else if (wFormatID == CF_BITMAP)
2910 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
2911 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2914 if (bsyn)
2915 X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, CF_FLAG_SYNTHESIZED, NULL, TRUE);
2917 return bsyn;
2922 /**************************************************************************
2923 * X11DRV_EndClipboardUpdate
2924 * TODO:
2925 * Add locale if it hasn't already been added
2927 void CDECL X11DRV_EndClipboardUpdate(void)
2929 INT count = ClipDataCount;
2931 /* Do Unicode <-> Text <-> OEM mapping */
2932 X11DRV_CLIPBOARD_SynthesizeData(CF_TEXT);
2933 X11DRV_CLIPBOARD_SynthesizeData(CF_OEMTEXT);
2934 X11DRV_CLIPBOARD_SynthesizeData(CF_UNICODETEXT);
2936 /* Enhmetafile <-> MetafilePict mapping */
2937 X11DRV_CLIPBOARD_SynthesizeData(CF_ENHMETAFILE);
2938 X11DRV_CLIPBOARD_SynthesizeData(CF_METAFILEPICT);
2940 /* DIB <-> Bitmap mapping */
2941 X11DRV_CLIPBOARD_SynthesizeData(CF_DIB);
2942 X11DRV_CLIPBOARD_SynthesizeData(CF_BITMAP);
2944 TRACE("%d formats added to cached data\n", ClipDataCount - count);
2948 /***********************************************************************
2949 * X11DRV_SelectionRequest_TARGETS
2950 * Service a TARGETS selection request event
2952 static Atom X11DRV_SelectionRequest_TARGETS( Display *display, Window requestor,
2953 Atom target, Atom rprop )
2955 UINT i;
2956 Atom* targets;
2957 ULONG cTargets;
2958 LPWINE_CLIPFORMAT format;
2959 LPWINE_CLIPDATA lpData;
2961 /* Create X atoms for any clipboard types which don't have atoms yet.
2962 * This avoids sending bogus zero atoms.
2963 * Without this, copying might not have access to all clipboard types.
2964 * FIXME: is it safe to call this here?
2966 intern_atoms();
2969 * Count the number of items we wish to expose as selection targets.
2971 cTargets = 1; /* Include TARGETS */
2973 if (!list_head( &data_list )) return None;
2975 LIST_FOR_EACH_ENTRY( lpData, &data_list, WINE_CLIPDATA, entry )
2976 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
2977 if ((format->wFormatID == lpData->wFormatID) &&
2978 format->lpDrvExportFunc && format->drvData)
2979 cTargets++;
2981 TRACE(" found %d formats\n", cTargets);
2983 /* Allocate temp buffer */
2984 targets = HeapAlloc( GetProcessHeap(), 0, cTargets * sizeof(Atom));
2985 if(targets == NULL)
2986 return None;
2988 i = 0;
2989 targets[i++] = x11drv_atom(TARGETS);
2991 LIST_FOR_EACH_ENTRY( lpData, &data_list, WINE_CLIPDATA, entry )
2992 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
2993 if ((format->wFormatID == lpData->wFormatID) &&
2994 format->lpDrvExportFunc && format->drvData)
2995 targets[i++] = format->drvData;
2997 if (TRACE_ON(clipboard))
2999 unsigned int i;
3000 for ( i = 0; i < cTargets; i++)
3002 char *itemFmtName = XGetAtomName(display, targets[i]);
3003 TRACE("\tAtom# %d: Property %ld Type %s\n", i, targets[i], itemFmtName);
3004 XFree(itemFmtName);
3008 /* We may want to consider setting the type to xaTargets instead,
3009 * in case some apps expect this instead of XA_ATOM */
3010 XChangeProperty(display, requestor, rprop, XA_ATOM, 32,
3011 PropModeReplace, (unsigned char *)targets, cTargets);
3013 HeapFree(GetProcessHeap(), 0, targets);
3015 return rprop;
3019 /***********************************************************************
3020 * X11DRV_SelectionRequest_MULTIPLE
3021 * Service a MULTIPLE selection request event
3022 * rprop contains a list of (target,property) atom pairs.
3023 * The first atom names a target and the second names a property.
3024 * The effect is as if we have received a sequence of SelectionRequest events
3025 * (one for each atom pair) except that:
3026 * 1. We reply with a SelectionNotify only when all the requested conversions
3027 * have been performed.
3028 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
3029 * we replace the atom in the property by None.
3031 static Atom X11DRV_SelectionRequest_MULTIPLE( HWND hWnd, XSelectionRequestEvent *pevent )
3033 Display *display = pevent->display;
3034 Atom rprop;
3035 Atom atype=AnyPropertyType;
3036 int aformat;
3037 unsigned long remain;
3038 Atom* targetPropList=NULL;
3039 unsigned long cTargetPropList = 0;
3041 /* If the specified property is None the requestor is an obsolete client.
3042 * We support these by using the specified target atom as the reply property.
3044 rprop = pevent->property;
3045 if( rprop == None )
3046 rprop = pevent->target;
3047 if (!rprop)
3048 return 0;
3050 /* Read the MULTIPLE property contents. This should contain a list of
3051 * (target,property) atom pairs.
3053 if (!XGetWindowProperty(display, pevent->requestor, rprop,
3054 0, 0x3FFF, False, AnyPropertyType, &atype,&aformat,
3055 &cTargetPropList, &remain,
3056 (unsigned char**)&targetPropList) != Success)
3058 if (TRACE_ON(clipboard))
3060 char * const typeName = XGetAtomName(display, atype);
3061 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
3062 typeName, aformat, cTargetPropList, remain);
3063 XFree(typeName);
3067 * Make sure we got what we expect.
3068 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
3069 * in a MULTIPLE selection request should be of type ATOM_PAIR.
3070 * However some X apps(such as XPaint) are not compliant with this and return
3071 * a user defined atom in atype when XGetWindowProperty is called.
3072 * The data *is* an atom pair but is not denoted as such.
3074 if(aformat == 32 /* atype == xAtomPair */ )
3076 unsigned int i;
3078 /* Iterate through the ATOM_PAIR list and execute a SelectionRequest
3079 * for each (target,property) pair */
3081 for (i = 0; i < cTargetPropList; i+=2)
3083 XSelectionRequestEvent event;
3085 if (TRACE_ON(clipboard))
3087 char *targetName, *propName;
3088 targetName = XGetAtomName(display, targetPropList[i]);
3089 propName = XGetAtomName(display, targetPropList[i+1]);
3090 TRACE("MULTIPLE(%d): Target='%s' Prop='%s'\n",
3091 i/2, targetName, propName);
3092 XFree(targetName);
3093 XFree(propName);
3096 /* We must have a non "None" property to service a MULTIPLE target atom */
3097 if ( !targetPropList[i+1] )
3099 TRACE("\tMULTIPLE(%d): Skipping target with empty property!\n", i);
3100 continue;
3103 /* Set up an XSelectionRequestEvent for this (target,property) pair */
3104 event = *pevent;
3105 event.target = targetPropList[i];
3106 event.property = targetPropList[i+1];
3108 /* Fire a SelectionRequest, informing the handler that we are processing
3109 * a MULTIPLE selection request event.
3111 X11DRV_HandleSelectionRequest( hWnd, &event, TRUE );
3115 /* Free the list of targets/properties */
3116 XFree(targetPropList);
3118 else TRACE("Couldn't read MULTIPLE property\n");
3120 return rprop;
3124 /***********************************************************************
3125 * X11DRV_HandleSelectionRequest
3126 * Process an event selection request event.
3127 * The bIsMultiple flag is used to signal when EVENT_SelectionRequest is called
3128 * recursively while servicing a "MULTIPLE" selection target.
3130 * Note: We only receive this event when WINE owns the X selection
3132 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple )
3134 Display *display = event->display;
3135 XSelectionEvent result;
3136 Atom rprop = None;
3137 Window request = event->requestor;
3139 TRACE("\n");
3142 * We can only handle the selection request if :
3143 * The selection is PRIMARY or CLIPBOARD, AND we can successfully open the clipboard.
3144 * Don't do these checks or open the clipboard while recursively processing MULTIPLE,
3145 * since this has been already done.
3147 if ( !bIsMultiple )
3149 if (((event->selection != XA_PRIMARY) && (event->selection != x11drv_atom(CLIPBOARD))))
3150 goto END;
3153 /* If the specified property is None the requestor is an obsolete client.
3154 * We support these by using the specified target atom as the reply property.
3156 rprop = event->property;
3157 if( rprop == None )
3158 rprop = event->target;
3160 if(event->target == x11drv_atom(TARGETS)) /* Return a list of all supported targets */
3162 /* TARGETS selection request */
3163 rprop = X11DRV_SelectionRequest_TARGETS( display, request, event->target, rprop );
3165 else if(event->target == x11drv_atom(MULTIPLE)) /* rprop contains a list of (target, property) atom pairs */
3167 /* MULTIPLE selection request */
3168 rprop = X11DRV_SelectionRequest_MULTIPLE( hWnd, event );
3170 else
3172 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, event->target);
3174 if (lpFormat && lpFormat->lpDrvExportFunc)
3176 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(lpFormat->wFormatID);
3178 if (lpData)
3180 unsigned char* lpClipData;
3181 DWORD cBytes;
3182 HANDLE hClipData = lpFormat->lpDrvExportFunc(display, request, event->target,
3183 rprop, lpData, &cBytes);
3185 if (hClipData && (lpClipData = GlobalLock(hClipData)))
3187 int mode = PropModeReplace;
3189 TRACE("\tUpdating property %s, %d bytes\n",
3190 debugstr_format(lpFormat->wFormatID), cBytes);
3193 int nelements = min(cBytes, 65536);
3194 XChangeProperty(display, request, rprop, event->target,
3195 8, mode, lpClipData, nelements);
3196 mode = PropModeAppend;
3197 cBytes -= nelements;
3198 lpClipData += nelements;
3199 } while (cBytes > 0);
3201 GlobalUnlock(hClipData);
3202 GlobalFree(hClipData);
3208 END:
3209 /* reply to sender
3210 * SelectionNotify should be sent only at the end of a MULTIPLE request
3212 if ( !bIsMultiple )
3214 result.type = SelectionNotify;
3215 result.display = display;
3216 result.requestor = request;
3217 result.selection = event->selection;
3218 result.property = rprop;
3219 result.target = event->target;
3220 result.time = event->time;
3221 TRACE("Sending SelectionNotify event...\n");
3222 XSendEvent(display,event->requestor,False,NoEventMask,(XEvent*)&result);
3227 /***********************************************************************
3228 * X11DRV_SelectionRequest
3230 void X11DRV_SelectionRequest( HWND hWnd, XEvent *event )
3232 X11DRV_HandleSelectionRequest( hWnd, &event->xselectionrequest, FALSE );
3236 /***********************************************************************
3237 * X11DRV_SelectionClear
3239 void X11DRV_SelectionClear( HWND hWnd, XEvent *xev )
3241 XSelectionClearEvent *event = &xev->xselectionclear;
3242 if (event->selection == XA_PRIMARY || event->selection == x11drv_atom(CLIPBOARD))
3243 X11DRV_CLIPBOARD_ReleaseSelection( event->display, event->selection,
3244 event->window, hWnd, event->time );