msvcp90: Use DEFINE_RTTI_DATA to define locale_facet RTTI base descriptor.
[wine.git] / dlls / winex11.drv / clipboard.c
blob6d0054e2fe96cdd60872fe2a3fd088e06e7f5861
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 XSetWindowAttributes attr;
264 attr.event_mask = (ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
265 ButtonPressMask | ButtonReleaseMask | EnterWindowMask | PropertyChangeMask);
267 wine_tsx11_lock();
268 w = XCreateWindow(thread_data->display, root_window, 0, 0, 1, 1, 0, screen_depth,
269 InputOutput, CopyFromParent, CWEventMask, &attr);
270 wine_tsx11_unlock();
272 if (w)
273 thread_data->selection_wnd = w;
274 else
275 FIXME("Failed to create window. Fetching selection data will fail.\n");
278 return w;
281 static const char *debugstr_format( UINT id )
283 WCHAR buffer[256];
285 if (GetClipboardFormatNameW( id, buffer, 256 ))
286 return wine_dbg_sprintf( "%04x %s", id, debugstr_w(buffer) );
288 switch (id)
290 #define BUILTIN(id) case id: return #id;
291 BUILTIN(CF_TEXT)
292 BUILTIN(CF_BITMAP)
293 BUILTIN(CF_METAFILEPICT)
294 BUILTIN(CF_SYLK)
295 BUILTIN(CF_DIF)
296 BUILTIN(CF_TIFF)
297 BUILTIN(CF_OEMTEXT)
298 BUILTIN(CF_DIB)
299 BUILTIN(CF_PALETTE)
300 BUILTIN(CF_PENDATA)
301 BUILTIN(CF_RIFF)
302 BUILTIN(CF_WAVE)
303 BUILTIN(CF_UNICODETEXT)
304 BUILTIN(CF_ENHMETAFILE)
305 BUILTIN(CF_HDROP)
306 BUILTIN(CF_LOCALE)
307 BUILTIN(CF_DIBV5)
308 BUILTIN(CF_OWNERDISPLAY)
309 BUILTIN(CF_DSPTEXT)
310 BUILTIN(CF_DSPBITMAP)
311 BUILTIN(CF_DSPMETAFILEPICT)
312 BUILTIN(CF_DSPENHMETAFILE)
313 #undef BUILTIN
314 default: return wine_dbg_sprintf( "%04x", id );
318 /**************************************************************************
319 * X11DRV_InitClipboard
321 void X11DRV_InitClipboard(void)
323 UINT i;
324 WINE_CLIPFORMAT *format;
326 /* Register built-in formats */
327 for (i = 0; i < sizeof(builtin_formats)/sizeof(builtin_formats[0]); i++)
329 if (!(format = HeapAlloc( GetProcessHeap(), 0, sizeof(*format )))) break;
330 format->wFormatID = builtin_formats[i].id;
331 format->drvData = GET_ATOM(builtin_formats[i].data);
332 format->lpDrvImportFunc = builtin_formats[i].import;
333 format->lpDrvExportFunc = builtin_formats[i].export;
334 list_add_tail( &format_list, &format->entry );
337 /* Register known mapping between window formats and X properties */
338 for (i = 0; i < sizeof(PropertyFormatMap)/sizeof(PropertyFormatMap[0]); i++)
339 X11DRV_CLIPBOARD_InsertClipboardFormat( RegisterClipboardFormatW(PropertyFormatMap[i].lpszFormat),
340 GET_ATOM(PropertyFormatMap[i].prop));
342 /* Set up a conversion function from "HTML Format" to "text/html" */
343 format = X11DRV_CLIPBOARD_InsertClipboardFormat( RegisterClipboardFormatW(wszHTMLFormat),
344 GET_ATOM(XATOM_text_html));
345 format->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportTextHtml;
349 /**************************************************************************
350 * intern_atoms
352 * Intern atoms for formats that don't have one yet.
354 static void intern_atoms(void)
356 LPWINE_CLIPFORMAT format;
357 int i, count, len;
358 char **names;
359 Atom *atoms;
360 Display *display;
361 WCHAR buffer[256];
363 count = 0;
364 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
365 if (!format->drvData) count++;
366 if (!count) return;
368 display = thread_init_display();
370 names = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*names) );
371 atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*atoms) );
373 i = 0;
374 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
375 if (!format->drvData) {
376 GetClipboardFormatNameW( format->wFormatID, buffer, 256 );
377 len = WideCharToMultiByte(CP_UNIXCP, 0, buffer, -1, NULL, 0, NULL, NULL);
378 names[i] = HeapAlloc(GetProcessHeap(), 0, len);
379 WideCharToMultiByte(CP_UNIXCP, 0, buffer, -1, names[i++], len, NULL, NULL);
382 wine_tsx11_lock();
383 XInternAtoms( display, names, count, False, atoms );
384 wine_tsx11_unlock();
386 i = 0;
387 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
388 if (!format->drvData) {
389 HeapFree(GetProcessHeap(), 0, names[i]);
390 format->drvData = atoms[i++];
393 HeapFree( GetProcessHeap(), 0, names );
394 HeapFree( GetProcessHeap(), 0, atoms );
398 /**************************************************************************
399 * register_format
401 * Register a custom X clipboard format.
403 static WINE_CLIPFORMAT *register_format( UINT id, Atom prop )
405 LPWINE_CLIPFORMAT lpFormat;
407 /* walk format chain to see if it's already registered */
408 LIST_FOR_EACH_ENTRY( lpFormat, &format_list, WINE_CLIPFORMAT, entry )
409 if (lpFormat->wFormatID == id) return lpFormat;
411 return X11DRV_CLIPBOARD_InsertClipboardFormat(id, prop);
415 /**************************************************************************
416 * X11DRV_CLIPBOARD_LookupProperty
418 static LPWINE_CLIPFORMAT X11DRV_CLIPBOARD_LookupProperty(LPWINE_CLIPFORMAT current, UINT drvData)
420 for (;;)
422 struct list *ptr = current ? &current->entry : &format_list;
423 BOOL need_intern = FALSE;
425 while ((ptr = list_next( &format_list, ptr )))
427 LPWINE_CLIPFORMAT lpFormat = LIST_ENTRY( ptr, WINE_CLIPFORMAT, entry );
428 if (lpFormat->drvData == drvData) return lpFormat;
429 if (!lpFormat->drvData) need_intern = TRUE;
431 if (!need_intern) return NULL;
432 intern_atoms();
433 /* restart the search for the new atoms */
438 /**************************************************************************
439 * X11DRV_CLIPBOARD_LookupData
441 static LPWINE_CLIPDATA X11DRV_CLIPBOARD_LookupData(DWORD wID)
443 WINE_CLIPDATA *data;
445 LIST_FOR_EACH_ENTRY( data, &data_list, WINE_CLIPDATA, entry )
446 if (data->wFormatID == wID) return data;
448 return NULL;
452 /**************************************************************************
453 * InsertClipboardFormat
455 static WINE_CLIPFORMAT *X11DRV_CLIPBOARD_InsertClipboardFormat( UINT id, Atom prop )
457 LPWINE_CLIPFORMAT lpNewFormat;
459 /* allocate storage for new format entry */
460 lpNewFormat = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPFORMAT));
462 if(lpNewFormat == NULL)
464 WARN("No more memory for a new format!\n");
465 return NULL;
467 lpNewFormat->wFormatID = id;
468 lpNewFormat->drvData = prop;
469 lpNewFormat->lpDrvImportFunc = X11DRV_CLIPBOARD_ImportClipboardData;
470 lpNewFormat->lpDrvExportFunc = X11DRV_CLIPBOARD_ExportClipboardData;
472 list_add_tail( &format_list, &lpNewFormat->entry );
474 TRACE("Registering format %s drvData %d\n",
475 debugstr_format(lpNewFormat->wFormatID), lpNewFormat->drvData);
477 return lpNewFormat;
483 /**************************************************************************
484 * X11DRV_CLIPBOARD_GetClipboardInfo
486 static BOOL X11DRV_CLIPBOARD_GetClipboardInfo(LPCLIPBOARDINFO cbInfo)
488 BOOL bRet = FALSE;
490 SERVER_START_REQ( set_clipboard_info )
492 req->flags = 0;
494 if (wine_server_call_err( req ))
496 ERR("Failed to get clipboard owner.\n");
498 else
500 cbInfo->hWndOpen = wine_server_ptr_handle( reply->old_clipboard );
501 cbInfo->hWndOwner = wine_server_ptr_handle( reply->old_owner );
502 cbInfo->hWndViewer = wine_server_ptr_handle( reply->old_viewer );
503 cbInfo->seqno = reply->seqno;
504 cbInfo->flags = reply->flags;
506 bRet = TRUE;
509 SERVER_END_REQ;
511 return bRet;
515 /**************************************************************************
516 * X11DRV_CLIPBOARD_ReleaseOwnership
518 static BOOL X11DRV_CLIPBOARD_ReleaseOwnership(void)
520 BOOL bRet = FALSE;
522 SERVER_START_REQ( set_clipboard_info )
524 req->flags = SET_CB_RELOWNER | SET_CB_SEQNO;
526 if (wine_server_call_err( req ))
528 ERR("Failed to set clipboard.\n");
530 else
532 bRet = TRUE;
535 SERVER_END_REQ;
537 return bRet;
542 /**************************************************************************
543 * X11DRV_CLIPBOARD_InsertClipboardData
545 * Caller *must* have the clipboard open and be the owner.
547 static BOOL X11DRV_CLIPBOARD_InsertClipboardData(UINT wFormatID, HANDLE hData, DWORD flags,
548 LPWINE_CLIPFORMAT lpFormat, BOOL override)
550 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormatID);
552 TRACE("format=%04x lpData=%p hData=%p flags=0x%08x lpFormat=%p override=%d\n",
553 wFormatID, lpData, hData, flags, lpFormat, override);
555 /* make sure the format exists */
556 if (!lpFormat) register_format( wFormatID, 0 );
558 if (lpData && !override)
559 return TRUE;
561 if (lpData)
563 X11DRV_CLIPBOARD_FreeData(lpData);
565 lpData->hData = hData;
567 else
569 lpData = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_CLIPDATA));
571 lpData->wFormatID = wFormatID;
572 lpData->hData = hData;
573 lpData->lpFormat = lpFormat;
574 lpData->drvData = 0;
576 list_add_tail( &data_list, &lpData->entry );
577 ClipDataCount++;
580 lpData->wFlags = flags;
582 return TRUE;
586 /**************************************************************************
587 * X11DRV_CLIPBOARD_FreeData
589 * Free clipboard data handle.
591 static void X11DRV_CLIPBOARD_FreeData(LPWINE_CLIPDATA lpData)
593 TRACE("%04x\n", lpData->wFormatID);
595 if ((lpData->wFormatID >= CF_GDIOBJFIRST &&
596 lpData->wFormatID <= CF_GDIOBJLAST) ||
597 lpData->wFormatID == CF_BITMAP ||
598 lpData->wFormatID == CF_DIB ||
599 lpData->wFormatID == CF_PALETTE)
601 if (lpData->hData)
602 DeleteObject(lpData->hData);
604 if ((lpData->wFormatID == CF_DIB) && lpData->drvData)
605 XFreePixmap(gdi_display, lpData->drvData);
607 else if (lpData->wFormatID == CF_METAFILEPICT)
609 if (lpData->hData)
611 DeleteMetaFile(((METAFILEPICT *)GlobalLock( lpData->hData ))->hMF );
612 GlobalFree(lpData->hData);
615 else if (lpData->wFormatID == CF_ENHMETAFILE)
617 if (lpData->hData)
618 DeleteEnhMetaFile(lpData->hData);
620 else if (lpData->wFormatID < CF_PRIVATEFIRST ||
621 lpData->wFormatID > CF_PRIVATELAST)
623 if (lpData->hData)
624 GlobalFree(lpData->hData);
627 lpData->hData = 0;
628 lpData->drvData = 0;
632 /**************************************************************************
633 * X11DRV_CLIPBOARD_UpdateCache
635 static BOOL X11DRV_CLIPBOARD_UpdateCache(LPCLIPBOARDINFO lpcbinfo)
637 BOOL bret = TRUE;
639 if (!X11DRV_CLIPBOARD_IsSelectionOwner())
641 if (!X11DRV_CLIPBOARD_GetClipboardInfo(lpcbinfo))
643 ERR("Failed to retrieve clipboard information.\n");
644 bret = FALSE;
646 else if (wSeqNo < lpcbinfo->seqno)
648 X11DRV_EmptyClipboard(TRUE);
650 if (X11DRV_CLIPBOARD_QueryAvailableData(thread_init_display(), lpcbinfo) < 0)
652 ERR("Failed to cache clipboard data owned by another process.\n");
653 bret = FALSE;
655 else
657 X11DRV_EndClipboardUpdate();
660 wSeqNo = lpcbinfo->seqno;
664 return bret;
668 /**************************************************************************
669 * X11DRV_CLIPBOARD_RenderFormat
671 static BOOL X11DRV_CLIPBOARD_RenderFormat(Display *display, LPWINE_CLIPDATA lpData)
673 BOOL bret = TRUE;
675 TRACE(" 0x%04x hData(%p)\n", lpData->wFormatID, lpData->hData);
677 if (lpData->hData) return bret; /* Already rendered */
679 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
680 bret = X11DRV_CLIPBOARD_RenderSynthesizedFormat(display, lpData);
681 else if (!X11DRV_CLIPBOARD_IsSelectionOwner())
683 if (!X11DRV_CLIPBOARD_ReadSelectionData(display, lpData))
685 ERR("Failed to cache clipboard data owned by another process. Format=%04x\n",
686 lpData->wFormatID);
687 bret = FALSE;
690 else
692 CLIPBOARDINFO cbInfo;
694 if (X11DRV_CLIPBOARD_GetClipboardInfo(&cbInfo) && cbInfo.hWndOwner)
696 /* Send a WM_RENDERFORMAT message to notify the owner to render the
697 * data requested into the clipboard.
699 TRACE("Sending WM_RENDERFORMAT message to hwnd(%p)\n", cbInfo.hWndOwner);
700 SendMessageW(cbInfo.hWndOwner, WM_RENDERFORMAT, lpData->wFormatID, 0);
702 if (!lpData->hData) bret = FALSE;
704 else
706 ERR("hWndClipOwner is lost!\n");
707 bret = FALSE;
711 return bret;
715 /**************************************************************************
716 * CLIPBOARD_ConvertText
717 * Returns number of required/converted characters - not bytes!
719 static INT CLIPBOARD_ConvertText(WORD src_fmt, void const *src, INT src_size,
720 WORD dst_fmt, void *dst, INT dst_size)
722 UINT cp;
724 if(src_fmt == CF_UNICODETEXT)
726 switch(dst_fmt)
728 case CF_TEXT:
729 cp = CP_ACP;
730 break;
731 case CF_OEMTEXT:
732 cp = CP_OEMCP;
733 break;
734 default:
735 return 0;
737 return WideCharToMultiByte(cp, 0, src, src_size, dst, dst_size, NULL, NULL);
740 if(dst_fmt == CF_UNICODETEXT)
742 switch(src_fmt)
744 case CF_TEXT:
745 cp = CP_ACP;
746 break;
747 case CF_OEMTEXT:
748 cp = CP_OEMCP;
749 break;
750 default:
751 return 0;
753 return MultiByteToWideChar(cp, 0, src, src_size, dst, dst_size);
756 if(!dst_size) return src_size;
758 if(dst_size > src_size) dst_size = src_size;
760 if(src_fmt == CF_TEXT )
761 CharToOemBuffA(src, dst, dst_size);
762 else
763 OemToCharBuffA(src, dst, dst_size);
765 return dst_size;
769 /**************************************************************************
770 * X11DRV_CLIPBOARD_RenderSynthesizedFormat
772 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedFormat(Display *display, LPWINE_CLIPDATA lpData)
774 BOOL bret = FALSE;
776 TRACE("\n");
778 if (lpData->wFlags & CF_FLAG_SYNTHESIZED)
780 UINT wFormatID = lpData->wFormatID;
782 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
783 bret = X11DRV_CLIPBOARD_RenderSynthesizedText(display, wFormatID);
784 else
786 switch (wFormatID)
788 case CF_DIB:
789 bret = X11DRV_CLIPBOARD_RenderSynthesizedDIB( display );
790 break;
792 case CF_BITMAP:
793 bret = X11DRV_CLIPBOARD_RenderSynthesizedBitmap( display );
794 break;
796 case CF_ENHMETAFILE:
797 bret = X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile( display );
798 break;
800 case CF_METAFILEPICT:
801 FIXME("Synthesizing CF_METAFILEPICT not implemented\n");
802 break;
804 default:
805 FIXME("Called to synthesize unknown format 0x%08x\n", wFormatID);
806 break;
810 lpData->wFlags &= ~CF_FLAG_SYNTHESIZED;
813 return bret;
817 /**************************************************************************
818 * X11DRV_CLIPBOARD_RenderSynthesizedText
820 * Renders synthesized text
822 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedText(Display *display, UINT wFormatID)
824 LPCSTR lpstrS;
825 LPSTR lpstrT;
826 HANDLE hData;
827 INT src_chars, dst_chars, alloc_size;
828 LPWINE_CLIPDATA lpSource = NULL;
830 TRACE("%04x\n", wFormatID);
832 if ((lpSource = X11DRV_CLIPBOARD_LookupData(wFormatID)) &&
833 lpSource->hData)
834 return TRUE;
836 /* Look for rendered source or non-synthesized source */
837 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
838 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
840 TRACE("UNICODETEXT -> %04x\n", wFormatID);
842 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
843 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
845 TRACE("TEXT -> %04x\n", wFormatID);
847 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
848 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
850 TRACE("OEMTEXT -> %04x\n", wFormatID);
853 if (!lpSource || (lpSource->wFlags & CF_FLAG_SYNTHESIZED &&
854 !lpSource->hData))
855 return FALSE;
857 /* Ask the clipboard owner to render the source text if necessary */
858 if (!lpSource->hData && !X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
859 return FALSE;
861 lpstrS = GlobalLock(lpSource->hData);
862 if (!lpstrS)
863 return FALSE;
865 /* Text always NULL terminated */
866 if(lpSource->wFormatID == CF_UNICODETEXT)
867 src_chars = strlenW((LPCWSTR)lpstrS) + 1;
868 else
869 src_chars = strlen(lpstrS) + 1;
871 /* Calculate number of characters in the destination buffer */
872 dst_chars = CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS,
873 src_chars, wFormatID, NULL, 0);
875 if (!dst_chars)
876 return FALSE;
878 TRACE("Converting from '%04x' to '%04x', %i chars\n",
879 lpSource->wFormatID, wFormatID, src_chars);
881 /* Convert characters to bytes */
882 if(wFormatID == CF_UNICODETEXT)
883 alloc_size = dst_chars * sizeof(WCHAR);
884 else
885 alloc_size = dst_chars;
887 hData = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE |
888 GMEM_DDESHARE, alloc_size);
890 lpstrT = GlobalLock(hData);
892 if (lpstrT)
894 CLIPBOARD_ConvertText(lpSource->wFormatID, lpstrS, src_chars,
895 wFormatID, lpstrT, dst_chars);
896 GlobalUnlock(hData);
899 GlobalUnlock(lpSource->hData);
901 return X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, hData, 0, NULL, TRUE);
905 /***********************************************************************
906 * bitmap_info_size
908 * Return the size of the bitmap info structure including color table.
910 static int bitmap_info_size( const BITMAPINFO * info, WORD coloruse )
912 unsigned int colors, size, masks = 0;
914 if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
916 const BITMAPCOREHEADER *core = (const BITMAPCOREHEADER *)info;
917 colors = (core->bcBitCount <= 8) ? 1 << core->bcBitCount : 0;
918 return sizeof(BITMAPCOREHEADER) + colors *
919 ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBTRIPLE) : sizeof(WORD));
921 else /* assume BITMAPINFOHEADER */
923 colors = info->bmiHeader.biClrUsed;
924 if (!colors && (info->bmiHeader.biBitCount <= 8))
925 colors = 1 << info->bmiHeader.biBitCount;
926 if (info->bmiHeader.biCompression == BI_BITFIELDS) masks = 3;
927 size = max( info->bmiHeader.biSize, sizeof(BITMAPINFOHEADER) + masks * sizeof(DWORD) );
928 return size + colors * ((coloruse == DIB_RGB_COLORS) ? sizeof(RGBQUAD) : sizeof(WORD));
933 /***********************************************************************
934 * create_dib_from_bitmap
936 * Allocates a packed DIB and copies the bitmap data into it.
938 static HGLOBAL create_dib_from_bitmap(HBITMAP hBmp)
940 BITMAP bmp;
941 HDC hdc;
942 HGLOBAL hPackedDIB;
943 LPBYTE pPackedDIB;
944 LPBITMAPINFOHEADER pbmiHeader;
945 unsigned int cDataSize, cPackedSize, OffsetBits;
946 int nLinesCopied;
948 if (!GetObjectW( hBmp, sizeof(bmp), &bmp )) return 0;
951 * A packed DIB contains a BITMAPINFO structure followed immediately by
952 * an optional color palette and the pixel data.
955 /* Calculate the size of the packed DIB */
956 cDataSize = abs( bmp.bmHeight ) * (((bmp.bmWidth * bmp.bmBitsPixel + 31) / 8) & ~3);
957 cPackedSize = sizeof(BITMAPINFOHEADER)
958 + ( (bmp.bmBitsPixel <= 8) ? (sizeof(RGBQUAD) * (1 << bmp.bmBitsPixel)) : 0 )
959 + cDataSize;
960 /* Get the offset to the bits */
961 OffsetBits = cPackedSize - cDataSize;
963 /* Allocate the packed DIB */
964 TRACE("\tAllocating packed DIB of size %d\n", cPackedSize);
965 hPackedDIB = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE /*| GMEM_ZEROINIT*/,
966 cPackedSize );
967 if ( !hPackedDIB )
969 WARN("Could not allocate packed DIB!\n");
970 return 0;
973 /* A packed DIB starts with a BITMAPINFOHEADER */
974 pPackedDIB = GlobalLock(hPackedDIB);
975 pbmiHeader = (LPBITMAPINFOHEADER)pPackedDIB;
977 /* Init the BITMAPINFOHEADER */
978 pbmiHeader->biSize = sizeof(BITMAPINFOHEADER);
979 pbmiHeader->biWidth = bmp.bmWidth;
980 pbmiHeader->biHeight = bmp.bmHeight;
981 pbmiHeader->biPlanes = 1;
982 pbmiHeader->biBitCount = bmp.bmBitsPixel;
983 pbmiHeader->biCompression = BI_RGB;
984 pbmiHeader->biSizeImage = 0;
985 pbmiHeader->biXPelsPerMeter = pbmiHeader->biYPelsPerMeter = 0;
986 pbmiHeader->biClrUsed = 0;
987 pbmiHeader->biClrImportant = 0;
989 /* Retrieve the DIB bits from the bitmap and fill in the
990 * DIB color table if present */
991 hdc = GetDC( 0 );
992 nLinesCopied = GetDIBits(hdc, /* Handle to device context */
993 hBmp, /* Handle to bitmap */
994 0, /* First scan line to set in dest bitmap */
995 bmp.bmHeight, /* Number of scan lines to copy */
996 pPackedDIB + OffsetBits, /* [out] Address of array for bitmap bits */
997 (LPBITMAPINFO) pbmiHeader, /* [out] Address of BITMAPINFO structure */
998 0); /* RGB or palette index */
999 GlobalUnlock(hPackedDIB);
1000 ReleaseDC( 0, hdc );
1002 /* Cleanup if GetDIBits failed */
1003 if (nLinesCopied != bmp.bmHeight)
1005 TRACE("\tGetDIBits returned %d. Actual lines=%d\n", nLinesCopied, bmp.bmHeight);
1006 GlobalFree(hPackedDIB);
1007 hPackedDIB = 0;
1009 return hPackedDIB;
1013 /**************************************************************************
1014 * X11DRV_CLIPBOARD_RenderSynthesizedDIB
1016 * Renders synthesized DIB
1018 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display)
1020 BOOL bret = FALSE;
1021 LPWINE_CLIPDATA lpSource = NULL;
1023 TRACE("\n");
1025 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) && lpSource->hData)
1027 bret = TRUE;
1029 /* If we have a bitmap and it's not synthesized or it has been rendered */
1030 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
1031 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1033 /* Render source if required */
1034 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1036 HGLOBAL hData = create_dib_from_bitmap( lpSource->hData );
1037 if (hData)
1039 X11DRV_CLIPBOARD_InsertClipboardData(CF_DIB, hData, 0, NULL, TRUE);
1040 bret = TRUE;
1045 return bret;
1049 /**************************************************************************
1050 * X11DRV_CLIPBOARD_RenderSynthesizedBitmap
1052 * Renders synthesized bitmap
1054 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display)
1056 BOOL bret = FALSE;
1057 LPWINE_CLIPDATA lpSource = NULL;
1059 TRACE("\n");
1061 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) && lpSource->hData)
1063 bret = TRUE;
1065 /* If we have a dib and it's not synthesized or it has been rendered */
1066 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
1067 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1069 /* Render source if required */
1070 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1072 HDC hdc;
1073 HBITMAP hData = NULL;
1074 unsigned int offset;
1075 LPBITMAPINFOHEADER lpbmih;
1077 hdc = GetDC(NULL);
1078 lpbmih = GlobalLock(lpSource->hData);
1079 if (lpbmih)
1081 offset = sizeof(BITMAPINFOHEADER)
1082 + ((lpbmih->biBitCount <= 8) ? (sizeof(RGBQUAD) *
1083 (1 << lpbmih->biBitCount)) : 0);
1085 hData = CreateDIBitmap(hdc, lpbmih, CBM_INIT, (LPBYTE)lpbmih +
1086 offset, (LPBITMAPINFO) lpbmih, DIB_RGB_COLORS);
1088 GlobalUnlock(lpSource->hData);
1090 ReleaseDC(NULL, hdc);
1092 if (hData)
1094 X11DRV_CLIPBOARD_InsertClipboardData(CF_BITMAP, hData, 0, NULL, TRUE);
1095 bret = TRUE;
1100 return bret;
1104 /**************************************************************************
1105 * X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile
1107 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile(Display *display)
1109 LPWINE_CLIPDATA lpSource = NULL;
1111 TRACE("\n");
1113 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_ENHMETAFILE)) && lpSource->hData)
1114 return TRUE;
1115 /* If we have a MF pict and it's not synthesized or it has been rendered */
1116 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
1117 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1119 /* Render source if required */
1120 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1122 METAFILEPICT *pmfp;
1123 HENHMETAFILE hData = NULL;
1125 pmfp = GlobalLock(lpSource->hData);
1126 if (pmfp)
1128 UINT size_mf_bits = GetMetaFileBitsEx(pmfp->hMF, 0, NULL);
1129 void *mf_bits = HeapAlloc(GetProcessHeap(), 0, size_mf_bits);
1130 if (mf_bits)
1132 GetMetaFileBitsEx(pmfp->hMF, size_mf_bits, mf_bits);
1133 hData = SetWinMetaFileBits(size_mf_bits, mf_bits, NULL, pmfp);
1134 HeapFree(GetProcessHeap(), 0, mf_bits);
1136 GlobalUnlock(lpSource->hData);
1139 if (hData)
1141 X11DRV_CLIPBOARD_InsertClipboardData(CF_ENHMETAFILE, hData, 0, NULL, TRUE);
1142 return TRUE;
1147 return FALSE;
1151 /**************************************************************************
1152 * X11DRV_CLIPBOARD_ImportXAString
1154 * Import XA_STRING, converting the string to CF_TEXT.
1156 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *display, Window w, Atom prop)
1158 LPBYTE lpdata;
1159 unsigned long cbytes;
1160 LPSTR lpstr;
1161 unsigned long i, inlcount = 0;
1162 HANDLE hText = 0;
1164 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1165 return 0;
1167 for (i = 0; i <= cbytes; i++)
1169 if (lpdata[i] == '\n')
1170 inlcount++;
1173 if ((hText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes + inlcount + 1)))
1175 lpstr = GlobalLock(hText);
1177 for (i = 0, inlcount = 0; i <= cbytes; i++)
1179 if (lpdata[i] == '\n')
1180 lpstr[inlcount++] = '\r';
1182 lpstr[inlcount++] = lpdata[i];
1185 GlobalUnlock(hText);
1188 /* Free the retrieved property data */
1189 HeapFree(GetProcessHeap(), 0, lpdata);
1191 return hText;
1195 /**************************************************************************
1196 * X11DRV_CLIPBOARD_ImportUTF8
1198 * Import XA_STRING, converting the string to CF_UNICODE.
1200 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *display, Window w, Atom prop)
1202 LPBYTE lpdata;
1203 unsigned long cbytes;
1204 LPSTR lpstr;
1205 unsigned long i, inlcount = 0;
1206 HANDLE hUnicodeText = 0;
1208 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1209 return 0;
1211 for (i = 0; i <= cbytes; i++)
1213 if (lpdata[i] == '\n')
1214 inlcount++;
1217 if ((lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbytes + inlcount + 1)))
1219 UINT count;
1221 for (i = 0, inlcount = 0; i <= cbytes; i++)
1223 if (lpdata[i] == '\n')
1224 lpstr[inlcount++] = '\r';
1226 lpstr[inlcount++] = lpdata[i];
1229 count = MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, NULL, 0);
1230 hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
1232 if (hUnicodeText)
1234 WCHAR *textW = GlobalLock(hUnicodeText);
1235 MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, textW, count);
1236 GlobalUnlock(hUnicodeText);
1239 HeapFree(GetProcessHeap(), 0, lpstr);
1242 /* Free the retrieved property data */
1243 HeapFree(GetProcessHeap(), 0, lpdata);
1245 return hUnicodeText;
1249 /**************************************************************************
1250 * X11DRV_CLIPBOARD_ImportCompoundText
1252 * Import COMPOUND_TEXT to CF_UNICODE
1254 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *display, Window w, Atom prop)
1256 int i, j, ret;
1257 char** srcstr;
1258 int count, lcount;
1259 int srclen, destlen;
1260 HANDLE hUnicodeText;
1261 XTextProperty txtprop;
1263 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &txtprop.value, &txtprop.nitems))
1265 return 0;
1268 txtprop.encoding = x11drv_atom(COMPOUND_TEXT);
1269 txtprop.format = 8;
1270 wine_tsx11_lock();
1271 ret = XmbTextPropertyToTextList(display, &txtprop, &srcstr, &count);
1272 wine_tsx11_unlock();
1273 HeapFree(GetProcessHeap(), 0, txtprop.value);
1274 if (ret != Success || !count) return 0;
1276 TRACE("Importing %d line(s)\n", count);
1278 /* Compute number of lines */
1279 srclen = strlen(srcstr[0]);
1280 for (i = 0, lcount = 0; i <= srclen; i++)
1282 if (srcstr[0][i] == '\n')
1283 lcount++;
1286 destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
1288 TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
1290 if ((hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (destlen + lcount + 1) * sizeof(WCHAR))))
1292 WCHAR *deststr = GlobalLock(hUnicodeText);
1293 MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1295 if (lcount)
1297 for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1299 deststr[j] = deststr[i];
1301 if (deststr[i] == '\n')
1302 deststr[--j] = '\r';
1306 GlobalUnlock(hUnicodeText);
1309 wine_tsx11_lock();
1310 XFreeStringList(srcstr);
1311 wine_tsx11_unlock();
1313 return hUnicodeText;
1317 /**************************************************************************
1318 * X11DRV_CLIPBOARD_ImportXAPIXMAP
1320 * Import XA_PIXMAP, converting the image to CF_DIB.
1322 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *display, Window w, Atom prop)
1324 LPBYTE lpdata;
1325 unsigned long cbytes;
1326 Pixmap *pPixmap;
1327 HANDLE hClipData = 0;
1329 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1331 HDC hdcMem;
1332 X_PHYSBITMAP *physBitmap;
1333 Pixmap orig_pixmap;
1334 HBITMAP hBmp = 0;
1335 Window root;
1336 int x,y; /* Unused */
1337 unsigned border_width; /* Unused */
1338 unsigned int depth, width, height;
1340 pPixmap = (Pixmap *) lpdata;
1342 /* Get the Pixmap dimensions and bit depth */
1343 wine_tsx11_lock();
1344 if (!XGetGeometry(gdi_display, *pPixmap, &root, &x, &y, &width, &height,
1345 &border_width, &depth)) depth = 0;
1346 wine_tsx11_unlock();
1347 if (!pixmap_formats[depth]) return 0;
1349 TRACE("\tPixmap properties: width=%d, height=%d, depth=%d\n",
1350 width, height, depth);
1353 * Create an HBITMAP with the same dimensions and BPP as the pixmap,
1354 * and make it a container for the pixmap passed.
1356 if (!(hBmp = CreateBitmap( width, height, 1, pixmap_formats[depth]->bits_per_pixel, NULL )))
1357 return 0;
1359 /* force bitmap to be owned by a screen DC */
1360 hdcMem = CreateCompatibleDC( 0 );
1361 SelectObject( hdcMem, SelectObject( hdcMem, hBmp ));
1362 DeleteDC( hdcMem );
1364 physBitmap = X11DRV_get_phys_bitmap( hBmp );
1366 /* swap the new pixmap in */
1367 orig_pixmap = physBitmap->pixmap;
1368 physBitmap->pixmap = *pPixmap;
1371 * Create a packed DIB from the Pixmap wrapper bitmap created above.
1372 * A packed DIB contains a BITMAPINFO structure followed immediately by
1373 * an optional color palette and the pixel data.
1375 hClipData = create_dib_from_bitmap( hBmp );
1377 /* we can now get rid of the HBITMAP and its original pixmap */
1378 physBitmap->pixmap = orig_pixmap;
1379 DeleteObject(hBmp);
1381 /* Free the retrieved property data */
1382 HeapFree(GetProcessHeap(), 0, lpdata);
1385 return hClipData;
1389 /**************************************************************************
1390 * X11DRV_CLIPBOARD_ImportImageBmp
1392 * Import image/bmp, converting the image to CF_DIB.
1394 static HANDLE X11DRV_CLIPBOARD_ImportImageBmp(Display *display, Window w, Atom prop)
1396 LPBYTE lpdata;
1397 unsigned long cbytes;
1398 HANDLE hClipData = 0;
1400 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1402 BITMAPFILEHEADER *bfh = (BITMAPFILEHEADER*)lpdata;
1404 if (cbytes >= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPCOREHEADER) &&
1405 bfh->bfType == 0x4d42 /* "BM" */)
1407 BITMAPINFO *bmi = (BITMAPINFO*)(bfh+1);
1408 HBITMAP hbmp;
1409 HDC hdc;
1411 hdc = GetDC(0);
1412 hbmp = CreateDIBitmap(
1413 hdc,
1414 &(bmi->bmiHeader),
1415 CBM_INIT,
1416 lpdata+bfh->bfOffBits,
1417 bmi,
1418 DIB_RGB_COLORS
1421 hClipData = create_dib_from_bitmap( hbmp );
1423 DeleteObject(hbmp);
1424 ReleaseDC(0, hdc);
1427 /* Free the retrieved property data */
1428 HeapFree(GetProcessHeap(), 0, lpdata);
1431 return hClipData;
1435 /**************************************************************************
1436 * X11DRV_CLIPBOARD_ImportMetaFilePict
1438 * Import MetaFilePict.
1440 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *display, Window w, Atom prop)
1442 LPBYTE lpdata;
1443 unsigned long cbytes;
1444 HANDLE hClipData = 0;
1446 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1448 if (cbytes)
1449 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata, (LPDWORD)&cbytes, FALSE);
1451 /* Free the retrieved property data */
1452 HeapFree(GetProcessHeap(), 0, lpdata);
1455 return hClipData;
1459 /**************************************************************************
1460 * X11DRV_ImportEnhMetaFile
1462 * Import EnhMetaFile.
1464 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *display, Window w, Atom prop)
1466 LPBYTE lpdata;
1467 unsigned long cbytes;
1468 HANDLE hClipData = 0;
1470 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1472 if (cbytes)
1473 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata, (LPDWORD)&cbytes, FALSE);
1475 /* Free the retrieved property data */
1476 HeapFree(GetProcessHeap(), 0, lpdata);
1479 return hClipData;
1483 /**************************************************************************
1484 * X11DRV_ImportClipbordaData
1486 * Generic import clipboard data routine.
1488 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *display, Window w, Atom prop)
1490 LPVOID lpClipData;
1491 LPBYTE lpdata;
1492 unsigned long cbytes;
1493 HANDLE hClipData = 0;
1495 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1497 if (cbytes)
1499 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
1500 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes);
1501 if (hClipData == 0)
1502 return NULL;
1504 if ((lpClipData = GlobalLock(hClipData)))
1506 memcpy(lpClipData, lpdata, cbytes);
1507 GlobalUnlock(hClipData);
1509 else
1511 GlobalFree(hClipData);
1512 hClipData = 0;
1516 /* Free the retrieved property data */
1517 HeapFree(GetProcessHeap(), 0, lpdata);
1520 return hClipData;
1524 /**************************************************************************
1525 X11DRV_CLIPBOARD_ExportClipboardData
1527 * Generic export clipboard data routine.
1529 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
1530 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1532 LPVOID lpClipData;
1533 UINT datasize = 0;
1534 HANDLE hClipData = 0;
1536 *lpBytes = 0; /* Assume failure */
1538 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1539 ERR("Failed to export %04x format\n", lpData->wFormatID);
1540 else
1542 datasize = GlobalSize(lpData->hData);
1544 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, datasize);
1545 if (hClipData == 0) return NULL;
1547 if ((lpClipData = GlobalLock(hClipData)))
1549 LPVOID lpdata = GlobalLock(lpData->hData);
1551 memcpy(lpClipData, lpdata, datasize);
1552 *lpBytes = datasize;
1554 GlobalUnlock(lpData->hData);
1555 GlobalUnlock(hClipData);
1556 } else {
1557 GlobalFree(hClipData);
1558 hClipData = 0;
1562 return hClipData;
1566 /**************************************************************************
1567 * X11DRV_CLIPBOARD_ExportXAString
1569 * Export CF_TEXT converting the string to XA_STRING.
1570 * Helper function for X11DRV_CLIPBOARD_ExportString.
1572 static HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1574 UINT i, j;
1575 UINT size;
1576 LPSTR text, lpstr = NULL;
1578 *lpBytes = 0; /* Assume return has zero bytes */
1580 text = GlobalLock(lpData->hData);
1581 size = strlen(text);
1583 /* remove carriage returns */
1584 lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1585 if (lpstr == NULL)
1586 goto done;
1588 for (i = 0,j = 0; i < size && text[i]; i++)
1590 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1591 continue;
1592 lpstr[j++] = text[i];
1595 lpstr[j]='\0';
1596 *lpBytes = j; /* Number of bytes in string */
1598 done:
1599 GlobalUnlock(lpData->hData);
1601 return lpstr;
1605 /**************************************************************************
1606 * X11DRV_CLIPBOARD_ExportUTF8String
1608 * Export CF_UNICODE converting the string to UTF8.
1609 * Helper function for X11DRV_CLIPBOARD_ExportString.
1611 static HANDLE X11DRV_CLIPBOARD_ExportUTF8String(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1613 UINT i, j;
1614 UINT size;
1615 LPWSTR uni_text;
1616 LPSTR text, lpstr = NULL;
1618 *lpBytes = 0; /* Assume return has zero bytes */
1620 uni_text = GlobalLock(lpData->hData);
1622 size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1624 text = HeapAlloc(GetProcessHeap(), 0, size);
1625 if (!text)
1626 goto done;
1627 WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1629 /* remove carriage returns */
1630 lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1631 if (lpstr == NULL)
1632 goto done;
1634 for (i = 0,j = 0; i < size && text[i]; i++)
1636 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1637 continue;
1638 lpstr[j++] = text[i];
1640 lpstr[j]='\0';
1642 *lpBytes = j; /* Number of bytes in string */
1644 done:
1645 HeapFree(GetProcessHeap(), 0, text);
1646 GlobalUnlock(lpData->hData);
1648 return lpstr;
1653 /**************************************************************************
1654 * X11DRV_CLIPBOARD_ExportCompoundText
1656 * Export CF_UNICODE to COMPOUND_TEXT
1657 * Helper function for X11DRV_CLIPBOARD_ExportString.
1659 static HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Display *display, Window requestor, Atom aTarget, Atom rprop,
1660 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1662 char* lpstr = 0;
1663 XTextProperty prop;
1664 XICCEncodingStyle style;
1665 UINT i, j;
1666 UINT size;
1667 LPWSTR uni_text;
1669 uni_text = GlobalLock(lpData->hData);
1671 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1672 lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1673 if (!lpstr)
1674 return 0;
1676 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1678 /* remove carriage returns */
1679 for (i = 0, j = 0; i < size && lpstr[i]; i++)
1681 if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1682 continue;
1683 lpstr[j++] = lpstr[i];
1685 lpstr[j]='\0';
1687 GlobalUnlock(lpData->hData);
1689 if (aTarget == x11drv_atom(COMPOUND_TEXT))
1690 style = XCompoundTextStyle;
1691 else
1692 style = XStdICCTextStyle;
1694 /* Update the X property */
1695 wine_tsx11_lock();
1696 if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1698 XSetTextProperty(display, requestor, &prop, rprop);
1699 XFree(prop.value);
1701 wine_tsx11_unlock();
1703 HeapFree(GetProcessHeap(), 0, lpstr);
1705 return 0;
1708 /**************************************************************************
1709 * X11DRV_CLIPBOARD_ExportString
1711 * Export string
1713 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget, Atom rprop,
1714 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1716 if (X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1718 if (aTarget == XA_STRING)
1719 return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1720 else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1721 return X11DRV_CLIPBOARD_ExportCompoundText(display, requestor, aTarget,
1722 rprop, lpData, lpBytes);
1723 else
1725 TRACE("Exporting target %ld to default UTF8_STRING\n", aTarget);
1726 return X11DRV_CLIPBOARD_ExportUTF8String(lpData, lpBytes);
1729 else
1730 ERR("Failed to render %04x format\n", lpData->wFormatID);
1732 return 0;
1736 /**************************************************************************
1737 * X11DRV_CLIPBOARD_ExportXAPIXMAP
1739 * Export CF_DIB to XA_PIXMAP.
1741 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget, Atom rprop,
1742 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1744 HDC hdc, memdc;
1745 HANDLE hData;
1746 unsigned char* lpData;
1748 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1750 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1751 return 0;
1754 if (!lpdata->drvData) /* If not already rendered */
1756 /* Create a DDB from the DIB */
1758 Pixmap pixmap = 0;
1759 X_PHYSBITMAP *physBitmap;
1760 HBITMAP hBmp;
1761 LPBITMAPINFO pbmi;
1763 hdc = GetDC(0);
1764 pbmi = GlobalLock( lpdata->hData );
1765 hBmp = CreateDIBitmap( hdc, &pbmi->bmiHeader, CBM_INIT,
1766 (LPBYTE)pbmi + bitmap_info_size( pbmi, DIB_RGB_COLORS ),
1767 pbmi, DIB_RGB_COLORS );
1768 GlobalUnlock( lpdata->hData );
1770 /* make sure it's owned by x11drv */
1771 memdc = CreateCompatibleDC( hdc );
1772 SelectObject( memdc, hBmp );
1773 DeleteDC( memdc );
1775 /* clear the physBitmap so that we can steal its pixmap */
1776 if ((physBitmap = X11DRV_get_phys_bitmap( hBmp )))
1778 pixmap = physBitmap->pixmap;
1779 physBitmap->pixmap = 0;
1781 DeleteObject( hBmp );
1782 ReleaseDC( 0, hdc );
1783 lpdata->drvData = pixmap;
1786 *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1788 /* Wrap pixmap so we can return a handle */
1789 hData = GlobalAlloc(0, *lpBytes);
1790 lpData = GlobalLock(hData);
1791 memcpy(lpData, &lpdata->drvData, *lpBytes);
1792 GlobalUnlock(hData);
1794 return hData;
1798 /**************************************************************************
1799 * X11DRV_CLIPBOARD_ExportImageBmp
1801 * Export CF_DIB to image/bmp.
1803 static HANDLE X11DRV_CLIPBOARD_ExportImageBmp(Display *display, Window requestor, Atom aTarget, Atom rprop,
1804 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1806 HANDLE hpackeddib;
1807 LPBYTE dibdata;
1808 UINT bmpsize;
1809 HANDLE hbmpdata;
1810 LPBYTE bmpdata;
1811 BITMAPFILEHEADER *bfh;
1813 *lpBytes = 0;
1815 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1817 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1818 return 0;
1821 hpackeddib = lpdata->hData;
1823 dibdata = GlobalLock(hpackeddib);
1824 if (!dibdata)
1826 ERR("Failed to lock packed DIB\n");
1827 return 0;
1830 bmpsize = sizeof(BITMAPFILEHEADER) + GlobalSize(hpackeddib);
1832 hbmpdata = GlobalAlloc(0, bmpsize);
1834 if (hbmpdata)
1836 bmpdata = GlobalLock(hbmpdata);
1838 if (!bmpdata)
1840 GlobalFree(hbmpdata);
1841 GlobalUnlock(hpackeddib);
1842 return 0;
1845 /* bitmap file header */
1846 bfh = (BITMAPFILEHEADER*)bmpdata;
1847 bfh->bfType = 0x4d42; /* "BM" */
1848 bfh->bfSize = bmpsize;
1849 bfh->bfReserved1 = 0;
1850 bfh->bfReserved2 = 0;
1851 bfh->bfOffBits = sizeof(BITMAPFILEHEADER) + bitmap_info_size((BITMAPINFO*)dibdata, DIB_RGB_COLORS);
1853 /* rest of bitmap is the same as the packed dib */
1854 memcpy(bfh+1, dibdata, bmpsize-sizeof(BITMAPFILEHEADER));
1856 *lpBytes = bmpsize;
1858 GlobalUnlock(hbmpdata);
1861 GlobalUnlock(hpackeddib);
1863 return hbmpdata;
1867 /**************************************************************************
1868 * X11DRV_CLIPBOARD_ExportMetaFilePict
1870 * Export MetaFilePict.
1872 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget, Atom rprop,
1873 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1875 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1877 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1878 return 0;
1881 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata->hData, lpBytes, TRUE);
1885 /**************************************************************************
1886 * X11DRV_CLIPBOARD_ExportEnhMetaFile
1888 * Export EnhMetaFile.
1890 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget, Atom rprop,
1891 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1893 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1895 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1896 return 0;
1899 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata->hData, lpBytes, TRUE);
1903 /**************************************************************************
1904 * get_html_description_field
1906 * Find the value of a field in an HTML Format description.
1908 static LPCSTR get_html_description_field(LPCSTR data, LPCSTR keyword)
1910 LPCSTR pos=data;
1912 while (pos && *pos && *pos != '<')
1914 if (memcmp(pos, keyword, strlen(keyword)) == 0)
1915 return pos+strlen(keyword);
1917 pos = strchr(pos, '\n');
1918 if (pos) pos++;
1921 return NULL;
1925 /**************************************************************************
1926 * X11DRV_CLIPBOARD_ExportTextHtml
1928 * Export HTML Format to text/html.
1930 * FIXME: We should attempt to add an <a base> tag and convert windows paths.
1932 static HANDLE X11DRV_CLIPBOARD_ExportTextHtml(Display *display, Window requestor, Atom aTarget,
1933 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1935 HANDLE hdata;
1936 LPCSTR data, field_value;
1937 UINT fragmentstart, fragmentend, htmlsize;
1938 HANDLE hhtmldata=NULL;
1939 LPSTR htmldata;
1941 *lpBytes = 0;
1943 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1945 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1946 return 0;
1949 hdata = lpdata->hData;
1951 data = GlobalLock(hdata);
1952 if (!data)
1954 ERR("Failed to lock HTML Format data\n");
1955 return 0;
1958 /* read the important fields */
1959 field_value = get_html_description_field(data, "StartFragment:");
1960 if (!field_value)
1962 ERR("Couldn't find StartFragment value\n");
1963 goto end;
1965 fragmentstart = atoi(field_value);
1967 field_value = get_html_description_field(data, "EndFragment:");
1968 if (!field_value)
1970 ERR("Couldn't find EndFragment value\n");
1971 goto end;
1973 fragmentend = atoi(field_value);
1975 /* export only the fragment */
1976 htmlsize = fragmentend - fragmentstart + 1;
1978 hhtmldata = GlobalAlloc(0, htmlsize);
1980 if (hhtmldata)
1982 htmldata = GlobalLock(hhtmldata);
1984 if (!htmldata)
1986 GlobalFree(hhtmldata);
1987 htmldata = NULL;
1988 goto end;
1991 memcpy(htmldata, &data[fragmentstart], fragmentend-fragmentstart);
1992 htmldata[htmlsize-1] = '\0';
1994 *lpBytes = htmlsize;
1996 GlobalUnlock(htmldata);
1999 end:
2001 GlobalUnlock(hdata);
2003 return hhtmldata;
2007 /**************************************************************************
2008 * X11DRV_CLIPBOARD_QueryTargets
2010 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection,
2011 Atom target, XEvent *xe)
2013 INT i;
2014 Bool res;
2016 wine_tsx11_lock();
2017 XConvertSelection(display, selection, target,
2018 x11drv_atom(SELECTION_DATA), w, CurrentTime);
2019 wine_tsx11_unlock();
2022 * Wait until SelectionNotify is received
2024 for (i = 0; i < SELECTION_RETRIES; i++)
2026 wine_tsx11_lock();
2027 res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
2028 wine_tsx11_unlock();
2029 if (res && xe->xselection.selection == selection) break;
2031 usleep(SELECTION_WAIT);
2034 if (i == SELECTION_RETRIES)
2036 ERR("Timed out waiting for SelectionNotify event\n");
2037 return FALSE;
2039 /* Verify that the selection returned a valid TARGETS property */
2040 if ((xe->xselection.target != target) || (xe->xselection.property == None))
2042 /* Selection owner failed to respond or we missed the SelectionNotify */
2043 WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
2044 return FALSE;
2047 return TRUE;
2051 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
2053 return (event->error_code == BadAtom);
2056 /**************************************************************************
2057 * X11DRV_CLIPBOARD_InsertSelectionProperties
2059 * Mark properties available for future retrieval.
2061 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
2063 UINT i, nb_atoms = 0;
2064 Atom *atoms = NULL;
2066 /* Cache these formats in the clipboard cache */
2067 for (i = 0; i < count; i++)
2069 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
2071 if (lpFormat)
2073 /* We found at least one Window's format that mapps to the property.
2074 * Continue looking for more.
2076 * If more than one property map to a Window's format then we use the first
2077 * one and ignore the rest.
2079 while (lpFormat)
2081 TRACE("Atom#%d Property(%d): --> Format %s\n",
2082 i, lpFormat->drvData, debugstr_format(lpFormat->wFormatID));
2083 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, lpFormat, FALSE);
2084 lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
2087 else if (properties[i])
2089 /* add it to the list of atoms that we don't know about yet */
2090 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
2091 (count - i) * sizeof(*atoms) );
2092 if (atoms) atoms[nb_atoms++] = properties[i];
2096 /* query all unknown atoms in one go */
2097 if (atoms)
2099 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
2100 if (names)
2102 X11DRV_expect_error( display, is_atom_error, NULL );
2103 if (!XGetAtomNames( display, atoms, nb_atoms, names )) nb_atoms = 0;
2104 if (X11DRV_check_error())
2106 WARN( "got some bad atoms, ignoring\n" );
2107 nb_atoms = 0;
2109 for (i = 0; i < nb_atoms; i++)
2111 WINE_CLIPFORMAT *lpFormat;
2112 LPWSTR wname;
2113 int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
2114 wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
2115 MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
2117 lpFormat = register_format( RegisterClipboardFormatW(wname), atoms[i] );
2118 HeapFree(GetProcessHeap(), 0, wname);
2119 if (!lpFormat)
2121 ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
2122 continue;
2124 TRACE("Atom#%d Property(%d): --> Format %s\n",
2125 i, lpFormat->drvData, debugstr_format(lpFormat->wFormatID));
2126 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, lpFormat, FALSE);
2128 wine_tsx11_lock();
2129 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
2130 wine_tsx11_unlock();
2131 HeapFree( GetProcessHeap(), 0, names );
2133 HeapFree( GetProcessHeap(), 0, atoms );
2138 /**************************************************************************
2139 * X11DRV_CLIPBOARD_QueryAvailableData
2141 * Caches the list of data formats available from the current selection.
2142 * This queries the selection owner for the TARGETS property and saves all
2143 * reported property types.
2145 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo)
2147 XEvent xe;
2148 Atom atype=AnyPropertyType;
2149 int aformat;
2150 unsigned long remain;
2151 Atom* targetList=NULL;
2152 Window w;
2153 unsigned long cSelectionTargets = 0;
2155 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
2157 ERR("Received request to cache selection but process is owner=(%08x)\n",
2158 (unsigned) selectionWindow);
2159 return -1; /* Prevent self request */
2162 w = thread_selection_wnd();
2163 if (!w)
2165 ERR("No window available to retrieve selection!\n");
2166 return -1;
2170 * Query the selection owner for the TARGETS property
2172 wine_tsx11_lock();
2173 if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
2174 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2176 wine_tsx11_unlock();
2177 if (use_primary_selection && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
2178 selectionCacheSrc = XA_PRIMARY;
2179 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
2180 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2181 else
2183 Atom xstr = XA_STRING;
2185 /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
2186 if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
2188 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2189 selectionCacheSrc = XA_PRIMARY;
2190 return 1;
2192 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
2194 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2195 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2196 return 1;
2198 else
2200 WARN("Failed to query selection owner for available data.\n");
2201 return -1;
2205 else /* No selection owner so report 0 targets available */
2207 wine_tsx11_unlock();
2208 return 0;
2211 /* Read the TARGETS property contents */
2212 wine_tsx11_lock();
2213 if(XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
2214 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
2215 &remain, (unsigned char**)&targetList) != Success)
2217 wine_tsx11_unlock();
2218 WARN("Failed to read TARGETS property\n");
2220 else
2222 wine_tsx11_unlock();
2223 TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
2224 atype, aformat, cSelectionTargets, remain);
2226 * The TARGETS property should have returned us a list of atoms
2227 * corresponding to each selection target format supported.
2229 if (atype == XA_ATOM || atype == x11drv_atom(TARGETS))
2231 if (aformat == 32)
2233 X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, cSelectionTargets);
2235 else if (aformat == 8) /* work around quartz-wm brain damage */
2237 unsigned long i, count = cSelectionTargets / sizeof(CARD32);
2238 Atom *atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(Atom) );
2239 for (i = 0; i < count; i++)
2240 atoms[i] = ((CARD32 *)targetList)[i]; /* FIXME: byte swapping */
2241 X11DRV_CLIPBOARD_InsertSelectionProperties( display, atoms, count );
2242 HeapFree( GetProcessHeap(), 0, atoms );
2246 /* Free the list of targets */
2247 wine_tsx11_lock();
2248 XFree(targetList);
2249 wine_tsx11_unlock();
2252 return cSelectionTargets;
2256 /**************************************************************************
2257 * X11DRV_CLIPBOARD_ReadSelectionData
2259 * This method is invoked only when we DO NOT own the X selection
2261 * We always get the data from the selection client each time,
2262 * since we have no way of determining if the data in our cache is stale.
2264 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData)
2266 Bool res;
2267 DWORD i;
2268 XEvent xe;
2269 BOOL bRet = FALSE;
2271 TRACE("%04x\n", lpData->wFormatID);
2273 if (!lpData->lpFormat)
2275 ERR("Requesting format %04x but no source format linked to data.\n",
2276 lpData->wFormatID);
2277 return FALSE;
2280 if (!selectionAcquired)
2282 Window w = thread_selection_wnd();
2283 if(!w)
2285 ERR("No window available to read selection data!\n");
2286 return FALSE;
2289 TRACE("Requesting conversion of %s property (%d) from selection type %08x\n",
2290 debugstr_format(lpData->lpFormat->wFormatID), lpData->lpFormat->drvData,
2291 (UINT)selectionCacheSrc);
2293 wine_tsx11_lock();
2294 XConvertSelection(display, selectionCacheSrc, lpData->lpFormat->drvData,
2295 x11drv_atom(SELECTION_DATA), w, CurrentTime);
2296 wine_tsx11_unlock();
2298 /* wait until SelectionNotify is received */
2299 for (i = 0; i < SELECTION_RETRIES; i++)
2301 wine_tsx11_lock();
2302 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
2303 wine_tsx11_unlock();
2304 if (res && xe.xselection.selection == selectionCacheSrc) break;
2306 usleep(SELECTION_WAIT);
2309 if (i == SELECTION_RETRIES)
2311 ERR("Timed out waiting for SelectionNotify event\n");
2313 /* Verify that the selection returned a valid TARGETS property */
2314 else if (xe.xselection.property != None)
2317 * Read the contents of the X selection property
2318 * into WINE's clipboard cache and converting the
2319 * data format if necessary.
2321 HANDLE hData = lpData->lpFormat->lpDrvImportFunc(display, xe.xselection.requestor,
2322 xe.xselection.property);
2324 if (hData)
2325 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, hData, 0, lpData->lpFormat, TRUE);
2326 else
2327 TRACE("Import function failed\n");
2329 else
2331 TRACE("Failed to convert selection\n");
2334 else
2336 ERR("Received request to cache selection data but process is owner\n");
2339 TRACE("Returning %d\n", bRet);
2341 return bRet;
2345 /**************************************************************************
2346 * X11DRV_CLIPBOARD_GetProperty
2347 * Gets type, data and size.
2349 static BOOL X11DRV_CLIPBOARD_GetProperty(Display *display, Window w, Atom prop,
2350 Atom *atype, unsigned char** data, unsigned long* datasize)
2352 int aformat;
2353 unsigned long pos = 0, nitems, remain, count;
2354 unsigned char *val = NULL, *buffer;
2356 TRACE("Reading property %lu from X window %lx\n", prop, w);
2358 for (;;)
2360 wine_tsx11_lock();
2361 if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
2362 AnyPropertyType, atype, &aformat, &nitems, &remain, &buffer) != Success)
2364 wine_tsx11_unlock();
2365 WARN("Failed to read property\n");
2366 HeapFree( GetProcessHeap(), 0, val );
2367 return FALSE;
2370 count = get_property_size( aformat, nitems );
2371 if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
2372 else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
2374 if (!*data)
2376 XFree( buffer );
2377 wine_tsx11_unlock();
2378 HeapFree( GetProcessHeap(), 0, val );
2379 return FALSE;
2381 val = *data;
2382 memcpy( (int *)val + pos, buffer, count );
2383 XFree( buffer );
2384 wine_tsx11_unlock();
2385 if (!remain)
2387 *datasize = pos * sizeof(int) + count;
2388 val[*datasize] = 0;
2389 break;
2391 pos += count / sizeof(int);
2394 /* Delete the property on the window now that we are done
2395 * This will send a PropertyNotify event to the selection owner. */
2396 wine_tsx11_lock();
2397 XDeleteProperty(display, w, prop);
2398 wine_tsx11_unlock();
2399 return TRUE;
2403 /**************************************************************************
2404 * X11DRV_CLIPBOARD_ReadProperty
2405 * Reads the contents of the X selection property.
2407 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
2408 unsigned char** data, unsigned long* datasize)
2410 Atom atype;
2411 XEvent xe;
2413 if (prop == None)
2414 return FALSE;
2416 if (!X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, data, datasize))
2417 return FALSE;
2419 wine_tsx11_lock();
2420 while (XCheckTypedWindowEvent(display, w, PropertyNotify, &xe))
2422 wine_tsx11_unlock();
2424 if (atype == x11drv_atom(INCR))
2426 unsigned char *buf = *data;
2427 unsigned long bufsize = 0;
2429 for (;;)
2431 int i;
2432 unsigned char *prop_data, *tmp;
2433 unsigned long prop_size;
2435 /* Wait until PropertyNotify is received */
2436 for (i = 0; i < SELECTION_RETRIES; i++)
2438 Bool res;
2440 wine_tsx11_lock();
2441 res = XCheckTypedWindowEvent(display, w, PropertyNotify, &xe);
2442 wine_tsx11_unlock();
2443 if (res && xe.xproperty.atom == prop &&
2444 xe.xproperty.state == PropertyNewValue)
2445 break;
2446 usleep(SELECTION_WAIT);
2449 if (i >= SELECTION_RETRIES ||
2450 !X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, &prop_data, &prop_size))
2452 HeapFree(GetProcessHeap(), 0, buf);
2453 return FALSE;
2456 /* Retrieved entire data. */
2457 if (prop_size == 0)
2459 HeapFree(GetProcessHeap(), 0, prop_data);
2460 *data = buf;
2461 *datasize = bufsize;
2462 return TRUE;
2465 tmp = HeapReAlloc(GetProcessHeap(), 0, buf, bufsize + prop_size + 1);
2466 if (!tmp)
2468 HeapFree(GetProcessHeap(), 0, buf);
2469 return FALSE;
2472 buf = tmp;
2473 memcpy(buf + bufsize, prop_data, prop_size + 1);
2474 bufsize += prop_size;
2475 HeapFree(GetProcessHeap(), 0, prop_data);
2479 return TRUE;
2483 /**************************************************************************
2484 * CLIPBOARD_SerializeMetafile
2486 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
2488 HANDLE h = 0;
2490 TRACE(" wFormat=%d hdata=%p out=%d\n", wformat, hdata, out);
2492 if (out) /* Serialize out, caller should free memory */
2494 *lpcbytes = 0; /* Assume failure */
2496 if (wformat == CF_METAFILEPICT)
2498 LPMETAFILEPICT lpmfp = GlobalLock(hdata);
2499 unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2501 h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
2502 if (h)
2504 char *pdata = GlobalLock(h);
2506 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
2507 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
2509 *lpcbytes = size + sizeof(METAFILEPICT);
2511 GlobalUnlock(h);
2514 GlobalUnlock(hdata);
2516 else if (wformat == CF_ENHMETAFILE)
2518 int size = GetEnhMetaFileBits(hdata, 0, NULL);
2520 h = GlobalAlloc(0, size);
2521 if (h)
2523 LPVOID pdata = GlobalLock(h);
2525 GetEnhMetaFileBits(hdata, size, pdata);
2526 *lpcbytes = size;
2528 GlobalUnlock(h);
2532 else
2534 if (wformat == CF_METAFILEPICT)
2536 h = GlobalAlloc(0, sizeof(METAFILEPICT));
2537 if (h)
2539 unsigned int wiresize;
2540 LPMETAFILEPICT lpmfp = GlobalLock(h);
2542 memcpy(lpmfp, hdata, sizeof(METAFILEPICT));
2543 wiresize = *lpcbytes - sizeof(METAFILEPICT);
2544 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
2545 ((const BYTE *)hdata) + sizeof(METAFILEPICT));
2546 GlobalUnlock(h);
2549 else if (wformat == CF_ENHMETAFILE)
2551 h = SetEnhMetaFileBits(*lpcbytes, hdata);
2555 return h;
2559 /**************************************************************************
2560 * X11DRV_CLIPBOARD_ReleaseSelection
2562 * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
2564 static void X11DRV_CLIPBOARD_ReleaseSelection(Display *display, Atom selType, Window w, HWND hwnd, Time time)
2566 /* w is the window that lost the selection
2568 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
2569 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
2571 if (selectionAcquired && (w == selectionWindow))
2573 CLIPBOARDINFO cbinfo;
2575 /* completely give up the selection */
2576 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
2578 X11DRV_CLIPBOARD_GetClipboardInfo(&cbinfo);
2580 if (cbinfo.flags & CB_PROCESS)
2582 /* Since we're still the owner, this wasn't initiated by
2583 another Wine process */
2584 if (OpenClipboard(hwnd))
2586 /* Destroy private objects */
2587 SendMessageW(cbinfo.hWndOwner, WM_DESTROYCLIPBOARD, 0, 0);
2589 /* Give up ownership of the windows clipboard */
2590 X11DRV_CLIPBOARD_ReleaseOwnership();
2591 CloseClipboard();
2595 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2597 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2599 wine_tsx11_lock();
2600 if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2602 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2603 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2605 else
2606 TRACE("We no longer own PRIMARY\n");
2607 wine_tsx11_unlock();
2609 else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2611 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2613 wine_tsx11_lock();
2614 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2616 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2617 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2619 else
2620 TRACE("We no longer own CLIPBOARD\n");
2621 wine_tsx11_unlock();
2624 selectionWindow = None;
2626 X11DRV_EmptyClipboard(FALSE);
2628 /* Reset the selection flags now that we are done */
2629 selectionAcquired = S_NOSELECTION;
2634 /**************************************************************************
2635 * IsSelectionOwner (X11DRV.@)
2637 * Returns: TRUE if the selection is owned by this process, FALSE otherwise
2639 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void)
2641 return selectionAcquired;
2645 /**************************************************************************
2646 * X11DRV Clipboard Exports
2647 **************************************************************************/
2650 static void selection_acquire(void)
2652 Window owner;
2653 Display *display;
2655 owner = thread_selection_wnd();
2656 display = thread_display();
2658 wine_tsx11_lock();
2660 selectionAcquired = 0;
2661 selectionWindow = 0;
2663 /* Grab PRIMARY selection if not owned */
2664 if (use_primary_selection)
2665 XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2667 /* Grab CLIPBOARD selection if not owned */
2668 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2670 if (use_primary_selection && XGetSelectionOwner(display, XA_PRIMARY) == owner)
2671 selectionAcquired |= S_PRIMARY;
2673 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2674 selectionAcquired |= S_CLIPBOARD;
2676 wine_tsx11_unlock();
2678 if (selectionAcquired)
2680 selectionWindow = owner;
2681 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2685 static DWORD WINAPI selection_thread_proc(LPVOID p)
2687 HANDLE event = p;
2689 TRACE("\n");
2691 selection_acquire();
2692 SetEvent(event);
2694 while (selectionAcquired)
2696 MsgWaitForMultipleObjectsEx(0, NULL, INFINITE, QS_SENDMESSAGE, 0);
2699 return 0;
2702 /**************************************************************************
2703 * AcquireClipboard (X11DRV.@)
2705 int CDECL X11DRV_AcquireClipboard(HWND hWndClipWindow)
2707 DWORD procid;
2708 HANDLE selectionThread;
2710 TRACE(" %p\n", hWndClipWindow);
2713 * It's important that the selection get acquired from the thread
2714 * that owns the clipboard window. The primary reason is that we know
2715 * it is running a message loop and therefore can process the
2716 * X selection events.
2718 if (hWndClipWindow &&
2719 GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, &procid))
2721 if (procid != GetCurrentProcessId())
2723 WARN("Setting clipboard owner to other process is not supported\n");
2724 hWndClipWindow = NULL;
2726 else
2728 TRACE("Thread %x is acquiring selection with thread %x's window %p\n",
2729 GetCurrentThreadId(),
2730 GetWindowThreadProcessId(hWndClipWindow, NULL), hWndClipWindow);
2732 return SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0);
2736 if (hWndClipWindow)
2738 selection_acquire();
2740 else
2742 HANDLE event = CreateEventW(NULL, FALSE, FALSE, NULL);
2743 selectionThread = CreateThread(NULL, 0, selection_thread_proc, event, 0, NULL);
2745 if (!selectionThread)
2747 WARN("Could not start clipboard thread\n");
2748 CloseHandle(event);
2749 return 0;
2752 WaitForSingleObject(event, INFINITE);
2753 CloseHandle(event);
2754 CloseHandle(selectionThread);
2757 return 1;
2761 /**************************************************************************
2762 * X11DRV_EmptyClipboard
2764 * Empty cached clipboard data.
2766 void CDECL X11DRV_EmptyClipboard(BOOL keepunowned)
2768 WINE_CLIPDATA *data, *next;
2770 LIST_FOR_EACH_ENTRY_SAFE( data, next, &data_list, WINE_CLIPDATA, entry )
2772 if (keepunowned && (data->wFlags & CF_FLAG_UNOWNED)) continue;
2773 list_remove( &data->entry );
2774 X11DRV_CLIPBOARD_FreeData( data );
2775 HeapFree( GetProcessHeap(), 0, data );
2776 ClipDataCount--;
2779 TRACE(" %d entries remaining in cache.\n", ClipDataCount);
2784 /**************************************************************************
2785 * X11DRV_SetClipboardData
2787 BOOL CDECL X11DRV_SetClipboardData(UINT wFormat, HANDLE hData, BOOL owner)
2789 DWORD flags = 0;
2790 BOOL bResult = TRUE;
2792 /* If it's not owned, data can only be set if the format data is not already owned
2793 and its rendering is not delayed */
2794 if (!owner)
2796 CLIPBOARDINFO cbinfo;
2797 LPWINE_CLIPDATA lpRender;
2799 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2801 if (!hData ||
2802 ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)) &&
2803 !(lpRender->wFlags & CF_FLAG_UNOWNED)))
2804 bResult = FALSE;
2805 else
2806 flags = CF_FLAG_UNOWNED;
2809 bResult &= X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData, flags, NULL, TRUE);
2811 return bResult;
2815 /**************************************************************************
2816 * CountClipboardFormats
2818 INT CDECL X11DRV_CountClipboardFormats(void)
2820 CLIPBOARDINFO cbinfo;
2822 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2824 TRACE(" count=%d\n", ClipDataCount);
2826 return ClipDataCount;
2830 /**************************************************************************
2831 * X11DRV_EnumClipboardFormats
2833 UINT CDECL X11DRV_EnumClipboardFormats(UINT wFormat)
2835 CLIPBOARDINFO cbinfo;
2836 struct list *ptr = NULL;
2838 TRACE("(%04X)\n", wFormat);
2840 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2842 if (!wFormat)
2844 ptr = list_head( &data_list );
2846 else
2848 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
2849 if (lpData) ptr = list_next( &data_list, &lpData->entry );
2852 if (!ptr) return 0;
2853 return LIST_ENTRY( ptr, WINE_CLIPDATA, entry )->wFormatID;
2857 /**************************************************************************
2858 * X11DRV_IsClipboardFormatAvailable
2860 BOOL CDECL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
2862 BOOL bRet = FALSE;
2863 CLIPBOARDINFO cbinfo;
2865 TRACE("(%04X)\n", wFormat);
2867 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2869 if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
2870 bRet = TRUE;
2872 TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
2874 return bRet;
2878 /**************************************************************************
2879 * GetClipboardData (USER.142)
2881 HANDLE CDECL X11DRV_GetClipboardData(UINT wFormat)
2883 CLIPBOARDINFO cbinfo;
2884 LPWINE_CLIPDATA lpRender;
2886 TRACE("(%04X)\n", wFormat);
2888 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2890 if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
2892 if ( !lpRender->hData )
2893 X11DRV_CLIPBOARD_RenderFormat(thread_init_display(), lpRender);
2895 TRACE(" returning %p (type %04x)\n", lpRender->hData, lpRender->wFormatID);
2896 return lpRender->hData;
2899 return 0;
2903 /**************************************************************************
2904 * ResetSelectionOwner
2906 * Called when the thread owning the selection is destroyed and we need to
2907 * preserve the selection ownership. We look for another top level window
2908 * in this process and send it a message to acquire the selection.
2910 void X11DRV_ResetSelectionOwner(void)
2912 HWND hwnd;
2913 DWORD procid;
2915 TRACE("\n");
2917 if (!selectionAcquired || thread_selection_wnd() != selectionWindow)
2918 return;
2920 selectionAcquired = S_NOSELECTION;
2921 selectionWindow = 0;
2923 hwnd = GetWindow(GetDesktopWindow(), GW_CHILD);
2926 if (GetCurrentThreadId() != GetWindowThreadProcessId(hwnd, &procid))
2928 if (GetCurrentProcessId() == procid)
2930 if (SendMessageW(hwnd, WM_X11DRV_ACQUIRE_SELECTION, 0, 0))
2931 return;
2934 } while ((hwnd = GetWindow(hwnd, GW_HWNDNEXT)) != NULL);
2936 WARN("Failed to find another thread to take selection ownership. Clipboard data will be lost.\n");
2938 X11DRV_CLIPBOARD_ReleaseOwnership();
2939 X11DRV_EmptyClipboard(FALSE);
2943 /**************************************************************************
2944 * X11DRV_CLIPBOARD_SynthesizeData
2946 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID)
2948 BOOL bsyn = TRUE;
2949 LPWINE_CLIPDATA lpSource = NULL;
2951 TRACE(" %04x\n", wFormatID);
2953 /* Don't need to synthesize if it already exists */
2954 if (X11DRV_CLIPBOARD_LookupData(wFormatID))
2955 return TRUE;
2957 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
2959 bsyn = ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
2960 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2961 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
2962 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2963 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
2964 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED);
2966 else if (wFormatID == CF_ENHMETAFILE)
2968 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2969 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2971 else if (wFormatID == CF_METAFILEPICT)
2973 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_ENHMETAFILE)) &&
2974 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2976 else if (wFormatID == CF_DIB)
2978 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
2979 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2981 else if (wFormatID == CF_BITMAP)
2983 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
2984 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2987 if (bsyn)
2988 X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, CF_FLAG_SYNTHESIZED, NULL, TRUE);
2990 return bsyn;
2995 /**************************************************************************
2996 * X11DRV_EndClipboardUpdate
2997 * TODO:
2998 * Add locale if it hasn't already been added
3000 void CDECL X11DRV_EndClipboardUpdate(void)
3002 INT count = ClipDataCount;
3004 /* Do Unicode <-> Text <-> OEM mapping */
3005 X11DRV_CLIPBOARD_SynthesizeData(CF_TEXT);
3006 X11DRV_CLIPBOARD_SynthesizeData(CF_OEMTEXT);
3007 X11DRV_CLIPBOARD_SynthesizeData(CF_UNICODETEXT);
3009 /* Enhmetafile <-> MetafilePict mapping */
3010 X11DRV_CLIPBOARD_SynthesizeData(CF_ENHMETAFILE);
3011 X11DRV_CLIPBOARD_SynthesizeData(CF_METAFILEPICT);
3013 /* DIB <-> Bitmap mapping */
3014 X11DRV_CLIPBOARD_SynthesizeData(CF_DIB);
3015 X11DRV_CLIPBOARD_SynthesizeData(CF_BITMAP);
3017 TRACE("%d formats added to cached data\n", ClipDataCount - count);
3021 /***********************************************************************
3022 * X11DRV_SelectionRequest_TARGETS
3023 * Service a TARGETS selection request event
3025 static Atom X11DRV_SelectionRequest_TARGETS( Display *display, Window requestor,
3026 Atom target, Atom rprop )
3028 UINT i;
3029 Atom* targets;
3030 ULONG cTargets;
3031 LPWINE_CLIPFORMAT format;
3032 LPWINE_CLIPDATA lpData;
3034 /* Create X atoms for any clipboard types which don't have atoms yet.
3035 * This avoids sending bogus zero atoms.
3036 * Without this, copying might not have access to all clipboard types.
3037 * FIXME: is it safe to call this here?
3039 intern_atoms();
3042 * Count the number of items we wish to expose as selection targets.
3044 cTargets = 1; /* Include TARGETS */
3046 if (!list_head( &data_list )) return None;
3048 LIST_FOR_EACH_ENTRY( lpData, &data_list, WINE_CLIPDATA, entry )
3049 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
3050 if ((format->wFormatID == lpData->wFormatID) &&
3051 format->lpDrvExportFunc && format->drvData)
3052 cTargets++;
3054 TRACE(" found %d formats\n", cTargets);
3056 /* Allocate temp buffer */
3057 targets = HeapAlloc( GetProcessHeap(), 0, cTargets * sizeof(Atom));
3058 if(targets == NULL)
3059 return None;
3061 i = 0;
3062 targets[i++] = x11drv_atom(TARGETS);
3064 LIST_FOR_EACH_ENTRY( lpData, &data_list, WINE_CLIPDATA, entry )
3065 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
3066 if ((format->wFormatID == lpData->wFormatID) &&
3067 format->lpDrvExportFunc && format->drvData)
3068 targets[i++] = format->drvData;
3070 wine_tsx11_lock();
3072 if (TRACE_ON(clipboard))
3074 unsigned int i;
3075 for ( i = 0; i < cTargets; i++)
3077 char *itemFmtName = XGetAtomName(display, targets[i]);
3078 TRACE("\tAtom# %d: Property %ld Type %s\n", i, targets[i], itemFmtName);
3079 XFree(itemFmtName);
3083 /* We may want to consider setting the type to xaTargets instead,
3084 * in case some apps expect this instead of XA_ATOM */
3085 XChangeProperty(display, requestor, rprop, XA_ATOM, 32,
3086 PropModeReplace, (unsigned char *)targets, cTargets);
3087 wine_tsx11_unlock();
3089 HeapFree(GetProcessHeap(), 0, targets);
3091 return rprop;
3095 /***********************************************************************
3096 * X11DRV_SelectionRequest_MULTIPLE
3097 * Service a MULTIPLE selection request event
3098 * rprop contains a list of (target,property) atom pairs.
3099 * The first atom names a target and the second names a property.
3100 * The effect is as if we have received a sequence of SelectionRequest events
3101 * (one for each atom pair) except that:
3102 * 1. We reply with a SelectionNotify only when all the requested conversions
3103 * have been performed.
3104 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
3105 * we replace the atom in the property by None.
3107 static Atom X11DRV_SelectionRequest_MULTIPLE( HWND hWnd, XSelectionRequestEvent *pevent )
3109 Display *display = pevent->display;
3110 Atom rprop;
3111 Atom atype=AnyPropertyType;
3112 int aformat;
3113 unsigned long remain;
3114 Atom* targetPropList=NULL;
3115 unsigned long cTargetPropList = 0;
3117 /* If the specified property is None the requestor is an obsolete client.
3118 * We support these by using the specified target atom as the reply property.
3120 rprop = pevent->property;
3121 if( rprop == None )
3122 rprop = pevent->target;
3123 if (!rprop)
3124 return 0;
3126 /* Read the MULTIPLE property contents. This should contain a list of
3127 * (target,property) atom pairs.
3129 wine_tsx11_lock();
3130 if(XGetWindowProperty(display, pevent->requestor, rprop,
3131 0, 0x3FFF, False, AnyPropertyType, &atype,&aformat,
3132 &cTargetPropList, &remain,
3133 (unsigned char**)&targetPropList) != Success)
3135 wine_tsx11_unlock();
3136 TRACE("\tCouldn't read MULTIPLE property\n");
3138 else
3140 if (TRACE_ON(clipboard))
3142 char * const typeName = XGetAtomName(display, atype);
3143 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
3144 typeName, aformat, cTargetPropList, remain);
3145 XFree(typeName);
3147 wine_tsx11_unlock();
3150 * Make sure we got what we expect.
3151 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
3152 * in a MULTIPLE selection request should be of type ATOM_PAIR.
3153 * However some X apps(such as XPaint) are not compliant with this and return
3154 * a user defined atom in atype when XGetWindowProperty is called.
3155 * The data *is* an atom pair but is not denoted as such.
3157 if(aformat == 32 /* atype == xAtomPair */ )
3159 unsigned int i;
3161 /* Iterate through the ATOM_PAIR list and execute a SelectionRequest
3162 * for each (target,property) pair */
3164 for (i = 0; i < cTargetPropList; i+=2)
3166 XSelectionRequestEvent event;
3168 if (TRACE_ON(clipboard))
3170 char *targetName, *propName;
3171 wine_tsx11_lock();
3172 targetName = XGetAtomName(display, targetPropList[i]);
3173 propName = XGetAtomName(display, targetPropList[i+1]);
3174 TRACE("MULTIPLE(%d): Target='%s' Prop='%s'\n",
3175 i/2, targetName, propName);
3176 XFree(targetName);
3177 XFree(propName);
3178 wine_tsx11_unlock();
3181 /* We must have a non "None" property to service a MULTIPLE target atom */
3182 if ( !targetPropList[i+1] )
3184 TRACE("\tMULTIPLE(%d): Skipping target with empty property!\n", i);
3185 continue;
3188 /* Set up an XSelectionRequestEvent for this (target,property) pair */
3189 event = *pevent;
3190 event.target = targetPropList[i];
3191 event.property = targetPropList[i+1];
3193 /* Fire a SelectionRequest, informing the handler that we are processing
3194 * a MULTIPLE selection request event.
3196 X11DRV_HandleSelectionRequest( hWnd, &event, TRUE );
3200 /* Free the list of targets/properties */
3201 wine_tsx11_lock();
3202 XFree(targetPropList);
3203 wine_tsx11_unlock();
3206 return rprop;
3210 /***********************************************************************
3211 * X11DRV_HandleSelectionRequest
3212 * Process an event selection request event.
3213 * The bIsMultiple flag is used to signal when EVENT_SelectionRequest is called
3214 * recursively while servicing a "MULTIPLE" selection target.
3216 * Note: We only receive this event when WINE owns the X selection
3218 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple )
3220 Display *display = event->display;
3221 XSelectionEvent result;
3222 Atom rprop = None;
3223 Window request = event->requestor;
3225 TRACE("\n");
3228 * We can only handle the selection request if :
3229 * The selection is PRIMARY or CLIPBOARD, AND we can successfully open the clipboard.
3230 * Don't do these checks or open the clipboard while recursively processing MULTIPLE,
3231 * since this has been already done.
3233 if ( !bIsMultiple )
3235 if (((event->selection != XA_PRIMARY) && (event->selection != x11drv_atom(CLIPBOARD))))
3236 goto END;
3239 /* If the specified property is None the requestor is an obsolete client.
3240 * We support these by using the specified target atom as the reply property.
3242 rprop = event->property;
3243 if( rprop == None )
3244 rprop = event->target;
3246 if(event->target == x11drv_atom(TARGETS)) /* Return a list of all supported targets */
3248 /* TARGETS selection request */
3249 rprop = X11DRV_SelectionRequest_TARGETS( display, request, event->target, rprop );
3251 else if(event->target == x11drv_atom(MULTIPLE)) /* rprop contains a list of (target, property) atom pairs */
3253 /* MULTIPLE selection request */
3254 rprop = X11DRV_SelectionRequest_MULTIPLE( hWnd, event );
3256 else
3258 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, event->target);
3260 if (lpFormat && lpFormat->lpDrvExportFunc)
3262 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(lpFormat->wFormatID);
3264 if (lpData)
3266 unsigned char* lpClipData;
3267 DWORD cBytes;
3268 HANDLE hClipData = lpFormat->lpDrvExportFunc(display, request, event->target,
3269 rprop, lpData, &cBytes);
3271 if (hClipData && (lpClipData = GlobalLock(hClipData)))
3273 int mode = PropModeReplace;
3275 TRACE("\tUpdating property %s, %d bytes\n",
3276 debugstr_format(lpFormat->wFormatID), cBytes);
3277 wine_tsx11_lock();
3280 int nelements = min(cBytes, 65536);
3281 XChangeProperty(display, request, rprop, event->target,
3282 8, mode, lpClipData, nelements);
3283 mode = PropModeAppend;
3284 cBytes -= nelements;
3285 lpClipData += nelements;
3286 } while (cBytes > 0);
3287 wine_tsx11_unlock();
3289 GlobalUnlock(hClipData);
3290 GlobalFree(hClipData);
3296 END:
3297 /* reply to sender
3298 * SelectionNotify should be sent only at the end of a MULTIPLE request
3300 if ( !bIsMultiple )
3302 result.type = SelectionNotify;
3303 result.display = display;
3304 result.requestor = request;
3305 result.selection = event->selection;
3306 result.property = rprop;
3307 result.target = event->target;
3308 result.time = event->time;
3309 TRACE("Sending SelectionNotify event...\n");
3310 wine_tsx11_lock();
3311 XSendEvent(display,event->requestor,False,NoEventMask,(XEvent*)&result);
3312 wine_tsx11_unlock();
3317 /***********************************************************************
3318 * X11DRV_SelectionRequest
3320 void X11DRV_SelectionRequest( HWND hWnd, XEvent *event )
3322 X11DRV_HandleSelectionRequest( hWnd, &event->xselectionrequest, FALSE );
3326 /***********************************************************************
3327 * X11DRV_SelectionClear
3329 void X11DRV_SelectionClear( HWND hWnd, XEvent *xev )
3331 XSelectionClearEvent *event = &xev->xselectionclear;
3332 if (event->selection == XA_PRIMARY || event->selection == x11drv_atom(CLIPBOARD))
3333 X11DRV_CLIPBOARD_ReleaseSelection( event->display, event->selection,
3334 event->window, hWnd, event->time );
3337 /***********************************************************************
3338 * X11DRV_Clipboard_Cleanup
3340 void X11DRV_Clipboard_Cleanup(void)
3342 selectionAcquired = S_NOSELECTION;
3344 X11DRV_EmptyClipboard(FALSE);