dinput: Add Lithuanian translation.
[wine/multimedia.git] / dlls / winex11.drv / clipboard.c
blobcaf2406da69fb5a2b4d33988bc03f0dbd7781bc3
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 * X11DRV_CLIPBOARD_RenderSynthesizedDIB
908 * Renders synthesized DIB
910 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedDIB(Display *display)
912 BOOL bret = FALSE;
913 LPWINE_CLIPDATA lpSource = NULL;
915 TRACE("\n");
917 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) && lpSource->hData)
919 bret = TRUE;
921 /* If we have a bitmap and it's not synthesized or it has been rendered */
922 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
923 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
925 /* Render source if required */
926 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
928 HDC hdc;
929 HGLOBAL hData;
931 hdc = GetDC(NULL);
932 hData = X11DRV_DIB_CreateDIBFromBitmap(hdc, lpSource->hData);
933 ReleaseDC(NULL, hdc);
935 if (hData)
937 X11DRV_CLIPBOARD_InsertClipboardData(CF_DIB, hData, 0, NULL, TRUE);
938 bret = TRUE;
943 return bret;
947 /**************************************************************************
948 * X11DRV_CLIPBOARD_RenderSynthesizedBitmap
950 * Renders synthesized bitmap
952 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedBitmap(Display *display)
954 BOOL bret = FALSE;
955 LPWINE_CLIPDATA lpSource = NULL;
957 TRACE("\n");
959 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) && lpSource->hData)
961 bret = TRUE;
963 /* If we have a dib and it's not synthesized or it has been rendered */
964 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
965 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
967 /* Render source if required */
968 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
970 HDC hdc;
971 HBITMAP hData = NULL;
972 unsigned int offset;
973 LPBITMAPINFOHEADER lpbmih;
975 hdc = GetDC(NULL);
976 lpbmih = GlobalLock(lpSource->hData);
977 if (lpbmih)
979 offset = sizeof(BITMAPINFOHEADER)
980 + ((lpbmih->biBitCount <= 8) ? (sizeof(RGBQUAD) *
981 (1 << lpbmih->biBitCount)) : 0);
983 hData = CreateDIBitmap(hdc, lpbmih, CBM_INIT, (LPBYTE)lpbmih +
984 offset, (LPBITMAPINFO) lpbmih, DIB_RGB_COLORS);
986 GlobalUnlock(lpSource->hData);
988 ReleaseDC(NULL, hdc);
990 if (hData)
992 X11DRV_CLIPBOARD_InsertClipboardData(CF_BITMAP, hData, 0, NULL, TRUE);
993 bret = TRUE;
998 return bret;
1002 /**************************************************************************
1003 * X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile
1005 static BOOL X11DRV_CLIPBOARD_RenderSynthesizedEnhMetaFile(Display *display)
1007 LPWINE_CLIPDATA lpSource = NULL;
1009 TRACE("\n");
1011 if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_ENHMETAFILE)) && lpSource->hData)
1012 return TRUE;
1013 /* If we have a MF pict and it's not synthesized or it has been rendered */
1014 else if ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
1015 (!(lpSource->wFlags & CF_FLAG_SYNTHESIZED) || lpSource->hData))
1017 /* Render source if required */
1018 if (lpSource->hData || X11DRV_CLIPBOARD_RenderFormat(display, lpSource))
1020 METAFILEPICT *pmfp;
1021 HENHMETAFILE hData = NULL;
1023 pmfp = GlobalLock(lpSource->hData);
1024 if (pmfp)
1026 UINT size_mf_bits = GetMetaFileBitsEx(pmfp->hMF, 0, NULL);
1027 void *mf_bits = HeapAlloc(GetProcessHeap(), 0, size_mf_bits);
1028 if (mf_bits)
1030 GetMetaFileBitsEx(pmfp->hMF, size_mf_bits, mf_bits);
1031 hData = SetWinMetaFileBits(size_mf_bits, mf_bits, NULL, pmfp);
1032 HeapFree(GetProcessHeap(), 0, mf_bits);
1034 GlobalUnlock(lpSource->hData);
1037 if (hData)
1039 X11DRV_CLIPBOARD_InsertClipboardData(CF_ENHMETAFILE, hData, 0, NULL, TRUE);
1040 return TRUE;
1045 return FALSE;
1049 /**************************************************************************
1050 * X11DRV_CLIPBOARD_ImportXAString
1052 * Import XA_STRING, converting the string to CF_TEXT.
1054 static HANDLE X11DRV_CLIPBOARD_ImportXAString(Display *display, Window w, Atom prop)
1056 LPBYTE lpdata;
1057 unsigned long cbytes;
1058 LPSTR lpstr;
1059 unsigned long i, inlcount = 0;
1060 HANDLE hText = 0;
1062 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1063 return 0;
1065 for (i = 0; i <= cbytes; i++)
1067 if (lpdata[i] == '\n')
1068 inlcount++;
1071 if ((hText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes + inlcount + 1)))
1073 lpstr = GlobalLock(hText);
1075 for (i = 0, inlcount = 0; i <= cbytes; i++)
1077 if (lpdata[i] == '\n')
1078 lpstr[inlcount++] = '\r';
1080 lpstr[inlcount++] = lpdata[i];
1083 GlobalUnlock(hText);
1086 /* Free the retrieved property data */
1087 HeapFree(GetProcessHeap(), 0, lpdata);
1089 return hText;
1093 /**************************************************************************
1094 * X11DRV_CLIPBOARD_ImportUTF8
1096 * Import XA_STRING, converting the string to CF_UNICODE.
1098 static HANDLE X11DRV_CLIPBOARD_ImportUTF8(Display *display, Window w, Atom prop)
1100 LPBYTE lpdata;
1101 unsigned long cbytes;
1102 LPSTR lpstr;
1103 unsigned long i, inlcount = 0;
1104 HANDLE hUnicodeText = 0;
1106 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1107 return 0;
1109 for (i = 0; i <= cbytes; i++)
1111 if (lpdata[i] == '\n')
1112 inlcount++;
1115 if ((lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbytes + inlcount + 1)))
1117 UINT count;
1119 for (i = 0, inlcount = 0; i <= cbytes; i++)
1121 if (lpdata[i] == '\n')
1122 lpstr[inlcount++] = '\r';
1124 lpstr[inlcount++] = lpdata[i];
1127 count = MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, NULL, 0);
1128 hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, count * sizeof(WCHAR));
1130 if (hUnicodeText)
1132 WCHAR *textW = GlobalLock(hUnicodeText);
1133 MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, textW, count);
1134 GlobalUnlock(hUnicodeText);
1137 HeapFree(GetProcessHeap(), 0, lpstr);
1140 /* Free the retrieved property data */
1141 HeapFree(GetProcessHeap(), 0, lpdata);
1143 return hUnicodeText;
1147 /**************************************************************************
1148 * X11DRV_CLIPBOARD_ImportCompoundText
1150 * Import COMPOUND_TEXT to CF_UNICODE
1152 static HANDLE X11DRV_CLIPBOARD_ImportCompoundText(Display *display, Window w, Atom prop)
1154 int i, j, ret;
1155 char** srcstr;
1156 int count, lcount;
1157 int srclen, destlen;
1158 HANDLE hUnicodeText;
1159 XTextProperty txtprop;
1161 if (!X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &txtprop.value, &txtprop.nitems))
1163 return 0;
1166 txtprop.encoding = x11drv_atom(COMPOUND_TEXT);
1167 txtprop.format = 8;
1168 wine_tsx11_lock();
1169 ret = XmbTextPropertyToTextList(display, &txtprop, &srcstr, &count);
1170 wine_tsx11_unlock();
1171 HeapFree(GetProcessHeap(), 0, txtprop.value);
1172 if (ret != Success || !count) return 0;
1174 TRACE("Importing %d line(s)\n", count);
1176 /* Compute number of lines */
1177 srclen = strlen(srcstr[0]);
1178 for (i = 0, lcount = 0; i <= srclen; i++)
1180 if (srcstr[0][i] == '\n')
1181 lcount++;
1184 destlen = MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, NULL, 0);
1186 TRACE("lcount = %d, destlen=%d, srcstr %s\n", lcount, destlen, srcstr[0]);
1188 if ((hUnicodeText = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (destlen + lcount + 1) * sizeof(WCHAR))))
1190 WCHAR *deststr = GlobalLock(hUnicodeText);
1191 MultiByteToWideChar(CP_UNIXCP, 0, srcstr[0], -1, deststr, destlen);
1193 if (lcount)
1195 for (i = destlen - 1, j = destlen + lcount - 1; i >= 0; i--, j--)
1197 deststr[j] = deststr[i];
1199 if (deststr[i] == '\n')
1200 deststr[--j] = '\r';
1204 GlobalUnlock(hUnicodeText);
1207 wine_tsx11_lock();
1208 XFreeStringList(srcstr);
1209 wine_tsx11_unlock();
1211 return hUnicodeText;
1215 /**************************************************************************
1216 * X11DRV_CLIPBOARD_ImportXAPIXMAP
1218 * Import XA_PIXMAP, converting the image to CF_DIB.
1220 static HANDLE X11DRV_CLIPBOARD_ImportXAPIXMAP(Display *display, Window w, Atom prop)
1222 HWND hwnd;
1223 HDC hdc;
1224 LPBYTE lpdata;
1225 unsigned long cbytes;
1226 Pixmap *pPixmap;
1227 HANDLE hClipData = 0;
1229 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1231 pPixmap = (Pixmap *) lpdata;
1233 hwnd = GetOpenClipboardWindow();
1234 hdc = GetDC(hwnd);
1236 hClipData = X11DRV_DIB_CreateDIBFromPixmap(*pPixmap, hdc);
1237 ReleaseDC(hwnd, hdc);
1239 /* Free the retrieved property data */
1240 HeapFree(GetProcessHeap(), 0, lpdata);
1243 return hClipData;
1247 /**************************************************************************
1248 * X11DRV_CLIPBOARD_ImportImageBmp
1250 * Import image/bmp, converting the image to CF_DIB.
1252 static HANDLE X11DRV_CLIPBOARD_ImportImageBmp(Display *display, Window w, Atom prop)
1254 LPBYTE lpdata;
1255 unsigned long cbytes;
1256 HANDLE hClipData = 0;
1258 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1260 BITMAPFILEHEADER *bfh = (BITMAPFILEHEADER*)lpdata;
1262 if (cbytes >= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPCOREHEADER) &&
1263 bfh->bfType == 0x4d42 /* "BM" */)
1265 BITMAPINFO *bmi = (BITMAPINFO*)(bfh+1);
1266 HBITMAP hbmp;
1267 HDC hdc;
1269 hdc = GetDC(0);
1270 hbmp = CreateDIBitmap(
1271 hdc,
1272 &(bmi->bmiHeader),
1273 CBM_INIT,
1274 lpdata+bfh->bfOffBits,
1275 bmi,
1276 DIB_RGB_COLORS
1279 hClipData = X11DRV_DIB_CreateDIBFromBitmap(hdc, hbmp);
1281 DeleteObject(hbmp);
1282 ReleaseDC(0, hdc);
1285 /* Free the retrieved property data */
1286 HeapFree(GetProcessHeap(), 0, lpdata);
1289 return hClipData;
1293 /**************************************************************************
1294 * X11DRV_CLIPBOARD_ImportMetaFilePict
1296 * Import MetaFilePict.
1298 static HANDLE X11DRV_CLIPBOARD_ImportMetaFilePict(Display *display, Window w, Atom prop)
1300 LPBYTE lpdata;
1301 unsigned long cbytes;
1302 HANDLE hClipData = 0;
1304 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1306 if (cbytes)
1307 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata, (LPDWORD)&cbytes, FALSE);
1309 /* Free the retrieved property data */
1310 HeapFree(GetProcessHeap(), 0, lpdata);
1313 return hClipData;
1317 /**************************************************************************
1318 * X11DRV_ImportEnhMetaFile
1320 * Import EnhMetaFile.
1322 static HANDLE X11DRV_CLIPBOARD_ImportEnhMetaFile(Display *display, Window w, Atom prop)
1324 LPBYTE lpdata;
1325 unsigned long cbytes;
1326 HANDLE hClipData = 0;
1328 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1330 if (cbytes)
1331 hClipData = X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata, (LPDWORD)&cbytes, FALSE);
1333 /* Free the retrieved property data */
1334 HeapFree(GetProcessHeap(), 0, lpdata);
1337 return hClipData;
1341 /**************************************************************************
1342 * X11DRV_ImportClipbordaData
1344 * Generic import clipboard data routine.
1346 static HANDLE X11DRV_CLIPBOARD_ImportClipboardData(Display *display, Window w, Atom prop)
1348 LPVOID lpClipData;
1349 LPBYTE lpdata;
1350 unsigned long cbytes;
1351 HANDLE hClipData = 0;
1353 if (X11DRV_CLIPBOARD_ReadProperty(display, w, prop, &lpdata, &cbytes))
1355 if (cbytes)
1357 /* Turn on the DDESHARE flag to enable shared 32 bit memory */
1358 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cbytes);
1359 if (hClipData == 0)
1360 return NULL;
1362 if ((lpClipData = GlobalLock(hClipData)))
1364 memcpy(lpClipData, lpdata, cbytes);
1365 GlobalUnlock(hClipData);
1367 else
1369 GlobalFree(hClipData);
1370 hClipData = 0;
1374 /* Free the retrieved property data */
1375 HeapFree(GetProcessHeap(), 0, lpdata);
1378 return hClipData;
1382 /**************************************************************************
1383 X11DRV_CLIPBOARD_ExportClipboardData
1385 * Generic export clipboard data routine.
1387 static HANDLE X11DRV_CLIPBOARD_ExportClipboardData(Display *display, Window requestor, Atom aTarget,
1388 Atom rprop, LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1390 LPVOID lpClipData;
1391 UINT datasize = 0;
1392 HANDLE hClipData = 0;
1394 *lpBytes = 0; /* Assume failure */
1396 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1397 ERR("Failed to export %04x format\n", lpData->wFormatID);
1398 else
1400 datasize = GlobalSize(lpData->hData);
1402 hClipData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, datasize);
1403 if (hClipData == 0) return NULL;
1405 if ((lpClipData = GlobalLock(hClipData)))
1407 LPVOID lpdata = GlobalLock(lpData->hData);
1409 memcpy(lpClipData, lpdata, datasize);
1410 *lpBytes = datasize;
1412 GlobalUnlock(lpData->hData);
1413 GlobalUnlock(hClipData);
1414 } else {
1415 GlobalFree(hClipData);
1416 hClipData = 0;
1420 return hClipData;
1424 /**************************************************************************
1425 * X11DRV_CLIPBOARD_ExportXAString
1427 * Export CF_TEXT converting the string to XA_STRING.
1428 * Helper function for X11DRV_CLIPBOARD_ExportString.
1430 static HANDLE X11DRV_CLIPBOARD_ExportXAString(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1432 UINT i, j;
1433 UINT size;
1434 LPSTR text, lpstr = NULL;
1436 *lpBytes = 0; /* Assume return has zero bytes */
1438 text = GlobalLock(lpData->hData);
1439 size = strlen(text);
1441 /* remove carriage returns */
1442 lpstr = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1);
1443 if (lpstr == NULL)
1444 goto done;
1446 for (i = 0,j = 0; i < size && text[i]; i++)
1448 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1449 continue;
1450 lpstr[j++] = text[i];
1453 lpstr[j]='\0';
1454 *lpBytes = j; /* Number of bytes in string */
1456 done:
1457 GlobalUnlock(lpData->hData);
1459 return lpstr;
1463 /**************************************************************************
1464 * X11DRV_CLIPBOARD_ExportUTF8String
1466 * Export CF_UNICODE converting the string to UTF8.
1467 * Helper function for X11DRV_CLIPBOARD_ExportString.
1469 static HANDLE X11DRV_CLIPBOARD_ExportUTF8String(LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1471 UINT i, j;
1472 UINT size;
1473 LPWSTR uni_text;
1474 LPSTR text, lpstr = NULL;
1476 *lpBytes = 0; /* Assume return has zero bytes */
1478 uni_text = GlobalLock(lpData->hData);
1480 size = WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, NULL, 0, NULL, NULL);
1482 text = HeapAlloc(GetProcessHeap(), 0, size);
1483 if (!text)
1484 goto done;
1485 WideCharToMultiByte(CP_UTF8, 0, uni_text, -1, text, size, NULL, NULL);
1487 /* remove carriage returns */
1488 lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size--);
1489 if (lpstr == NULL)
1490 goto done;
1492 for (i = 0,j = 0; i < size && text[i]; i++)
1494 if (text[i] == '\r' && (text[i+1] == '\n' || text[i+1] == '\0'))
1495 continue;
1496 lpstr[j++] = text[i];
1498 lpstr[j]='\0';
1500 *lpBytes = j; /* Number of bytes in string */
1502 done:
1503 HeapFree(GetProcessHeap(), 0, text);
1504 GlobalUnlock(lpData->hData);
1506 return lpstr;
1511 /**************************************************************************
1512 * X11DRV_CLIPBOARD_ExportCompoundText
1514 * Export CF_UNICODE to COMPOUND_TEXT
1515 * Helper function for X11DRV_CLIPBOARD_ExportString.
1517 static HANDLE X11DRV_CLIPBOARD_ExportCompoundText(Display *display, Window requestor, Atom aTarget, Atom rprop,
1518 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1520 char* lpstr = 0;
1521 XTextProperty prop;
1522 XICCEncodingStyle style;
1523 UINT i, j;
1524 UINT size;
1525 LPWSTR uni_text;
1527 uni_text = GlobalLock(lpData->hData);
1529 size = WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, NULL, 0, NULL, NULL);
1530 lpstr = HeapAlloc(GetProcessHeap(), 0, size);
1531 if (!lpstr)
1532 return 0;
1534 WideCharToMultiByte(CP_UNIXCP, 0, uni_text, -1, lpstr, size, NULL, NULL);
1536 /* remove carriage returns */
1537 for (i = 0, j = 0; i < size && lpstr[i]; i++)
1539 if (lpstr[i] == '\r' && (lpstr[i+1] == '\n' || lpstr[i+1] == '\0'))
1540 continue;
1541 lpstr[j++] = lpstr[i];
1543 lpstr[j]='\0';
1545 GlobalUnlock(lpData->hData);
1547 if (aTarget == x11drv_atom(COMPOUND_TEXT))
1548 style = XCompoundTextStyle;
1549 else
1550 style = XStdICCTextStyle;
1552 /* Update the X property */
1553 wine_tsx11_lock();
1554 if (XmbTextListToTextProperty(display, &lpstr, 1, style, &prop) == Success)
1556 XSetTextProperty(display, requestor, &prop, rprop);
1557 XFree(prop.value);
1559 wine_tsx11_unlock();
1561 HeapFree(GetProcessHeap(), 0, lpstr);
1563 return 0;
1566 /**************************************************************************
1567 * X11DRV_CLIPBOARD_ExportString
1569 * Export string
1571 static HANDLE X11DRV_CLIPBOARD_ExportString(Display *display, Window requestor, Atom aTarget, Atom rprop,
1572 LPWINE_CLIPDATA lpData, LPDWORD lpBytes)
1574 if (X11DRV_CLIPBOARD_RenderFormat(display, lpData))
1576 if (aTarget == XA_STRING)
1577 return X11DRV_CLIPBOARD_ExportXAString(lpData, lpBytes);
1578 else if (aTarget == x11drv_atom(COMPOUND_TEXT) || aTarget == x11drv_atom(TEXT))
1579 return X11DRV_CLIPBOARD_ExportCompoundText(display, requestor, aTarget,
1580 rprop, lpData, lpBytes);
1581 else
1583 TRACE("Exporting target %ld to default UTF8_STRING\n", aTarget);
1584 return X11DRV_CLIPBOARD_ExportUTF8String(lpData, lpBytes);
1587 else
1588 ERR("Failed to render %04x format\n", lpData->wFormatID);
1590 return 0;
1594 /**************************************************************************
1595 * X11DRV_CLIPBOARD_ExportXAPIXMAP
1597 * Export CF_DIB to XA_PIXMAP.
1599 static HANDLE X11DRV_CLIPBOARD_ExportXAPIXMAP(Display *display, Window requestor, Atom aTarget, Atom rprop,
1600 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1602 HDC hdc;
1603 HANDLE hData;
1604 unsigned char* lpData;
1606 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1608 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1609 return 0;
1612 if (!lpdata->drvData) /* If not already rendered */
1614 /* For convert from packed DIB to Pixmap */
1615 hdc = GetDC(0);
1616 lpdata->drvData = (UINT) X11DRV_DIB_CreatePixmapFromDIB(lpdata->hData, hdc);
1617 ReleaseDC(0, hdc);
1620 *lpBytes = sizeof(Pixmap); /* pixmap is a 32bit value */
1622 /* Wrap pixmap so we can return a handle */
1623 hData = GlobalAlloc(0, *lpBytes);
1624 lpData = GlobalLock(hData);
1625 memcpy(lpData, &lpdata->drvData, *lpBytes);
1626 GlobalUnlock(hData);
1628 return hData;
1632 /**************************************************************************
1633 * X11DRV_CLIPBOARD_ExportImageBmp
1635 * Export CF_DIB to image/bmp.
1637 static HANDLE X11DRV_CLIPBOARD_ExportImageBmp(Display *display, Window requestor, Atom aTarget, Atom rprop,
1638 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1640 HANDLE hpackeddib;
1641 LPBYTE dibdata;
1642 UINT bmpsize;
1643 HANDLE hbmpdata;
1644 LPBYTE bmpdata;
1645 BITMAPFILEHEADER *bfh;
1647 *lpBytes = 0;
1649 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1651 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1652 return 0;
1655 hpackeddib = lpdata->hData;
1657 dibdata = GlobalLock(hpackeddib);
1658 if (!dibdata)
1660 ERR("Failed to lock packed DIB\n");
1661 return 0;
1664 bmpsize = sizeof(BITMAPFILEHEADER) + GlobalSize(hpackeddib);
1666 hbmpdata = GlobalAlloc(0, bmpsize);
1668 if (hbmpdata)
1670 bmpdata = GlobalLock(hbmpdata);
1672 if (!bmpdata)
1674 GlobalFree(hbmpdata);
1675 GlobalUnlock(hpackeddib);
1676 return 0;
1679 /* bitmap file header */
1680 bfh = (BITMAPFILEHEADER*)bmpdata;
1681 bfh->bfType = 0x4d42; /* "BM" */
1682 bfh->bfSize = bmpsize;
1683 bfh->bfReserved1 = 0;
1684 bfh->bfReserved2 = 0;
1685 bfh->bfOffBits = sizeof(BITMAPFILEHEADER) + bitmap_info_size((BITMAPINFO*)dibdata, DIB_RGB_COLORS);
1687 /* rest of bitmap is the same as the packed dib */
1688 memcpy(bfh+1, dibdata, bmpsize-sizeof(BITMAPFILEHEADER));
1690 *lpBytes = bmpsize;
1692 GlobalUnlock(hbmpdata);
1695 GlobalUnlock(hpackeddib);
1697 return hbmpdata;
1701 /**************************************************************************
1702 * X11DRV_CLIPBOARD_ExportMetaFilePict
1704 * Export MetaFilePict.
1706 static HANDLE X11DRV_CLIPBOARD_ExportMetaFilePict(Display *display, Window requestor, Atom aTarget, Atom rprop,
1707 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1709 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1711 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1712 return 0;
1715 return X11DRV_CLIPBOARD_SerializeMetafile(CF_METAFILEPICT, lpdata->hData, lpBytes, TRUE);
1719 /**************************************************************************
1720 * X11DRV_CLIPBOARD_ExportEnhMetaFile
1722 * Export EnhMetaFile.
1724 static HANDLE X11DRV_CLIPBOARD_ExportEnhMetaFile(Display *display, Window requestor, Atom aTarget, Atom rprop,
1725 LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1727 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1729 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1730 return 0;
1733 return X11DRV_CLIPBOARD_SerializeMetafile(CF_ENHMETAFILE, lpdata->hData, lpBytes, TRUE);
1737 /**************************************************************************
1738 * get_html_description_field
1740 * Find the value of a field in an HTML Format description.
1742 static LPCSTR get_html_description_field(LPCSTR data, LPCSTR keyword)
1744 LPCSTR pos=data;
1746 while (pos && *pos && *pos != '<')
1748 if (memcmp(pos, keyword, strlen(keyword)) == 0)
1749 return pos+strlen(keyword);
1751 pos = strchr(pos, '\n');
1752 if (pos) pos++;
1755 return NULL;
1759 /**************************************************************************
1760 * X11DRV_CLIPBOARD_ExportTextHtml
1762 * Export HTML Format to text/html.
1764 * FIXME: We should attempt to add an <a base> tag and convert windows paths.
1766 static HANDLE X11DRV_CLIPBOARD_ExportTextHtml(Display *display, Window requestor, Atom aTarget,
1767 Atom rprop, LPWINE_CLIPDATA lpdata, LPDWORD lpBytes)
1769 HANDLE hdata;
1770 LPCSTR data, field_value;
1771 UINT fragmentstart, fragmentend, htmlsize;
1772 HANDLE hhtmldata=NULL;
1773 LPSTR htmldata;
1775 *lpBytes = 0;
1777 if (!X11DRV_CLIPBOARD_RenderFormat(display, lpdata))
1779 ERR("Failed to export %04x format\n", lpdata->wFormatID);
1780 return 0;
1783 hdata = lpdata->hData;
1785 data = GlobalLock(hdata);
1786 if (!data)
1788 ERR("Failed to lock HTML Format data\n");
1789 return 0;
1792 /* read the important fields */
1793 field_value = get_html_description_field(data, "StartFragment:");
1794 if (!field_value)
1796 ERR("Couldn't find StartFragment value\n");
1797 goto end;
1799 fragmentstart = atoi(field_value);
1801 field_value = get_html_description_field(data, "EndFragment:");
1802 if (!field_value)
1804 ERR("Couldn't find EndFragment value\n");
1805 goto end;
1807 fragmentend = atoi(field_value);
1809 /* export only the fragment */
1810 htmlsize = fragmentend - fragmentstart + 1;
1812 hhtmldata = GlobalAlloc(0, htmlsize);
1814 if (hhtmldata)
1816 htmldata = GlobalLock(hhtmldata);
1818 if (!htmldata)
1820 GlobalFree(hhtmldata);
1821 htmldata = NULL;
1822 goto end;
1825 memcpy(htmldata, &data[fragmentstart], fragmentend-fragmentstart);
1826 htmldata[htmlsize-1] = '\0';
1828 *lpBytes = htmlsize;
1830 GlobalUnlock(htmldata);
1833 end:
1835 GlobalUnlock(hdata);
1837 return hhtmldata;
1841 /**************************************************************************
1842 * X11DRV_CLIPBOARD_QueryTargets
1844 static BOOL X11DRV_CLIPBOARD_QueryTargets(Display *display, Window w, Atom selection,
1845 Atom target, XEvent *xe)
1847 INT i;
1848 Bool res;
1850 wine_tsx11_lock();
1851 XConvertSelection(display, selection, target,
1852 x11drv_atom(SELECTION_DATA), w, CurrentTime);
1853 wine_tsx11_unlock();
1856 * Wait until SelectionNotify is received
1858 for (i = 0; i < SELECTION_RETRIES; i++)
1860 wine_tsx11_lock();
1861 res = XCheckTypedWindowEvent(display, w, SelectionNotify, xe);
1862 wine_tsx11_unlock();
1863 if (res && xe->xselection.selection == selection) break;
1865 usleep(SELECTION_WAIT);
1868 if (i == SELECTION_RETRIES)
1870 ERR("Timed out waiting for SelectionNotify event\n");
1871 return FALSE;
1873 /* Verify that the selection returned a valid TARGETS property */
1874 if ((xe->xselection.target != target) || (xe->xselection.property == None))
1876 /* Selection owner failed to respond or we missed the SelectionNotify */
1877 WARN("Failed to retrieve TARGETS for selection %ld.\n", selection);
1878 return FALSE;
1881 return TRUE;
1885 static int is_atom_error( Display *display, XErrorEvent *event, void *arg )
1887 return (event->error_code == BadAtom);
1890 /**************************************************************************
1891 * X11DRV_CLIPBOARD_InsertSelectionProperties
1893 * Mark properties available for future retrieval.
1895 static VOID X11DRV_CLIPBOARD_InsertSelectionProperties(Display *display, Atom* properties, UINT count)
1897 UINT i, nb_atoms = 0;
1898 Atom *atoms = NULL;
1900 /* Cache these formats in the clipboard cache */
1901 for (i = 0; i < count; i++)
1903 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, properties[i]);
1905 if (lpFormat)
1907 /* We found at least one Window's format that mapps to the property.
1908 * Continue looking for more.
1910 * If more than one property map to a Window's format then we use the first
1911 * one and ignore the rest.
1913 while (lpFormat)
1915 TRACE("Atom#%d Property(%d): --> Format %s\n",
1916 i, lpFormat->drvData, debugstr_format(lpFormat->wFormatID));
1917 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, lpFormat, FALSE);
1918 lpFormat = X11DRV_CLIPBOARD_LookupProperty(lpFormat, properties[i]);
1921 else if (properties[i])
1923 /* add it to the list of atoms that we don't know about yet */
1924 if (!atoms) atoms = HeapAlloc( GetProcessHeap(), 0,
1925 (count - i) * sizeof(*atoms) );
1926 if (atoms) atoms[nb_atoms++] = properties[i];
1930 /* query all unknown atoms in one go */
1931 if (atoms)
1933 char **names = HeapAlloc( GetProcessHeap(), 0, nb_atoms * sizeof(*names) );
1934 if (names)
1936 X11DRV_expect_error( display, is_atom_error, NULL );
1937 if (!XGetAtomNames( display, atoms, nb_atoms, names )) nb_atoms = 0;
1938 if (X11DRV_check_error())
1940 WARN( "got some bad atoms, ignoring\n" );
1941 nb_atoms = 0;
1943 for (i = 0; i < nb_atoms; i++)
1945 WINE_CLIPFORMAT *lpFormat;
1946 LPWSTR wname;
1947 int len = MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, NULL, 0);
1948 wname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR));
1949 MultiByteToWideChar(CP_UNIXCP, 0, names[i], -1, wname, len);
1951 lpFormat = register_format( RegisterClipboardFormatW(wname), atoms[i] );
1952 HeapFree(GetProcessHeap(), 0, wname);
1953 if (!lpFormat)
1955 ERR("Failed to register %s property. Type will not be cached.\n", names[i]);
1956 continue;
1958 TRACE("Atom#%d Property(%d): --> Format %s\n",
1959 i, lpFormat->drvData, debugstr_format(lpFormat->wFormatID));
1960 X11DRV_CLIPBOARD_InsertClipboardData(lpFormat->wFormatID, 0, 0, lpFormat, FALSE);
1962 wine_tsx11_lock();
1963 for (i = 0; i < nb_atoms; i++) XFree( names[i] );
1964 wine_tsx11_unlock();
1965 HeapFree( GetProcessHeap(), 0, names );
1967 HeapFree( GetProcessHeap(), 0, atoms );
1972 /**************************************************************************
1973 * X11DRV_CLIPBOARD_QueryAvailableData
1975 * Caches the list of data formats available from the current selection.
1976 * This queries the selection owner for the TARGETS property and saves all
1977 * reported property types.
1979 static int X11DRV_CLIPBOARD_QueryAvailableData(Display *display, LPCLIPBOARDINFO lpcbinfo)
1981 XEvent xe;
1982 Atom atype=AnyPropertyType;
1983 int aformat;
1984 unsigned long remain;
1985 Atom* targetList=NULL;
1986 Window w;
1987 unsigned long cSelectionTargets = 0;
1989 if (selectionAcquired & (S_PRIMARY | S_CLIPBOARD))
1991 ERR("Received request to cache selection but process is owner=(%08x)\n",
1992 (unsigned) selectionWindow);
1993 return -1; /* Prevent self request */
1996 w = thread_selection_wnd();
1997 if (!w)
1999 ERR("No window available to retrieve selection!\n");
2000 return -1;
2004 * Query the selection owner for the TARGETS property
2006 wine_tsx11_lock();
2007 if ((use_primary_selection && XGetSelectionOwner(display,XA_PRIMARY)) ||
2008 XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2010 wine_tsx11_unlock();
2011 if (use_primary_selection && (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, x11drv_atom(TARGETS), &xe)))
2012 selectionCacheSrc = XA_PRIMARY;
2013 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), x11drv_atom(TARGETS), &xe))
2014 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2015 else
2017 Atom xstr = XA_STRING;
2019 /* Selection Owner doesn't understand TARGETS, try retrieving XA_STRING */
2020 if (X11DRV_CLIPBOARD_QueryTargets(display, w, XA_PRIMARY, XA_STRING, &xe))
2022 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2023 selectionCacheSrc = XA_PRIMARY;
2024 return 1;
2026 else if (X11DRV_CLIPBOARD_QueryTargets(display, w, x11drv_atom(CLIPBOARD), XA_STRING, &xe))
2028 X11DRV_CLIPBOARD_InsertSelectionProperties(display, &xstr, 1);
2029 selectionCacheSrc = x11drv_atom(CLIPBOARD);
2030 return 1;
2032 else
2034 WARN("Failed to query selection owner for available data.\n");
2035 return -1;
2039 else /* No selection owner so report 0 targets available */
2041 wine_tsx11_unlock();
2042 return 0;
2045 /* Read the TARGETS property contents */
2046 wine_tsx11_lock();
2047 if(XGetWindowProperty(display, xe.xselection.requestor, xe.xselection.property,
2048 0, 0x3FFF, True, AnyPropertyType/*XA_ATOM*/, &atype, &aformat, &cSelectionTargets,
2049 &remain, (unsigned char**)&targetList) != Success)
2051 wine_tsx11_unlock();
2052 WARN("Failed to read TARGETS property\n");
2054 else
2056 wine_tsx11_unlock();
2057 TRACE("Type %lx,Format %d,nItems %ld, Remain %ld\n",
2058 atype, aformat, cSelectionTargets, remain);
2060 * The TARGETS property should have returned us a list of atoms
2061 * corresponding to each selection target format supported.
2063 if (atype == XA_ATOM || atype == x11drv_atom(TARGETS))
2065 if (aformat == 32)
2067 X11DRV_CLIPBOARD_InsertSelectionProperties(display, targetList, cSelectionTargets);
2069 else if (aformat == 8) /* work around quartz-wm brain damage */
2071 unsigned long i, count = cSelectionTargets / sizeof(CARD32);
2072 Atom *atoms = HeapAlloc( GetProcessHeap(), 0, count * sizeof(Atom) );
2073 for (i = 0; i < count; i++)
2074 atoms[i] = ((CARD32 *)targetList)[i]; /* FIXME: byte swapping */
2075 X11DRV_CLIPBOARD_InsertSelectionProperties( display, atoms, count );
2076 HeapFree( GetProcessHeap(), 0, atoms );
2080 /* Free the list of targets */
2081 wine_tsx11_lock();
2082 XFree(targetList);
2083 wine_tsx11_unlock();
2086 return cSelectionTargets;
2090 /**************************************************************************
2091 * X11DRV_CLIPBOARD_ReadSelectionData
2093 * This method is invoked only when we DO NOT own the X selection
2095 * We always get the data from the selection client each time,
2096 * since we have no way of determining if the data in our cache is stale.
2098 static BOOL X11DRV_CLIPBOARD_ReadSelectionData(Display *display, LPWINE_CLIPDATA lpData)
2100 Bool res;
2101 DWORD i;
2102 XEvent xe;
2103 BOOL bRet = FALSE;
2105 TRACE("%04x\n", lpData->wFormatID);
2107 if (!lpData->lpFormat)
2109 ERR("Requesting format %04x but no source format linked to data.\n",
2110 lpData->wFormatID);
2111 return FALSE;
2114 if (!selectionAcquired)
2116 Window w = thread_selection_wnd();
2117 if(!w)
2119 ERR("No window available to read selection data!\n");
2120 return FALSE;
2123 TRACE("Requesting conversion of %s property (%d) from selection type %08x\n",
2124 debugstr_format(lpData->lpFormat->wFormatID), lpData->lpFormat->drvData,
2125 (UINT)selectionCacheSrc);
2127 wine_tsx11_lock();
2128 XConvertSelection(display, selectionCacheSrc, lpData->lpFormat->drvData,
2129 x11drv_atom(SELECTION_DATA), w, CurrentTime);
2130 wine_tsx11_unlock();
2132 /* wait until SelectionNotify is received */
2133 for (i = 0; i < SELECTION_RETRIES; i++)
2135 wine_tsx11_lock();
2136 res = XCheckTypedWindowEvent(display, w, SelectionNotify, &xe);
2137 wine_tsx11_unlock();
2138 if (res && xe.xselection.selection == selectionCacheSrc) break;
2140 usleep(SELECTION_WAIT);
2143 if (i == SELECTION_RETRIES)
2145 ERR("Timed out waiting for SelectionNotify event\n");
2147 /* Verify that the selection returned a valid TARGETS property */
2148 else if (xe.xselection.property != None)
2151 * Read the contents of the X selection property
2152 * into WINE's clipboard cache and converting the
2153 * data format if necessary.
2155 HANDLE hData = lpData->lpFormat->lpDrvImportFunc(display, xe.xselection.requestor,
2156 xe.xselection.property);
2158 if (hData)
2159 bRet = X11DRV_CLIPBOARD_InsertClipboardData(lpData->wFormatID, hData, 0, lpData->lpFormat, TRUE);
2160 else
2161 TRACE("Import function failed\n");
2163 else
2165 TRACE("Failed to convert selection\n");
2168 else
2170 ERR("Received request to cache selection data but process is owner\n");
2173 TRACE("Returning %d\n", bRet);
2175 return bRet;
2179 /**************************************************************************
2180 * X11DRV_CLIPBOARD_GetProperty
2181 * Gets type, data and size.
2183 static BOOL X11DRV_CLIPBOARD_GetProperty(Display *display, Window w, Atom prop,
2184 Atom *atype, unsigned char** data, unsigned long* datasize)
2186 int aformat;
2187 unsigned long pos = 0, nitems, remain, count;
2188 unsigned char *val = NULL, *buffer;
2190 TRACE("Reading property %lu from X window %lx\n", prop, w);
2192 for (;;)
2194 wine_tsx11_lock();
2195 if (XGetWindowProperty(display, w, prop, pos, INT_MAX / 4, False,
2196 AnyPropertyType, atype, &aformat, &nitems, &remain, &buffer) != Success)
2198 wine_tsx11_unlock();
2199 WARN("Failed to read property\n");
2200 HeapFree( GetProcessHeap(), 0, val );
2201 return FALSE;
2204 count = get_property_size( aformat, nitems );
2205 if (!val) *data = HeapAlloc( GetProcessHeap(), 0, pos * sizeof(int) + count + 1 );
2206 else *data = HeapReAlloc( GetProcessHeap(), 0, val, pos * sizeof(int) + count + 1 );
2208 if (!*data)
2210 XFree( buffer );
2211 wine_tsx11_unlock();
2212 HeapFree( GetProcessHeap(), 0, val );
2213 return FALSE;
2215 val = *data;
2216 memcpy( (int *)val + pos, buffer, count );
2217 XFree( buffer );
2218 wine_tsx11_unlock();
2219 if (!remain)
2221 *datasize = pos * sizeof(int) + count;
2222 val[*datasize] = 0;
2223 break;
2225 pos += count / sizeof(int);
2228 /* Delete the property on the window now that we are done
2229 * This will send a PropertyNotify event to the selection owner. */
2230 wine_tsx11_lock();
2231 XDeleteProperty(display, w, prop);
2232 wine_tsx11_unlock();
2233 return TRUE;
2237 /**************************************************************************
2238 * X11DRV_CLIPBOARD_ReadProperty
2239 * Reads the contents of the X selection property.
2241 static BOOL X11DRV_CLIPBOARD_ReadProperty(Display *display, Window w, Atom prop,
2242 unsigned char** data, unsigned long* datasize)
2244 Atom atype;
2245 XEvent xe;
2247 if (prop == None)
2248 return FALSE;
2250 if (!X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, data, datasize))
2251 return FALSE;
2253 wine_tsx11_lock();
2254 while (XCheckTypedWindowEvent(display, w, PropertyNotify, &xe))
2256 wine_tsx11_unlock();
2258 if (atype == x11drv_atom(INCR))
2260 unsigned char *buf = *data;
2261 unsigned long bufsize = 0;
2263 for (;;)
2265 int i;
2266 unsigned char *prop_data, *tmp;
2267 unsigned long prop_size;
2269 /* Wait until PropertyNotify is received */
2270 for (i = 0; i < SELECTION_RETRIES; i++)
2272 Bool res;
2274 wine_tsx11_lock();
2275 res = XCheckTypedWindowEvent(display, w, PropertyNotify, &xe);
2276 wine_tsx11_unlock();
2277 if (res && xe.xproperty.atom == prop &&
2278 xe.xproperty.state == PropertyNewValue)
2279 break;
2280 usleep(SELECTION_WAIT);
2283 if (i >= SELECTION_RETRIES ||
2284 !X11DRV_CLIPBOARD_GetProperty(display, w, prop, &atype, &prop_data, &prop_size))
2286 HeapFree(GetProcessHeap(), 0, buf);
2287 return FALSE;
2290 /* Retrieved entire data. */
2291 if (prop_size == 0)
2293 HeapFree(GetProcessHeap(), 0, prop_data);
2294 *data = buf;
2295 *datasize = bufsize;
2296 return TRUE;
2299 tmp = HeapReAlloc(GetProcessHeap(), 0, buf, bufsize + prop_size + 1);
2300 if (!tmp)
2302 HeapFree(GetProcessHeap(), 0, buf);
2303 return FALSE;
2306 buf = tmp;
2307 memcpy(buf + bufsize, prop_data, prop_size + 1);
2308 bufsize += prop_size;
2309 HeapFree(GetProcessHeap(), 0, prop_data);
2313 return TRUE;
2317 /**************************************************************************
2318 * CLIPBOARD_SerializeMetafile
2320 static HANDLE X11DRV_CLIPBOARD_SerializeMetafile(INT wformat, HANDLE hdata, LPDWORD lpcbytes, BOOL out)
2322 HANDLE h = 0;
2324 TRACE(" wFormat=%d hdata=%p out=%d\n", wformat, hdata, out);
2326 if (out) /* Serialize out, caller should free memory */
2328 *lpcbytes = 0; /* Assume failure */
2330 if (wformat == CF_METAFILEPICT)
2332 LPMETAFILEPICT lpmfp = GlobalLock(hdata);
2333 unsigned int size = GetMetaFileBitsEx(lpmfp->hMF, 0, NULL);
2335 h = GlobalAlloc(0, size + sizeof(METAFILEPICT));
2336 if (h)
2338 char *pdata = GlobalLock(h);
2340 memcpy(pdata, lpmfp, sizeof(METAFILEPICT));
2341 GetMetaFileBitsEx(lpmfp->hMF, size, pdata + sizeof(METAFILEPICT));
2343 *lpcbytes = size + sizeof(METAFILEPICT);
2345 GlobalUnlock(h);
2348 GlobalUnlock(hdata);
2350 else if (wformat == CF_ENHMETAFILE)
2352 int size = GetEnhMetaFileBits(hdata, 0, NULL);
2354 h = GlobalAlloc(0, size);
2355 if (h)
2357 LPVOID pdata = GlobalLock(h);
2359 GetEnhMetaFileBits(hdata, size, pdata);
2360 *lpcbytes = size;
2362 GlobalUnlock(h);
2366 else
2368 if (wformat == CF_METAFILEPICT)
2370 h = GlobalAlloc(0, sizeof(METAFILEPICT));
2371 if (h)
2373 unsigned int wiresize;
2374 LPMETAFILEPICT lpmfp = GlobalLock(h);
2376 memcpy(lpmfp, hdata, sizeof(METAFILEPICT));
2377 wiresize = *lpcbytes - sizeof(METAFILEPICT);
2378 lpmfp->hMF = SetMetaFileBitsEx(wiresize,
2379 ((const BYTE *)hdata) + sizeof(METAFILEPICT));
2380 GlobalUnlock(h);
2383 else if (wformat == CF_ENHMETAFILE)
2385 h = SetEnhMetaFileBits(*lpcbytes, hdata);
2389 return h;
2393 /**************************************************************************
2394 * X11DRV_CLIPBOARD_ReleaseSelection
2396 * Release XA_CLIPBOARD and XA_PRIMARY in response to a SelectionClear event.
2398 static void X11DRV_CLIPBOARD_ReleaseSelection(Display *display, Atom selType, Window w, HWND hwnd, Time time)
2400 /* w is the window that lost the selection
2402 TRACE("event->window = %08x (selectionWindow = %08x) selectionAcquired=0x%08x\n",
2403 (unsigned)w, (unsigned)selectionWindow, (unsigned)selectionAcquired);
2405 if (selectionAcquired && (w == selectionWindow))
2407 CLIPBOARDINFO cbinfo;
2409 /* completely give up the selection */
2410 TRACE("Lost CLIPBOARD (+PRIMARY) selection\n");
2412 X11DRV_CLIPBOARD_GetClipboardInfo(&cbinfo);
2414 if (cbinfo.flags & CB_PROCESS)
2416 /* Since we're still the owner, this wasn't initiated by
2417 another Wine process */
2418 if (OpenClipboard(hwnd))
2420 /* Destroy private objects */
2421 SendMessageW(cbinfo.hWndOwner, WM_DESTROYCLIPBOARD, 0, 0);
2423 /* Give up ownership of the windows clipboard */
2424 X11DRV_CLIPBOARD_ReleaseOwnership();
2425 CloseClipboard();
2429 if ((selType == x11drv_atom(CLIPBOARD)) && (selectionAcquired & S_PRIMARY))
2431 TRACE("Lost clipboard. Check if we need to release PRIMARY\n");
2433 wine_tsx11_lock();
2434 if (selectionWindow == XGetSelectionOwner(display, XA_PRIMARY))
2436 TRACE("We still own PRIMARY. Releasing PRIMARY.\n");
2437 XSetSelectionOwner(display, XA_PRIMARY, None, time);
2439 else
2440 TRACE("We no longer own PRIMARY\n");
2441 wine_tsx11_unlock();
2443 else if ((selType == XA_PRIMARY) && (selectionAcquired & S_CLIPBOARD))
2445 TRACE("Lost PRIMARY. Check if we need to release CLIPBOARD\n");
2447 wine_tsx11_lock();
2448 if (selectionWindow == XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)))
2450 TRACE("We still own CLIPBOARD. Releasing CLIPBOARD.\n");
2451 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), None, time);
2453 else
2454 TRACE("We no longer own CLIPBOARD\n");
2455 wine_tsx11_unlock();
2458 selectionWindow = None;
2460 X11DRV_EmptyClipboard(FALSE);
2462 /* Reset the selection flags now that we are done */
2463 selectionAcquired = S_NOSELECTION;
2468 /**************************************************************************
2469 * IsSelectionOwner (X11DRV.@)
2471 * Returns: TRUE if the selection is owned by this process, FALSE otherwise
2473 static BOOL X11DRV_CLIPBOARD_IsSelectionOwner(void)
2475 return selectionAcquired;
2479 /**************************************************************************
2480 * X11DRV Clipboard Exports
2481 **************************************************************************/
2484 static void selection_acquire(void)
2486 Window owner;
2487 Display *display;
2489 owner = thread_selection_wnd();
2490 display = thread_display();
2492 wine_tsx11_lock();
2494 selectionAcquired = 0;
2495 selectionWindow = 0;
2497 /* Grab PRIMARY selection if not owned */
2498 if (use_primary_selection)
2499 XSetSelectionOwner(display, XA_PRIMARY, owner, CurrentTime);
2501 /* Grab CLIPBOARD selection if not owned */
2502 XSetSelectionOwner(display, x11drv_atom(CLIPBOARD), owner, CurrentTime);
2504 if (use_primary_selection && XGetSelectionOwner(display, XA_PRIMARY) == owner)
2505 selectionAcquired |= S_PRIMARY;
2507 if (XGetSelectionOwner(display,x11drv_atom(CLIPBOARD)) == owner)
2508 selectionAcquired |= S_CLIPBOARD;
2510 wine_tsx11_unlock();
2512 if (selectionAcquired)
2514 selectionWindow = owner;
2515 TRACE("Grabbed X selection, owner=(%08x)\n", (unsigned) owner);
2519 static DWORD WINAPI selection_thread_proc(LPVOID p)
2521 HANDLE event = p;
2523 TRACE("\n");
2525 selection_acquire();
2526 SetEvent(event);
2528 while (selectionAcquired)
2530 MsgWaitForMultipleObjectsEx(0, NULL, INFINITE, QS_SENDMESSAGE, 0);
2533 return 0;
2536 /**************************************************************************
2537 * AcquireClipboard (X11DRV.@)
2539 int CDECL X11DRV_AcquireClipboard(HWND hWndClipWindow)
2541 DWORD procid;
2542 HANDLE selectionThread;
2544 TRACE(" %p\n", hWndClipWindow);
2547 * It's important that the selection get acquired from the thread
2548 * that owns the clipboard window. The primary reason is that we know
2549 * it is running a message loop and therefore can process the
2550 * X selection events.
2552 if (hWndClipWindow &&
2553 GetCurrentThreadId() != GetWindowThreadProcessId(hWndClipWindow, &procid))
2555 if (procid != GetCurrentProcessId())
2557 WARN("Setting clipboard owner to other process is not supported\n");
2558 hWndClipWindow = NULL;
2560 else
2562 TRACE("Thread %x is acquiring selection with thread %x's window %p\n",
2563 GetCurrentThreadId(),
2564 GetWindowThreadProcessId(hWndClipWindow, NULL), hWndClipWindow);
2566 return SendMessageW(hWndClipWindow, WM_X11DRV_ACQUIRE_SELECTION, 0, 0);
2570 if (hWndClipWindow)
2572 selection_acquire();
2574 else
2576 HANDLE event = CreateEventW(NULL, FALSE, FALSE, NULL);
2577 selectionThread = CreateThread(NULL, 0, selection_thread_proc, event, 0, NULL);
2579 if (!selectionThread)
2581 WARN("Could not start clipboard thread\n");
2582 return 0;
2585 WaitForSingleObject(event, INFINITE);
2586 CloseHandle(event);
2587 CloseHandle(selectionThread);
2590 return 1;
2594 /**************************************************************************
2595 * X11DRV_EmptyClipboard
2597 * Empty cached clipboard data.
2599 void CDECL X11DRV_EmptyClipboard(BOOL keepunowned)
2601 WINE_CLIPDATA *data, *next;
2603 LIST_FOR_EACH_ENTRY_SAFE( data, next, &data_list, WINE_CLIPDATA, entry )
2605 if (keepunowned && (data->wFlags & CF_FLAG_UNOWNED)) continue;
2606 list_remove( &data->entry );
2607 X11DRV_CLIPBOARD_FreeData( data );
2608 HeapFree( GetProcessHeap(), 0, data );
2609 ClipDataCount--;
2612 TRACE(" %d entries remaining in cache.\n", ClipDataCount);
2617 /**************************************************************************
2618 * X11DRV_SetClipboardData
2620 BOOL CDECL X11DRV_SetClipboardData(UINT wFormat, HANDLE hData, BOOL owner)
2622 DWORD flags = 0;
2623 BOOL bResult = TRUE;
2625 /* If it's not owned, data can only be set if the format data is not already owned
2626 and its rendering is not delayed */
2627 if (!owner)
2629 CLIPBOARDINFO cbinfo;
2630 LPWINE_CLIPDATA lpRender;
2632 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2634 if (!hData ||
2635 ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)) &&
2636 !(lpRender->wFlags & CF_FLAG_UNOWNED)))
2637 bResult = FALSE;
2638 else
2639 flags = CF_FLAG_UNOWNED;
2642 bResult &= X11DRV_CLIPBOARD_InsertClipboardData(wFormat, hData, flags, NULL, TRUE);
2644 return bResult;
2648 /**************************************************************************
2649 * CountClipboardFormats
2651 INT CDECL X11DRV_CountClipboardFormats(void)
2653 CLIPBOARDINFO cbinfo;
2655 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2657 TRACE(" count=%d\n", ClipDataCount);
2659 return ClipDataCount;
2663 /**************************************************************************
2664 * X11DRV_EnumClipboardFormats
2666 UINT CDECL X11DRV_EnumClipboardFormats(UINT wFormat)
2668 CLIPBOARDINFO cbinfo;
2669 struct list *ptr = NULL;
2671 TRACE("(%04X)\n", wFormat);
2673 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2675 if (!wFormat)
2677 ptr = list_head( &data_list );
2679 else
2681 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(wFormat);
2682 if (lpData) ptr = list_next( &data_list, &lpData->entry );
2685 if (!ptr) return 0;
2686 return LIST_ENTRY( ptr, WINE_CLIPDATA, entry )->wFormatID;
2690 /**************************************************************************
2691 * X11DRV_IsClipboardFormatAvailable
2693 BOOL CDECL X11DRV_IsClipboardFormatAvailable(UINT wFormat)
2695 BOOL bRet = FALSE;
2696 CLIPBOARDINFO cbinfo;
2698 TRACE("(%04X)\n", wFormat);
2700 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2702 if (wFormat != 0 && X11DRV_CLIPBOARD_LookupData(wFormat))
2703 bRet = TRUE;
2705 TRACE("(%04X)- ret(%d)\n", wFormat, bRet);
2707 return bRet;
2711 /**************************************************************************
2712 * GetClipboardData (USER.142)
2714 HANDLE CDECL X11DRV_GetClipboardData(UINT wFormat)
2716 CLIPBOARDINFO cbinfo;
2717 LPWINE_CLIPDATA lpRender;
2719 TRACE("(%04X)\n", wFormat);
2721 X11DRV_CLIPBOARD_UpdateCache(&cbinfo);
2723 if ((lpRender = X11DRV_CLIPBOARD_LookupData(wFormat)))
2725 if ( !lpRender->hData )
2726 X11DRV_CLIPBOARD_RenderFormat(thread_init_display(), lpRender);
2728 TRACE(" returning %p (type %04x)\n", lpRender->hData, lpRender->wFormatID);
2729 return lpRender->hData;
2732 return 0;
2736 /**************************************************************************
2737 * ResetSelectionOwner
2739 * Called when the thread owning the selection is destroyed and we need to
2740 * preserve the selection ownership. We look for another top level window
2741 * in this process and send it a message to acquire the selection.
2743 void X11DRV_ResetSelectionOwner(void)
2745 HWND hwnd;
2746 DWORD procid;
2748 TRACE("\n");
2750 if (!selectionAcquired || thread_selection_wnd() != selectionWindow)
2751 return;
2753 selectionAcquired = S_NOSELECTION;
2754 selectionWindow = 0;
2756 hwnd = GetWindow(GetDesktopWindow(), GW_CHILD);
2759 if (GetCurrentThreadId() != GetWindowThreadProcessId(hwnd, &procid))
2761 if (GetCurrentProcessId() == procid)
2763 if (SendMessageW(hwnd, WM_X11DRV_ACQUIRE_SELECTION, 0, 0))
2764 return;
2767 } while ((hwnd = GetWindow(hwnd, GW_HWNDNEXT)) != NULL);
2769 WARN("Failed to find another thread to take selection ownership. Clipboard data will be lost.\n");
2771 X11DRV_CLIPBOARD_ReleaseOwnership();
2772 X11DRV_EmptyClipboard(FALSE);
2776 /**************************************************************************
2777 * X11DRV_CLIPBOARD_SynthesizeData
2779 static BOOL X11DRV_CLIPBOARD_SynthesizeData(UINT wFormatID)
2781 BOOL bsyn = TRUE;
2782 LPWINE_CLIPDATA lpSource = NULL;
2784 TRACE(" %04x\n", wFormatID);
2786 /* Don't need to synthesize if it already exists */
2787 if (X11DRV_CLIPBOARD_LookupData(wFormatID))
2788 return TRUE;
2790 if (wFormatID == CF_UNICODETEXT || wFormatID == CF_TEXT || wFormatID == CF_OEMTEXT)
2792 bsyn = ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_UNICODETEXT)) &&
2793 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2794 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_TEXT)) &&
2795 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED) ||
2796 ((lpSource = X11DRV_CLIPBOARD_LookupData(CF_OEMTEXT)) &&
2797 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED);
2799 else if (wFormatID == CF_ENHMETAFILE)
2801 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_METAFILEPICT)) &&
2802 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2804 else if (wFormatID == CF_METAFILEPICT)
2806 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_ENHMETAFILE)) &&
2807 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2809 else if (wFormatID == CF_DIB)
2811 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_BITMAP)) &&
2812 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2814 else if (wFormatID == CF_BITMAP)
2816 bsyn = (lpSource = X11DRV_CLIPBOARD_LookupData(CF_DIB)) &&
2817 ~lpSource->wFlags & CF_FLAG_SYNTHESIZED;
2820 if (bsyn)
2821 X11DRV_CLIPBOARD_InsertClipboardData(wFormatID, 0, CF_FLAG_SYNTHESIZED, NULL, TRUE);
2823 return bsyn;
2828 /**************************************************************************
2829 * X11DRV_EndClipboardUpdate
2830 * TODO:
2831 * Add locale if it hasn't already been added
2833 void CDECL X11DRV_EndClipboardUpdate(void)
2835 INT count = ClipDataCount;
2837 /* Do Unicode <-> Text <-> OEM mapping */
2838 X11DRV_CLIPBOARD_SynthesizeData(CF_TEXT);
2839 X11DRV_CLIPBOARD_SynthesizeData(CF_OEMTEXT);
2840 X11DRV_CLIPBOARD_SynthesizeData(CF_UNICODETEXT);
2842 /* Enhmetafile <-> MetafilePict mapping */
2843 X11DRV_CLIPBOARD_SynthesizeData(CF_ENHMETAFILE);
2844 X11DRV_CLIPBOARD_SynthesizeData(CF_METAFILEPICT);
2846 /* DIB <-> Bitmap mapping */
2847 X11DRV_CLIPBOARD_SynthesizeData(CF_DIB);
2848 X11DRV_CLIPBOARD_SynthesizeData(CF_BITMAP);
2850 TRACE("%d formats added to cached data\n", ClipDataCount - count);
2854 /***********************************************************************
2855 * X11DRV_SelectionRequest_TARGETS
2856 * Service a TARGETS selection request event
2858 static Atom X11DRV_SelectionRequest_TARGETS( Display *display, Window requestor,
2859 Atom target, Atom rprop )
2861 UINT i;
2862 Atom* targets;
2863 ULONG cTargets;
2864 LPWINE_CLIPFORMAT format;
2865 LPWINE_CLIPDATA lpData;
2867 /* Create X atoms for any clipboard types which don't have atoms yet.
2868 * This avoids sending bogus zero atoms.
2869 * Without this, copying might not have access to all clipboard types.
2870 * FIXME: is it safe to call this here?
2872 intern_atoms();
2875 * Count the number of items we wish to expose as selection targets.
2877 cTargets = 1; /* Include TARGETS */
2879 if (!list_head( &data_list )) return None;
2881 LIST_FOR_EACH_ENTRY( lpData, &data_list, WINE_CLIPDATA, entry )
2882 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
2883 if ((format->wFormatID == lpData->wFormatID) &&
2884 format->lpDrvExportFunc && format->drvData)
2885 cTargets++;
2887 TRACE(" found %d formats\n", cTargets);
2889 /* Allocate temp buffer */
2890 targets = HeapAlloc( GetProcessHeap(), 0, cTargets * sizeof(Atom));
2891 if(targets == NULL)
2892 return None;
2894 i = 0;
2895 targets[i++] = x11drv_atom(TARGETS);
2897 LIST_FOR_EACH_ENTRY( lpData, &data_list, WINE_CLIPDATA, entry )
2898 LIST_FOR_EACH_ENTRY( format, &format_list, WINE_CLIPFORMAT, entry )
2899 if ((format->wFormatID == lpData->wFormatID) &&
2900 format->lpDrvExportFunc && format->drvData)
2901 targets[i++] = format->drvData;
2903 wine_tsx11_lock();
2905 if (TRACE_ON(clipboard))
2907 unsigned int i;
2908 for ( i = 0; i < cTargets; i++)
2910 char *itemFmtName = XGetAtomName(display, targets[i]);
2911 TRACE("\tAtom# %d: Property %ld Type %s\n", i, targets[i], itemFmtName);
2912 XFree(itemFmtName);
2916 /* We may want to consider setting the type to xaTargets instead,
2917 * in case some apps expect this instead of XA_ATOM */
2918 XChangeProperty(display, requestor, rprop, XA_ATOM, 32,
2919 PropModeReplace, (unsigned char *)targets, cTargets);
2920 wine_tsx11_unlock();
2922 HeapFree(GetProcessHeap(), 0, targets);
2924 return rprop;
2928 /***********************************************************************
2929 * X11DRV_SelectionRequest_MULTIPLE
2930 * Service a MULTIPLE selection request event
2931 * rprop contains a list of (target,property) atom pairs.
2932 * The first atom names a target and the second names a property.
2933 * The effect is as if we have received a sequence of SelectionRequest events
2934 * (one for each atom pair) except that:
2935 * 1. We reply with a SelectionNotify only when all the requested conversions
2936 * have been performed.
2937 * 2. If we fail to convert the target named by an atom in the MULTIPLE property,
2938 * we replace the atom in the property by None.
2940 static Atom X11DRV_SelectionRequest_MULTIPLE( HWND hWnd, XSelectionRequestEvent *pevent )
2942 Display *display = pevent->display;
2943 Atom rprop;
2944 Atom atype=AnyPropertyType;
2945 int aformat;
2946 unsigned long remain;
2947 Atom* targetPropList=NULL;
2948 unsigned long cTargetPropList = 0;
2950 /* If the specified property is None the requestor is an obsolete client.
2951 * We support these by using the specified target atom as the reply property.
2953 rprop = pevent->property;
2954 if( rprop == None )
2955 rprop = pevent->target;
2956 if (!rprop)
2957 return 0;
2959 /* Read the MULTIPLE property contents. This should contain a list of
2960 * (target,property) atom pairs.
2962 wine_tsx11_lock();
2963 if(XGetWindowProperty(display, pevent->requestor, rprop,
2964 0, 0x3FFF, False, AnyPropertyType, &atype,&aformat,
2965 &cTargetPropList, &remain,
2966 (unsigned char**)&targetPropList) != Success)
2968 wine_tsx11_unlock();
2969 TRACE("\tCouldn't read MULTIPLE property\n");
2971 else
2973 if (TRACE_ON(clipboard))
2975 char * const typeName = XGetAtomName(display, atype);
2976 TRACE("\tType %s,Format %d,nItems %ld, Remain %ld\n",
2977 typeName, aformat, cTargetPropList, remain);
2978 XFree(typeName);
2980 wine_tsx11_unlock();
2983 * Make sure we got what we expect.
2984 * NOTE: According to the X-ICCCM Version 2.0 documentation the property sent
2985 * in a MULTIPLE selection request should be of type ATOM_PAIR.
2986 * However some X apps(such as XPaint) are not compliant with this and return
2987 * a user defined atom in atype when XGetWindowProperty is called.
2988 * The data *is* an atom pair but is not denoted as such.
2990 if(aformat == 32 /* atype == xAtomPair */ )
2992 unsigned int i;
2994 /* Iterate through the ATOM_PAIR list and execute a SelectionRequest
2995 * for each (target,property) pair */
2997 for (i = 0; i < cTargetPropList; i+=2)
2999 XSelectionRequestEvent event;
3001 if (TRACE_ON(clipboard))
3003 char *targetName, *propName;
3004 wine_tsx11_lock();
3005 targetName = XGetAtomName(display, targetPropList[i]);
3006 propName = XGetAtomName(display, targetPropList[i+1]);
3007 TRACE("MULTIPLE(%d): Target='%s' Prop='%s'\n",
3008 i/2, targetName, propName);
3009 XFree(targetName);
3010 XFree(propName);
3011 wine_tsx11_unlock();
3014 /* We must have a non "None" property to service a MULTIPLE target atom */
3015 if ( !targetPropList[i+1] )
3017 TRACE("\tMULTIPLE(%d): Skipping target with empty property!\n", i);
3018 continue;
3021 /* Set up an XSelectionRequestEvent for this (target,property) pair */
3022 event = *pevent;
3023 event.target = targetPropList[i];
3024 event.property = targetPropList[i+1];
3026 /* Fire a SelectionRequest, informing the handler that we are processing
3027 * a MULTIPLE selection request event.
3029 X11DRV_HandleSelectionRequest( hWnd, &event, TRUE );
3033 /* Free the list of targets/properties */
3034 wine_tsx11_lock();
3035 XFree(targetPropList);
3036 wine_tsx11_unlock();
3039 return rprop;
3043 /***********************************************************************
3044 * X11DRV_HandleSelectionRequest
3045 * Process an event selection request event.
3046 * The bIsMultiple flag is used to signal when EVENT_SelectionRequest is called
3047 * recursively while servicing a "MULTIPLE" selection target.
3049 * Note: We only receive this event when WINE owns the X selection
3051 static void X11DRV_HandleSelectionRequest( HWND hWnd, XSelectionRequestEvent *event, BOOL bIsMultiple )
3053 Display *display = event->display;
3054 XSelectionEvent result;
3055 Atom rprop = None;
3056 Window request = event->requestor;
3058 TRACE("\n");
3061 * We can only handle the selection request if :
3062 * The selection is PRIMARY or CLIPBOARD, AND we can successfully open the clipboard.
3063 * Don't do these checks or open the clipboard while recursively processing MULTIPLE,
3064 * since this has been already done.
3066 if ( !bIsMultiple )
3068 if (((event->selection != XA_PRIMARY) && (event->selection != x11drv_atom(CLIPBOARD))))
3069 goto END;
3072 /* If the specified property is None the requestor is an obsolete client.
3073 * We support these by using the specified target atom as the reply property.
3075 rprop = event->property;
3076 if( rprop == None )
3077 rprop = event->target;
3079 if(event->target == x11drv_atom(TARGETS)) /* Return a list of all supported targets */
3081 /* TARGETS selection request */
3082 rprop = X11DRV_SelectionRequest_TARGETS( display, request, event->target, rprop );
3084 else if(event->target == x11drv_atom(MULTIPLE)) /* rprop contains a list of (target, property) atom pairs */
3086 /* MULTIPLE selection request */
3087 rprop = X11DRV_SelectionRequest_MULTIPLE( hWnd, event );
3089 else
3091 LPWINE_CLIPFORMAT lpFormat = X11DRV_CLIPBOARD_LookupProperty(NULL, event->target);
3093 if (lpFormat && lpFormat->lpDrvExportFunc)
3095 LPWINE_CLIPDATA lpData = X11DRV_CLIPBOARD_LookupData(lpFormat->wFormatID);
3097 if (lpData)
3099 unsigned char* lpClipData;
3100 DWORD cBytes;
3101 HANDLE hClipData = lpFormat->lpDrvExportFunc(display, request, event->target,
3102 rprop, lpData, &cBytes);
3104 if (hClipData && (lpClipData = GlobalLock(hClipData)))
3106 int mode = PropModeReplace;
3108 TRACE("\tUpdating property %s, %d bytes\n",
3109 debugstr_format(lpFormat->wFormatID), cBytes);
3110 wine_tsx11_lock();
3113 int nelements = min(cBytes, 65536);
3114 XChangeProperty(display, request, rprop, event->target,
3115 8, mode, lpClipData, nelements);
3116 mode = PropModeAppend;
3117 cBytes -= nelements;
3118 lpClipData += nelements;
3119 } while (cBytes > 0);
3120 wine_tsx11_unlock();
3122 GlobalUnlock(hClipData);
3123 GlobalFree(hClipData);
3129 END:
3130 /* reply to sender
3131 * SelectionNotify should be sent only at the end of a MULTIPLE request
3133 if ( !bIsMultiple )
3135 result.type = SelectionNotify;
3136 result.display = display;
3137 result.requestor = request;
3138 result.selection = event->selection;
3139 result.property = rprop;
3140 result.target = event->target;
3141 result.time = event->time;
3142 TRACE("Sending SelectionNotify event...\n");
3143 wine_tsx11_lock();
3144 XSendEvent(display,event->requestor,False,NoEventMask,(XEvent*)&result);
3145 wine_tsx11_unlock();
3150 /***********************************************************************
3151 * X11DRV_SelectionRequest
3153 void X11DRV_SelectionRequest( HWND hWnd, XEvent *event )
3155 X11DRV_HandleSelectionRequest( hWnd, &event->xselectionrequest, FALSE );
3159 /***********************************************************************
3160 * X11DRV_SelectionClear
3162 void X11DRV_SelectionClear( HWND hWnd, XEvent *xev )
3164 XSelectionClearEvent *event = &xev->xselectionclear;
3165 if (event->selection == XA_PRIMARY || event->selection == x11drv_atom(CLIPBOARD))
3166 X11DRV_CLIPBOARD_ReleaseSelection( event->display, event->selection,
3167 event->window, hWnd, event->time );
3170 /***********************************************************************
3171 * X11DRV_Clipboard_Cleanup
3173 void X11DRV_Clipboard_Cleanup(void)
3175 selectionAcquired = S_NOSELECTION;
3177 X11DRV_EmptyClipboard(FALSE);